text
stringlengths
180
608k
[Question] [ Your task, if you wish to accept it, is to write a program that outputs a non-zero number(can be integer or float). The tricky part is that if I reverse your source code, the output must be the original integer negated. # Rules * You must build a **full program**. That is, your output has to be printed to STDOUT. * Both the numbers must be in base 10 (outputting them in any other base or with scientific notation is forbidden). * Outputting the numbers with trailing / leading spaces is allowed. * This is code-golf, so the shortest (original) code in each language wins! * Default Loopholes apply. ## Example Let's say your source code is `ABC` and its corresponding output is `4`. If I write `CBA` instead and run it, the output must be `-4`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes ``` (1 ``` [Try it online!](https://tio.run/##yy9OTMpM/f9fw/D/fwA "05AB1E – Try It Online") [!enilno ti yrT](https://tio.run/##yy9OTMpM/f/fUOP/fwA "05AB1E – Try It Online") ``` ( # negate nothing 1 # push 1 (and implictly output it) ``` ``` 1 # push 1 ( # negate it (and implictly output it) ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~4~~ 3 bytes ``` 1-0 ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31DX4P9/AA "PowerShell – Try It Online") or [!enilno ti yrT](https://tio.run/##K8gvTy0qzkjNyfn/30DX8P9/AA "PowerShell – Try It Online") *Golfed a byte by using arithmetic instead of the number-comment-number format.* --- This is apparently also the same as jshell (per [Sam](https://codegolf.stackexchange.com/users/89348/sam)), and jq (per [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) -- [`1-0`](https://tio.run/##yyr8/99Q1@D//3/5BSWZ@XnF/3XzAA) and [`0-1`](https://tio.run/##yyr8/99A1/D//3/5BSWZ@XnF/3XzAA)). [Answer] # [JavaScript (V8)](https://v8.dev/), 19 bytes ``` print(1)//)1-(tnirp ``` [Try it online!](https://tio.run/##TYxNCsMgEIX3niK7zECd4K5QcpJSiJihGMQRFa9vGqi0u/fzvXfYZovLPlXd7t3JzuvWU/axgsFlQaOhRp9T36gE7xjMTRtUKnPjXHif1ulJRNfwRd8QkA7xEeYZH0o5iUUCU5A3XNgn42bD0P/1OB3Iz/cT "JavaScript (V8) – Try It Online") --- almost identical to... # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 19 bytes ``` Print(1)//)1-(tnirP ``` [Try it online!](https://tio.run/##Sy7WTS7O/P8/oCgzr0TDUFNfX9NQV6MkL7Mo4P9/AA "C# (Visual C# Interactive Compiler) – Try It Online") *(thanks to @someone for pointing it out)* --- still pretty much the same in... # [Lua](https://www.lua.org/), 19 bytes ``` print(1)--)1-(tnirp ``` [Try it online!](https://tio.run/##yylN/J@cn5JqqxEd/b@gKDOvRMNQU1dX01BXoyQvs6jgf2ysplVxaZKGoY6ukSYXV1FqWWpRcWqKgq0CSJsVlK8BlILoBolqcuXkJ6ZAmEAZiARMJ1QSztXQ/A8A "Lua – Try It Online") --- but shorter in... # [Python 2](https://docs.python.org/2/), 15 bytes ``` print 1#1-tnirp ``` [Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EwVDZULckL7Oo4P9/AA "Python 2 – Try It Online") --- Even shorter in PHP, because it has this magic printing tool: `<?=` ... # [PHP](https://php.net/), 12 bytes ``` <?=1;#;1-=?< ``` [Try it online!](https://tio.run/##K8go@P/fxt7W0FrZ2lDX1t7m/38A "PHP – Try It Online") --- Even shorterer in Ruby, because you can `inspect` rather than print # [Ruby](https://www.ruby-lang.org/), 8 bytes ``` p 1#1- p ``` [Try it online!](https://tio.run/##KypNqvz/v0DBUNlQV6Hg/38A "Ruby – Try It Online") [Answer] # [///](https://esolangs.org/wiki////), 4 bytes ``` 9/9- ``` Outputs `9`. [Try it online!](https://tio.run/##K85JLM5ILf7/31LfUvf/fwA "/// – Try It Online") Reversed: ``` -9/9 ``` Outputs `-9`. [Try it online!](https://tio.run/##K85JLM5ILf7/X9dS3/L/fwA "/// – Try It Online") Everything before the `/` is printed, while the rest is ignored (not really used slashes much so I don't know exactly what happens, but it doesn't output anything). [Answer] # [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 21 bytes ``` S S S T N T N S T N N N T S N T N T T S S ``` Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only. Outputs `1`/`-1`. [Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgZOLkwtIcHFxKgBZnJwKCv//AwA) or [try it online reversed](https://tio.run/##K8/ILEktLkhMTv3/X0GBk5OLk0uBk4uLi1MByOJUUFD4/x8A) (with raw spaces, tabs and new-lines only). **Explanation:** Utilizing the *Exit Program* builtin being a short palindrome `NNN`. The regular program will: ``` SSSTN # Push 1 to the stack TNST # Pop and print the top of the stack as number NNN # Exit the program, making everything after it no-ops ``` The reverse program will: ``` SSTTN # Push -1 to the stack TNST # Pop and print the top of the stack as number NNN # Exit the program, making everything after it no-ops ``` Small additional explanation of pushing a number: * First `S`: Enable Stack Manipulation * Second `S`: Push a number to the stack * `S` or `T`: Positive/negative respectively * Some `S`/`T` followed by a trailing `N`: number in binary, where `S=0` and `T=1` I.e. `SSTTSTSN` pushes `-10`. [Answer] ## [Stack Cats](https://github.com/m-ender/stackcats) `-mn`, 4 bytes ``` :-:_ ``` [Try it online!](https://tio.run/##FcshDgAhDERRzy1qm/QCvUE9jrANQW4WA5K7d6fm5Y@YfcZ85zg7QkU9iF0LS0s68CzPagI6cGLABG5SQX6LXgE1MUx7TCPkWz8 "Stack Cats – Try It Online") In the footer I've included all other 4-byte solutions. (Stack Cats ignores everything after the first linefeed.) [Try the reverse!](https://tio.run/##Ky5JTM5OTiwp/v8/3krX6v///7q5eQA "Stack Cats – Try It Online") ### Explanation The `-n` flag turns on numeric output (and input, but we don't have any), and the `-m` flag is normally just a golfing convenience which lets you avoid the redundant part of the source code. This is because every Stack Cats program needs to have mirror symmetry. With the `-m` flag you only give it the first half (plus the central character). So the *actual* program here is: ``` :-:_:-: ``` As you can see in the first TIO link, there's a ton of 4-byte solutions, but I picked this one for its simplicity. Stack Cats is stack-based, and this program only uses the initial stack. Since we don't have any input, it contains a single `-1` (an EOF marker) on top of an infinite well of zeros. The three commands in the program have the following meaning: ``` : Swap the top two stack elements. - Negate the top stack element (i.e. multiply by -1). _ Pop a. Peek b. Push b-a. ``` So here is how the program modifies the stack (states and commands are staggered to indicate how each command changes the stack from one state to the next): ``` : - : _ : - : -1 0 0 -1 1 0 0 1 0 -1 -1 0 0 1 1 0 0 0 0 0 0 0 0 0 … … … … … … … … ``` As it turns out, the only command that really does anything here is `_` which turns our EOF marker into a `1`. Output at the end of the program is implicit, and the EOF marker is optional, so this just prints out the `1` we get. Now if we reverse the source code, due to the implicit mirroring, the actual program becomes: ``` _:-:-:_ ``` This does something very different: ``` _ : - : - : _ -1 1 0 0 1 -1 0 -1 0 0 1 1 0 0 -1 -1 0 0 0 0 0 0 0 0 … … … … … … … … ``` This time the bottom of the stack *is* still a `-1` so it does act as the EOF marker and only the `-1` on top of it gets printed. ... Now with all of that said, since Stack Cats has such a unique relationship with reversing code, I feel that using `-m` is a little cheating. It's normally only meant to save bytes by omitting the redundant part of the source code, but here it actually makes the challenge a lot easier and even the full program shorter. This is because reversing a full program will only change the program if it contains any of `<>[]`, which also means that the program ends up making use of multiple stacks (Stack Cats actually has a tape of stacks, where all but the initial one are only filled with zeros to begin with). Furthermore, reversing it then just swaps the `<>` and `[]` pairs, which still makes the execution symmetric. The only way to break that symmetry is to use `I` which does `-]` or `-[` or nothing depending on the sign of the top of the stack. So... --- ## [Stack Cats](https://github.com/m-ender/stackcats) `-n`, 11 bytes ``` *|]I*:*I[|* ``` [Try it online!](https://tio.run/##TdG7jgMhDAXQfr8i0zoaRbslQtPf3h0BFKVcKU1S8u@zNr5IW8BwwDaPeX8ez9/n4/M@TxkVkgRlyLmPLAesjf3y/bWPgp46KoViqggpIzXESIqRIS8HL7ykUOrf3pcfE6SmIliqtlYoZaSGGLkUkaFD0K8dksV26C1vds7taN3lA/jUEjqWDslIsN7VOvN6c/kAM9uUtlTsRtW@lN2ImhmY2RQiMdQMjbInsCr@IJRVofwQdhY/kqmMY8uwNqpLKZ3yaXjAklWh7Ff5DawvUzqlUxj3qduASymdqswrIeaF7ly7hbjmOs/99Qc "Stack Cats – Try It Online") The footer again includes all other alternatives at the same byte count. Some of those output 1/-1 and some output 2/-2 as indicated after each program. I picked this one to explain kinda randomly as one of the ones that output 2. [Try the reverse!](https://tio.run/##Ky5JTM5OTiwp/v9fqybaU8tKyzO2Ruv///@6eQA "Stack Cats – Try It Online") ### Explanation As I said, this one's a bit longer. Even if we did use the `-m` notation for this, it would weigh in at 6 bytes instead of the above 4. The commands in use this time: ``` * Toggle the least significant bit of the top of the stack. | Reverse the longest non-zero of prefix on this stack. [] Move one stack to the left/right and take the top of the current stack with you. I If the top of the stack is positive, -], if it's negative, -[, otherwise do nothing. : Swap the top two stack elements. ``` The first program only uses two stacks. That's a bit messy to do in ASCII art, but I'll try my best. The square brackets indicate which stack the tape head is on, and I'll put the commands between each pair of stack states. ``` [-1] … 0 0 … 0 0 … … * [-2] … 0 0 … 0 0 … … | (does nothing) ] [-2] … 0 0 … 0 0 … … I [2] … 0 0 … 0 0 … … * [3] … 0 0 … 0 0 … … : [0] … 3 0 … 0 0 … … * [1] … 3 0 … 0 0 … … I [-1] … 3 0 … 0 0 … … [ [-1] … 3 0 … 0 0 … … | [ 3] … -1 0 … 0 0 … … * [ 2] … -1 0 … 0 0 … … ``` Now the `-1` acts as an EOF marker and the `2` gets printed. The other program is the same until the `[`. It's still virtually the same all the way until the second `I`. We'll technically be on a different stack, but without values on them, they're all indistinguishable. But then the difference between `I[` and `I]` ends up mattering: ``` *|[I*:*I [-1] … 3 0 0 … 0 0 0 … … … ] [-1] … 3 0 0 … 0 0 0 … … … | (does nothing) * [-2] … 3 0 0 … 0 0 0 … … … ``` And this time, we don't have an EOF marker, but the program still outputs the `-2`. [Answer] # [Google](https://www.google.com), 3 bytes ``` 2-1 ``` [Try it online!](https://www.google.com/search?q=2-1) [!enilno ti yrT](https://www.google.com/search?q=1-2) [Answer] # [Klein](https://github.com/Wheatwizard/Klein) 011, 5 bytes ``` 1- @/ ``` [Try it online!](https://tio.run/##y85Jzcz7/99Ql8tB/////waGhgA "Klein – Try It Online") # Reversed ``` /@ -1 ``` [Try it online!](https://tio.run/##y85Jzcz7/1/fgUvX8P///waGhgA "Klein – Try It Online") These take advantage of Klein's unique topology, specifically the real projective plane. (Although individually each answer only needs a Klein bottle). [Answer] # [Haskell](https://www.haskell.org/) without comments, 41 bytes Forwards prints `1` + newline: ``` main=print$!1 niam=main "1-"!$rtStup=niam ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RF0ZArLzMx1xYkxKVkqKukqFJUElxSWmALEv7/HwA "Haskell – Try It Online") Reversed prints `-1` with no newline (which could be added at a cost of 2 bytes): ``` main=putStr$!"-1" niam=main 1!$tnirp=niam ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oLQkuKRIRVFJ11CJKy8zMdcWJMxlqKhSkpdZVGALEvr/HwA "Haskell – Try It Online") * The first line of each program prints the number. + For `-1` string output is used to avoid parentheses. + Using `$!` (strict application) instead of a space allows the reversed line to be a valid definition of the operator `!$` (just `$` wouldn't do since the redefinition would break the use). * The middle line ensures that `niam` is defined for the last line. * The last line is a definition of an operator `!$`, which is not used but needs to parse and typecheck correctly. [Answer] # [PHP](https://php.net/), ~~15~~ 13 bytes A PHP version without comment abuse. `ohce` is an undefined constant, so it will be equal to string value of its name. As a result, this will try to print `+1-'ohce'` or `-1+'ohce'` when reversed. Since `'ohce'` is a non-numeric value, 0 will be used instead in the arithmetic operations and only `1` or `-1` will be printed. ``` ;echo+1-ohce; ``` [Try it online!](https://tio.run/##K8go@G9jXwAkrVOTM/K1DXXzM5JTrf//BwA "PHP – Try It Online") [‮Try it online!](https://tio.run/##K8go@G9jXwAkrVOTM/J1DbXzM5JTrf//BwA "PHP – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) Any single digit integer `>0` can be used in place of the `2` as can `A-G`, `H`, `I`, `J` or `L` (`10-16`, `32`, `64`, `-1` & `100`, respectively). ``` n2 ``` [Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=bjI) | [Reversed](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Mm4) The `n` method when applied to an integer, subtracts that integer from the argument passed to it, which defaults to `0`. When run forwards, the `n` method is being run on the implicit first input, which also defaults to `0`. Alternatively, the `g` method could be used instead of `n`, which gives the sign of the result of subtracting its argument from the integer it's applied to. [Answer] # [Cubix](https://github.com/ETHproductions/cubix), ~~7~~ ~~6~~ 5 bytes ``` @)O(@ ``` [Try it here](https://ethproductions.github.io/cubix/?code=QClPKEA=&input=&speed=3) [Reversed](https://ethproductions.github.io/cubix/?code=QChPKUA=&input=&speed=3) ### Explanation Cubified: ``` @ ) O ( @ . ``` Unrolling the control flow, we execute `)O(@`, which increments, outputs, decrements, and exits. Reversed and cubified: ``` @ ( O ) @ . ``` Unrolling the control flow, we execute `(O)@`, which decrements, outputs, increments, and exits. ### Previous version ``` @O(.)O@ ``` [Try it here](https://ethproductions.github.io/cubix/?code=ICAgIEAgTwogICAgKCAuCikgTyBAIC4gLiAuIC4gLgouIC4gLiAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=&speed=3) [Reversed](https://ethproductions.github.io/cubix/?code=ICAgIEAgTwogICAgKSAuCiggTyBAIC4gLiAuIC4gLgouIC4gLiAuIC4gLiAuIC4KICAgIC4gLgogICAgLiAuCg==&input=&speed=3) Not as short, but aesthetically pleasing. [Answer] # T-SQL, 16 bytes ``` --Forwards: PRINT 4--4-TNIRP --Backwards: PRINT-4--4 TNIRP ``` Picked 4 because 1 is overused :) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` NC ``` [Try it online!](https://tio.run/##y0rNyan8/9/P@f9/AA "Jelly – Try It Online") `N`egative, results in `0`, then `C`omplement, results in `1-0` = `1`. --- ``` CN ``` [Try it online!](https://tio.run/##y0rNyan8/9/Z7/9/AA "Jelly – Try It Online") `C`omplement, results in `1-0` = `1`. `N`egative, results in `-1`. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 3 bytes ``` 2-1 ``` [Try it online!](https://tio.run/##y9bNS8/7/99I1/D/fwA "K (ngn/k) – Try It Online") am i missing something? seems obvious for REPL languages [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 5 bytes ``` 1!@!( ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/99Q0UFR4/9/AA "Hexagony – Try It Online") Any valid program must: * Have a termination command (`@` or `:`). The latter is only different for the former when there's a memory pointer movement command. Also this command must not be at the first or the last byte. * Have an output command. (`!`, `;` is also possible but would probably take more bytes) * Have a memory manipulation command. Therefore a 2-byte program is obviously impossible. A 3-byte program is impossible because the second byte must be the termination command, and the first byte must not be a mirror/IP manipulation command, therefore only 1 byte can be executed. I think a 4-byte program is not possible. Such a program must have the form `a@bc` with hexagonal grid ``` Forward: | Backward: | c b | a @ @ a . | b c . . . | . . ``` Therefore `a` must be a IP redirection command. However it's impossible to generate both positive and negative number with only 1 memory manipulation command. [Answer] # [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 4 bytes ``` 1@Z1 ``` [Try it online!](https://tio.run/##KyrNy0z@/9/QIcrw/38A "Runic Enchantments – Try It Online") [Try it Reversed!](https://tio.run/##KyrNy0z@/98wysHw/38A "Runic Enchantments – Try It Online") I couldn't find a way to re-use the `1` command, even at the expense of a byte or two. [`1@ɩ`](https://tio.run/##KyrNy0z@/9/Q4eTK//8B) also works, but is the same number of bytes. [Answer] # [Zsh](https://www.zsh.org/), 12 bytes ``` <<<2 # 2-<<< ``` [Try it online!](https://tio.run/##qyrO@P/fxsbGSEFZwUgXyABxdME8EAcA "Zsh – Try It Online") Basic forward, comment, reverse method. --- If I/O is less restrictive, then a more interesting **11 byte** solution is possible thanks to Zsh supporting negative return codes: ``` return -127 ``` Reversed, `721- nruter` exits with code `127` (command not found). `exit -127` cannot be used, it would be cast to a `u8`. [Try it online!](https://tio.run/##qyrO@J@moVn9vyi1pLQoT0HX0Mj8fy1XEVCIy9zIUFchr6i0JLWIq5aLK40rNTkjX0HFnourCMb8DwA "Zsh – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~4~~ 3 bytes ``` 1-0 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRDXQOudCBtoGsIFOBKBwA "APL (Dyalog Unicode) – Try It Online") Trivial answer. Prints `1` when run and `¯1` when run reversed. [Answer] # [CJam](https://sourceforge.net/p/cjam), 3 bytes ``` W;1 ``` Try it online! * [Normal](https://tio.run/##S85KzP3/P9za8P9/AA) * [Reversed](https://tio.run/##S85KzP3/39A6/P9/AA) ### How they work Normal version: ``` W e# Push -1 ; e# Delete 1 e# Push 1 e# Implicit display ``` Reverse version: you get the idea. [Answer] # [MATL](https://github.com/lmendo/MATL), 3 bytes ``` Nqv ``` Try it online! * [Normal](https://tio.run/##y00syfn/36@w7P9/AA) * [Reversed](https://tio.run/##y00syfn/v6zQ7/9/AA) ### How they work Normal: ``` N % Push number of elements in the stack: 0 q % Subtract 1: gives -1 v % Concatenate stack contents vertically: leaves -1 as is % Implicit display stack contents ``` Reversed: ``` v % Concatenate stack contents vertically: gives the empty array, [] q % Subtract 1: leaves [] as is N % Push number of elements in the stack: 1 % Implicit display. [] is not displayed ``` [Answer] # [Perl 5](https://www.perl.org/) (-p), 12 bytes ``` \$--{}}{++$\ ``` [Try it online!](https://tio.run/##K0gtyjH9/z9GRVe3ura2WltbJeb//3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [!enilno ti yrT](https://tio.run/##K0gtyjH9/z9GRVu7ura2WldXJeb//3/5BSWZ@XnF/3ULAA) The `}{` pseudo-operator really comes in handy. --- ## [Perl 5](https://www.perl.org/) (-M5.010), 9 bytes *Provided by Nahuel Fouilleul in a comment* ``` say+1-yas ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVLbULcysfj//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [!enilno ti yrT](https://tio.run/##K0gtyjH9/784sVLXULsysfj//3/5BSWZ@XnF/3V9TfUMDA0A "Perl 5 – Try It Online") [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), 6 bytes ``` -`< - ``` Prints `1`. [Try it online!](https://tio.run/##K0otycxLNPz/XzfBhkuX6/9/AA "Retina – Try It Online") --- ``` - <`- ``` Prints `-1`. [Try it online!](https://tio.run/##K0otycxLNPz/n0uXyyZB9/9/AA "Retina – Try It Online") ### Explanation: `1` ``` -`< - ``` This... does nothing. Due to the ```, this is a substitution from `<` to `-` (with configuration `-`, which does nothing), but the input is empty, so the output is empty as well. ``` ``` And this second stage matches the empty regex against the empty input and counts the number of matches, which is exactly 1. Output is implicit. ### Explanation: `-1` ``` - ``` This time we replace the empty regex with `-`. This does indeed turn the empty input into a single `-`. ``` <`- ``` Here, the configuration actually does something: `<` prints the stage's input before executing the stage, so we print the `-`. Then `-` counts the hyphens in the stage's input which is again 1. Due to the implicit output, this prints a `1` after the `-`, giving us `-1` as required. [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~21~~ 18 bytes ``` Print@1;tnirP//1-0 ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78r/Q/oCgzr8TB0LokL7MoQF/fUNfgv5K@vgaXQki@a0VBUWpxcWZ@noOyNZpAcAlQX3pQallqUXGqgzKXptp/AA "Wolfram Language (Mathematica) – Try It Online") -3 thanks to [Martin Ender](https://codegolf.stackexchange.com/questions/192979/i-reverse-the-source-code-you-negate-the-output/193040?noredirect=1#comment460420_193040) [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 156 bytes ``` +++++++++++++++++++++++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++<+++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++ ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fmxSgp00qsCFZB5Id//8DAA "brainfuck – Try It Online") / [Forward/backward verifier in Bash](https://tio.run/##nY@7DoMwDEV3f4WHSh4qmm5IVdqhQ38CEMoLgaABhQCfn0YdStWhLw@WdeVzfS3FWIegNDJ/HcA7TDRSbpGQcyTTV4QnFLB9qQ8C7H4l7gLw/7DnaxAzA8CiMFExuBI@dqPqHmAwrsNk2KdpapA25dGZ2bjR4KYkFPFPGXdcY32FdOndIpw@YJZlBKwfPJNONLaaVLtOkeLItJmZnbruARdFkVtazc5Ctd@4yTduIdwA "Bash – Try It Online") Prints `-1` forward and `\n1` backwards. Despite being almost trivial, I believe this is the optimal solution for this particular fixed output. Proof: * The program cannot have `[` or `]`. Therefore the program must have the form `<A> . <B> . <C>`. * Each `,` can be replaced with a sufficient number of `<` without increasing the number of `+` or `-`. * Each `+` is only useful in either the forward or the backward program, never both. Proof: `+` in part A is obviously only useful in the forward program, and `+` in part C is obviously only useful in the backward program. Denote `shift(P)` = number of `<` in P - number of `>` in P. Consider program `<B> = <D> + <E>`, the `+` in the middle is useful in the forward program \$\iff\$ `shift(E) = 0`, similarly it's useful in the backward program \$\iff\$ `shift(D) = 0`. However if `shift(D) = shift(E) = 0` then the program `B` executed either forward or backward would add a fixed value to the current cell before printing the second time, which can't be the case because `ord('1') - ord('\n') != ord('1') - ord('-')`. Therefore the program needs at least `ord('-')+ord('1')+ord('\n')+ord('1') = 153` `+`s, 2 `.`s, and at least a `<` `>` or `,` because `shift(B) != 0`. [Answer] # Google Sheets, 12 Fun problem! Forward: ``` =1+N("(N+1-= ``` Backward: ``` =-1+N("(N+1= ``` Google sheets auto-closes quotes and parens. `N(string)` is always 0. [Answer] # [Haskell](https://www.haskell.org/), 28 bytes ``` main=print 1--)1-(tnirp=niam ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0TBUFdX01BXoyQvs6jANi8zMff/fwA "Haskell – Try It Online") [Try it enilno!](https://tio.run/##y0gszk7Nyfn/PzcxM8@2oCgzr0RD11BTV9dQoSQvs6jANi8zMff/fwA "Haskell – Try It Online") [Answer] # [Triangular](https://github.com/aaronryank/triangular), 4 bytes ``` i%%d ``` [Try it online!](https://tio.run/##KynKTMxLL81JLPr/P1NVNeX/fwA "Triangular – Try It Online") Outputs 1. Ungolfed: ``` i % % d ``` **Reversed:** ``` d%%i ``` [Try it online!](https://tio.run/##KynKTMxLL81JLPr/P0VVNfP/fwA "Triangular – Try It Online") Outputs -1. [Answer] # Java 5 or 6, ~~127~~ 67 bytes ``` enum A{A;{System.out.print(9);}}//}};)9-(tnirp.tuo.metsyS{;A{A mune ``` Outputs `9`/`-9`. No online compiler, because Java 5 or 6 isn't available anywhere. You can however try this **127 bytes** Java 8 equivalent: [Try it online](https://tio.run/##Dc3BCoUgEEDRX5mlLrJ19A9tXEaLQS2mhxo6CSF@u8/tgcu9seB021/vFNilE42DrWZGJgMlkgWPFITmROHaD5RVf5mdV/Fl9Qxksci1tXlubZXLJDhQehS/UXnH@dNV4rFfA1mLQOjBUixgaBxy3cAZPJMbUe9/) or [try it online reversed](https://tio.run/##Dc3BCoUgEEDRX5mlLrJ19A9tXEaLQS2mhxo6CSF@u8/tgcu9seB021/vFNilE42DrWZGJgMlkgWPFITmROHaD5RVf5mdV/Fl9QxkMS1ybW2eW1vlIjhQehS/UXnH@dNV4rFfA1mLQOjBUixgaBxy3cAZPJMbUe9/). **Explanation:** ``` enum A{ // Create an enum A; // With a mandatory value { // And in a separate instance code-block: System.out.print(9);}} // Print 9 to STDOUT //}};)9-(tnirp.tuo.metsyS{;A{A mune // Comment and thus a no-op ``` Java 5 and 6 had a bug allowing you to create a code block inside an enum to do something, despite missing a program's mandatory main-method. This will result in an error: > > java.lang.NoSuchMethodError: main > > Exception in thread "main" > > > But will still output what we'd want to STDOUT first, so [we can ignore that](https://codegolf.meta.stackexchange.com/a/12503/52210). [Answer] # JavaScript, 31 bytes The obligatory comment abuse for JavaScript! ``` console.log(1)//)1-(gol.elosnoc ``` and reversed: ``` console.log(-1)//)1(gol.elosnoc ``` ]
[Question] [ ## About the Series This is a guest entry for the Random Golf of the Day series. First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series [in the first post](https://codegolf.stackexchange.com/q/45302/8478). # Input No input is taken. # Output A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and ***all 26 probabilities must be distinct***. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other. # Scoring This is code golf. Shortest code in bytes wins. A valid entry is a [full program or function](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) that has zero probability of not terminating. # Alphabet To avoid confusion, the particular alphabet to be used is the Latin alphabet: Either ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` or ``` abcdefghijklmnopqrstuvwxyz ``` You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower). # Explanation As it won't be at all obvious from the output, **please include a clear explanation of how you achieved the 26 distinct probabilities.** # Leaderboard *(from [here](http://meta.codegolf.stackexchange.com/questions/5139/leaderboard-snippet))* ``` var QUESTION_ID=89621,OVERRIDE_USER=20283;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> ``` **[The first post of the series also generates an overall leaderboard.](https://codegolf.stackexchange.com/q/45302/8478)** To make sure that your answers show up, please start every 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 ``` *(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)* [Answer] # MATL, 6 Characters ``` 1Y2Xr) ``` Explanation: `Xr` Take a normally distributed random number `)` Use this to index into... `1Y2` The alphabet The distribution is symmetrical around 0, and the translation of number to char is symmetrical around 0.5. As such the probabilities should be distinct. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes ### Code ``` A.pJ.R ``` ### Explanation ``` A # Pushes the alphabet .p # Computes all prefixes J # Join them together ``` We now have the following string: ``` aababcabcdabcdeabcdefabcdefgabcdefghabcdefghiabcdefghijabcdefghijkabcdefghijklabcdefghijklmabcdefghijklmnabcdefghijklmnoabcdefghijklmnopabcdefghijklmnopqabcdefghijklmnopqrabcdefghijklmnopqrsabcdefghijklmnopqrstabcdefghijklmnopqrstuabcdefghijklmnopqrstuvabcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyz ``` After that, we pick a random element using `.R`. ### The probabilities ``` a > 7.4074074074074066% b > 7.122507122507122% c > 6.837606837606838% d > 6.552706552706553% e > 6.267806267806268% f > 5.982905982905983% g > 5.698005698005698% h > 5.413105413105414% i > 5.128205128205128% j > 4.843304843304843% k > 4.5584045584045585% l > 4.273504273504274% m > 3.988603988603989% n > 3.7037037037037033% o > 3.418803418803419% p > 3.133903133903134% q > 2.849002849002849% r > 2.564102564102564% s > 2.2792022792022792% t > 1.9943019943019944% u > 1.7094017094017095% v > 1.4245014245014245% w > 1.1396011396011396% x > 0.8547008547008548% y > 0.5698005698005698% z > 0.2849002849002849% ``` [Try it online!](http://05ab1e.tryitonline.net/#code=QS5wSi5S&input=). [Answer] # Pyth, 5 ``` Os._G ``` [Try it here](http://pyth.herokuapp.com/?code=Os._G&debug=0) Computes the prefixes of the alphabet, so: `["a", "ab", "abc", ..., "abcdefghijklmnopqrstuvwxyz"]`. Then flattens the list and selects a random element from it uniformly. This means that since `a` appears 26 times, while `b` appears 25 times, all the way down to `z` with only 1 appearance, each letter has a different chance of appearing. The total string has 351 characters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØA»ẊX ``` [Try it online!](http://jelly.tryitonline.net/#code=w5hBwrvhuopY&input=) ### How it works ``` ØA«ẊX Main link. No arguments. ØA Set argument and return value to the alphabet. Ẋ Shuffle it. » Yield the maximum of each letter in the sorted alphabet, and the corresponding character in the shuffled one. X Pseudo-randomly select a letter of the resulting array. ``` ### Background Let **L0, …, L25** denotes the letters of the alphabet in their natural order, and **S0, …, S25** a uniformly at random selected permutation of **L**. Define the finite sequence **M** by **Mn = max(Ln, Sn)**. Fix **n** in **0, … 25** and define **k** as the index such that **Ln = Sk**. With probability **1 / 26**, **Ln = Sn** and **n = k**, so **Mn = Ln** and **Ln** occurrs once in **M**. With probability **25 /26**, **Ln ≠ Sn** and **n ≠ k**. In this case, the following happens. * With probability **n / 25**, **Sn** is one of **L0, …, Ln - 1**, so **Ln > Sn** and **Mn = Ln**. * Independently, also with probability **n / 25**, **k** is one of **0, … n - 1**, so **Sk > Lk** and **Mk = Sk = Ln**. Thus, the expected number of occurrences of **Ln** in **M** is **1/26 + 25/26 · (n/25 + n/25) = (2n + 1)/26**. Finally, if we now select a term **m** of **M** uniformly at random, the letter **Ln** we be chosen with probability **(2n + 1)/26 / 26 = (2n + 1)/676**. This yields the following distribution of probabilities. ``` p(m = A) = 1/676 ≈ 0.00148 p(m = B) = 3/676 ≈ 0.00444 p(m = C) = 5/676 ≈ 0.00740 p(m = D) = 7/676 ≈ 0.01036 p(m = E) = 9/676 ≈ 0.01331 p(m = F) = 11/676 ≈ 0.01627 p(m = G) = 13/676 ≈ 0.01923 p(m = H) = 15/676 ≈ 0.02219 p(m = I) = 17/676 ≈ 0.02515 p(m = J) = 19/676 ≈ 0.02811 p(m = K) = 21/676 ≈ 0.03107 p(m = L) = 23/676 ≈ 0.03402 p(m = M) = 25/676 ≈ 0.03698 p(m = N) = 27/676 ≈ 0.03994 p(m = O) = 29/676 ≈ 0.04290 p(m = P) = 31/676 ≈ 0.04586 p(m = Q) = 33/676 ≈ 0.04882 p(m = R) = 35/676 ≈ 0.05178 p(m = S) = 37/676 ≈ 0.05473 p(m = T) = 39/676 ≈ 0.05769 p(m = U) = 41/676 ≈ 0.06065 p(m = V) = 43/676 ≈ 0.06361 p(m = W) = 45/676 ≈ 0.06657 p(m = X) = 47/676 ≈ 0.06953 p(m = Y) = 49/676 ≈ 0.07249 p(m = Z) = 51/676 ≈ 0.07544 ``` You can empirically verify the distribution by [calling the link 100,000 times](http://jelly.tryitonline.net/#code=w5hBwrvhuopYCsKiCsi3NcOH4oKsxKBM4oKsw7fItzXFkuG5mOKCrHowWsOYQcW8S-KCrFk&input=) (takes a few seconds). [Answer] # [MATL](https://github.com/lmendo/MATL), 10 bytes ``` 1Y2rU26*k) ``` [**Try it online!**](http://matl.tryitonline.net/#code=MVkyclUyNiprKQ&input=) The code generates a uniform random variable on the interval (0,1) (`r`) and computes its square (`U`). This results in a non-uniform, decreasing probability density. Multiplying by 26 (`26*`) ensures that the result is on the interval (0,26), and rounding down (`k`) produces the values 0,1,...,25 with decreasing probabilities. The value is used as an index (`)`) into the uppercase alphabet (`1Y2`). Since MATL uses 1-based modular indexing, 0 corresponds to Z, 1 to A, 2 to B etc. As an illustration that the probabilities are distinct, here's a discrete histogram resulting from 1000000 random realizations. The graph is produced by running this in Matlab: ``` bar(0:25, histc(floor(26*rand(1,1e6).^2), 0:25)) ``` [![enter image description here](https://i.stack.imgur.com/Piomw.png)](https://i.stack.imgur.com/Piomw.png) [Answer] # Java 7, ~~62~~ ~~57~~ 56 bytes **5 bytes thanks to Poke.** **1 byte thanks to trichoplax.** ``` ~~char r(){return(char)(65+(int)Math.sqrt(Math.random()\*676));}~~ ~~char r(){return(char)(65+Math.sqrt(Math.random()\*676));}~~ char r(){return(char)(65+Math.sqrt(Math.random())*26);} ``` [Ideone it!](http://ideone.com/V00YIi) ### Frequency diagram (1e6 runs, scaling factor 1/1000) ``` 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: *************************************************************************** ``` [Answer] ## Perl, 24 bytes *-4 bytes thanks to @Martin Ender* *-1 byte thanks to @Dom Hastings* ``` say+(A..Z)[rand rand 26] ``` Needs `-M5.010` or `-E` to run : ``` perl -E 'say+(A..Z)[rand rand 26]' ``` Running the following code will show the occurrence of each letter : ``` perl -MData::Printer -E '$h{(A..Z)[rand rand 26]}++ for 1 .. 1_000_000;$h{$_} = int($h{$_} / 100) / 100 for A .. Z;p %h;' A 16.4 B 11.02 C 8.99 ... Z 0.07 ``` **How it works** : I guess the code is pretty explicit, but still : it chooses a random number between `0` and `rand 26`. So there is a much higher probability that numbers close to `0` (letter `A`) are choosen. [Answer] # PHP, ~~44~~ ~~36~~ ~~29~~ 27 bytes [Crossed out 44 is still regular 44 ;(](http://meta.codegolf.stackexchange.com/a/7427/53880) *Thanks to insertusernamehere, Petah, and Crypto for all the help* ``` <?=chr(65+rand(0,675)**.5); ``` It chooses a random number between 0 and 675 (=262-1), takes its square root, and floors it (the `chr` function converts its argument to an integer). Since the squares have different intervals between them, the probability of each number being chosen is distinct. Every n is chosen with probability (2n+1)/676. Adding 65 to this number gives you a random character from `A` to `Z`. [Ideone of the code running 1,000,000 times](http://ideone.com/h19wuf) [Answer] # R, ~~40~~ 27 bytes ``` LETTERS[sample(26,1,,1:26)] ``` This will take `1` number from `26` numbers generated with growing probability toward `Z`, without replacing, and display a letter the index of which is this number, from the list of uppercase letters `LETTERS`. The arguments of the `sample` function are : ``` sample( 26, #How many numbers to generate 1, #How many numbers to sample , #Replacing ? Here, no by default 1:26, #Weight of probabilities ) ``` [Answer] ## [><>](http://esolangs.org/wiki/Fish), 14 bytes ``` lx ;>dd+%'A'+o ``` ><> is a toroidal 2D language, and the distinct probabilities part just naturally happens due to the language's only source of randomness. [Try it online!](http://fish.tryitonline.net/#code=bHgKOz5kZCslJ0EnK28&input=) The relevant commands are: ``` [Row 1] l Push length of stack x Change the instruction pointer direction to one of up/down/left/right This gives a 50/50 chance of continuing on the first row (moving left/right) or going to the next row (moving up/down, wrapping if up) [Row 2] > Change IP direction to right dd+% Take top of stack mod 26 (dd+ = 13+13 = 26) 'A'+ Add 65 o Output as character ; Halt ``` Thus the output probabilities are: ``` A: 1/2^1 + 1/2^27 + 1/2^53 + ... = 33554432 / 67108863 ~ 0.50000000745 B: 1/2^2 + 1/2^28 + 1/2^54 + ... = half of chance for A C: 1/2^3 + 1/2^29 + 1/2^55 + ... = half of chance for B ... Z: 1/2^26 + 1/2^52 + 1/2^78 + ... = half of chance for Y ``` [Answer] # R, 23 bytes ``` sample(LETTERS,1,,1:26) ``` Just 'samples' a letter from a builtin. the `1:26` is a vector of weights giving each letter a different probability. [Answer] # Python 2, ~~58~~ 57 bytes ``` from random import* print chr(int(65+(random()*676)**.5)) ``` Explanation: this generates a random floating point number in the interval `[0, 676)`, takes the square root and then floors it. Then it adds 65 (the ascii value of "A"), converts it to a char, and prints it. This gives each number from 0 to 25 a distinct probability. To understand why, think about it like this. How many numbers, ignoring non-integers, when you take the square root and floor give 0? Only one number will (zero). This means that zero has a probability of `1/676`. How many numbers will produce 1? 3 will, 1, 2, and 3. This means one has a probability of `3/676`. A two can be produced with a 4, 5, 6, 7, or 8, giving it probability 5, a three has probability 7, etc. and since the difference between consecutive squares increases steadily by two, this pattern continues for every number up to 25 (Z). *1 byte saved thanks to leaky nun!* [Answer] # [Befunge](https://github.com/catseye/Befunge-93), 40 bytes Revisiting this 7 years later, I realized I I could just add the whole alphabet in one string and pop off a random amount of letters before printing. Suddenly it beats Python! ``` "ZYXWVUTSRQPONMLKJIHGFEDCBA"> #$?:#@ #,_ ``` Probabilities are the same as before; Starting from A, there is a *1/4* chance of printing the top of the stack, *2/4* to try again, and *1/4* to pop off one letter and repeat. If it somehow manages to move past Z it just starts over again with A. Trying a few times, the highest I got was an E. [Try it online!](https://tio.run/##S0pNK81LT/3/XykqMiI8LDQkOCgwwN/P18fby9PD3c3VxdnJUclOQVnF3krZQUFZJ/7/fwA "Befunge-93 – Try It Online") # Befunge, ~~168~~ 164 bytes More compact than the first one, with a little different probabilities: The first `?` have a *1/4* chance of printing an A on "first try", *2/4* chance to come back to the same `?`, and *1/4* to move to the next. The rest of the `?`s each have *1/4* chance of printing the letter underneath them, *1/4* to try again, *1/4* moving to the next letter, *1/4* moving to the previous. Again, the probability of printing an A is *a lot* higher than printing a Z. ``` ??????????????????????????> """""""""""""""""""""""""" ABCDEFGHIJKLMNOPQRSTUVWXYZ """""""""""""""""""""""""" >>>>>>>>>>>>>>>>>>>>>>>>>>,@ ########################## ``` # Befunge, 186 bytes Obviously not gonna win with this, but I think it's an interesting answer nonetheless :) `v` and `>` steers the cursor respectively downwards and to the right. The `?` operator sends the cursor off in one of four directions randomly. The first `?` is "blocked" by `v` and `>` in two directions, so it only has two way to go: Either to print the A, or down to the next `?`. So from the first `?` alone there is a 50% chance of printing an A. The next `?` has a *1/3* chance of printing a B, *1/3* of going back up, and *1/3* of going further down. Etc etc. It should be quite obvious that the higher letters have a much larger chance of being printed than the lower ones, but I'm not exactly sure what each letter's chances are. **Some help with the exact math would be appreciated :)** At least there's a *1/2 \* 1/3^25* chance that the cursor moves all the way down to the Z on the first try, but I'm uncertain how the chances of the cursor moving up and down affects each letter. `,@` prints and quits. ``` v >?"A"v >?"B"v >?"C"v >?"D"v >?"E"v >?"F"v >?"G"v >?"H"v >?"I"v >?"J"v >?"K"v >?"L"v >?"M"v >?"N"v >?"O"v >?"P"v >?"Q"v >?"R"v >?"S"v >?"T"v >?"U"v >?"V"v >?"W"v >?"X"v >?"Y"v >?"Z">,@ ``` [Answer] ## PowerShell v2+, ~~33~~ 31 bytes ``` [char](65..90|%{,$_*$_}|Random) ``` Takes a range from `65` to `90` (i.e., ASCII `A` to `Z`), pipes it through a loop. Each iteration, we use the comma-operator to create an array of that element times that number. For example, this will make 65 `65`s, 66 `66`s, 67 `67`s, etc. That big array is piped to `Get-Random` which will (uniformly PRNG) select one element. Since there are different quantities of each element, each character has a slightly distinct percentage chance of being picked. We then encapsulate that in parens and cast it as a `char`. That's left on the pipeline and output is implicit. *(Thanks to [@LeakyNun](http://chat.stackexchange.com/transcript/message/31633603#31633603) for golfing a few bytes even before it was posted. :D)* --- ### The probabilities *(slight rounding so I could demonstrate the `P` option of the `-f`ormat operator)* ``` PS C:\Tools\Scripts\golfing> 65..90|%{"$([char]$_): {0:P}"-f($_/2015)} A: 3.23 % B: 3.28 % C: 3.33 % D: 3.37 % E: 3.42 % F: 3.47 % G: 3.52 % H: 3.57 % I: 3.62 % J: 3.67 % K: 3.72 % L: 3.77 % M: 3.82 % N: 3.87 % O: 3.92 % P: 3.97 % Q: 4.02 % R: 4.07 % S: 4.12 % T: 4.17 % U: 4.22 % V: 4.27 % W: 4.32 % X: 4.37 % Y: 4.42 % Z: 4.47 % ``` [Answer] # CJam, ~~21~~ ~~17~~ 12 bytes *Thanks to Martin Ender for saving me 5 bytes!* ### New version ``` '\,:,s_el-mR ``` This forms an array of strings following the pattern `A`, `AB`, `ABC`, and so on. It flattens it and chooses a random character. Since this string contains 26 A's, 25 B's, 24 C's, and so on, each letter has a distinct probability of being chosen. [Try it online!](http://cjam.aditsu.net/#code='%5C%2C%20%20%20%20%20%20%20%20%20%20e%23%20Push%20the%20range%20of%20all%20characters%20up%20to%20'Z'%0A%20%20%20%3A%2C%20%20%20%20%20%20%20%20e%23%20For%20each%20one%2C%20take%20the%20range%20of%20all%20characters%20up%20to%20it%0A%20%20%20%20%20s%20%20%20%20%20%20%20e%23%20Convert%20the%20array%20of%20ranges%20to%20one%20string%0A%20%20%20%20%20%20_el-%20%20%20e%23%20Subtract%20the%20lower%20case%20version%20of%20the%20string%20from%20itself%0A%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20This%20leaves%20only%20capital%20letters%20in%20the%20string%0A%20%20%20%20%20%20%20%20%20%20mR%20e%23%20Take%20a%20random%20character%20from%20it) **Explanation** ``` '\, e# Push the range of all characters up to 'Z' :, e# For each one, take the range of all characters up to it s e# Convert the array of ranges to one string _el- e# Subtract the lower case version of the string from itself e# This leaves only capital letters in the string mR e# Take a random character from it ``` ### Old version ``` 26,:)'[,'A,- .*M*mr0= ``` Gets distinct probabilities by making a string in which each letter appears a number of times equal to its position in the alphabet. ``` 26,:) e# Push 1, 2, ... 26 '[,'A,- e# Push 'A', 'B', ... 'Z' .* e# Vectorize: repeat each letter the corresponding number of times M* e# Join with no separator mr e# Shuffle the string 0= e# Get the first character ``` [Answer] # C, 35 bytes This program assumes `RAND_MAX` is (2^32 / 2) - 1 as it is on gcc by default. Compile with the `-lm` flag to link the `sqrt` function. The output is written to stdout as capital letters without trailing newlines. ``` f(){putchar(sqrt(rand())/1783+65);} ``` Optionally, if `RAND_MAX` is (2^16 / 2) - 1, a shorter 32 byte version can be used: ``` f(){putchar(sqrt(rand())/7+65);} ``` Just for fun, I also made a version that does not use the `sqrt` function or require the math library included (this one must have `RAND_MAX` as (2^32 / 2) - 1), but it ended up being longer even though I thought it was pretty cool: ``` f(){float r=rand()/64+1;putchar((*(int*)&r>>23)-62);} ``` ## Explanation ### [First Program] For the first two using `sqrt`, the function simply maps the range `[0, RAND_MAX)` to `[0, 25]` through division, and then adds 65 (ASCII `A`) to the value to shift it into the ASCII alphabet before outputting it. ### [Second Program] The second program is a bit more complex as it does a similar strategy, but without the `sqrt` operator. Since a floating point's exponent bits are automatically calculated upon assigning an integer, they can effectively be used as a crude way to get the base 2 logarithm of a number. Since we only want the range up to `RAND_MAX` to reach an encoded exponent value of 25, the calculation (2^32 / 2 - 1) / (2 ^ 25) gives us just about 64, which is used during the division of `rand` to map it to this new range. I also added 1 to the value as 0's floating point representation is rather odd and would break this algorithm. Next, the float is type-punned to an integer to allow for bitshifting and other such operations. Since in IEEE 754 floating point numbers the exponent bits are bits 30-23, the number is then shifted right 23 bits, cutting off the mantissa and allowing the raw exponent value to be read as an integer. Do note that the sign bit is also beyond the exponent bits, but since there are never any negatives it does not have to be masked out. Rather than adding 65 to this result like we did before however, floating point exponents are represented as an unsigned 8 bit integer from 0 to 255, where the exponent value of 0 is 127 (Simply subtract 127 to get the actual "signed" exponent value). Since 127 - 65 is 62, we instead simply subtract 62 to both shift it out of this floating point exponent range and into the ASCII alphabet range all in one operation. ## Distribution I'm not math expert so I cannot say for sure the exact formula for these distributions, but I can (and did) test every value on the range `[0, RAND_MAX)` to show that the distance between where one letter's range ends and the other begins are never the same. (Note these tests assume the (2^32 / 2) - 1) random maximum) ### [First Program] ``` Letter - Starting Location A - 0 B - 3179089 C - 12716356 D - 28611801 E - 50865424 F - 79477225 G - 114447204 H - 155775361 I - 203461696 J - 257506209 K - 317908900 L - 384669769 M - 457788816 N - 537266041 O - 623101444 P - 715295025 Q - 813846784 R - 918756721 S - 1030024836 T - 1147651129 U - 1271635600 V - 1401978249 W - 1538679076 X - 1681738081 Y - 1831155264 Z - 1986930625 ``` ### [Second Program] ``` Letter - Starting Location A - 0 B - 64 C - 192 D - 448 E - 960 F - 1984 G - 4032 H - 8128 I - 16320 J - 32704 K - 65472 L - 131008 M - 262080 N - 524224 O - 1048512 P - 2097088 Q - 4194240 R - 8388544 S - 16777152 T - 33554368 U - 67108800 V - 134217664 W - 268435392 X - 536870848 Y - 1073741760 Z - 2147483520 ``` [Answer] ## Python 2, 72 bytes ``` from random import* print choice(''.join(i*chr(i)for i in range(65,91))) ``` Multiplies the character by its ascii value, then picks one character at random from the resulting string. Here are the probabilities for each letter being selected, in percentages: ``` A 3.23 B 3.28 C 3.33 D 3.37 E 3.42 F 3.47 G 3.52 H 3.57 I 3.62 J 3.67 K 3.72 L 3.77 M 3.82 N 3.87 O 3.92 P 3.97 Q 4.02 R 4.07 S 4.12 T 4.17 U 4.22 V 4.27 W 4.32 X 4.37 Y 4.42 Z 4.47 ``` Try it: <https://repl.it/Cm0x> [Answer] ## [Labyrinth](https://github.com/m-ender/labyrinth), 19 bytes ``` __v6%_65+.@ " ) "^2 ``` [Try it online!](http://labyrinth.tryitonline.net/#code=X192NiVfNjUrLkAKIiApCiJeMg&input=) This is a loop which, at each iteration, either a) increments a counter which starts at zero or b) terminates, both with probability 50%. At the end of the loop, the counter is taken modulo 26 and added to 65 to give a letter between `A` and `Z`. This gives a probability for `A` just a bit over 50%, `B` just a bit over 25% and so on up to `Z` just a bit over 1/226. In theory, there is the possibility of this running forever, but this event has probability zero as required by the challenge (in practice that's probably not possible anyway because the PRNG will return both possible results at some point over its period). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØAxJX ``` (Equal score, but a *different method*, to [an existing Jelly solution](https://codegolf.stackexchange.com/a/89659/53748) by Dennis.) The probability of yielding each letter is it's 1-based index in the alphabet divided by 351 - the 26th triangular number: * P(`A`) = 1 / 351, P(`B`) = 2 / 351, ..., P(`Z`) = 26 / 351. Since 1+2+...+26 = 351, P(letter) = 1. Implementation: ``` ØAxJX - no input taken ØA - yield the alphabet: 'ABC...Z' J - yield [1,...,len(Left)]: [1,2,3,...26] x - Left times Right: 'abbccc...zzzzzzzzzzzzzzzzzzzzzzzzzz' X - choose random element from Left ``` Test it on [**TryItOnline**](http://jelly.tryitonline.net/#code=w5hBeEpY&input=) or get the [distribution of 100K runs](http://jelly.tryitonline.net/#code=w5hBeEpYCsKiCsi3NcOH4oKsxIvDkOKCrMOYQcO3yLc1w5hBxbxH&input=) (code credit to Dennis) [Answer] # q, 38 bytes Not particularly short but... ``` .Q.A(reverse 0.9 xexp til 26)binr 1?1f ``` The discrete cumulative distribution function is the sequence `0.9 ^ 26, 0.9 ^ 25, ..., 0.9 ^ 0` And we merely sample from the distribution. [Answer] # JavaScript (ES6), 45 bytes ``` _=>(n=Math.random(),10+n*n*26|0).toString(36) ``` Achieves non-uniform distribution by squaring the random value. `Math.random()` returns a float of the range `[0,1)` so the result of squaring this tends towards `0` (or `a`). ## Test ``` var solution = _=>(n=Math.random(),10+n*n*26|0).toString(36) var frequency = Array(26).fill(0); for (var i = 0, tests = 1000000; i < tests; i++) frequency[solution().charCodeAt(0) - 97]++; result.textContent = frequency .map((n, i) => [ String.fromCharCode(97 + i), n ]) .sort((a, b) => b[1] - a[1]) .map((x) => `${x[0]}: ${(x[1] / tests * 100).toFixed(2)}%`) .join('\n'); ``` ``` <pre id="result"></pre> ``` [Answer] # Oracle SQL 11.2, 212 bytes Using character position in the alphabet as probability ``` SELECT c FROM(SELECT dbms_random.value(0,351)v FROM DUAL),(SELECT c,e,LAG(e,1,0)OVER(ORDER BY c)s FROM(SELECT CHR(LEVEL+64)c,SUM(LEVEL)OVER(ORDER BY LEVEL)e FROM DUAL CONNECT BY LEVEL<27))WHERE v BETWEEN s AND e; ``` Un-golfed ``` SELECT c FROM (SELECT dbms_random.value(0,351)v FROM DUAL), -- random value ( SELECT c,e,LAG(e,1,0)OVER(ORDER BY c)s -- Mapping each character to its interval FROM ( -- Each char has it's position in the alphabet as probability SELECT CHR(LEVEL+64)c,SUM(LEVEL)OVER(ORDER BY LEVEL)e FROM DUAL CONNECT BY LEVEL<27 ) ) WHERE v BETWEEN s AND e -- match the random value to an interval ``` [Answer] # TI-Basic, 39 bytes ``` sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",int(26^rand),1 ``` `rand` generates a uniform value in (0,1]. This gives 26^rand a different probability to equal the integers from 1 to 26. **Older version, 45 bytes** ``` sub("ABCDEFGHIJKLMNOPQRSTUVWXYZAAA",1+int(4abs(invNorm(rand))),1 ``` Limited precision of the TI-Basic integers limits normal distributions to generating numbers within µ±7.02σ (see [`randNorm(`](http://tibasicdev.wikidot.com/randnorm)). So we get the absolute value of a random number with µ 0 and σ 1, multiplying by four to increase the practical range mentioned before to µ±28.08σ. Then, we floor the value and add 1, since `sub(` is 1-indexed, giving us a range from 1-29 with different probabilities of each. [Answer] # PHP, 92 84 bytes ``` for($i=65,$x=0;$i<91;$a.=str_repeat(chr($i++),$x))$x++;echo substr($a,rand(0,$x),1); ``` Builds a string of all letters, repeated the number of times through the loop we are, and then picks a letter from that string at random. Letters later in the alphabet have a higher probability as a result Thanks to insertusernamehere for shaving off bytes ## outcome probabililities (ordered by %) > > A => 0.29% > > B => 0.62% > > C => 0.82% > > > > [Answer] # Julia, 24 bytes ``` !c='a':c|>rand;c()=!!'z' ``` [Try it online!](http://julia.tryitonline.net/#code=IWM9J2EnOmN8PnJhbmQ7YygpPSEhJ3onCgpyZXN1bHRzID0gW2MoKSBmb3IgXyBpbiAxOjFlNl0KCmZvciBsZXR0ZXIgaW4gJ2EnOid6JwogICAgQHByaW50ZigiJWMgJS42ZlxuIiwgbGV0dGVyLCBzdW0ocmVzdWx0cyAuPT0gbGV0dGVyKSAvIDFlNikKZW5k&input=) ### How it works The function `c()` simply calls `!` twice, with initial argument **z**. In turn `!c` creates a character range from **a** to its argument `c` and pseudo-randomly selects a character from this range. The distribution of probabilities is as follows. Let **x1, …, x26** denote the letters of the alphabet in their natural order. Select a letter **Y** among these, uniformly at random, then select a letter **X** from **L1, … Y**, also uniformly at random. Fix **n** and **k** in **1, …, 26**. If **n ≤ k**, then **p(X = xn | Y = xk) = 1/k**. On the other hand, if **n > k**, then **p(X = xn | Y = xk) = 0**. Therefore, **p(X = xn) = Σ p(Y = xk) \* p(X = xn | Y = xk) = 1/26 · (1/n + ⋯ + 1/26)**, giving the following probability distribution. ``` p(X = a) = 103187226801/696049754400 ≈ 0.148247 p(X = b) = 76416082401/696049754400 ≈ 0.109785 p(X = c) = 63030510201/696049754400 ≈ 0.090555 p(X = d) = 54106795401/696049754400 ≈ 0.077734 p(X = e) = 47414009301/696049754400 ≈ 0.068119 p(X = f) = 42059780421/696049754400 ≈ 0.060426 p(X = g) = 37597923021/696049754400 ≈ 0.054016 p(X = h) = 33773473821/696049754400 ≈ 0.048522 p(X = i) = 30427080771/696049754400 ≈ 0.043714 p(X = j) = 27452509171/696049754400 ≈ 0.039440 p(X = k) = 24775394731/696049754400 ≈ 0.035594 p(X = l) = 22341654331/696049754400 ≈ 0.032098 p(X = m) = 20110725631/696049754400 ≈ 0.028893 p(X = n) = 18051406831/696049754400 ≈ 0.025934 p(X = o) = 16139182231/696049754400 ≈ 0.023187 p(X = p) = 14354439271/696049754400 ≈ 0.020623 p(X = q) = 12681242746/696049754400 ≈ 0.018219 p(X = r) = 11106469546/696049754400 ≈ 0.015956 p(X = s) = 9619183746/696049754400 ≈ 0.013820 p(X = t) = 8210176146/696049754400 ≈ 0.011795 p(X = u) = 6871618926/696049754400 ≈ 0.009872 p(X = v) = 5596802526/696049754400 ≈ 0.008041 p(X = w) = 4379932326/696049754400 ≈ 0.006293 p(X = x) = 3215969526/696049754400 ≈ 0.004620 p(X = y) = 2100505176/696049754400 ≈ 0.003018 p(X = z) = 1029659400/696049754400 ≈ 0.001479 ``` [Answer] # J, ~~20~~ 18 bytes ``` ~~({~?@#)u:64+#~1+i.26~~ ({~?@#)u:64+#~i.27 ``` [Online interpreter](http://tryj.tk) Uppercase. Each letter's probability is its 1-based index in the alphabet. [Answer] # zsh, 63 bytes ``` for i in {A..Z};for j in {1..$[#i]};s+=$i;echo $s[RANDOM%$#s+1] ``` it works by creating this string: ``` AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ ``` aka 65 times A, 66 times B, 67 times C... and then it chooses a random character in it [Answer] ## CJam, 11 bytes ``` 4.mrmqC*'A+ ``` or ``` 676.mrmq'A+ ``` [Try it online!](http://cjam.tryitonline.net/#code=Njc2Lm1ybXEnQSs&input=) This solution is similar to Luis's idea and creates a non-uniform distribution by taking the square root of the random variable. [Answer] ## Batch, 116 bytes ``` @set/ar=%random%%%676,s=r/26,r%%=26,s-=(r-s)*(r-s^>^>31) @set a=ABCDEFGHIJKLMNOPQRSTUVWXYZ @call echo %%a:~%s%,1%% ``` Works by picking the larger or smaller (I forget which) of two random variables. [Answer] # Matlab, 22 Will often return early letters, but can theoretically touch them all! Takes one devided by a random number, limits this to 26 and turns it in to a character. ``` ['' 96+min(1/rand,26)] ``` Not very short of course, but perhaps the concept can inspire other answers. ]
[Question] [ What general tips do you have for golfing in Perl? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Perl (e.g. "remove comments" is not an answer). Please post one tip per answer. [Answer] ## TMTOWTDI That's the most important Perl golfing tip you need to know. Whenever you're looking at some too-long sequence of characters you absolutely have to have in order to accomplish your task, ask yourself if there isn't some other way to get the same effect using a different feature. There usually is. Here are just a handful: * `~~` enforces a scalar context and is 4 chars shorter than `scalar`. * `y///c` is one char shorter than `length` when getting the length of `$_`. * Need to iterate over the chars in `$_`? Replace `split//` with `/./gs`. (Or use `/./g` if you also want to skip newlines.) This works with other variables: replace `split//,$x` with `$x=~/./gs`. * Every Perl builtin returns something. `print` returns 1, for example, to indicate successful I/O. If you need to initialize `$_` to a true value, for example, `$_=print$foo` allows you to kill two birds with one stone. * Almost every statement in Perl can be written as an expression, allowing it to be to used in a wider variety of contexts. Multiple statements can be become multiple expressions chained together with commas. Tests can be done with short-circuiting operators `?:` `&&` `||`, and also with `and` and `or`, which do the same thing but with precedence lower than all other operators (including assignment). Loops can be done via `map` or `grep`. Even keywords like `next`, `last` and `return` can be used in an expression context, even though they don't return! Keeping these kinds of transformations in mind give you opportunities to replace code blocks with expressions that can be stuffed into a wider variety of contexts. [Answer] Abuse Perl's special variables! * As noted in a previous answer `$/` and `$"` are initialized by default to `"\n"` and `" "`, respectively. * `$,` and `$\` are both set to `undef` by default, and are 3 chars shorter. * Setting `$\` to a value will cause it to be appended to every `print`. For example: `perl -ple '$\="=".hex.$/'` is a handy hex-to-decimal converter. * If you're not reading files from the command-line, you can use the `-i` command-line switch as an extra channel for inputting a string. Its value will be stored in `$^I`. * `$=` forces whatever is assigned to it to be an integer. Try running `perl -ple '$_=$==$_'` and giving it various inupts. Likewise, `$-` forces its value to be a non-negative integer (i.e. a leading dash is treated as a non-numeric character). * You can use `$.` as a boolean flag that is automatically reset to a true (nonzero) value on every iteration of a `while(<>)` loop. [Answer] # `-n` and unmatched curly brackets It is well known that the command line switch `-n` can be used to execute the script once for every line. `perl --help` says: ``` -n assume "while (<>) { ... }" loop around program ``` What it doesn't say explicitly is that Perl doesn't just assume a loop around the program; it *literally* wraps `while (<>) { ... }` around it. This way, the following commands are equivalent to each other: ``` perl -e 'while(<>){code}morecode' perl -ne 'code;END{morecode}' perl -ne 'code}{morecode' ``` # `-p` and unmatched curly brackets Similarly to the above, the `-p` switch wraps `while (<>) { ... ; print }` around the program. By using unmatched curly brackets, `perl -p 'code}{morecode'` will only print once after executing `code` for all lines of input, followed by `morecode`. Since `$_` is undefined when `morecode;print` is executed, the output record separator `$\` can be abused to print the actual output. For example ``` perl -pe '$\+=$_}{' ``` reads one number per line from STDIN and prints their sum. [Answer] Use `$_` to eliminate scalar references. It is the special variable that is used as a default by most functions, and just leaving out parameters is a shortcut to reference this variable. By changing `$n` to `$_`, you can change `$n=<>;chop$n;print$n` to `$_=<>;chop;print` Here, the `print` function prints the contents of `$_` by default, and `chop` also works on `$_`. [Answer] Use Perl's special variables where-ever you can, eg: * Use `$"` instead of `" "` * Use `$/` instead of `"\n"` They have the added benefit of being a guaranteed one-character long identifier, with help from the lexer. This makes it possible to glue it to the keyword following it, as in: `print$.for@_` The list of all the special variables is available here: [Special Variables](http://perldoc.perl.org/perlvar.html) [Answer] Don't use `qw`. This is waste of two characters that could be used in better way. For example, don't write the following. ``` @i=qw(unique value); ``` Instead use barewords. ``` @i=(unique,value); ``` Or if you cannot use barewords, use `glob` syntax. ``` @i=<unique value>; ``` `glob` syntax can also be used for interesting effects. ``` @i=<item{1,2,3}>; ``` [Answer] Use statement modifiers instead of compound statements. Compound statements tend to require parentheses for the argument and braces for the block, whereas statement modifiers need neither. Compare: * `$a++,$b++while$n--` vs `while($n--){$a++;$b++}` * `chop$,if$c` vs `if($c){chop$,}` Note that the last example ties with `$c&&chop$,`, but starts really shining for most multi-statement operations. Basically anything that loses operator precedence to `&&`. [Answer] Don't `use strict`. (don't quote me on this, PCG.SE context kinda matters) And, more importantly, don't code as if under strict. The usual suspects: * don't `my`-declare variables if you can avoid it. The only variables that really need `my` are those you want lexically scoped. That's barely any of them when golfing, where you don't need scope protection and tend to fully control recursion. * don't quote one-word strings: ([example](https://codegolf.stackexchange.com/a/8746/199)). Do ensure you don't have a function with the same name, though. [Answer] I'm sure some of these have formal names and I'm just not aware of them. * If you have a while loop (or a for loop you can make into a while loop) you can define the "while" after the command: `print $n++ while ($n < 10)` * If you need to read everything from STDIN into a string: `$var = join('',<>)` * As CeilingSpy pointed out, using $/ instead of \n is faster in some situations: `print ('X'*10) . "\n";` is longer than `print ('X'*10) . $/;` * Perl's `say` function is shorter than `print`, but you'll have to run the code with `-E` instead of `-e` * Use ranges like `a..z` or even `aa..zz`. If needed as a string, use `join`. * Incrementing strings: `$z = 'z'; print ++$z;` will display `aa` That's all I can think of right now. I may add some more later. [Answer] # Use non-word characters as variable names Using `$%` instead of `$a` can allow you to place the variable name right next to an `if`, `for` or `while` construct as in: `@r=(1,2,3,4,5);$%=4;` `print$_*$%for@r` Many can be used, but check the [docs](http://perldoc.perl.org/perlvar.html) and [@BreadBox's answer](https://codegolf.stackexchange.com/questions/5105/tips-for-golfing-in-perl#answer-5957) for which ones have magic effects! --- # Use map when you can't use statement modifiers If you can't use statement modfiers as per [@JB's answer](https://codegolf.stackexchange.com/questions/5105/tips-for-golfing-in-perl#answer-5130), map might save a byte: `for(@c){}` vs. `map{}@c;` and is useful if you want to do nested iterations as you can put postfix `for` loops inside the `map`. --- # Use all the magic Regular Expression variables Perl has magic variables for 'text before match' and 'text after match' so it is possible to split to groups of two with potentially fewer characters: ``` ($x,$y)=split/,/,$_; ($x,$y)=/(.+),(.+)/; /,/; # $x=$`, $y=$' # Note: you will need to save the variables if you'll be using more regex matches! ``` This might also work well as a replacement for `substr`: ``` $s=substr$_,1; /./;# $s=$' $s=substr$_,4; /.{4}/;# $s=$' ``` If you need the contents of the match, `$&` can be used, eg: ``` # assume input like '10 PRINT "Hello, World!"' ($n,$c,$x)=split/ /,$_; / .+ /; # $n=$`, $c=$&, $x=$' ``` --- # Replace subs with long names with a shorter name If you call say `print` four or more times in your code (this obviously varies with the length of the routine you're calling), replace it with a shorter sub name: ``` sub p{print@_}p;p;p;p ``` vs. ``` print;print;print;print ``` --- # Replace conditional incrementors/decrementors If you have code like: ``` $i--if$i>0 ``` you can use: ``` $i-=$i>0 ``` instead to save some bytes. --- # Convert to integer If you aren't assigning to a variable and so can't use [breadbox's](https://codegolf.stackexchange.com/q/5957) tip, you can use the expression `0|`: ``` rand 25 # random float eg. 19.3560355885212 int rand 25 # random int 0|rand 25 # random int rand 25|0 # random int ~~rand 25 # random int ``` It's worth noting however than you don't need to use an integer to access an array index: ``` @letters = A..Z; $letters[rand 26]; # random letter ``` [Answer] `redo` adds loop behavior to a block without `for` or `while`. `{redo}` is an infinite loop. [Answer] Don't parenthesize function calls. Perl lets you call a known (core or predeclared) function using the `NAME LIST` syntax. This lets you drop the `&` sigil (if you were still using it) as well as the parentheses. For example: `$v=join'',<>` [Full documentation](http://perldoc.perl.org/perlsub.html) [Answer] You can run multiple different statements within nested ternary logic. Suppose you have a big `if`-`elsif` statement. This could be any logic and any number of statements. ``` if( $_ < 1 ) { $a=1; $b=2; $c=3; say $a.$b.$c; } elsif($_ < 2 ) { $a=3; $b=2; $c=1; say $a.$b.$c; } elsif( $_ < 3) { $a=2; $b=2; $c=2; say $a.$b.$c; } ``` You can use `(cmd1, cmd2, cmd3)` inside the ternary operator to run all of the commands. ``` $_ < 1 ? ($a=1,$b=2,$c=3,say$a.$b.$c): $_ < 2 ? ($a=3,$b=2,$c=1,say$a.$b.$c): $_ < 3 ? ($a=2,$b=2,$c=2,say$a.$b.$c): 0; #put the else here if we have one ``` Here's a dummy example: ``` perl -nE'$_<1?($a=1,$b=2,$c=3,say$a.$b.$c):$_<2?($a=3,$b=2,$c=1,say$a.$b.$c):$_<3?($a=2,$b=2,$c=2,say$a.$b.$c):0;' <(echo 2) ``` [Answer] # If you need an alternating boolean Instead of doing something like `$-++%2`, use `$|--`. [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRKVGVzctv0jBUE/P0OD//3/5BSWZ@XnF/3VzAA "Perl 5 – Try It Online") [Answer] Try to use the value of an assignment expression, like so: ``` # 14 characters $n=pop;$o=$n&1 # 13 characters, saves 1 $o=($n=pop)&1 ``` This works because `$n` is 2 characters in Perl. You may change `$n` to `()` at no cost, and save 1 semicolon by moving the assignment into the parentheses. [Answer] # Use the free `;` from `-n`/`-p` Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for letting me know this tip wasn't in the list! Further to [@Dennis' tip](https://codegolf.stackexchange.com/a/32884/9365) of using the implicit code added via `-n`/`-p`, a `;` is inserted as well and using this to your advantage, you can sometimes save a byte: Using `$;` as the final variable: `$a=$_*say$--1?"...":$_-1if$-=$_-1-$a` vs. [`$;=$_*say$--1?"...":$_-1if$-=$_-1-$`](https://codegolf.stackexchange.com/a/249643/9365) Used with a quote-like operator: `s/(.)(.)/$2$1/` vs. [`s;(.)(.);$2$1`](https://codegolf.stackexchange.com/a/249567/9365) Or used with a list: `pop@a;push@a,/\w+/g;$,="/";/{/&&say@a` vs. [`pop@;;push@;,/\w+/g;$,="/";/{/&&say@`](https://codegolf.stackexchange.com/a/246920/9365) The only stipulation is that it needs to be the last statement. [Answer] # Use `select(undef,undef,undef,$timeout)` instead of `Time::HiRes` (Taken from <https://stackoverflow.com/a/896928/4739548>) Many challenges require you to sleep with greater precision than integers. `select()`'s timeout argument can do just that. ``` select($u,$u,$u,0.1) ``` is much more efficient than: ``` import Time::HiRes qw(sleep);sleep(0.1) ``` The former is only 20 bytes, whereas the latter takes up 39. However, the former requires you aren't using `$u` and have never defined it. If you're going to use it a lot importing `Time::HiRes` pays off, but if you only need it once, using `select($u,$u,$u,0.1)` saves 19 bytes, which is definitely an improvement in most cases. [Answer] ## Use expression regexes. Decent illustration of this is the following code shaping the input into sine wave: ``` s/./print" "x(sin($i+=.5)*5+5).$&/eg; ``` As you can see, it's a pretty compact way of iterating over characters in standard input. You could use other regex to change the way how things are matched. [Answer] # Use globs like string literals Occasionally (often when dealing with [quine](/questions/tagged/quine "show questions tagged 'quine'") or [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'") challenges) you benefit greatly from the ability to nest string literals. Normally, you'd do this with `q(…)`. However, depending on what characters you need inside the string, you may be able to save a byte and use `<…>`, the glob operator. (Note that what's inside the angle brackets can't look like a filehandle, and can't look like it's meant to be expanded into a list of filenames, which means that quite a lot of characters won't work correctly.) [Answer] # Useful escape sequences See [perlrebackslash](https://perldoc.perl.org/perlrebackslash.html), but you can potentially save a lot of bytes using these effectively. In matches: ``` [A-Za-z] \pl [^A-Za-z] \Pl (?<=\w) \B ``` In replacements (or double quoted strings): ``` \utext Text (e.g s/ (.)/uc$1/e vs. s/ (.)/\u$1/) \Utext TEXT \lTEXT tEXT \LTEXT text ``` [Answer] # Don't reassign `$_` in nested `for`/`map`s If you aren't using `m//` or `s///` in the body of the loop, you can make the most of `$'` in a nested loop by performing an empty match (`//`) and using `$'` instead of assigning `$_` to another variable: ``` $i=$_,say map{qw(0 * +)[max(abs,abs$i)%3]}@;for @;=- --$_..$_ ``` vs. ``` //,say map{qw(0 * +)[max(abs,abs$')%3]}@;for@;=- --$_..$_ ``` [Answer] # Use `sub` signatures If you're submitting a function, using `-Mfeature+signatures` might save you 4 bytes vs. using `@_`: ``` sub{($a,$b)=@_;...} sub($a,$b){...} ``` [Answer] # Use hash keys for random ordering. If a set of items needs to be in a random order, or you need a (pseudo)random subset of items, storing them as hash keys will allow them to be ordered randomly without a call to `rand`. The order will remain consistent within a program run as long as no insertions or deletions are made to the hash. # Hash keys can be defined quickly If the information to be stored/randomized is already in an array, the hash can quickly be created with: ``` @hash{@array}++; ``` The values of the hash are not particularly useful here, but then the array elements can be retrieved in a random order with: ``` @random_ordered_array = keys %hash; ``` [Answer] # Shorten your print statements Unless the challenge specifies otherwise, you don't need trailing newlines. Our 'challenge' says 'output a random number from 0 to 9 to STDOUT'. We can take this code (28 bytes): ``` $s=int(rand(10));print"$s\n" ``` And shorten it to this (25 bytes): ``` $s=int(rand(10));print $s ``` by simply printing the variable. This last one only applies to this challenge specifically (19 bytes): ``` print int(rand(10)) ``` but that only works when you don't have to do anything to the variable in between assignment and printing. [Answer] # If you need a variable that is falsy on first call and truthy thereafter Instead of something like `!!$x++`, use `$|++`. [Try it online!](https://tio.run/##K0gtyjH9/7@gKDOvRKVGWzstv0jBUE/P0OD//3/5BSWZ@XnF/3VzAA "Perl 5 – Try It Online") [Answer] # Use `s///` to set `$_` instead of `$_="..."` If you ever need to set an empty `$_` to, or add a prefix of, a value that would otherwise require quoting, using `s//<value to set>/` can save a byte: ``` $_="A'B"; # vs: s//A'B/; ``` [Answer] Chain transliterations and substitutions with the `/r` modifier instead of assigning to `$_` first, and directly use the result, rather than using `$_` (possibly implicitly) in a separate statement. For example, if your code does: ``` $_="complex_string";s/pat/repl/;print # Or when $_ is in use, the even more verbose $a="complex_string";$a=~/pat/repl/;print$a ``` you can shave two characters, and free up `$_` for other uses, with: ``` print"complex_string"=~s/pat/repl/r ``` [Answer] # Arrays become strings become numbers When needing to do math involving the first element of an array, `"@array"` will evaluate to the same value as `$array[0]` and is one byte shorter. This assumes that the value of `$"` has not been modified in a way that would join the elements of the array into a single number when concatenated together. This is because `"@array"` expands to `$array[0].$".$array[1].$".$array[2]...`. When Perl parses a scalar in a numeric context, it stops parsing it after encountering a character that is not part of the number, leaving just the first number in the string to be used as the value. [Answer] # Two copies of input The `-F` and `-a` give you a split version of your input in `@F` as well as the complete input in `$_`. Both `@F` and `$_` can be used and modified as needed. ]
[Question] [ I would like to generate (as a return result of a function, or simply as the output of a program) the [ordinal](http://en.wikipedia.org/wiki/Ordinal_number_%28linguistics%29) suffix of a positive integer concatenated to the number. Samples: ``` 1st 2nd 3rd 4th ... 11th 12th 13th ... 20th 21st 22nd 23rd 24th ``` And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over. The input would be the number and the output the ordinal string as shown above. What is the smallest algorithm for this? [Answer] # Python 2, 49 bytes ``` lambda n:`n`+'tsnrhtdd'[n%5*(n%100^15>4>n%10)::4] ``` An anonymous function. A [full program](http://golf.shinh.org/reveal.rb?1st%202nd%203rd%204th/xsot_1456205408&py) would be counted at 55 bytes. `'tsnrhtdd'[i::4]` encodes the suffixes `th st nd rd` for values of `i` from 0 to 3. Given this, all we need is a way to map the values of `n` to the index of the corresponding suffix, `i`. A straightforward expression that works is `(n%10)*(n%10<4 and not 10<n%100<14)`. We can easily shorten this by dropping the first set of parentheses and observing that `n%5` gives the same results as `n%10` for the values of `n` with the special suffixes. With a bit of trial and error, one may also shorten `not 10<n%100<14` to `n%100^15>4`, which can be chained with the other conditional to save even more bytes. [Answer] ## Perl, 37 + 1 characters ``` s/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg ``` This is a regexp substitution that appends the appropriate ordinal suffix to any numbers in `$_` that are not already followed by a letter. To apply it to file input, use the `p` command line switch, like this: ``` perl -pe 's/1?\d\b/$&.((0,st,nd,rd)[$&]||th)/eg' ``` This is a complete Perl program that reads input from stdin and writes the processed output to stdout. The actual code is 37 chars long, but the `p` switch [counts as one extra character](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions). ### Sample input: ``` This is the 1 line of the sample input... ...and this is the 2. 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 101 102 103 104 105 106 107 108 109 110 ``` ### Output: ``` This is the 1st line of the sample input... ...and this is the 2nd. 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 101st 102nd 103rd 104th 105th 106th 107th 108th 109th 110th ``` Numbers already followed by letters will be ignored, so feeding the output again through the filter won't change it. Spaces, commas and periods between numbers are not treated specially, so they're assumed to separate numbers like any other punctuation. Thus, e.g. `3.14159` becomes `3rd.14159th`. ### How does it work? * First, this is a global regexp replacement (`s///g`). The regexp being matched is `1?\d\b`, where `\d` matches any digit and `\b` is a zero-width assertion matching the boundary between an alphanumeric and a non-alphanumeric character. Thus, `1?\d\b` matches the last digit of any number, plus the previous digit if it happens to be `1`. * In the substitution, which is evaluated as Perl code due to the `/e` switch, we take the matched string segment (`$&`) and append (`.`) to it the suffix obtained by using `$&` itself as an integer index to the list `(0,st,nd,rd)`; if this suffix is zero or undefined (i.e. when `$&` is zero or greater than three), the `||` operator replaces it with `th`. --- **Edit:** If the input is restricted to a single integer, then this 35 character solution will suffice: ``` s/1?\d$/$&.((0,st,nd,rd)[$&]||th)/e ``` [Answer] ## Python, 68 characters ``` i=input() k=i%10 print"%d%s"%(i,"tsnrhtdd"[(i/10%10!=1)*(k<4)*k::4]) ``` [Answer] # Mathematica ~~39~~ 45 bytes Note: In recent versions of Mathematica, asking for the `nth` part of `p`, where `p` is undefined, generates an error message, but returns the correct answer anyway. I've added `Quiet` to prevent the error message from printing. ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]]& ``` **Usage** ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &[31] ``` > > 31st > > > ``` Quiet@StringSplit[SpokenString[p[[#]]]][[2]] &/@Range[21] ``` > > {"1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", > "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", > "18th", "19th", "20th", "21st"} > > > --- **How it works** `SpokenString` writes out an any valid Mathematica expression as it might be spoken. Below are two examples from the documentation for [SpokenString](http://reference.wolfram.com/mathematica/ref/SpokenString.html), ``` SpokenString[Sqrt[x/(y + z)]] ``` > > "square root of the quantity x over the quantity y plus z" \*) > > > ``` SpokenString[Graphics3D[Sphere[{{0, 0, 0}, {1, 1, 1}}]], "DetailedGraphics" -> True] ``` > > "a three-dimensional graphic consisting of unit spheres centered at 0, 0, 0 and 1, 1, 1" > > > --- Now, for the example at hand, ``` Quiet@SpokenString[p[[#]]] &[31] ``` > > "the 31st element of p" > > > Let's represent the above string as a list of words: ``` StringSplit[%] ``` > > {"the", "31st", "element", "of", "p"} > > > and take the second element... ``` %[[2]] ``` > > 31st > > > [Answer] # Javascript (ES6) ~~50~~ 44 Bytes ``` a=>a+=[,"st","nd","rd"][a.match`1?.$`]||"th" ``` ### Notes * takes imput as a string * Removed 6 bytes, thanks @user81655 [Answer] ## Ruby, 60 It's not as good as the Perl entry, but I figured I'd work on my Ruby skills. ``` def o(n)n.to_s+%w{th st nd rd}[n/10%10==1||n%10>3?0:n%10]end ``` Function takes one integer argument, `n`, and returns a string as the ordinal form. Works according to the following logic: If the tens digit is a 1 or the ones digit is greater than 3 use the suffix 'th'; otherwise find the suffix from the array ['th', 'st', 'nd', 'rd'] using the final digit as the index. [Answer] ## Javascript, ~~68~~ 71 ``` function o(n){return n+([,'st','nd','rd'][~~(n/10%10)-1?n%10:0]||'th')} ``` Joint effort with ItsCosmo. EDIT: Wasn't working properly with numbers > 100 [Answer] # JavaScript, 64 characters (ES3) or 47 characters (ES6) ### ES3 (64 characters): `function(n){return n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'}` ### ES6 (47 characters): `n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'` ### Explanation The expression `n % 100 >> 3 ^ 1` evaluates to 0 for any positive `n` ending with digits `08`–`15`. Thus, for any `n mod 100` ending in `11`, `12`, or `13`, the array lookup returns `undefined`, leading to a suffix of `th`. For any positive `n` ending in other digits than `08`–`15`, the expression `n % 100 >> 3 ^ 1` evaluates to a positive integer, invoking the expression `n % 10` for array lookup, returning `st`,`nd`, or `rd` for `n` which ends with `1`, `2`, or `3`. Otherwise, `th`. [Answer] ## Haskell, ~~95~~ 100 chars ``` h=foldr g"th".show g '1'"th"="1st" g '2'"th"="2nd" g '3'"th"="3rd" g '1'[x,_,_]='1':x:"th" g a s=a:s ``` Testing: ``` *Main> map h [1..40] ["1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13t h","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th", "25th","26th","27th","28th","29th","30th","31st","32nd","33rd","34th","35th","36 th","37th","38th","39th","40th"] ``` Must be loaded with -XNoMonomorphismRestriction. [Answer] # J - ~~44~~ 41 char Nothing in J? This is an outrage! ``` (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) ``` Explained (note that `1` is boolean true in J and `0` is false): * `100&|` - First, reduce the input modulo 100. * `10(|*|~:-~)` - In this subexpression, `|` is the input mod 10 and `-~` is the input (mod 100) minus 10. You don't get many trains as clean as this one in J, so it's a treat to see here! + `~:` is not-equals, so `|~:-~` is false if the tens digit is 1 and true otherwise. + `*` is just multiplication, so we're taking the input mod 10 and multiplying by a boolean, which will zero it out if false. The result of this is "input mod 10, except 0 on the tens". * `4|4<.` - Min (`<.`) the above with 4, to clamp down larger values, and then reduce modulo 4 so that they all go to zero. * `th`st`nd`rd{::~` - Use that as an index into the list of suiffixes. Numbers ending in X1 or X2 or X3, but not in 1X, will find their suffix, and everything else will take the 0th suffix `th`. * `":,` - Finally, take the original input, convert it to a string (`":`), and append the suffix. Usage is obvious, though as-is the verb can only take one ordinal, not a list. ``` (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 112 NB. single use 112th (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|) 1 2 3 4 5 NB. doing it wrong |length error | (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)1 2 3 4 5 NB. i.5 10 makes a 5x10 grid of increasing integers NB. &.> to operate on each integer separately, and box the result after (":,th`st`nd`rd{::~4|4<.10(|*|~:-~)100&|)&.> i.5 10 NB. all better +----+----+----+----+----+----+----+----+----+----+ |0th |1st |2nd |3rd |4th |5th |6th |7th |8th |9th | +----+----+----+----+----+----+----+----+----+----+ |10th|11th|12th|13th|14th|15th|16th|17th|18th|19th| +----+----+----+----+----+----+----+----+----+----+ |20th|21st|22nd|23rd|24th|25th|26th|27th|28th|29th| +----+----+----+----+----+----+----+----+----+----+ |30th|31st|32nd|33rd|34th|35th|36th|37th|38th|39th| +----+----+----+----+----+----+----+----+----+----+ |40th|41st|42nd|43rd|44th|45th|46th|47th|48th|49th| +----+----+----+----+----+----+----+----+----+----+ ``` Alternative 41 char solution showing off a couple logical variants: ``` (":;@;st`nd`rd`th{~3<.10(|+3*|=-~)100|<:) ``` Previously I had an overlong explanation of this 44 char hunk of junk. `10 10#:` takes the last two decimal digits and `/@` puts logic between them. ``` (":,th`st`nd`rd{::~10 10(]*[(~:*])4>])/@#:]) ``` [Answer] ## Golfscript, 34 characters ``` ~.10/10%1=!1$10%*.4<*'thstndrd'2/= ``` [Answer] # [R](https://www.r-project.org/), ~~79~~ 76 bytes Since there is no R solution yet... no tricks here, basic vector indexing, golfed down 3 chars thanks to Giuseppe. Previously tried index: `[1+(x%%10)-(x%%100==11)]` and `[1+(x%%10)*(x%%100!=11)]`. ``` function(x)paste0(x,c("th","st","nd","rd",rep("th",6))[1+x%%10*!x%%100==11]) ``` [Try it online!](https://tio.run/##K/qfbqP7P600L7kkMz9Po0KzILG4JNVAo0InWUOpJENJR6m4BEjkpQCJIiBRlFoAETfT1Iw21K5QVTU00FIEUwa2toaGsZr/ixMLCnIqNQytDA0NddI1uf4DAA "R – Try It Online") With `substr`, 79 bytes: ``` function(x,y=1+2*min(x%%10-(x%%100==11),4))paste0(x,substr("thstndrdth",y,y+1)) ``` [Try it online!](https://tio.run/##JcrLCoMwEEbhvY8hCJk6Qn7pqpiHSb1Dm4bMCM3TR8HV@RYnlXXoynKEUfdfMH/ODm3/@O6Xmwa2u2OdA4ifRNGLzvYa5XiLJlPrJhqmNOlWc@bcgqiIj/GTDV4AeKWqnA "R – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~38~~ 36 bytes Thanks to ngn for fixing a bug while maintaining byte count. Anonymous tacit prefix function. Requires `⎕IO` (**I**ndex **O**rigin) set to `0`, which is default on many systems. Even works for 0! ``` ⍕,{2↑'thstndrd'↓⍨2×⊃⍵⌽∊1 0 8\⊂10↑⍳4} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/9OA5KPeqTrVRo/aJqqXZBSX5KUUpag/apv8qHeF0eHpj7qaH/VufdSz91FHl6GCgYJFzKOuJkMDoOJHvZtNav//T1Mw4EpTMARiIwUFIGkMJk2ApLqenp46SM4QLGQIkTc0RpIyMgCLGYG1G4EIYxBhAgA "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda; `⍵` is argument:  `⍳4` first four **ɩ**ndices; `[0,1,2,3]`  `10↑` take first ten elements from that, padding with zeros: `[0,1,2,3,0,0,0,0,0,0]`  `⊂` enclose to treat as single element; `[[0,1,2,3,0,0,0,0,0,0]]`  `1 0 8\` expand to one copy, a prototypical copy (all-zero), eight copies;   `[[0,1,2,3,0,0,0,0,0,0],`    `[0,0,0,0,0,0,0,0,0,0],`    `[0,1,2,3,0,0,0,0,0,0],`    `[0,1,2,3,0,0,0,0,0,0],`    ⋮ (5 more)    `[0,1,2,3,0,0,0,0,0,0]]`  `∊` **ϵ**nlist (flatten);   `[0,1,2,3,0,0,0,0,0,0,`    `0,0,0,0,0,0,0,0,0,0,`    `0,1,2,3,0,0,0,0,0,0,`    `0,1,2,3,0,0,0,0,0,0,`    ⋮ (50 more)    `0,1,2,3,0,0,0,0,0,0]`  `⍵⌽` cyclically rotate left as many steps as indicated by the argument  `⊃` pick the first number (i.e. the argument-mod-100'th number)  `2×` multiply two by that (gives `0`, `2`, `4`, or `6`)  `'thstndrd'↓⍨`drop that many characters from this string  `2↑` take the first two of the remaining characters `⍕,` concatenate the stringified argument to that [Answer] # Javascript, ~~75~~ 60 With the new arrow notation: ``` o=(s)=>s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th") ``` *Old version, without arrow notation (75 chars):* ``` function o(s){return s+((0|s/10%10)==1?"th":[,"st","nd","rd"][s%10]||"th")} ``` [Answer] Bash (Cardinal to ordinal) **91** Bytes: ``` function c(){ case "$1" in *1[0-9]|*[04-9])"$1"th;;*1)"$1"st;;*2)"$1"nd;;*3)"$1"rd;;esac } ``` [Answer] ## PowerShell, 92 ``` process{"$_$(switch -r($_){"(?<!1)1$"{'st'}"(?<!1)2$"{'nd'}"(?<!1)3$"{'rd'}default{'th'}})"} ``` Works with one number per line of input. Input is given through the pipeline. Making it work for only a single number doesn't reduce the size. [Answer] ## PHP, 151 I know that this program is not comparable to the others. Just felt like giving a solution. ``` <?$s=explode(' ',trim(fgets(STDIN)));foreach($s as$n){echo$n;echo(int)(($n%100)/10)==1?'th':($n%10==1?'st':($n%10==2?'nd':($n%10==3?'rd':'th')))."\n";} ``` [Answer] # K - 44 char It so happens that this is exactly as long as the J, and works in almost the same way. ``` {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} ``` Explained: * `x$:` - First, we convert the operand `x` into a string, and then assign that back to `x`. We will need its string rep again later, so doing it now saves characters. * `.:'` - Convert (`.:`) each (`'`) digit back into a number. * `-2#0,` - Append a 0 to the front of the list of digits (in case of single-digit numbers), and then take the last two. * `{y*(y<4)*~1=x}.` - Use the two digits as arguments `x` and `y` to this inner function, which returns `y` if `y` is less than 4 and `x` is not equal to 1, otherwise 0. * ``th`st`nd`rd@` - Index the list of suffixes by this result. * `x,$` - Convert the suffix from symbol to string, and append it to the original number. Usage: ``` {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:} 3021 "3021st" {x,$`th`st`nd`rd@{y*(y<4)*~1=x}.-2#0,.:'x$:}' 1 2 3 4 11 12 13 14 /for each in list ("1st" "2nd" "3rd" "4th" "11th" "12th" "13th" "14th") ``` [Answer] # PHP, 98 bytes ``` function c($n){$c=$n%100;$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];} ``` The 11-13 bit is killing me here. Works for any integer `$n >= 0`. For any integer `$n`: # PHP, 103 bytes ``` function c($n){$c=abs($n%100);$s=['','st','nd','rd'];echo$c>9&&$c<14||!$s[$c%10]?$n.'th':$n.$s[$c%10];} ``` [Answer] # Javascript ES6, 52 chars ``` n=>n+(!/1.$/.test(--n)&&'snr'[n%=10]+'tdd'[n]||'th') ``` [Answer] # C#, 62 bytes ``` n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd"); ``` Full program and verification: ``` using System; namespace OutputOrdinalNumbers { class Program { static void Main(string[] args) { Func<int,string>f= n=>n+(n/10%10==1||(n%=10)<1||n>3?"th":n<2?"st":n<3?"nd":"rd"); for (int i=1; i<=124; i++) Console.WriteLine(f(i)); } } } ``` [Answer] # Mathematica 29 + 5 = 34 bytes ``` SpokenStringDump`SpeakOrdinal ``` +5 bytes because `Speak` function must be called before using this built-in. **Usage** ``` SpokenStringDump`SpeakOrdinal[1] ``` > > `"1st "` > > > ``` SpokenStringDump`SpeakOrdinal[4707] ``` > > `"4,707th "` > > > [Answer] # Java 7, ~~91~~ 81 bytes ``` String d(int n){return n+(n/10%10==1|(n%=10)<1|n>3?"th":n<2?"st":n<3?"nd":"rd");} ``` Port from [*@adrianmp*'s C# answer](https://codegolf.stackexchange.com/a/94774/52210). Old answer (**91 bytes**): ``` String c(int n){return n+((n%=100)>10&n<14?"th":(n%=10)==1?"st":n==2?"nd":n==3?"rd":"th");} ``` **Ungolfed & test code:** [Try it here.](https://ideone.com/pA66N2) ``` class M{ static String c(int n){ return n + ((n%=100) > 10 & n < 14 ?"th" : (n%=10) == 1 ? "st" : n == 2 ? "nd" : n == 3 ? "rd" :"th"); } static String d(int n){ return n + (n/10%10 == 1 | (n%=10) < 1 | n > 3 ? "th" : n < 2 ? "st" : n < 3 ? "nd" :"rd"); } public static void main(String[] a){ for(int i = 1; i < 201; i++){ System.out.print(c(i) + ", "); } System.out.println(); for(int i = 1; i < 201; i++){ System.out.print(d(i) + ", "); } } } ``` **Output:** ``` 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, 16th, 17th, 18th, 19th, 20th, 21st, 22nd, 23rd, 24th, 25th, 26th, 27th, 28th, 29th, 30th, 31st, 32nd, 33rd, 34th, 35th, 36th, 37th, 38th, 39th, 40th, 41st, 42nd, 43rd, 44th, 45th, 46th, 47th, 48th, 49th, 50th, 51st, 52nd, 53rd, 54th, 55th, 56th, 57th, 58th, 59th, 60th, 61st, 62nd, 63rd, 64th, 65th, 66th, 67th, 68th, 69th, 70th, 71st, 72nd, 73rd, 74th, 75th, 76th, 77th, 78th, 79th, 80th, 81st, 82nd, 83rd, 84th, 85th, 86th, 87th, 88th, 89th, 90th, 91st, 92nd, 93rd, 94th, 95th, 96th, 97th, 98th, 99th, 100th, 101st, 102nd, 103rd, 104th, 105th, 106th, 107th, 108th, 109th, 110th, 111th, 112th, 113th, 114th, 115th, 116th, 117th, 118th, 119th, 120th, 121st, 122nd, 123rd, 124th, 125th, 126th, 127th, 128th, 129th, 130th, 131st, 132nd, 133rd, 134th, 135th, 136th, 137th, 138th, 139th, 140th, 141st, 142nd, 143rd, 144th, 145th, 146th, 147th, 148th, 149th, 150th, 151st, 152nd, 153rd, 154th, 155th, 156th, 157th, 158th, 159th, 160th, 161st, 162nd, 163rd, 164th, 165th, 166th, 167th, 168th, 169th, 170th, 171st, 172nd, 173rd, 174th, 175th, 176th, 177th, 178th, 179th, 180th, 181st, 182nd, 183rd, 184th, 185th, 186th, 187th, 188th, 189th, 190th, 191st, 192nd, 193rd, 194th, 195th, 196th, 197th, 198th, 199th, 200th, ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ∆o2NȯJ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLiiIZvMk7Ir0oiLCIiLCIyMyJd) [Answer] Python 2.7, 137 chars ``` def b(n): for e,o in[[i,'th']for i in['11','12','13']+list('4567890')]+[['2','nd'],['1','st'],['3','rd']]: if n.endswith(e):return n+o ``` `n` should be a string I know I'm beaten by the competition here already, but I thought I'd provide my idea anyways this just basically generates a list of key, value pairs with number (as a string) ending `e` and the ordinal `o`. It attempts to match 'th' first (hence why I didn't use a dictionary), so that it won't accidentally return 'st', for example, when it should be 'th'. This will work for any positive integer [Answer] ### Scala 86 ``` def x(n:Int)=n+{if(n%100/10==1)"th"else(("thstndrd"+"th"*6).sliding(2,2).toSeq(n%10))} ``` Scala 102: ``` def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".take(n+1)%5*2.drop(n%5*2))else n+"th" ``` 102 as well: ``` def x(n:Int)=if((n%100)/10==1)n+"th"else if(n%10<4)n+("thstndrd".sliding(2,2).toSeq(n%10))else n+"th" ``` ungolfed: ``` def x (n: Int) = n + { if (((n % 100) / 10) == 1) "th" else (("thstndrd" + ("th" * 6)).sliding (2, 2).toSeq (n % 10)) } ``` [Answer] # C: 95 characters A ridiculously long solution: ``` n;main(){scanf("%d",&n);printf("%d%s",n,n/10%10-1&&(n=n%10)<4&&n?n>2?"rd":n<2?"st":"nd":"th");} ``` It needs to be mangled more. [Answer] # OCaml I'm pretty new to OCaml, but this is the shortest i could get. ``` let n x = let v = x mod 100 and string_v = string_of_int x in let z = v mod 10 in if v=11 || v=12 || v=13 then string_v^"th" else if v = 1 || z = 1 then string_v^"st" else if v = 2 || z = 2 then string_v^"nd" else if v = 3 || z = 3 then string_v^"rd" else string_v^"th";; ``` I created a function n that takes a number as a parameter and does the work. Its long but thought it'd be great to have a functional example. [Answer] # C - 95 83 characters ``` main(n,k){scanf("%d",&n);k=(n+9)%10;printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th");} ``` Degolfed: ``` main(n,k) { scanf("%d",&n); k=(n+9)%10; // xx1->0, xx2->1, xx3->2 printf("%d%s\n",n,k<3?"st\0nd\0rd"+3*k:"th"); } ``` We could do `k=(n-1)%10` instead of adding 9, but for n=0 we would get an incorrect behaviour, because in C `(-1)%10` evaluates to -1, not 9. [Answer] # Javascript, 75 ``` function s(i){return i+'thstndrd'.substr(~~(i/10%10)-1&&i%10<4?i%10*2:0,2)} ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 7 years ago. [Improve this question](/posts/1082/edit) Your task is to tack on a feature to a programming language, either by implementing a very clever library, or by processing the input text and/or tweaking the compilation process. Ideas: * Add PHP-style presentation interleaving to C (e.g. `<?c printf("Hello,"); ?> world!`). * Add a [null coalescing operator](https://softwareengineering.stackexchange.com/questions/2730/what-would-be-the-coolest-new-feature-for-a-programming-language/3871#3871) to one of those languages that isn't C#. * Add macros to PHP. * Add `goto` to JavaScript. * Add pattern matching to language X. * Add namespace support to a language that doesn't have it. * Make C look like PHP. * Make Haskell look like Pascal. * ... (feel free to post ideas in the comment section) Rules: * Bring something to the table. Don't just say "Template Haskell" to add metaprogramming facilities to Haskell. This isn't StackOverflow. * The entire implementation should fit in one screenful (not counting the example). * Do not host code on an external site specifically for this task. * The most impressive or surprising feature wins. Don't worry about implementing the feature 100% correctly. Far from it! The main challenge is figuring out what you want to do and *viciously cutting away details* until your planned undertaking becomes feasible. ## Example: Add a [lambda operator](https://stackoverflow.com/questions/890128/python-lambda-why/890188#890188) to the C programming language. Initial approach: > > Okay, I know I'd want to use [libgc](http://www.hpl.hp.com/personal/Hans_Boehm/gc/) so my lambdas will solve the upward and downward funarg problems. I guess the first thing I'd need to do is write/find a parser for the C programming language, then I'd need to learn all about C's type system. I'd have to figure out how to make sense of it as far as types go. Would I need to implement type inference, or should I simply require that the formal parameter be typed as given? What about all those crazy features in C I don't know about yet? > > > It's quite clear that implementing lambda in C *correctly* would be a huge undertaking. Forget about correctness! Simplify, simplify. Better: > > Screw upward funargs, who needs 'em? I might be able to do something tricky with GNU C's [nested functions](http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html) and [statement expressions](http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html). I wanted to show off an amazing syntactic transformation on C with terse, hacky code, but I won't even need a parser for this. That can wait for another day. > > > Result (requires GCC): ``` #include <stdio.h> #include <stdlib.h> #define lambda(d,e)({d;typeof(e)f(d){return(e);};f;}) #define map(F,A)({typeof(F)f=(F);typeof(*(A))*a=(A);({int i,l=((int*)(a))[-1]; \ typeof(f(*a))*r=(void*)((char*)malloc(sizeof(int)+l*sizeof(*r))+sizeof(int)); \ ((int*)r)[-1]=l;for(i=0;i<l;i++)r[i]=f(a[i]);r;});}) #define convert_to(T) lambda(T x, x) #define print(T, fmt) lambda(T x, printf(fmt "\n", x)) int main(void) { int *array = 1 + (int[]){10, 1,2,3,4,5,6,7,8,9,10}; map(print(int, "%d"), array); double *array2 = map(lambda(int x, (double)x * 0.5), array); map(print(double, "%.1f"), array2); long *array3 = map(convert_to(long), array2); map(print(long, "%ld"), array3); long product = 1; map(lambda(int x, product *= x), array); printf("product: %ld\n", product); return 0; } ``` That was easy, wasn't it? I even threw in a `map` macro to make it useful and pretty. [Answer] ## OOP syntax in Haskell ``` import Prelude hiding ((.)) a . b = b a ``` Objects can have properties: ``` [1,5,3,2].length -- 4 [1,5,3,2].maximum -- 5 'a'.succ -- 'b' ``` ...and methods: ``` "Hello world!".take(5) -- "Hello" "Hello world!".splitAt(2) -- ("He","llo world!") "Hello world!".map(toUpper) -- "HELLO WORLD!" ``` [Answer] ## `goto` in JavaScript? My first thought was a **functional approach** – to add a parameter to the function to indicate where execution should start, using that with a `switch` statement and an outer loop [repeatedly calling the function on its own return value](http://en.wikipedia.org/wiki/Iterated_function). Unfortunately, that would preclude the use of local variables, as they would lose their values with every goto. I could use a [`with` statement](http://www.yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/) and move all variable declarations to the beginning of the function, but there had to be a better way. It eventually came to me to use **JavaScript's exception handling**. In fact, Joel Spolsky said, ["I consider exceptions to be no better than "goto's..."](http://www.joelonsoftware.com/items/2003/10/13.html) – obviously a perfect fit. The idea was to put an infinite loop inside a function, terminated only by a `return` statement or an uncaught exception. All gotos, treated as exceptions, would be caught within the loop to prevent its termination. Here is the result of that approach: ``` function rewriteGoTo(func) { var code = '('; code += func.toString() .replace(/^\s*(\w+)\s*:/gm, 'case "$1":') .replace('{', '{ var $_label = ""; function goTo(label) { $_label = label; throw goTo; } while(true) try { { switch($_label) { case "": '); code += '} return; } catch($_e) { if($_e !== goTo) throw $_e; } })'; return code; } ``` You can use it like this – **even in ES5 strict mode** – except in Internet Explorer ([**demo**](http://jsfiddle.net/5eHv9/25/)): ``` var test = eval(rewriteGoTo(function(before) { var i = 1; again: print(before + i); i = i + 1; if(i <= 10) goTo('again'); })); ``` [Internet Explorer, for some reason, fails to eval the code of an anonymous function, so one would have to give the function a name (before rewriting) and call it using that name. Of course, that would probably break strict mode's rules.] This does not allow jumping to a statement located within a block (until such constructs as Duff's device become legal), but we can deal with that (another, self-executing rewritten function), right? [Answer] ## #define in Java I thought it would be fun to implement macros in Java. ``` import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * defines the use of #define. Usage: * * #def toReplaceCanHaveNoSpaces replacement can have extra spaces * * must be at the beginning of the line (excluding starting spaces or tabs) * * @author Quincunx */ public class Define { public static void main(String[] args) { if (args.length != 1) { err("Please provide exactly 1 argument"); } File source = new File(args[0]); if (!source.exists()) { err("Supplied filepath does not point to an existing file"); } if (!getExtension(args[0]).equalsIgnoreCase(".java")) { err("Supplied file is not of type .java"); } ArrayList<String> sourceData = new ArrayList<>(); ArrayList<String[]> replacements = new ArrayList<>(); try { BufferedReader read = new BufferedReader(new FileReader(source)); String data; while ((data = read.readLine()) != null) { sourceData.add(data); } read.close(); } catch (IOException ex) { Logger.getLogger(Define.class.getName()).log(Level.SEVERE, null, ex); } for (int index = 0; index < sourceData.size(); index++) { String line = sourceData.get(index); line = line.replaceAll("\t", " "); for (String[] e : replacements) { line = line.replace(e[0], e[1]); } if (line.trim().charAt(0) != '#') { sourceData.set(index, line); continue; } while (line.charAt(0) != '#') { line = line.substring(1); } int indexOf = line.indexOf(" "); String type = line.substring(1, indexOf); switch (type) { case "def": case "define": String toReplace = line.substring(indexOf + 1, line.indexOf(" ", indexOf + 1)); replacements.add(new String[]{toReplace, line.substring(line.indexOf(":") + 1)}); break; default: err("The source code contains a # in which there is no correct type"); } } try { BufferedWriter write = new BufferedWriter(new FileWriter(source)); for (String s : sourceData) { write.write(s); write.newLine(); } write.close(); } catch (IOException ex) { Logger.getLogger(Define.class.getName()).log(Level.SEVERE, null, ex); } } public static void err(String message) { System.err.println(message); System.exit(1); } public static String getExtension(String filePath) { return filePath.substring(filePath.lastIndexOf(".")); } } ``` Sample usage (converts to previously posted code; let's make it weird): ``` #def @ o #def ~ a #def $ i #def ` e #d`f % m #d`f ! { #d`f & d #&`f _ } #&`f 2 ( #&`f 7 ) #&`f $%p@rt$@. $%p@rt j~v~.$@. #&`f $%p@rtu. $%p@rt j~v~.ut$l. #&`f ps publ$c st~t$c #&`f Str Str$ng $%p@[[email protected]](/cdn-cgi/l/email-protection)`r`&R`~&`r; $%p@[[email protected]](/cdn-cgi/l/email-protection)`r`&Wr$t`r; $%p@[[email protected]](/cdn-cgi/l/email-protection)$l`; $%p@[[email protected]](/cdn-cgi/l/email-protection)$l`R`~&`r; $%p@[[email protected]](/cdn-cgi/l/email-protection)$l`Wr$t`r; $%p@[[email protected]](/cdn-cgi/l/email-protection)`pt$@n; $%[[email protected]](/cdn-cgi/l/email-protection)~yL$st; $%[[email protected]](/cdn-cgi/l/email-protection)@gg$ng.L`v`l; $%[[email protected]](/cdn-cgi/l/email-protection)@gg$ng.L@gg`r; #d`f L$st Arr~yL$st #d`f l@g; L@gg`r.g`tL@gg`r2D`f$n`.cl~ss.g`tN~m`277.l@g2L`v`l.SEVERE, null, `x7; publ$c cl~ss D`f$n` ! ps v@$d %ain2Str[] ~rgs7! $f 2~rgs.l`ngth != 17 ! `rr2"Pl`~s` pr@v$&` `x~ctly 1 ~rgu%`nt"7; _ F$l` squrc` = n`w F$l`2~rgs[0]7; $f 2!sourc`.`x$sts277 ! `rr2"Suppli`& f$l`p~th &@`s n@t p@int t@ ~n `x$st$ng f$l`"7; _ $f 2!g`tExt`ns$@n2~rgs[0]7.`qu~lsIgn@r`C~s`2".j~v~"77 ! `rr2"Suppl$`& f$l` $s n@t @f typ` .j~v~"7; _ L$st<Str> s@urceDat~ = n`w List<>27; L$st<Str[]> repl~cem`nts = n`w L$st<>27; try ! Buff`r`&R`a&`r r`a& = new Buff`redRe~&`r2n`w F$l`R`~&`r2s@urc`77; Str &~t~; wh$l` 22&~t~ = r`~&.r`~&L$n`277 != null7 ! s@urc`D~t~.~&&2&ata7; _ re~&.cl@se27; _ c~tch 2IOExc`ption ex7 ! log; _ f@r 2$nt $n&`x = 0; $ndex < s@urc`D~t~.s$z`27; $nd`x++7 ! Str l$n` = s@urc`D~ta.get2index7; line = line.r`pl~c`All2"\t", " "7; for 2Str[] ` : r`pl~c`%`nts7 { line = line.r`pl~c`2`[0], e[1]7; _ if 2l$ne.tr$%27.ch~rAt207 != '#'7 ! sourc`D~t~.s`t2$n&`x, l$n`7; c@nt$nu`; _ wh$l` 2line.ch~rAt207 != '#'7 ! l$ne = l$ne.substr$ng217; _ $nt in&`xOf = line.$n&`xOf2" "7; Str typ` = line.substring21, indexOf7; sw$tch 2type7 ! c~s` "&`f": c~s` "def$n`": str t@R`pl~c` = line.substring2indexOf + 1, line.indexOf2" ", indexOf + 177; r`pl~c`%`nts.~&&2n`w s\Str[]!t@R`place, line.substring2line.indexOf2":"7 + 17_7; br`~k; def~ult: err2"Th` s@urc` c@&` c@nt~$ns ~ # $n wh$ch th`r` i$s n@ c@rr`ct typ`"7; _ _ try ! Buff`r`&Wr$ter wr$te = new BufferedWriter2new F$l1Wr$t1r2s@urc177; for 2Str s : s@urceData7 ! wr$te.write2s7; wr$te.n`wLin`27; _ wr$t`.cl@s`27; _ c~tch 2IOExc`pt$@n `x7 ! l@g; _ _ ps v@$& `rr2Str m`ss~g`7 ! Syst`%.`rr.pr$ntln2message7; Syst`%.`x$t217; _ ps Str g`tExt`nsi@n2Str fileP~th7 ! r`turn f$lePath.substr$ng2f$l`P~th.l~stInd`xOf2"."77; _ _ ``` [Answer] ## Foreach in C Iterate arrays (works for static arrays, not ones, received through pointer) ``` //syntactic beauty #define in , //syntactic beauty's helper macro #define foreach(a) _foreach(a) //the real foreach macro #define _foreach(e,arr)\ typeof (&arr[0]) e;\ for (e=&arr[0];e!=&arr[sizeof(arr)/sizeof(arr[0])];e++) ``` To test it: ``` int int_arr[3]={10,20,30}; char *strings[]={"Hello","World","Foreach","Test"}; foreach (num in int_arr) { printf ("num=%d\n",*num); } foreach (str in strings) { printf ("str=%s\n",*str); } ``` result: ``` num=10 num=20 num=30 str=Hello str=World str=Foreach str=Test ``` [Answer] ## Properties in C [Tomasz Wegrzanowski implemented](http://t-a-w.blogspot.com/2007/03/segfaulting-own-programs-for-fun-and.html) [properties](https://en.wikipedia.org/wiki/Property_%28programming%29) in plain C, by **intentionally segfaulting** the program when the property is accessed. An object with a "property" is set up by creating a `struct` that crosses multiple pages, ensuring that the property's memory address lies in a different page from the real data members. The property's page is marked as no-access, guaranteeing that attempting to access the property will cause a segfault. A fault handler then figures out which property access caused the segfault, and calls the appropriate function to compute the property's value, which gets stored at the property's memory address. The fault handler also marks the data page as read-only to ensure the computed value remains consistent; when you next try to write to a data member, that triggers a segfault, whose handler sets the data page as read-write and the property page as no-access (indicating that it needs to be recomputed). [Answer] # Computed come-from in Common Lisp I initially implemented come-from. But that wasn't good enough. Inspired by the computed goto, I decided to implement computed come-from. ``` (defmacro computed-come-from-tagbody (&rest statements) (let ((has-comp-come-from nil) (comp-come-from-var nil) (start-tag (gensym)) (end-tag (gensym))) (let ((current-tag start-tag) (come-froms (make-hash-table :test #'eq))) (let ((clauses '())) (loop for statement in statements do (if (symbolp statement) (setf current-tag statement)) (cond ((and (consp statement) (eql 'come-from (car statement))) (setf has-comp-come-from t) (setf (gethash (cadr statement) come-froms) current-tag)) (t (push statement clauses)))) (if (not has-comp-come-from) `(tagbody ,@(reverse clauses)) (let ((res '()) (current-tag start-tag)) (loop for clause in (reverse clauses) do (cond ((symbolp clause) (push clause res) (setf current-tag clause) ;; check all vars for jumps (push `(progn ,@(loop for k being the hash-key of come-froms for v being the hash-value of come-froms collect `(when (eql ,k ,current-tag) (go ,v)))) res)) (t (push clause res)))) `(macrolet ((come-from (idx) (declare (ignore idx)) (error "Come-from cannot be used with another form."))) (tagbody ,@(reverse res))))))))) ``` ## Examples of usage ``` (come-from x) ; whenever we're at the top of a labeled block and the value of x is equal to the label, jump back to this point. ``` For each come-from declaration in the tagbody, it will check at each label if the come-from variable is equal to the current label, and if so, jump to the corresponding come-from declaration. **Greeter** ``` (let ((x :repeat) (y :exit)) (computed-come-from-tagbody :loop ;; when x == :loop jump to :loop. when y == :loop jump to :exit (come-from x) (format t "What is your name? ") (let ((name (read-line))) (terpri) (format t "Hello ~a~%" name) (print (string= name "exit")) (when (string= name "exit") (setf x nil y :repeat))) :repeat ;; when x = :repeat jump to loop, when y = :repeat jump to exit :exit ;; when x = :exit jump to loop, when y = :exit jump to exit (come-from y))) ``` **FizzBuzz** ``` (let ((i 0) (x nil) (y nil)) (computed-come-from-tagbody :loop (come-from x) (cond ((> i 100) (setf x nil y :end-iteration)) (t (or (and (zerop (mod i 3)) (zerop (mod i 5)) (print "FizzBuzz")) (and (zerop (mod i 3)) (print "Fizz")) (and (zerop (mod i 5)) (print "Buzz")) (print i)) (incf i) (setf x :end-iteration))) :end-iteration :end (come-from y) (print "done"))) ``` [Answer] # "Auto-strings" in Ruby The code is quite simple: ``` def self.method_missing *a; a.join ' '; end ``` Now you can do ``` print This is an automatic string #=> This is an automatic string print hooray #=> hooray x = code golf print This is + ' ' + x + '!' #=> This is code golf! ``` [Answer] ## Add macros to PHP We can just use the C preprocessor for this task. A php script: ``` <?php #define ERROR(str) trigger_error(#str, E_USER_ERROR) function test() { ERROR(Oops); } ``` Pipe it though cpp: ``` cpp < test.php ``` Result: ``` <?php function test() { trigger_error("Oops", E_USER_ERROR); } ``` [Answer] ## Pattern Matching Guards in Python ``` def pattern_match(n, s="__fns"): s=n+s;g=globals() def m(f): def a(*r): for f in g[s]: if reduce(lambda c,t:c and eval(t[1:],{},dict(zip(f.func_code.co_varnames,r))),filter(lambda x:x and x[0]is"|",map(lambda x:x.strip(),f.func_doc.split("\n")))): return f(*r) g[n]=a;g[s]=(g.get(s)or[])+[f] return a return m ``` The body of the function comes in at 288 characters. Pattern Matching Guards allow you to use completely different functions depending on argument values. Although it can be easily emulated with a series of `if` statements, ~~pattern matching~~ guards can help separate sections of code, and it's a great excuse to do some crazy metaprogramming. `pattern_match` is a decorator that creates a new function that implements pattern matching guards. The conditions for each "sub-function" given in each docstring on lines starting with a pipe (`|`). If all conditions evaluate truthily, that version of the function is run. Functions are tested in order until a match is found. Otherwise, `None` is returned. An example will help clarify: ``` @pattern_match("test1") def test1_a(a, b, c): """ This guard tests if a and c are positive | a > 0 | c > 0 """ return a + b + c @pattern_match("test1") def test1_b(a, b, c): """ This pattern only ensures b is positive | b > 0 """ return b + c @pattern_match("test1") def test1_c(a, b, c): """ Final catchall | True """ return 0 print test1(1,2,3) # (a) >>> 6 print test1(1,2,0) # (b) >>> 2 print test1(1,0,0) # (c) >>> 0 print test1(0,0,1) # (b) >>> 1 ``` [Answer] [Coroutine](http://en.wikipedia.org/wiki/Coroutine) I can't take credit for this, so i've marked it CW. [Coroutines in C](http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html) by Simon Tatham [Answer] ## Custom operators in Lua Pogs [cleverly abused operator overloading in Lua](https://github.com/Pogs/lua-snippets/blob/master/custom-operator.lua) in order to allow custom infix operators to be defined. I've expanded this to support operator sectioning (partially applying an operator with either operand) and calling the resulting object as if it were a function. ``` ---- implementation function infix(f) local function g(self, x) return f(self[1] or x, self[2] or x) end local mt = { __sub = g, __call = g } local self = {} return setmetatable(self, { __sub = function (lhs,rhs) return rhs == self and setmetatable({ lhs, nil }, mt) or setmetatable({ nil, rhs }, mt) end }) end ---- testing local eq = infix(function (a, b) return a == b end) local ge = infix(function (a, b) return a >= b end) local comp = infix(function (a, b) return a < b and -1 or a > b and 1 or 0 end) function filter(pred, xs) local res = {} for i=1,#xs do if pred(xs[i]) then table.insert(res, xs[i]) end end return res end print(1 -eq- 1) --> true print(1 -comp- 0) --> 1 print((4 -ge)(1)) --> true print(table.unpack(filter(ge- 0, {1,-4,3,2,-8,0}))) --> 1 3 2 0 ``` [Answer] # Make C simpler This code allows you to write C programs that kind of resemble a scripting language a bit more. It features keywords such as 'var', 'is', 'string', 'plus', 'equal' and several others. It works through *a lot* of define statements. ``` // pretty.c #include<stdio.h> #define function int #define var int #define is = #define then { #define do { #define does { #define end } #define equal == #define notequal != #define greater > #define less < #define greaterequal >= #define lessequal <= #define display printf #define otherwise }else{ #define increase ++ #define decrease -- #define plus + #define minus - #define times * #define divide / #define character char #define string char* #define integer int ``` This allows you to write code like: ``` /* Preprocessor abuse, Yay! */ #include "pretty.c" function main() does var myVar is 1; if(myVar greater 2)then display("Yep\n"); otherwise display("Nope\n"); end for(var i is 0; i less 10; i increase)do display("Loop: %d\n", i); end string myString = "Hello"; display(myString); end ``` The above gets expanded to: ``` int main() { int myVar = 1; if(myVar > 2){ printf("Yep\n"); }else{ printf("Nope\n"); } for(int i = 0; i < 10; i ++){ printf("Loop: %d\n", i); } char* myString = "Hello"; printf(myString); } ``` Probably not overly useful but I found it quite interesting that you could essentially create an entire programming language through a bunch of `#define`s. [Answer] # Multiline strings in javascript in this elaborate syntax for multiline strings, every multiline string will be preceded with `(function(){/*` and a newline, and followed by a newline and `*/}+'').split('\n').slice(1,-1).join('\n')`. using this amazing, intuitive syntax, we can finally use multiline strings: ``` var string = (function(){/* THIS IS A MULTILINE STRING HOORAY!!! */}+'').split('\n').slice(1,-1).join('\n'); console.log(string) // THIS IS A MULTILINE STRING // HOORAY!!! ``` for people who don't like our simple syntax, we have a compiler to our fabulous new language: ``` function compile(code) { return code.replace("#{", "(function(){/*").replace("}#", "*/}+'').split('\n').slice(1,-1).join('\n')") } ``` the same example, in the compiled-language version: ``` var string = #{ THIS IS A MULTILINE STRING HOORAY!!! }#; console.log(string) // THIS IS A MULTILINE STRING // HOORAY!!! ``` [Answer] # Goto in PostScript My first thought was that I'd have to muck about with the exec stack, so this false start digs up the continuation operator for stopped from ghostscript (or xpost). ``` /_stopped_mark {countexecstack array execstack dup length 2 sub get} stopped pop def ``` But, it's simpler than that. Because file-position is the same for all duplicates of the file handle (`setfileposition` consumes its argument, so this is the only useful semantics for that function). ``` /LABELS 10 dict def /: { % n : define label LABELS exch currentfile fileposition put } def /goto { % goto label currentfile exch LABELS exch get setfileposition } def /x 0 def /here : /x x 1 add def x 5 ne { /here goto } if x = ``` It prints `5`. There are some limitations with the above. The jump is not immediate, but happens when the if-body returns to the top-level and the interpreter is again reading from the file (instead of reading from the array that contains the if-body). At that point, the file has been repositioned and the 'goto' takes effect. [Answer] # Sliceable List in C# (like Python) I always enjoyed python's [slice notation](https://stackoverflow.com/questions/509211/pythons-slice-notation) and wish it was available in C# Usage: ``` SliceList<int> list = new SliceList<int>() { 5, 6, 2, 3, 1, 6 }; var a = list["-1"]; // Grab the last element (6) var b = list["-2:"]; // Grab the last two elements (1,6) var c = list[":-2"]; // Grab all but the last two elements (5,6,2,3) var d = list["::-1"]; // Reverse the list (6,1,3,2,6,5) var e = list["::2"]; // Grab every second item (5,2,1) ``` Code, far from error proof: ``` public class SliceList<T> : List<T> { public object this[string slice] { get { if (string.IsNullOrWhiteSpace(slice)) return this.ToList(); int[] values = { 0, Count, 1 }; string[] data = slice.Split(':'); for(int i = 0; i < data.Length; i++) { if (string.IsNullOrEmpty(data[i])) continue; int value; int.TryParse(data[i], out value); if(value < 0 && i < 2) value += Count; values[i] = value; } if (data.Length == 1) return this[values[0]]; int start = Math.Min(values[0], values[1]); int stop = Math.Max(values[0], values[1]); int step = values[2]; int sign = Math.Sign(step); if (sign < 0) { var temp = start; start = stop-1; stop = temp-1; } SliceList<T> newList = new SliceList<T>(); for (int i = start; i != stop; i += step) newList.Add(this[i]); return newList; } } } ``` [Answer] ### Tcl Tcl has no `do ... while` or `do ... until` so... ``` proc do {body op expr} { uplevel 1 $body switch -exact -- $op { while { while {[uplevel 1 [list expr $expr]} { uplevel 1 $body } } until { while {![uplevel 1 [list expr $expr]} { uplevel 1 $body } } } } ``` Example: ``` do { puts -nonewline "Are you sure? " flush stdout set result [gets stdin] } while {[string is boolean -strict $result]} ``` [`uplevel`](http://www.tcl.tk/man/tcl8.6/TclCmd/uplevel.htm) executes a script in the callers scope. [Answer] ## `Symbol#to_proc` with arguments in Ruby `Symbol#to_proc` is probably one of my favorite tricks for writing really succinct Ruby code. Suppose you have ``` nums = [1, 2, 3, 4] text = %w(this is a test) ``` and you want to convert the contents of `nums` and `text` to Floats and uppercase words, respectively. `Symbol#to_proc` allows you to shorten code like this: ``` nums.map { |num| num.to_f } text.map { |word| word.upcase } ``` to this: ``` nums.map(&:to_f) text.map(&:upcase) ``` Awesome! But what if we want to raise every element in `nums` to the `i`th power, or replace every occurrence of `s` with `*` in `text`? Is there any way to shorten code like this? ``` nums.map { |num| num ** 1i } nums.map { |word| word.gsub('s', '*') } ``` Alas, there's no easy way to pass arguments when using `Symbol#to_proc`. I've seen it done multiple ways, but probably two of the most clever and usable involve monkey-patching the `Symbol` class [[1](https://stackoverflow.com/a/23711606/2980254), [2](https://gist.github.com/banister/9551558)]. I'll illustrate the first way below. ``` class Symbol def with(*args, &block) ->(caller, *rest) { caller.send(self, *rest, *args, &block) } end end ``` Now you can do things like: ``` nums.map(&:**.with(1i)) text.map(&:gsub.with('s', '*')) nums.take_while(&:<.with(3)) text.delete_if(&:[].with('is')) ``` [Answer] # JavaScript foreach ``` var arr = ["Seattle", "WA", "New York", "NY", "Chicago", "IL"]; function foreach(fn, arr) { var s = fn.toString(); var args = s.substring(s.indexOf('(')+1,s.indexOf(')')).split(","); var argsLen = args.length; var len = arr.length; for (var i = 0; i < len; i+=argsLen) { var part = arr.slice(i, i+argsLen); fn.apply(undefined, part); } } foreach (function(city, state) { console.log(city + ', ' + state); }, arr); ``` Output ``` Seattle, WA New York, NY Chicago, IL ``` Alternate syntax, more like Tcl. ``` // Tcl's foreach loop for javascript. // Keys in loop are prefixed with "this". function tclForeach(keys, values, fn) { var obj={}, klen=keys.length, vlen=values.length, j, i; for (i=0, klen=keys.length; i < klen; i++) obj[keys[i]]=null; for(i = 0; i < vlen; i+=klen) { for(j=klen; j--;) obj[keys[j]] = values[i+j]; fn.apply(obj); } } tclForeach(["city","state"], arr, function() { console.log(this.city + ', ' + this.state); }); ``` [Answer] # Gotos in Haskell the basic idea is that gotos can be partially simulated using the last statement in `do`-notations. for example: ``` main = do loop: print 3 goto loop ``` is equivalent to ``` main = do loop loop = do print 3 loop ``` because execution will jump to the last statement, it is optimal to express gotos. because the way it is done, gotos only jumps when they are at the `do` block of a toplevel definition directly. it is actually "call x and ignore the rest of the **lexically seen** statements" rather than "all x and ignore the rest of the statements", like a real goto. the biggest problem is that when there is no way to leave execution from the middle of an IO action - even `return` doesn't; `return` does nothing when it isn't the last statement. this overcomes this by capturing the rest of the statements by another `do` block. ``` goto loop print 3 ``` becomes ``` const loop $ do print 3 ``` the `print 3` statement is captured by the `do` block, so `loop` becomes the last statement. this transformation also supports variables being present at the scope of the actions. this is done by remembering the variables which are in scope, and passing them into the actions. for example: ``` printer r = do loop: putStrLn r goto loop print "this isn't executed" ``` this simply translates into: ``` printer r = do loop r loop = do putStrLn r const (loop r) $ do print "this isn't executed" ``` some notes: also, a `return undefined` statement is added to ensure the capturing `do` block is not empty. because sometimes there is type ambiguity in the capturing `do` block, instead of `const` we use `asTypeOf`, which is the same as `const` but requires both its parameters to have the same type. **the actual implementation** (in javascript): ``` function makeGoto(code) { var vars = [] // the known variables // add the arguments to the functions to scope code.split('\n')[0].split('=')[0].split(' ').slice(1).forEach(function(varname){vars.push(varname)}) return code.replace(/([ \t]*)([a-zA-Z]+):|([ \t]*)goto[ \t]+([a-zA-Z]+)|[ \t]+([a-zA-Z]+)[ \t]*<-/gm, function match(match, labelSpaces, label, gotoSpaces, goto, x) { if (label != undefined) return labelSpaces+label+" "+vars.join(' ')+"\n"+label+" "+vars.join(' ')+"=do "; else if(goto != undefined) return gotoSpaces+"asTypeOf("+goto+" "+vars.join(' ')+")$do\n"+gotoSpaces+"return undefined"; else { vars.push(x); return match } }) } ``` an exampe: ``` main = do putSrtLn "a" goto label putStrLn "b" label: putStrLn "c" ``` becomes: ``` main = do putStrLn "a" asTypeOf(label )$do return undefined putStrLn "b" label label =do putStrLn "c" ``` output: ``` a c ``` [Answer] # Python Goto ### goto.py ``` import sys, re globals_ = globals() def setglobals(g): global globals_ globals_ = g def goto(l): global globals_ with open(sys.argv[0], "rb") as f: data = f.read() data_ = data.split('\n') if isinstance(l, int): l-=1 if l > 0 else 0 elif isinstance(l, str): r=re.search(r"^\s*(#{0}|(def|class)\s+{0})".format(l), data, re.MULTILINE) l=len(data_)-(data[r.start():].count("\n")) if r else len(data_) if 0 < l < len(data_) or 0 < (l*-1) <= len(data_): exec("".join(data_[l:]),globals_) sys.exit(1) ``` ### Usage ``` setglobals(globals()) #Set the globals to be used in exec to this file's globals (if imports or other variables are needed) goto(8) #Goto line 8 goto(-8)#Goto 8th last line goto("label")#Goto first occurrence of #label goto("funcName")#Goto definition of funcName goto("className")#Goto definition of className ``` ### Sample Test Case ``` import goto, sys goto.goto(-1) sys.exit(-1) print "Asdf" ``` ### Sample Test Case Output ``` Asdf ``` Just a little fun with exec(). Can raise a maximum recursion depth error if not used properly. [Answer] //import javascript without especifically using the script tag in a HTML page ``` function i(u) { document.write("script src=\" + u + \"></script>"); } i("http://www.mysite.com/myscript.js"); ``` It's lame yeah I know. Length: 99 ]
[Question] [ The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional. The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc. Example input: ``` bonobo ``` Example output: ``` bonoobbooo ``` Standard I/O rules apply. The shortest code in bytes wins. Tests provided by @Neil : ``` tutu -> tuttuu queue -> queuuee bookkeeper -> boookkkeeepeeer repetitive -> repeetittiiveee uncopyrightables -> uncopyrightables abracadabra -> abraacaaadaaaabbrraaaaa mississippi -> misssiisssssssiiipppiiii ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;\f" ``` [Try it online!](http://jelly.tryitonline.net/#code=O1xmIg&input=&args=bWlzc2lzc2lwcGk) ### How it works ``` ;\f" Main link. Argument: S (string) ;\ Cumulatively reduce by concatenation. This yields the array of all prefixes of S. f" Vectorized filter. Keep only occurrences of the nth letter in the nth prefix. ``` [Answer] # Pyth, 6 bytes Thanks to [@Doorknob](https://codegolf.stackexchange.com/users/3808/doorknob) for taking off 1 byte. Thanks to [@Maltysen](https://codegolf.stackexchange.com/users/31343/maltysen) for taking off 5 bytes. ``` s@VQ._ ``` [Try it online!](http://pyth.herokuapp.com/?code=s%40VQ._&input=%22bonobo%22&debug=0) ## How it works --- For example, take the string `"bonobo"`. `._` makes a list: `['b', 'bo', 'bon', 'bono', 'bonob', 'bonobo']` `VQ._` means "the preceding function vectorized (applied in parallel) over `Q` and `._`", which means `Q` (the input evaluated) will be treated as a list: `['b', 'o', 'n', 'o', 'b', 'o']`, and then they will be paired by the `@` like this: ``` Q ._ @ (intersect) 0: 'b' 'b' 'b' 1: 'o' 'bo' 'o' 2: 'n' 'bon' 'n' 3: 'o' 'bono' 'oo' 4: 'b' 'bonob' 'bb' 5: 'o' 'bonobo' 'ooo' ``` Therefore, `@VQ._` will produce `['b', 'o', 'n', 'oo', 'bb', 'ooo']`. The `s` then joins them all together, creating a string `'bonoobbooo'`, which is then implicitly printed out to become `bonoobbooo`. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~34~~ 19 bytes *Saved 15 bytes by taking some inspiration from isaacg's solution.* Byte count assumes ISO 8859-1 encoding. ``` $`¶ (\D)(?!.*\1¶) ``` The leading and trailing empty lines are significant. [Try it online!](http://retina.tryitonline.net/#code=CiRgwrYKKFxEKSg_IS4qXDHCtikK&input=Ym9va2tlZXBlcg) ### Explanation ``` $`¶ ``` This is a replace stage which matches the empty regex (i.e. every zero-width position in the string) and substitutes `$`¶` for it, where `$`` is the prefix of the match and `¶` inserts a linefeed. This basically computes all the prefixes and puts them on a separate line together with the last character of that prefix: ``` bb obo oboo kbook kbookk ebookke ebookkee pbookkeep ebookkeepe rbookkeeper ``` There will be some leading and trailing linefeeds, but we can ignore them. From each of these prefixes we want to keep the characters that are equal to the last character. For that we use another replace stage: ``` (\D)(?!.*\1¶) ``` This matches everything we *don't* want to keep and replaces it with a nothing. We match any character (using `\D` since we know there won't be digits in the input) and then make sure that there *isn't* another copy of that character at the end of the line. [Answer] ## Haskell, 39 bytes ``` f""="" f x=f(init x)++filter(==last x)x ``` Usage example: `f "bonobo"` -> `"bonoobbooo"`. Different enough from [@Damien's answer](https://codegolf.stackexchange.com/a/77047/34531). Builds the string from the right by extracting all occurrences of the last character from the string and prepending a recursive call with all but the last character. [Answer] ## Python, 56 bytes I seem to be stuck with two answers of the same length: ``` f=lambda x,*y:x and-~y.count(x[0])*x[0]+f(x[1:],x[0],*y) f=lambda x,y=0:x[y:]and-~x[:y].count(x[y])*x[y]+f(x,y+1) ``` Edit: See [@pacholik's answer](https://codegolf.stackexchange.com/a/77059/21487) for a shorter, alternative Python approach. [Answer] ## [><>](http://esolangs.org/wiki/Fish), 27 bytes ``` >i:0g1+:\ :{-1v!?:<}o /p${/ ``` Requires the official interpreter which exits with an error when trying to print code point -1. [Try it online!](http://fish.tryitonline.net/#code=Pmk6MGcxKzpcCjp7LTF2IT86PH1vCi9wJHsv&input=c2VzcXVpY2VudGVubmlhbA) The code reads input one char at a time and uses the first row of the codebox as a large array which stores the number of times each char has been seen so far (><> initialises non-program cells to 0). The second row is a loop for outputting a char multiple times. Alternatively, here's a version which exits cleanly (37 bytes, not properly golfed): ``` >i:0(?;:0g1+:\ }o:{-1v!?: < v p${< ``` [Answer] ## JavaScript (ES6), ~~48~~ 45 bytes ``` s=>s.replace(n=/./g,c=>c.repeat(n[c]=-~n[c])) ``` Edit: Saved 3 bytes thanks to @user81655. [Answer] # Haskell, ~~50~~ ~~42~~ 41 bytes Saved 8 bytes thanks to Lynn ``` f t=[c|(i,c)<-zip[1..]t,x<-take i t,c==x] ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), 8 bytes ``` tt!=RsY" ``` [Try it online!](http://matl.tryitonline.net/#code=dHQhPVJzWSI&input=J2Jvbm9ibyc) Or [verify all test cases at once](http://matl.tryitonline.net/#code=YGkKdHQhPVJzWSIKdEQ&input=J3R1dHUnCidxdWV1ZScKJ2Jvb2trZWVwZXInCidyZXBldGl0aXZlJwondW5jb3B5cmlnaHRhYmxlcycKJ2FicmFjYWRhYnJhJwonbWlzc2lzc2lwcGkn). ### Explanation ``` t % take input string implictly. Duplicate t! % duplicate and transpose into a column = % test for equality with broadcast. Gives an NxN array, where N is % input string length R % upper triangular part: set entries below the diagonal to 0 s % sum of each column. For each postion in the input, gives how many % times that letter has appeared up to that position Y" % replicate elements (run-length decoding). Display implicitly ``` [Answer] ## [Labyrinth](https://github.com/mbuettner/labyrinth), ~~54~~ 25 bytes ``` <#; "#: ={},> }=}(.);("@ ``` Another collab with @MartinBüttner, who actually did ~~most~~ almost all of the golfing for this one. By revamping the algorithm, we've managed to cut down the program size by quite a bit! [Try it online!](http://labyrinth.tryitonline.net/#code=PCM7ICIjOiA9e30sPgogfT19KC4pOygiQA&input=c2VzcXVpY2VudGVubmlhbA) ### Explanation A quick Labrinth primer: * Labyrinth is a stack-based 2D language. There are two stacks, a main and auxiliary stack, and popping from an empty stack yields zero. * At each junction, where there are multiple paths for the instruction pointer to move down, the top of the main stack is checked to see where to go next. Negative is turn left, zero is straight ahead and positive is turn right. The two stacks of arbitrary-precision integers isn't much flexibility in terms of memory options. To perform the counting, this program actually uses the two stacks as a tape, with shifting a value from one stack to the other being akin to moving a memory pointer left/right by a cell. It's not quite the same as that though, since we need to drag a loop counter with us on the way up. [![enter image description here](https://i.stack.imgur.com/doALR.png)](https://i.stack.imgur.com/doALR.png) First off, the `<` and `>` on either end pop an offset and rotate the row of code that offset away by one either left or right. This mechanism is used to make the code run in a loop - the `<` pops a zero and rotates the current row left, putting the IP at the right of the code, and the `>` pops another zero and fixes the row back. Here's what happens each iteration, in relation to the diagram above: ``` [Section 1] ,} Read char of input and shift to aux - the char will be used as a counter to determine how many elements to shift [Section 2 - shift loop] { Shift counter from aux " No-op at a junction: turn left to [Section 3] if char was EOF (-1), otherwise turn right ( Decrement counter; go forward to [Section 4] if zero, otherwise turn right = Swap tops of main and aux - we've pulled a value from aux and moved the decremented counter to aux, ready for the next loop iteration [Section 3] @ Terminate [Section 4] ; Pop the zeroed counter ) Increment the top of the main stack, updating the count of the number of times we've seen the read char : Copy the count, to determine how many chars to output [Section 5 - output loop] #. Output (number of elements on stack) as a char ( Decrement the count of how many chars to output; go forward to [Section 6] if zero, otherwise turn right " No-op [Section 6] } Shift the zeroed counter to aux [Section 7a] This section is meant to shift one element at a time from main to aux until the main stack is empty, but the first iteration actually traverses the loop the wrong way! Suppose the stack state is [... a b c | 0 d e ...]. = Swap tops of main and aux [... a b 0 | c d e ...] } Move top of main to aux [... a b | 0 c d e ...] #; Push stack depth and pop it (no-op) = Swap tops of main and aux [... a 0 | b c d e ...] Top is 0 at a junction - can't move forwards so we bounce back ; Pop the top 0 [... a | b c d e ... ] The net result is that we've shifted two chars from main to aux and popped the extraneous zero. From here the loop is traversed anticlockwise as intended. [Section 7b - unshift loop] # Push stack depth; if zero, move forward to the <, else turn left }= Move to aux and swap main and aux, thus moving the char below (stack depth) to aux ; Pop the stack depth ``` [Answer] ## Perl, 17 **(16 bytes code, +1 for -p)** ``` s/./${$&}.=$&/ge ``` ### Usage: ``` perl -pe 's/./${$&}.=$&/ge' <<< 'bonobo' bonoobbooo ``` [Answer] # Pyth, 7 bytes ``` s@Led._ ``` [Test suite](https://pyth.herokuapp.com/?code=s%40Led._&input=%22bonobo%22&test_suite=1&test_suite_input=%22tutu%22%0A%22queue%22%0A%22uncopyrightables%22%0A%22bookkeeper%22%0A%22repetitive%22%0A%22abracadabra%22%0A%22mississippi%22&debug=0) *Test suite thanks to DenkerAffe* Explanation: ``` s@Led._ ._ All prefixes, implicitly applied to the input. @L Filter each prefix for characters equal to ed the last character of the prefix s Concatenate and implicitly print. ``` [Answer] # Python 3, 52 ``` def f(s):*s,x=s;return s and f(s)+x+x*s.count(x)or x ``` [Answer] ## PowerShell v2+, ~~52~~ 47 bytes ``` $b=@{};-join([char[]]$args[0]|%{"$_"*++$b[$_]}) ``` Constructs an empty hashtable, stores it in `$b`. This is our "counter" of what letters we've seen. We then take input `$args[0]`, cast it as a char-array, and send it through a loop. Each iteration, we take the current character `"$_"` and multiply it by the pre-incremented counter at the given value, which will make the first occurrence be multiplied by `1`, the second by `2` and so on. We encapsulate that with a `-join` so it's all one word being output. Saved 5 bytes thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) by using a hashtable instead of an array, so we didn't need to decrement the ASCII character by `97` to reach the appropriate index. This works because pre-incrementing the hash index implicitly calls `.Add()` in the background if that index doesn't exist, since hashtables are mutable. ``` PS C:\Tools\Scripts\golfing> .\stretch-the-word.ps1 tessellatingheckler tessseelllattingheeeckllleeeer ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 6 bytes ``` ∊,\∩¨⊢ ``` [TryAPL!](http://tryapl.org/?a=f%u2190%u220A%2C%5C%u2229%A8%u22A2%20%u22C4%20f%27bonobo%27%20%u22C4%20f%27uncopyrightables%27&run) 4 functions is an atop (2-train) of a fork (3-train): ``` ┌──┴──┐ ∊ ┌───┼─┐ \ ¨ ⊢ ┌─┘ ┌─┘ , ∩ ``` First `⊢` (right – a no-op) on the given string, giving `'bonobo'` Then `,\` (concatenation scan) on the string, giving `'b' 'bo' 'bon' 'bono' 'bonob' 'bonobo'` The two are forked together with (given as right and left arguments to) `∩¨` (intersection each), i.e. `('b'∩'b') ('bo'∩'o') ('bon'∩'n') ('bono'∩'o') ('bonob'∩'b') ('bonobo'∩'o')`, which is `'b' 'o' 'n' 'oo' 'bb' 'ooo'` Finally, `∊` (enlist) is applied to the result to flatten it, giving `'bonoobbooo'` Hey, at least it matches [Pyth](https://codegolf.stackexchange.com/a/77064/43319)! Obviously [Jelly](https://codegolf.stackexchange.com/a/77072/43319) is shorter as it is a golf version of J, which in turn is an advanced 2-character-per-function dialect of APL. [Answer] # Pyth, 11 bytes ``` s.e*b/<Qhkb ``` [Try it here!](http://pyth.herokuapp.com/?code=s.e*b%2F%3CQhkb&input=%22bonobo%22&test_suite=1&test_suite_input=%22tutu%22%0A%22queue%22%0A%22uncopyrightables%22%0A%22bookkeeper%22%0A%22repetitive%22%0A%22abracadabra%22%0A%22mississippi%22&debug=0) ## Explanation ``` s.e*b/<Qhkb # Q = input .e # map over input with b as value and k as index (Q get appended at the end inplicitly) <Qhk # take the first k+1 chars of Q / b # count occurences of b in there *b # repeat b that many times s # join resulting list into one string ``` [Answer] ## J, 11 bytes ``` #~+/@(={:)\ ``` This is a monadic verb. [Try it here.](http://tryj.tk/) Usage: ``` f =: #~+/@(={:)\ f 'tutu' 'tuttuu' ``` ## Explanation ``` #~+/@(={:)\ ( )\ For each non-empty prefix: {: Take last element, = compare for equality to the others and itself +/@ and take sum (number of matches). #~ Replicate original elements wrt the resulting array. ``` [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 10 bytes Code: ``` $vy«Dy¢y×? ``` Explanation: ``` $ # Push the number 1 and input v # Map over the input string y« # Concat the letter to the previous string (initial 1) D # Duplicate this string y¢ # Count the occurences of the current character in the string y× # Multiply this number with the current character ? # Pop and print without a newline ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=JHZ5wqtEecKiecOXPw&input=Ym9ub2Jv) [Answer] # CJam, 14 ``` q:A,{)A<_)--}/ ``` [Try it online](http://cjam.aditsu.net/#code=q%3AA%2C%7B)A%3C_)--%7D%2F&input=bonobo) **Explanation:** ``` q:A read the input and store in A , get the string length {…}/ for each number from 0 to length-1 ) increment the number A< get the prefix of A with that length _ duplicate it ) separate the last character - remove it from the rest of the prefix - remove all the remaining characters (different from the last one) from the prefix ``` [Answer] # Perl 6, 37 bytes ``` {.split('').map({$_ x++%.{$_}}).join} ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 52 bytes ``` i:0(?;&l:?!v1-$:&:&=?\}70.> 6f+0.00o:&~/ \:o ``` It stacks every letter read, prints them once and once again for every similar letter in the stack. It uses the `&` register, because having to handle 3 variables on the stack (current read letter, position in the stack, letter at this position) is a pain. You can try it [here](https://fishlanguage.com/playground)! [Answer] # Rust, 176 Bytes ``` fn s(w:&str)->String{let mut m=std::collections::HashMap::new();w.chars().map(|c|{let mut s=m.remove(&c).unwrap_or(String::new());s.push(c);m.insert(c,s.clone());s}).collect()} ``` This uses a map to store a string for every character in the input. For each character, the string will be removed from the map, concatenated with the character, inserted back into the map and appended to the output. I would have liked to use `get(...)` instead of `remove(...)`, but the borrow checker had me change my mind. [Answer] # Mathcad, 66 bytes Unfortunately, Mathcad doesn't have particularly good string handling, so I've converted the input string to a vector and then used a (character code indexed) vector to keep track of the number of times a character is encountered, adding the character that number of times to a result vector. Finally, the result vector is converted back to a string. Quite lenghty unfortunately. [![enter image description here](https://i.stack.imgur.com/80uU2.jpg)](https://i.stack.imgur.com/80uU2.jpg) Note that Mathcad uses a 2D "whiteboard" interface, with a mix of normal text and operators; operators are normally entered via a toolbar or keyboard shortcut; for example, ctl-# enters the for loop operator, which comprises the keyword for, the element-of symbol and 3 empty "placeholders" for the iteration variable, range and body expressions respectively. Typing [ after a variable name enters array index mode, Typing ' enters a matched pair of parentheses (*mostly ... there are exceptions depending upon what else is in the surrounding expression*) [Answer] # Javascript ES6 44 bytes ``` q=>q.replace(/./g,a=>x[a]=(x[a]||'')+a,x=[]) ``` --- old answer Javascript ES6 46 bytes ``` q=>(x=[...q]).map(a=>x[a]=(x[a]||'')+a).join`` //thanks user81655 for -1 byte ``` [Answer] # Ruby, 35 bytes ``` ->s{s.gsub(/./){$&*-~$`.count($&)}} ``` It's an anonymous function using regex and some magical variables. Usage: ``` ->s{s.gsub(/./){$&*-~$`.count($&)}}["bonobo"] => "bonoobbooo" ``` [Answer] # Julia, ~~38~~ 35 bytes ``` !s=[]==s?s:[!s[1:end-1];s∩s[end]] ``` I/O is in the from of character arrays. [Try it online!](http://julia.tryitonline.net/#code=IXM9W109PXM_czpbIXNbMTplbmQtMV07c-KIqXNbZW5kXV0KCmZvciBzIGluICgidHV0dSIsInF1ZXVlIiwiYm9va2tlZXBlciIsInJlcGV0ZXRpdmUiLCJ1bmNvcHlyaWdodGFibGVzIiwiYWJyYWNhZGFicmEiLCJtaXNzaXNzaXBwaSIpCiAgICAhW3MuLi5dIHw-IGpvaW4gfD4gcHJpbnRsbgplbmQ&input=) ### How it works We (re)define the monadic operator **!** for our purposes. When **!** is called, it checks if its argument **s** is empty. If it is, it returns its argument. If **s** is non-empty, we intersect **s** with its last character (`s[end]`), which yields all occurrences of that character in **s**. This result is concatenated with the return value of a recursive call to **!** with **s** minus its last character (`s[1:end-1]`) as argument. [Answer] # PHP, ~~54~~ ~~51~~ ~~50~~ 47 bytes ``` for(;$C=$argn[$X++];)echo str_repeat($C,++$$C); ``` Run like this: ``` echo abracadabra | php -nR 'for(;$C=$argn[$X++];)echo str_repeat($C,++$$C); echo"\n";' ``` ## Tweaks * Saved 3 bytes by using variable variables. Changed used variables to uppercase to prevent collision * Saved a byte by removing type cast `null` to `int` for string offset, as string offset is cast to int anyway * Saved 3 bytes by using `$argn` instead of `$argv` (thx Titus) [Answer] ## Mathematica, 57 bytes ``` StringReplace[Clear@c;c@_=0;#,x_:>x~StringRepeat~++c[x]]& ``` We use `c[x]` as a lookup table of how often character `x` has already occurred. This is incremented each time it's retrieved in `x~StringRepeat~++c[x]`. Unfortunately, to make the function reusable, we need to reset the lookup table each time with `Clear@c;c@_=0;`, which is quite expensive. [Answer] # awk, 72 bytes ``` BEGIN{FS=""}{for(i=1;i<=NF;i++){a[$i]++;for(j=0;j<a[$i];j++)printf $i}} ``` The idea is to store the count of the appearing character in an associative array and print the character this count times. [Answer] # Beam, 32 ~~33~~ ~~42~~ bytes This should have been smaller, but I lost some bytes initializing the memory slots to 0. Swapping some flow directions managed to eliminate a lot of empty space. ``` >+\ vus/ >rnH >g'\ (@v's/ ^`< ``` [Try it in this snippet](https://codegolf.stackexchange.com/a/57190) General explanation. * Set all the memory slots from 0-255 to 0 * Read in the input ascii value into the beam * If beam is 0 halt (beam = store) * Get the memory[beam] value into the store, increment it and save back * Decrement the store to 0 printing out the beam character * Repeat ]
[Question] [ Write a program or function that outputs this exact text, case-insensitive: ``` 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. ``` (Based on the [alphabet song](https://en.wikipedia.org/wiki/Alphabet_song#The_A.B.C._.28Verse_1.29) that many American kids learn to help memorize the alphabet, though edited for more compressibility.) The output must *look* exactly the same as the above (again, case-insensitive), but may contain trailing spaces on each line and/or trailing newlines. Notice the period at the end. This is code-golf, so **the shortest code in bytes wins.** [Answer] # Vim, ~~42~~, 40 keystrokes/bytes ``` :h<_<cr>jjYZZP:s/./&, /g<cr>7f r<cr>9;.3;.3;.$ch. ``` Thanks to [Lynn and her awesome vim answer](https://codegolf.stackexchange.com/a/87010/31716) for the tip to grab the alphabet from help. Thanks to RomanGräf for saving two bytes! Explanation: ``` :h<_<cr> " Open up vim-help jj " Move down two lines Y " Yank this line (containing the alphabet) ZZ " Close this buffer P " Paste the line we just yanked :s/./&, /g<cr> " Replace every character with that character followed by a comma and a space 7f " Find the seven space on this line r<cr> " And replace it with a newline 9; " Repeat the last search (space) 9 times . " Repeat the last edit (replace with a newline) 3; " Third space . " Replace with newline 3; " Third space . " Replace with newline ``` Then, we move the end of the of the line with `$`, change back a character with `ch` and insert a dot. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 16 bytes **Code** ``` A',â79334S£»¨'.J ``` **Explanation:** ``` A # Push the alphabet. ',â # Cartesian product with ','. 79334S # Push [7, 9, 3, 3, 4]. £ # Contigious substring, pushes the substrings [0:7], [7:7+9], [7+9:7+9+3], [7+9+3:7+9+3+3], [7+9+3+3:7+9+3+3+4]. » # Gridify, join the inner arrays with spaces and join those arrays with newlines. ¨ # Remove the last character. '.J # Append a '.'-character. ``` Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=QScsw6I3OTMzNFPCo8K7wqgnLko&input=) [Answer] # Bash + GNU utilities, 36 * 5 bytes saved thanks to Neil. ``` echo {A..Y}, Z.|sed 's/[HQTW]/\n&/g' ``` [Ideone.](https://ideone.com/6YcyW7) [Answer] # JavaScript (ES6), ~~66~~ 65 bytes Beating [@Neil](https://codegolf.stackexchange.com/a/95006/42545) was impossible... That's why I did it. :-) ``` f=(i=10)=>i>34?"z.":i.toString(++i)+","+` `[9568512>>i-9&1]+f(i) ``` Golfed 1 byte thanks to a trick from [@LevelRiverSt](https://codegolf.stackexchange.com/a/95044/42545). Using `String.fromCharCode` is 7 bytes longer: ``` f=(i=65)=>i>89?"Z.":String.fromCharCode(i,44,i%86%83%80%71?32:10)+f(i+1) ``` ### How it works This recursively generates each character of the alphabet from `a` to `y`, using `.toString()`. A comma is appended after each letter, plus a newline if `9568512>>i-9&1` is 1, or a space otherwise. When the recursion gets past 34, i.e. to `z`, the function simply returns `"z."`. [Answer] # Python 2.7, ~~67 66~~ 63 bytes ``` a=65;exec"print'%c'%a+',.'[a>89]+'\\n'[a%42%39%9^2:],;a+=1;"*26 ``` Dennis saved a byte. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ØAp”,ṁ79334DR¤GṖ”. ``` *Thanks to @Adnan for golfing off 1 byte!* [Try it online!](http://jelly.tryitonline.net/#code=w5hBcOKAnSzhuYE3OTMzNERSwqRH4bmW4oCdLg&input=) ### How it works ``` ØAp”,ṁ79334DR¤GṖ”. Main link. No arguments. ØA Yield "ABCDEFGHIJKLMNOPQRSTUVWXYZ". p”, Cartesian product with ','; append a comma to each letter. ¤ Combine the two links to the left into a niladic chain. 79334D Decimal; yield [7, 9, 3, 3, 4]. R Range; yield [[1, 2, 3, 4, 5, 6, 7], ..., [1, 2, 3, 4]]. ṁ Mold; reshape the array of letters with commata like the generated 2D array. G Grid; separate rows by spaces, columns by linefeeds. Ṗ Pop; discard the last comma. ”. Print the previous result and set the return value to '.'. (implicit) Print the return value. ``` [Answer] ## Pyke, ~~23~~ ~~19~~ 17 bytes ``` G\,J\.+2cu /P ``` [Try it here!](http://pyke.catbus.co.uk/?code=G%5C%2CJ%5C.%2B2cu%04%07%09%03%03%2FP) ``` G\,J\.+ - ",".join(alphabet)+"." 2c - split(^, size=2) / - split_sized(^, V) u - yield list [7,9,3,3] (actual bytes `u%04%07%09%03%03`) P - print(^) ``` [Answer] ## Brainfuck, 117 bytes ``` +[++[-<]-[->->]<]+++[->++>+++>+>+<<<<<--<<->>>]>+[[-<<<<<+.>-.+>.>>>]>[[-<+>]>]<<[<]<.>>]<<-[---<<<+.>-.+>.>]<<<+.>+. ``` The first four lines each have a trailing space, and the program assumes 8-bit cells. [Try it online!](http://brainfuck.tryitonline.net/#code=K1srK1stPF0tWy0-LT5dPF0rKytbLT4rKz4rKys-Kz4rPDw8PDwtLTw8LT4-Pl0-K1tbLTw8PDw8Ky4-LS4rPi4-Pj5dPltbLTwrPl0-XTw8WzxdPC4-Pl08PC1bLS0tPDw8Ky4-LS4rPi4-XTw8PCsuPisu&input=) (Handling the last line is tricky...) [Answer] # Vim, 32 bytes `26o<C-V><C-V>64,<Esc>r.V{g<C-A>8Jj9Jj3Jj.j4JcH<C-R>"` Leaves a blank line at the end, which was allowed, but it's weird being this clumsy. Even worse, I'm ending in insert mode. I've seen some other folks do it here, so I guess it's allowed? It feels dirty. * `26o<C-V><C-V>64,<Esc>`: The first `<C-V>` makes the second one insert literally. The `<C-V>64`s this leaves in the buffer will be turned into ASCII code points, then into letters. Commas already in. * `r.`: Never going to be at the end again, so do the `.` now. * `V{g<C-A>`: Uses visual increment to turn all the `64`s into the ASCII code points of the capital letters. * `8Jj9Jj3Jj.j4J`: The arbitrary line joins. First one is `8J` instead of `7J` because we're dealing with the blank line. The repeated `3J`s are eligible for a dot repeat. * `cH<C-R>"`: People usually think of `i<C-R>` as an insert mode paste, but it's more like an insert mode macro. Stuff like `<C-V>65` will run as if typed, and interpreted as a decimal code point. This leaves an extra (allowed) line at the end, and stays in insert mode. [Answer] ## JavaScript (ES6), ~~80~~ 74 bytes ``` _=>[...`ABCDEFGHIJKLMNOPQRSTUVWXYZ`].join`, `.replace(/[HQTW]/g,` $&`)+`.` ``` Probably possible to shorten this with atob/btoa if you can work out how to use ISO-8859-1 encoding. Edit: Saved 6 bytes thanks to @RickHitchcock. [Answer] ## CJam, 26 bytes ``` 'A79333Ab{{',S2$)}*N\}/'.@ ``` [Online interpreter](http://cjam.aditsu.net/#code='A79333Ab%7B%7B'%2CS2%24%29%7D*N%5C%7D%2F'.%40) ``` 'A Push 'A' 79333Ab Push [7 9 3 3 3] { }/ For each number n in the previous array... { }* Execute n times... ',S Push a comma and a space 2$) Copy last letter and increment N\ Place a newline under the letter on top '.@ Push '.' and rotate ``` [Answer] ## Perl, 37 bytes *Credits to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) for this solution (3 bytes shorter than mine, see bellow).* ``` say+(map"$_, ".$/x/[GPSV]/,A..Y),"Z." ``` Run with `-E` (or `-M5.010`) flag : ``` perl -E 'say+(map"$_, ".$/x/[GPSV]/,A..Y),"Z."' ``` My previous version, 3 bytes longer (total of 40 bytes) : ``` perl -E '$_=join", ",A..Z;s/[HQTW]/\n$&/g;say"$_."' ``` [Answer] # R, ~~83~~ 71 bytes ``` a=rbind(LETTERS[-26],","," ");a[3,7+3*c(0,3:5)]="\n";cat(a,"Z.",sep="") ``` [Try it online!](https://tio.run/##K/r/P9G2KCkzL0XDxzUkxDUoOFrXyCxWRwkEFZQ0rROjjXXMtY21kjUMdIytTDVjbZVi8pSskxNLNBJ1lKL0lHSKUwtslZQ0//8HAA "R – Try It Online") Makes a matrix of 3 rows (one with the letters, one with the commas and the other with either a space or a newline). **Edit**: Thanks Billywob! [Answer] # Brainfuck, 157 bytes ``` +++++[>+>+++<<-]>>[->+>++++>+++>++<<<<]>----->+++++.>-.>++.<<<<<+[->>>+.>.>.<<<<<]+++++++++>>.<<[->>>+.>.>.<<<<<]<---[+>+++>>.<<[->>>+.>.>.<<<<<]<]>>>>+.>++. ``` [Try it online](http://brainfuck.tryitonline.net/#code=KysrKytbPis-KysrPDwtXT4-Wy0-Kz4rKysrPisrKz4rKzw8PDxdPi0tLS0tPisrKysrLj4tLj4rKy48PDw8PCtbLT4-PisuPi4-Ljw8PDw8XSsrKysrKysrKz4-Ljw8Wy0-Pj4rLj4uPi48PDw8PF08LS0tWys-KysrPj4uPDxbLT4-PisuPi4-Ljw8PDw8XTxdPj4-PisuPisrLg&input=) [Answer] # JavaScript (ES6), ~~66~~ ~~64~~ 60 bytes ``` _=>`ABCDEFG HIJKLMNOP QRS TUV WXY`.replace(/./g,"$&, ")+"Z." ``` Regex matches the characters but not the carriage returns, so, using regex replace, I can add the ", " to each character. Edit: Removed 2 characters thanks to ETHProductions Edit: Changed from CRLF to LF, thanks @Olivier Grégoire [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes ``` n\,Ẋ7933fẇ⁋Ṫ\.+ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJuXFws4bqKNzkzM2bhuofigYvhuapcXC4rIiwiIiwiIl0=) -2 thanks to lyxal. -1 thanks to ffseq ``` n # Uppercase alphabet Ẋ # Each prepended to \, # "," ẇ # Cut into chunks of lengths 7933f # Digits of 7933 (+ rest, which is 4) ⁋ # Join by newlines Ṫ # Remove the last character \.+ # Append a dot ``` [Answer] # Cheddar, 70 bytes ``` ->[65@"71,72@"80,"QRS","TUV","WXYZ"].map(@.chars.join(", ")).vfuse+'.' ``` Looks like it's not getting shorter than this. I've made other versions of this which use quite interesting methods but this is shortest [Try it online!](http://cheddar.tryitonline.net/#code=LT5bNjVAIjcxLDcyQCI4MCwiUVJTIiwiVFVWIiwiV1hZWiJdLm1hcChALmNoYXJzLmpvaW4oIiwgIikpLnZmdXNlKycuJw&input=) ## Explanation ``` -> // Function with no arguments [ // Array, each item represents a line 65@"71, // See below on what @" does 72@"80, "QRS", "TUV", "WXYZ" ].map( // On each item... @.chars.join(", ") // Join the characters on ", " ).vfuse // Vertical fuse or join by newlines + '.' // The period at the end ``` --- The `@"` operator is used to generate string ranged. It generates a string starting from the left char code to the right char code. For example, `65` is the char code for `A` and `90` for `Z`. Doing `65 @" 90` would generate A through Z or the alphabet. [Answer] # MATL, ~~38~~ 29 bytes *9 bytes saved thanks to @Luis!* ``` 1Y2X{', '&Zc46h1[CEII]I*11hY{ ``` [**Try it Online!**](http://matl.tryitonline.net/#code=MVkyWHsnLCAnJlpjNDZoMVtDRUlJXUkqMTFoWXs&input=) **Explanation** ``` 1Y2 % Push the upper-case alphabet to the stack X{ % Break the character array into a cell array (similar to a list) % where each element is a letter ', '&Zc % Combine back into a string with ', ' between each element 46h % Append '.' (via ASCII code) to the end of the string 1 % Push the number 1 [CEII] % Push the array: [7, 9, 3, 3] I* % Multiply this array by 3: [21, 27, 9, 9] llh % Append an 11 to this array: [21, 27, 9, 9, 11] Y{ % Break our comma-separated list of characters into groups of this size % Implicitly display the result ``` [Answer] ## C, ~~112~~ ~~102~~ 81 bytes Thanks to cleblanc & LevelRiverSt! ``` i,c;main(){for(c=64;++c<91;)printf("%c%c%c",c,44+c/90*2,c=="‌​GPSVZ"[i]?++i,10:32)‌​;} ``` [Answer] # Japt, 24 bytes ``` ;B¬qJ+S r"[HQTW]"@R+XÃ+L ``` [Test it online!](http://ethproductions.github.io/japt/?v=master&code=O0KscUorUyByIltIUVRXXSJAUitYwytM&input=) ### How it works ``` ; // Reset various variables. B is set to "ABC...XYZ", J is set to ",", and L is set to ".". B¬ // Take the uppercase alphabet and split into chars. qJ+S // Join with ", ". r"[HQTW]" // Replace each H, Q, T, or W with @R+Xà // a newline plus the character. +L // Append a period to the result. // Implicit: output last expression ``` [Answer] # Ruby, ~~56~~ 54 bytes ``` $><<(?A..?Y).map{|c|c+('GPSV'[c]?", ":", ")}.join+"Z." ``` The first line ends with a literal newline. **Edit:** saved two bytes by replacing `'A'..'Y'` with `?A..?Y`. [Answer] # Java, ~~116~~ ~~109~~ ~~105~~ 104 ``` String f(){String s="";for(char c=65;c<91;)s=s+c+(c>89?46:',')+("GPSV".indexOf(c++)<0?' ':10);return s;} ``` Ungolfed: ``` String f() { String s = ""; for (char c = 65; c < 91;) { s = s + c + (c > 89 ? 46 : ',') + ("GPSV".indexOf(c++) < 0 ? ' ' : 10); } return s; } ``` [Answer] # q, 46 bytes ``` -1@'(", "sv/:0 7 16 19 22_,:'[.Q.A]),'",,,,."; ``` [Answer] ## PowerShell v3+, ~~60~~ ~~78~~ 67 bytes ``` -join(65..90|%{[char]$_+'.,'[$_-le89]+" "+"`n"*($_-in71,80,83,86)}) ``` OK. I've actually read, understood, and followed the spec this time. Promise. :D Takes the array `65..90` and loops over each element `|%{...}`. Each iteration, we're constructing a new string using concatenation, indexing, and multiplication. First, we take the current number and `char` cast it to make it an ASCII letter. That's concatenated with another char, based on indexing into the string `'.,'` whether we're at `90` or not (i.e., to account for `Z.` while having all the rest be commas). That's string concatenated with `" "` to space-separate the letters, and string multiplication of `"`n"` based on Boolean value for whether the current element is `-in` the specified array (i.e., whether we need to concatenate on a newline character). The resulting string is left on the pipeline. Those strings are encapsulated in parens, and `-join`ed together into a new string, which is then also left on the pipeline and implicit `Write-Output` at the end prints the result. Since we have ``n` in the string, it's automatically converted to newlines upon printing. Requires v3+ for the `-in` operator. Has a trailing space on each line, which is OK per the challenge specs. ### Example ``` PS C:\Tools\Scripts\golfing> .\now-i-know-my-abc.ps1 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. ``` [Answer] # PHP, 62 Bytes ``` <?=preg_filter("# ([HQTW])#","\n$1",join(", ",range(A,Z)));?>. ``` only for comparison 87 Bytes ``` <?="A, B, C, D, E, F, G,\nH, I, J, K, L, M, N, O, P,\nQ, R, S,\nT, U, V,\nW, X, Y, Z."; ``` [Answer] # Pyth, 25 bytes ``` +Pjmj\ dc*G\,j94092 23)\. ``` A program that prints the result to STDOUT. [Try it online](http://pyth.herokuapp.com/?code=%2BPjmj%5C+dc%2aG%5C%2Cj94092+23%29%5C.&debug=0) **How it works** ``` +Pjmj\ dc*G\,j94092 23)\. Program. Input: none G Yield string literal'abcdefghijklmnopqrstuvwxyz' * \, Cartesian product of that with ',', yielding a list of characters with appended commas j94092 23) Yield the integer 94092 in base-23, giving [7, 16, 19, 22] c Split the comma-appended character list at those indices mj\ Join each element of that on spaces j Join that on newlines P All but the last element of that, removing trailing ',' + \. Append '.' Implicitly print ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 19 bytes 18 bytes of code, +1 for the `-n` flag. Outputs in lowercase. ``` (zJk).'.^@A*"?09B" ``` The `?` represents a non-printing character, ASCII code 21. [Try it online!](http://pip.tryitonline.net/#code=KHpKaykuJy5eQEEqIhUwOUIi&input=&args=LW4) ### Explanation ``` z Lowercase alphabet Jk Join on ", " ( ).'. Append a period A*"?09B" Map ascval() over that string, results in list: [21 48 57 66] ^@ Split at those indices Join on newline and print (implicit, -n flag) ``` [Answer] ## R, 146 bytes ``` L=LETTERS f=function(x,y=""){paste(x,collapse=paste0(", ",y))} cat(f(c(f(L[1:7]),f(L[8:16]),f(L[17:19]),f(L[20:22]),f(L[23:26])),"\n"),".",sep="") ``` **Explanation:** `LETTERS` is predefined for uppercase letters. The `f` function is for concatenating vector x on `,` with additional `y` (used for newlines). The cat is the used as it prints `\n` as newlines. `f` is called on the letters to form rows and then on the rows again to form the whole output. *Probably golfable - I don't like the multiple calls of f...* [Answer] # CJam, 31 bytes ``` '[,65>", "*7933Ab{3*/(\:+}%N*'. ``` Explanation: ``` '[,65> push uppercase alphabet ", "* ", " between all letters 7933Ab push [7 9 3 3] {3*/(\:+}% slices of lengths 21, 27, 9, 9 N*'. join slices with newlines, add final "." ``` [Try it online](http://cjam.tryitonline.net/#code=J1ssNjU-IiwgIio3OTMzQWJ7MyovKFw6K30lTionLg&input=) [Answer] # Julia, 71 bytes ``` f()=join(join.(['A':'G','H':'P',"QRS","TUV","WXYZ"],[", "]),",\n")*"." ``` Requires 0.5 or better for broadcasting `.()` ]
[Question] [ Based on the [Duct tape can fix anything](https://codegolf.stackexchange.com/questions/26778/duct-tape-can-fix-anything) question, that was too broad, with very similar rules. Only this time the objective is very specific: # The challenge Your mission is to make a program that displays `hello mom` -- without ever writing a single line of code. You can only use code which is already written for you, both in questions and answers from StackOverflow. All you can do is duct tape it all together the best you can. And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated. --- # Rules 1. You must include links to the questions/answers you used in your answer. 2. You *may not* modify the code you find, with the following exceptions: a. You may rename variables, functions, and methods. (This doesn't mean you can change a method *invocation*, by changing, say `scanner.nextInt()` to `scanner.nextLine()` and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.). *The solution should still work if variables, functions or methods would be renamed again, so renaming code to contain `hello mom` as a variable name does not count.* b. You may adjust indentation appropriately. c. You can assume that the proper modules are loaded for the code snippets to work. (e.g., `import` statements for Java and Python, `using` statements for C# and C++, and their equivalents in all languages) If the code snippet includes the `import`s for you, you can move them to the top of the code. d. If the language requires the code to be in some kind of method body to execute (e.g., `public static void main(String[] args)` for Java, `static int Main(string[] args)` for C#, and so on), you can wrap your code in the appropriate method. But the *contents* of that main method must remain unmodified. 3. You must supply an explicit list of any variable/method/function/class rename-ings performed. 4. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing) 5. Provide a brief description of what the code does for people who aren't intimate with the language you're using. 6. You must use snippets posted before this challenge was started. 7. Popularity contest, so the most upvotes wins! # Deadline I will accept the the submission that has the most votes around the end of mothersday (midnight of the UTC-11 timezone), but later submissions can still get votes. [Answer] # Brainfuck Oh god why did I do this to myself? It is actually possible to find each BF symbol by itself as a code snippet in some answer somewhere. The interesting bit was piecing together bits of other people's code, each representing a block of BF instructions. Unfortunately there are basically no unmatched `[` and `]` symbols out there, so I had to cheat a bit for those, and I had to get an awful lot of mileage out of a funky Haskell snippet which had a bunch of pluses in it. There are probably others out there. Beyond that, here's some Frankensteined code: ``` byte x = 1; byte y = 2; byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte' addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} [ int a = (b > 10) ? some_value : another_value; addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} int a = (b > 10) ? c : d; byte x = 1; byte y = 2; byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte' addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} ?"<<-" ] exec >{space}> (command) byte z = (int) x + (int) y; addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} find . -type f -print -exec cat {} \; git reset . byte x = 1; byte y = 2; byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte' addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} System.out.print("B"); addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} fatal: Failed to resolve 'HEAD' as a valid ref. while read p; do echo $p done < $filename static HMODULE hMod = NULL; static bool once = false; if (!once++) hMod = LoadLibrary("xxx"); if (originalValue.length > size) { static HMODULE hMod = NULL; static bool once = true; if (once--) hMod = LoadLibrary("xxx"); $ cd /usr/local/wherever $ grep timmy accounts.txt addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} ls -ld $(find .) git commit --amend -m "New commit message" wget -q -O - $line git rebase --interactive $parent_of_flawed_commit find . -type f -user 'user1' -maxdepth 1 ``` And, since my mother is British, the output is quite simply `hello mum` # Bibliography: <https://stackoverflow.com/questions/17845014/what-does-the-regex-mean> `[` and `]`, with apologies <https://stackoverflow.com/a/21460161/2581168> ``` find . -type f -print -exec cat {} \; ``` <https://stackoverflow.com/questions/6161328/what-exactly-does-this-do-exec-command> ``` exec >{space}> (command) ``` <https://stackoverflow.com/questions/20130538/what-is-in-haskell> ``` addop = do {symb "+"; return Op Add} +++ do {symb "-"; return Op Sub} ``` <https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing> ``` System.out.print("B"); ``` <https://stackoverflow.com/questions/941584/byte-byte-int-why> ``` byte x = 1; byte y = 2; byte z = x + y; // ERROR: Cannot implicitly convert type 'int' to 'byte' ``` <https://stackoverflow.com/a/160295/2581168> ``` int a = (b > 10) ? c : d; ``` And ``` int a = (b > 10) ? some_value : another_value; ``` <https://stackoverflow.com/questions/13273002/what-does-mean-in-r> ``` ?"<<-" ``` <https://stackoverflow.com/questions/3450420/bool-operator-and> ``` static HMODULE hMod = NULL; static bool once = false; if (!once++) hMod = LoadLibrary("xxx"); ``` And ``` static HMODULE hMod = NULL; static bool once = false; if (!once--) hMod = LoadLibrary("xxx"); ``` <https://stackoverflow.com/questions/22776085/in-which-case-will-size-originalvalue-length-in-string-constructor-string> ``` if (originalValue.length > size) { ``` <https://stackoverflow.com/questions/3797795/does-mean-stdout-in-bash> ``` wget -q -O - $line ``` <https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git/179147#179147> ``` git commit --amend -m "New commit message" ``` And ``` git rebase --interactive $parent_of_flawed_commit ``` <https://stackoverflow.com/questions/14763413/grep-ls-output-across-tabs/14763499#14763499> ``` find . -type f -user 'user1' -maxdepth 1 ``` <https://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history> ``` $ cd /usr/local/wherever $ grep timmy accounts.txt ``` <https://stackoverflow.com/questions/348170/undo-git-add-before-commit/682343#682343> ``` fatal: Failed to resolve 'HEAD' as a valid ref. ``` [Answer] # Java Start with these: <https://stackoverflow.com/a/19509316/1768232> ``` String myStr = "hello"; String myStr1 = "hello"; ``` <https://stackoverflow.com/a/8341513/1768232> ``` String[] history = new String[] { "hey", "you", "Mom" }; ``` <https://stackoverflow.com/a/23300004/1768232> ``` String editednames = titleCase(name); ``` <https://stackoverflow.com/a/20698093/1768232> ``` myString = myString.toLowerCase(); ``` <https://stackoverflow.com/a/19393222/1768232> ``` System.out.println(Name + " " + Income); ``` <https://stackoverflow.com/a/1181979/1768232> ``` public static <T> T last(T[] array) { return array[array.length - 1]; } ``` Add the required `class` and `public static void main(String[] args){ }` as allowed in Rule #2d (not around the static method), and change some variable / method names in exactly 3 of 6 snippets: * Change `name` -> `history` in the third snippet * Change `editednames` -> `myString` in the third snippet * Change `Name` -> `myStr` in the fifth snippet * Change `Income` -> `myString` in the fifth snippet * Change `last` -> `titleCase` in the sixth snippet Resulting program: ``` public class DuctTape { public static void main(String[] args) { // https://stackoverflow.com/a/19509316/1768232 String myStr = "hello"; String myStr1 = "hello"; // https://stackoverflow.com/a/8341513/1768232 String[] history = new String[] { "hey", "you", "Mom" }; // https://stackoverflow.com/a/23300004/1768232 String myString = titleCase(history); // https://stackoverflow.com/a/20698093/1768232 myString = myString.toLowerCase(); // https://stackoverflow.com/a/19393222/1768232 System.out.println(myStr + " " + myString); } // https://stackoverflow.com/a/1181979/1768232 public static <T> T titleCase(T[] array) { return array[array.length - 1]; } } ``` Output: ``` hello mom ``` [Answer] # C# Possibly crazy, roundabout, and convoluted way to get to the (exact) result - with only variable renames and without any literal "mom" in any of the code. Reading the "if you take a code block from a post, you take the whole thing" rule very literally probably didn't help - but made it more fun. ``` using System; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; public class Program { void Main() { // Step 1 var n = 3; var helloAndGoodbye = "12345678900" .Select((c, i) => new { letter = c, group = i / n }) .GroupBy(l => l.group, l => l.letter) .Select(g => string.Join("", g)) .ToList(); // Step 2 string place = "world"; string greet = String.Format("Hello {0}!", place); // Step 3 byte[] b1 = System.Text.Encoding.UTF8.GetBytes (greet); byte[] b2 = System.Text.Encoding.ASCII.GetBytes (greet); // Step 4 string encryptionKey = "test"; var md5 = MD5.Create(); var keyBytes = Encoding.UTF8.GetBytes(encryptionKey); byte[] encryptionKeyBytes = md5.ComputeHash(keyBytes); // Step 5 string strName = md5.GetType().Name; if(strName == "Person") { //My Code } // Step 6 string HashAlgorithm = new string(strName.Take(n).ToArray()); // Step 7 int previousYear = DateTime.Now.AddYears(-1).Year; // Step 8 string myString = previousYear.ToString(); // Step 9 string totallyRandomString = new string(myString.Take(n).ToArray()); // Step 10 int myInt = System.Convert.ToInt32(totallyRandomString); // Step 11 int x = myInt << 1 + 1; // Step 12 PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(place, b1, HashAlgorithm, x); byte[] KeyBytes = DerivedPassword.GetBytes(32); // Step 13 string base64 = Convert.ToBase64String(KeyBytes); byte[] bytes = Convert.FromBase64String(base64); // Step 14 var split = base64.Split('/'); var last = split[split.Length -1]; var prev = split[split.Length -2]; // Step 15 string truncatedToNLength = new string(last.Take(n).ToArray()); // Step 16 Regex rgx = new Regex("[^a-zA-Z0-9 -]"); greet = rgx.Replace(greet, ""); // Step 17 var newString = greet.Replace(place.ToString(), truncatedToNLength); // Step 18 var searchStr = newString.ToLower(); searchStr = searchStr.Trim(); // Step 19 Console.WriteLine(searchStr); } } ``` ### .NET Fiddle <http://dotnetfiddle.net/PbjhPn> <http://dotnetfiddle.net/bg20wb> (with redundant lines in code blocks removed) ### Short explanation Basically, we get "Hello world!" from a simple string format. Now we need "mom" to replace it. For that, we use the Base64 encoded result of running 804 iterations of PBKDF1 using MD5 with "world" as password and "Hello world!" as salt. That yields a string "ciSf5cCls1l/**MoM**...". We extract that "MoM" and use it as a replacement for "world". Then we clean up the string. How do we get to 804? The previous year clipped to three characters (= "201"), and then multiplied by 4. ### Long explanation and attributions **1:** We start with a bit of rule-following overkill. The integer 3 is a very very important constant in this program. Here we assign that integer to `n`. We must include the entire block from the source. It may be redundant, but it will compile just fine, as long as we rename the `split` variable that we'll be needing later. [Source](https://stackoverflow.com/a/4133512/1169696) Replaced variable names: ``` split > helloAndGoodbye ``` **2:** Set up starting string ("Hello world!"). [Source](https://stackoverflow.com/a/7077/1169696) This is a very personal message to our mom. So we obviously need some cryptography to deal with those NSA types. For that, we'll need some parameters, which we prepare now. **3:** Convert `greet` ("Hello world!") to byte array for salting. [Source](https://stackoverflow.com/a/472918/1169696) ``` myString > greet ``` **4:** Although we're using cryptography, we don't actually need to instantiate the MD5 class. We do, however, need the string "MD5" assigned for one of our parameters to be used further down - and that's not easy to find in usable code. So we'll take another... "shortcut"... Once again, entire code block included as per rules, although we only need the second line. [Source](https://stackoverflow.com/questions/11038954) **5:** Now we need the name of the type of the `md5` variable (`MD5CryptoServiceProvider`). The `if` is yet another redundancy. [Source](https://stackoverflow.com/questions/8207447) ``` entity > md5 ``` **6:** Get the first 3 (ooh, there's our constant!) characters of the type name. [Source](https://stackoverflow.com/a/3566852/1169696) ``` s > strName truncatedToNLength > HashAlgorithm ``` **7:** Code-trolling: Using `DateTime.Now` would mean this would only work until 2019. To make it a bit more future proof, we use the previous year. Then it will work until 2020 ;-)[Source](https://stackoverflow.com/a/13122370/1169696) **8:** Convert our `previousYear` to string. [Source](https://stackoverflow.com/a/3081919/1169696) ``` myInt > previousYear ``` **9:** Hey, code reuse! ;-) Get the first 3 (our constant!) characters of our year. [Source](https://stackoverflow.com/a/3566852/1169696) ``` s > myString truncatedToNLength > totallyRandomString ``` **10:** Aaaaaaaand... convert the result back to integer. [Source](https://stackoverflow.com/a/2344421/1169696) ``` myString > totallyRandomString ``` **11:** Eric Lippert makes every answer better. Multiply by 4 in a roundabout way. [Source](https://stackoverflow.com/a/3060658/1169696) ``` y > myInt ``` **12:** Send `place` (password) and `greet` (salt) through PBKDF1 using MD5 with `x` (which is now `201*4 = 804`) iterations. [Source](https://stackoverflow.com/questions/9231754) ``` Password > place SaltValueBytes > b1 PasswordIterations > x ``` **13:** Jon Skeet also makes every answer better. Convert our derived password to base 64. We throw out the `bytes` array. [Source](https://stackoverflow.com/a/1134696/1169696) ``` bytes (first occurrence) > KeyBytes ``` **14:** What a crazy random happenstance! We now have a `base64` with "MoM" in it. Conveniently, right before "MoM" is a single '/'. So split the string with that character as delimiter: [Source](https://stackoverflow.com/a/10387374/1169696) ``` filePath > base64 ``` **15:** Hey, our favorite piece of code reuse tape! Get the first 3 (constant!) letters of `last`. [Source](https://stackoverflow.com/a/3566852/1169696) ``` s > last ``` **16:** Remove "!". [Source](https://stackoverflow.com/a/3210410/1169696) ``` str > greet ``` **17:** MoM is our world - so make the string reflect that (replace "world" with "MoM"). [Source](https://stackoverflow.com/a/1948984/1169696) ``` someTestString > greet someID > place sessionID > truncatedToNLength ``` **18:** Finally, convert to lower case. Trim for good measure (or possibly because it's part of the duct tape block). [Source](https://stackoverflow.com/questions/5303231) ``` wordToSearchReplacemntsFor > newString ``` **19:** Output to console. [Source](https://stackoverflow.com/questions/8695946) ``` _surface > searchStr ``` ### A bit of "bonus material"/commentary * At first I tried every combination of built-in cryptographic hashes (each combined with HMAC) and inputs ("world", "Hello world!", "Hello world", "hello world" etc.) to see if something would miraculously give a usable output to derive "mom" from - before taking the easy route of just looking for a number of iterations of PDKDB1 (or 2) that would be useful. * Wasn't quite happy with the use of the year as input for the 201\*4 = 804 iterations. At first I tried to find some useful code for `HttpStatusCode.Created` (201) to use as input - with a "troll excuse" along the lines of "we've created our 'Hello world!' string, so a good practice would be to use a 'Created' status code" here. Unfortunately, I never found a usage of the `HttpStatusCode` enumeration that didn't introduce a dependency on most of the ASP.NET WebAPI framework. * The start of the code (the "Hello world!" string format) was never looked at again after I first added it. If I had, yeah, I might have realized that the assignment of `place` was actually in a different block in the source - so I could have simply assigned my derived "mom" to `place` rather than using "world" and later replacing it. Ah well. [Answer] # Befunge 98 * [`var abc = function(){};`](https://stackoverflow.com/a/338053/1896169) * [`display: table-*`](https://stackoverflow.com/a/1030017/1896169) * [`+`](https://stackoverflow.com/a/7124907/1896169) * [`, new {area = ""}`](https://stackoverflow.com/q/2270861/1896169) * [`byte z = x + y;`](https://stackoverflow.com/a/941665/1896169) * [`"1,23,4"`](https://stackoverflow.com/q/7124884/1896169) * [`String[] temp = data.split("\\s+\\^,?\"'\\|+");`](https://stackoverflow.com/q/23561872/1896169) * [`List<Set<Integer>> foo;`](https://stackoverflow.com/q/23448156/1896169) * [`: base(name)`](https://stackoverflow.com/q/10605798/1896169) * [`10001.10010110011`](https://stackoverflow.com/a/618596/1896169) * [`[5326, 4223, 1204]`](https://stackoverflow.com/q/23557240/1896169) * <https://stackoverflow.com/q/23044400/1896169> ``` Runnable prs = new Runnable() { public void run() { Document doc = null; try { doc = Jsoup.connect("http://play.radio.com/").get(); } catch (IOException e) { e.printStackTrace(); } parser.postDelayed(prs, 10000); } }; ``` * [`$selector.append("somestuff");`](https://stackoverflow.com/q/1180213/1896169) * [`-new Date().getTimezoneOffset()/60;`](https://stackoverflow.com/a/1809974/1896169) * <https://stackoverflow.com/a/8928476/1896169> ``` [0000] push ebp [0001] mov ebp,esp [0003] push edi [0004] push esi [0005] push ebx [0006] sub esp,1Ch [0009] xor eax,eax [000b] mov dword ptr [ebp-20h],eax [000e] mov dword ptr [ebp-1Ch],eax [0011] mov dword ptr [ebp-18h],eax [0014] mov dword ptr [ebp-14h],eax [0017] xor eax,eax [0019] mov dword ptr [ebp-18h],eax *[001c] mov esi,1 [0021] xor edi,edi [0023] mov dword ptr [ebp-28h],1 [002a] mov dword ptr [ebp-24h],0 [0031] inc ecx [0032] mov ebx,2 [0037] cmp ecx,2 [003a] jle 00000024 [003c] mov eax,esi [003e] mov edx,edi [0040] mov esi,dword ptr [ebp-28h] [0043] mov edi,dword ptr [ebp-24h] [0046] add eax,dword ptr [ebp-28h] [0049] adc edx,dword ptr [ebp-24h] [004c] mov dword ptr [ebp-28h],eax [004f] mov dword ptr [ebp-24h],edx [0052] inc ebx [0053] cmp ebx,ecx [0055] jl FFFFFFE7 [0057] jmp 00000007 [0059] call 64571ACB [005e] mov eax,dword ptr [ebp-28h] [0061] mov edx,dword ptr [ebp-24h] [0064] lea esp,[ebp-0Ch] [0067] pop ebx [0068] pop esi [0069] pop edi [006a] pop ebp [006b] ret ``` * <https://stackoverflow.com/q/23569160/1896169> ``` def logme(func): def wrapped(*args): for arg in args: print str(arg) func(*args) return wrapped @logme def my_func(*args): res = 1 for arg in args : print "Multiplying %s by %s" % (arg, res) res*=arg print res return res ``` My code: ``` var abc = function(){}; display: table-* display: table-* display: table-* display: table-* display: table-* display: table-* display: table-* display: table-* + + + + + + + , new {area = ""} byte z = x + y; byte z = x + y; byte z = x + y; byte z = x + y; byte z = x + y; byte z = x + y; byte z = x + y; byte z = x + y; display: table-* + + + + + + + + , new {area = ""} "1,23,4" String[] temp = data.split("\\s+\\^,?\"'\\|+"); List<Set<Integer>> foo; "1,23,4" + : base(name) : base(name) , new {area = ""} , new {area = ""} 10001.10010110011 10001.10010110011 10001.10010110011 + + + , new {area = ""} "1,23,4" String[] temp = data.split("\\s+\\^,?\"'\\|+"); "1,23,4" , new {area = ""} "1,23,4" [5326, 4223, 1204] Runnable prs = new Runnable() { public void run() { Document doc = null; try { doc = Jsoup.connect("http://play.radio.com/").get(); } catch (IOException e) { e.printStackTrace(); } parser.postDelayed(prs, 10000); } }; "1,23,4" $selector.append("somestuff"); $selector.append("somestuff"); -new Date().getTimezoneOffset()/60; : base(name) 10001.10010110011 10001.10010110011 10001.10010110011 + + + [0000] push ebp [0001] mov ebp,esp [0003] push edi [0004] push esi [0005] push ebx [0006] sub esp,1Ch [0009] xor eax,eax [000b] mov dword ptr [ebp-20h],eax [000e] mov dword ptr [ebp-1Ch],eax [0011] mov dword ptr [ebp-18h],eax [0014] mov dword ptr [ebp-14h],eax [0017] xor eax,eax [0019] mov dword ptr [ebp-18h],eax *[001c] mov esi,1 [0021] xor edi,edi [0023] mov dword ptr [ebp-28h],1 [002a] mov dword ptr [ebp-24h],0 [0031] inc ecx [0032] mov ebx,2 [0037] cmp ecx,2 [003a] jle 00000024 [003c] mov eax,esi [003e] mov edx,edi [0040] mov esi,dword ptr [ebp-28h] [0043] mov edi,dword ptr [ebp-24h] [0046] add eax,dword ptr [ebp-28h] [0049] adc edx,dword ptr [ebp-24h] [004c] mov dword ptr [ebp-28h],eax [004f] mov dword ptr [ebp-24h],edx [0052] inc ebx [0053] cmp ebx,ecx [0055] jl FFFFFFE7 [0057] jmp 00000007 [0059] call 64571ACB [005e] mov eax,dword ptr [ebp-28h] [0061] mov edx,dword ptr [ebp-24h] [0064] lea esp,[ebp-0Ch] [0067] pop ebx [0068] pop esi [0069] pop edi [006a] pop ebp [006b] ret 10001.10010110011 + : base(name) , new {area = ""} "1,23,4" List<Set<Integer>> foo; "1,23,4" + 10001.10010110011 10001.10010110011 10001.10010110011 + + + , new {area = ""} , new {area = ""} def logme(func): def wrapped(*args): for arg in args: print str(arg) func(*args) return wrapped @logme def my_func(*args): res = 1 for arg in args : print "Multiplying %s by %s" % (arg, res) res*=arg print res return res ``` This works because the first `v` (in the first line) sends the IP downward. So we are basically executing this program: ``` dddddddd+++++++,bbbbbbbbd++++++++," L"+::,,111+++," ","[R }"$$-:111+++ * 1+:,"L "+111+++,,d @ ``` Which does this: * `dddddddd+++++++,` pushes `104` and prints * `bbbbbbbbd++++++++,` pushes `101` and prints * `" L"+,` pushes `32` and the ascii value of `L`, then adds them, duplicates twice, and prints twice * To the one that was duplicated, `111+++,` adds 3 and prints * `" ",` prints a space. `"[R }"$$-:111+++` pushes a `9` and duplicates it, then adds 3 to the top value * `*` multiplies the top two values * `1+:,` increments that number, duplicates, and prints * `"L "+111+++,` prints `o`. `,` prints the `m` from earlier, and `d @` pushes `13` (which does nothing) and ends the program. [Answer] # Java ``` import java.util.*; public class HelloMom { public static void main(String[] args) { Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("Answer", "42"); ht.put("Hello", "World"); // First value association for "Hello" key. ht.put("Hello", "Mom"); // Second value association for "Hello" key. for (Map.Entry<String, String> e : ht.entrySet()) { System.out.println(e); } } } ``` # Output ``` Answer=42 Hello=Mom ``` There is a pesky = in there, but this is the best I could do <https://stackoverflow.com/a/1050075/573421> [Answer] # C Most of this code comes from an answer to [Find the beginning of the first word that is a palindrom](https://stackoverflow.com/a/11685575/1679849) [sic] posted by [BLUEPIXY](https://stackoverflow.com/users/971127), which outputs the word `mom`. At lines 21 and 22, the `hello` is printed by a code snippet at the end of an answer to [printf(“%%%s”,“hello”)](https://stackoverflow.com/q/5436777/1679849) by user142019 (who fortunately added a semicolon at the end), and the space between the words comes from an answer to [How to print space with padding in c](https://stackoverflow.com/a/21360942/1679849) by [M Oehm](https://stackoverflow.com/users/2979617). ### Output: ``` %hello mom ``` I wasn't able to eliminate the extra spaces or the percent character, unfortunately :( ### Source code: ``` #include <stdio.h> #include <stdlib.h> #include <string.h> int isPalindrome(const char *str){ const char *front, *back; front=str; back =str + strlen(str)-1; for(;front<back;++front,--back){ while(!isalpha(*front))++front;//isalnum? while(!isalpha(*back))--back; if(front > back || tolower(*front)!=tolower(*back)) return 0; } return 1; } int main(){ const char *data="Hello mom and dad, how is it going?"; char *p, *src; printf("%%%s", "hello"); printf(" "); p=src=strdup(data); for(;NULL!=(p=strtok(p, " \t\n,.!?"));p=NULL){ if(isPalindrome(p)){ printf("%s\n", p); break; } } free(src); return 0; } ``` [Answer] # Java ``` import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Random; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author LH */ public class Kopierpaste { //https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world //randomizer code for the first String public static String randomString(int i) { Random ran = new Random(i); StringBuilder sb = new StringBuilder(); for (int n = 0;; n++) { int k = ran.nextInt(27); if (k == 0) { break; } sb.append((char) ('`' + k)); } return sb.toString(); } public static void main(String[] nope) { //catching a System.out() based code snippet //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java ByteArrayOutputStream baos = new ByteArrayOutputStream(); System.setOut(new PrintStream(baos)); //same as randomizer //getting hello, world inside a ByteArray System.out.println(randomString(-229985452) + " " + randomString(-147909649)); //undo the redirecct of System.out() //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java && https://stackoverflow.com/a/14716148/1405227 System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); //stringify the out of first part //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java String text = baos.toString(); //getting rid of the world part //https://stackoverflow.com/a/17008136/1405227 String firstWord = text.substring(0, text.indexOf(' ')); //needing the word Mom //https://stackoverflow.com/a/8341513/1405227 //history -> a String[] a = new String[] { "hey", "you", "Mom" }; //stitching the array together in a certain fashion ([elem1, elem2, elem3] //https://stackoverflow.com/a/2822736/1405227 //myarray->a String b = Arrays.toString(a); //getting rid of the ,s //https://stackoverflow.com/a/7552284/1405227 stripping annoying bullcrap out //result ->c //yourString ->b String c = b.replaceAll("[-+.^:,]", ""); //getting the Mom] part //https://stackoverflow.com/a/15317037/1405227 //sentence -> c String lastToken = c.replaceAll(".* ", ""); //getting rid of more crap //https://stackoverflow.com/a/18599016/1405227 //message -> lastToken lastToken = lastToken.replaceAll("\\W", ""); //finally out //https://stackoverflow.com/a/19393222/1405227 //name -> firstWord //income -> lastToken System.out.println(firstWord + " " + lastToken); } } ``` Documentation and source links are in the comments ( starting with // ) clean list of sources used * <https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world> * <https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java> * <https://stackoverflow.com/a/14716148/1405227> * <https://stackoverflow.com/a/17008136/1405227> * <https://stackoverflow.com/a/2822736/1405227> * <https://stackoverflow.com/a/7552284/1405227> * <https://stackoverflow.com/a/15317037/1405227> * <https://stackoverflow.com/a/18599016/1405227> * <https://stackoverflow.com/a/19393222/1405227> ]
[Question] [ # 4-Man Standoff ## Description You've somehow found yourself into a four-way standoff. A loaded gun rests in your hands, and some grenades are hooked on your belt. The objective is to have the most health at the end of a standoff. A standoff is over when at most one person has a positive amount of health. Each player has `5` health, and dies when their health drops to/below `0`. The turn a player dies is the last turn that player can take damage. If there is a live player at the end of a standoff, that player wins. Otherwise, the player with the least negative health wins. ## Actions * **Shoot**: Take a shot at someone. + `2` damage if shooting a live enemy + `0` damage if shooting a dead enemy + `health_at_start_of_turn+2` damage if shooting yourself. (Note that this will leave you with at MOST `-2` health.) + If one enemy shoots at you on the same turn you shoot yourself, you will end the standoff with -4 health (you still take damage from other players the turn you kill yourself). + Your action the following turn will be ignored (and assumed to be `Nothing`). * **Dodge**: Try to dodge a single opponent's shot. * **Prepare**: Unhook your grenade and prepare to throw it. + You only have three turns to throw it, before you get blown up (`6` damage to yourself, `3` damage to all live enemies) + Dying with an unthrown grenade is equivalent to not throwing the grenade for three turns. * **Throw**: Chuck the grenade towards someone and hope for the best. + Target receives `8` damage if alive + Everyone else (including yourself) receives `3` damage if alive * **Nothing**: Stand idly for a turn and watch everyone die. ## Input Your program will be passed the following information: * The health of each player * A list of actions taken by that player since the start of the standoff Below is the format for the information passed per player: ``` [Health],[Action 1],[Action 2],[Action 3],... ``` Actions will be given in the format specified in the **Output** section. You will recieve 4 such strings, separated by a space, and passed as a single argument. The order of these strings is: ``` [Player Info] [Opponent 1 Info] [Opponent 2 Info] [Opponent 3 Info] ``` The strings are passed as the second argument. The first argument contains an integer that uniquely identifies the standoff being enacted. Standoffs between the same set of players are guaranteed not to be simultaneous. However, multiple standoffs *will* occur at the same time. For example: ``` $./Player.bash 5 "3,S2,N 5,P,N 3,S0,N -2,S3,N" ``` Currently, the player and the second opponent have 3 health, the first opponent has 5 health, and the third opponent has -2 health and is dead. On the first turn: * Player 1 shot enemy 2 * Enemy 1 prepared a grenade * Enemy 2 shot player * Enemy 3 shot himself On the second turn: * All players did nothing. (Player and enemy 2 can not do anything since they shot on the previous turn. Enemy 3 is dead: he will do `Nothing` for the rest of the standoff.) The second argument at the start of a standoff is: `5 5 5 5`. ## Output A command should be outputted in the below listed format. An invalid output is interpreted as 'Nothing'. A command requiring a target should be followed by an integer (`0-3`, with `0` representing the player, and `1-3` representing enemies 1-3). * `S[target]`: Shoots [target]. * `D[target]`: Tries to dodge [target]. * `P`: Prepare a grenade. * `T[target]`: Throw the grenade at [target]. * `N`: Do nothing. A command that needs a target, but is fed a target not between `0` and `3` or not fed a target entirely will be assumed to target `0` (the player). ## Scoring At the end of each standoff, players receive a score calculated by the following formula: ``` 35 + health at end of standoff ``` In the case that a player ends a standoff with negative health, they **will** receive a score **below 35**. The following points are also rewarded as a bonus: * Most health: +4 points * Second most health: +2 points * Third most health: +1 point. In case of a tie, the lower bonus is granted (if two people tie with most health, both are granted +2; if there are 3 people with the most health, +1, and if everyone ends equally, +0). The final score is determined by calculating the mean of all individual scores. ## Rules/Details * Order of events within a turn are as follows: + All players do their actions. + Players who have 0 or less health die. + Unthrown grenades that need to explode, will explode (players who just died are still hurt, as this is still the turn they died). * No collaboration between entries. * Three\* standoffs will occur between each set of 4 players. (Order of players may vary with each standoff). * Entries consuming excessive amounts of memory of disk space will be disqualified. * Reading from or modifying files other than your entry's will disqualify your entry. * A truck, driven by a drunkard, will run over all living players after the `50th` turn, if the standoff is not yet over at the end of the `50th` turn. + This truck deals **20** damage to all live players. * Standoffs happen quickly. Programs are cut off after 1 second. * Your program will be called every turn, even after you have died. * You may read or write files to your directory only (if your entry is named JohnDoe, you may save files in the directory players/JohnDoe/); however, this will NOT be the current directory while your script is running. * The standoffs will take place on a machine running Arch Linux (Release 2014.08.01). The controller is available on [GitHub](https://github.com/es1024/4-Man-Standoff-controller). Please include the following in your post: * A name for your bot * A shell command to run the bot (ex. `java Doe.java`) Input will be passed through the command line as a single argument (`java Doe.java 5 "-2,S0 -2,S1 -2,S2 5,N"`) * Code of your bot * How the bot should be compiled (if applicable) * Language (and version if applicable, especially for python) \*Controller is taking way too long for six. ## Scoreboard ``` Observer 43.280570409982 MuhammadAli 43.134861217214 Osama 43.031983702572 LateBoomer 42.560275019099 SimpleShooter 42.412885154062 LessSimpleShooter 42.3772 Neo 42.3738 Scared 42.3678 Richochet 42.3263 Equivocator 42.2833 TwentyFourthsAndAHalfCentury 42.2640 Darwin 42.1584 HanSolo 42.1025 Coward 42.0458 ManipulativeBastard 41.8948 Sadist 41.7232 Aggressor 41.7058 CourageTheDog 41.5629 Grenadier 40.9889 Bomberman 40.8840 Spock 40.8713 Sniper 40.6346 DONTNUKEMEBRO 39.8151 PriorityTargets 39.6126 Hippolyta 39.2480 EmoCowboy 39.2069 Zaenille 39.1971 AntiGrenadier 39.1919 PoliticallyCorrectGunman 39.1689 InputAnalyzer 39.1517 Rule0Bot 39.1000 BiasedOne 39.0664 Pacifist 39.0481 StraightShooter 39.0292 Ninja 38.7801 MAD 38.2543 Monkey 37.7089 Label1Goto1 36.2131 Generated: 2014/08/22 03:56:13.470264860 UTC ``` Logs: [on GitHub](https://github.com/es1024/4-Man-Standoff-controller/tree/master/build/results) [Answer] # Grenadier Guns are overrated. A *true* Scotsman's standoff goes like this: * Prepare * Throw at enemy with most health * Repeat (if by some miracle you're still alive) While this seems trivial, it's probably not a *terrible* strategy. Since guns and grenades both have a two-turn cycle, this is by far the more efficient1 way to deal damage. Of course, if all three opponents shoot me on the first round it's no good. But not much else would be, either. ``` public class Grenadier { public static void main(String[] args) { if(args.length < 2) return; String[] list = args[1].split(" "); if(list.length < 4) return; if(list[0].charAt(list[0].length()-1) != 'P'){ System.out.print("P"); return; } int target = 1; for(int i=2;i<4;i++) if(list[i].charAt(0)>list[target].charAt(0)) target = i; System.out.print("T"+target); } } ``` Compile/run in the standard Java way: ``` > javac Grenadier.java > java Grenadier arg0 arg1 ``` --- 1 Pointless footnote [Answer] ## Asimov's Rule Number 0 Bot - Python > > A robot may not harm humanity, or, by inaction, allow humanity to come > to harm. > > > Pretty straight forward, he'll attack the first player he sees holding a grenade in order to protect the majority of humans. If no one is a threat to the majority of humans, he'll do nothing. ``` import sys def total_humans_alive(humans): return sum([is_alive(human) for human in humans]) def is_alive(x): return int(x.split(",")[0]) > 0 def is_threat_to_humanity(lastAction): return lastAction == "P" action = "N" threat_id = 1 humans = sys.argv[2].split()[1:]; if total_humans_alive(humans) == 3: for human in humans: if is_threat_to_humanity(human[-1]): action = "S" + str(threat_id) break threat_id= threat_id+ 1 print action ``` Run it like: ``` python rule0bot.py ``` [Answer] ## Han Solo - Python Han shot first. In this case, he'll shoot first by picking the closest target alive. ``` import sys def is_alive(player): return int(player.split(",")[0]) > 0 closest_living_target = 1; for player in sys.argv[2].split()[1:]: if is_alive(player): action = "S" + str(closest_living_target) break closest_living_target = closest_living_target + 1 print action ``` Run it like: ``` python hansolo.py ``` **Note**: This is the first thing I ever wrote in Python, so if you see any python-specific bad practices, please let me know. [Answer] **EmoCowboy** Why wait to die? Just kill yourself now. Hopefully the rest of the fools will blow eachother up to much less than -2. Score will normally be -2. Sometimes -4 if people decide to shoot me off the bat. Rarely more than that, which means this should beat several of the current submissions. Python ``` print('S0') python EmoCowboy.py ``` EDIT: This isn't a joke, which is generally why these emo submissions are frowned upon. This is a legitimate strategy. Being alive is deadly! [Answer] # Pacifist He's a real swell guy, just got caught up with the wrong crowd. ``` main = putStr "N" ``` Run as `runghc pacifist.hs`, but you might want to compile it with -O3 if efficiency is an issue. [Answer] **Monkey** -- Python (First ever entry!) Monkey see, monkey do. Will repeat exactly the last action taken by a random player. ``` import sys, random targetData = sys.argv[2].split()[random.randint(0,3)] print(targetData.split(',')[len(targetData.split(','))-1]) ``` Can be run like this: "python monkey.py args" No extra steps required. [Answer] # Observer This guy analyses his enemies. The goal is to survive until only one "aggressive" opponent is left, and then kill that one in an epic standoff. Compile: `javac Observer.java` Run: `java Observer arg0 arg1` ``` import java.util.List; import java.util.ArrayList; import java.util.Random; class Observer { private static List<Integer> aggressiveEnemies = new ArrayList<>(); private static List<Integer> enemyGrenadiers = new ArrayList<>(); private static List<Integer> aliveEnemies = new ArrayList<>(); public static void main(String[] args) { if (args[1].length() <= 7) { //first round Random rand = new Random(); printResult("D" + (rand.nextInt(3) + 1)); } String players[] = args[1].split(" "); if (truckIsOnWay(players[0])) { printResult("P"); } calcEnemyInfo(players); // end this standoff now if (truckWillHit(players[0])) { if (isGrenadier(players[0])) printResult("T" + aliveEnemies.get(0)); else printResult("S0"); } // shoot enemy who is not aggressive if (aggressiveEnemies.size() == 0) { printResult("S" + aliveEnemies.get(0)); } // only one enemy to handle if (aggressiveEnemies.size() == 1) { String player = players[aggressiveEnemies.get(0)]; if (isGrenadier(player)) { printResult("S" + aggressiveEnemies.get(0)); } else if (shotLastTurn(player, aggressiveEnemies.get(0))) { //safe to shoot him without receiving damage printResult("S" + aggressiveEnemies.get(0)); } else { printResult("D" + aggressiveEnemies.get(0)); } } // multiple aggressive enemies if (enemyGrenadiers.size() > 0) { printResult("S" + enemyGrenadiers.get(0)); } else { int id = aggressiveEnemies.get(0); for (int playerId : aggressiveEnemies) { if (!shotLastTurn(players[playerId], playerId)) { id = playerId; } } printResult("D" + id); } } private static void printResult(String result) { System.out.print(result); System.exit(0); } private static boolean isAlive(String player) { return !(player.charAt(0) == '-' || player.charAt(0) == '0'); } private static void calcEnemyInfo(String[] players) { for (int i = 1; i < players.length; i++) { if (isAlive(players[i])) { aliveEnemies.add(i); if (isAggressive(players[i], i)) { aggressiveEnemies.add(i); } if (isGrenadier(players[i])) { enemyGrenadiers.add(i); } } } } private static boolean truckIsOnWay(String player) { return player.length() - player.replace(",", "").length() == 48; } private static boolean truckWillHit(String player) { return player.length() - player.replace(",", "").length() == 49; } private static boolean isAggressive(String player, int id) { return (player.contains("S") || player.contains("P")) && !player.contains("S" + id); } private static boolean isGrenadier(String player) { return player.contains("P"); } private static boolean shotLastTurn(String player, int id) { return player.charAt(player.length() - 2) == 'S' && !player.contains("S" + id); } } ``` [Answer] # Simple Shooter - Perl *(fixed bug)* This bot shoots at the opponent with the most health. It's a very simple strategy, but I think it has a decent chance of actually doing well. ``` @history = map([split(",",$_)],split(" ",$ARGV[1])); $target = 1; for(2..3){ if($history[$_][0] >= $history[$target][0]){$target = $_} } print "S$target" ``` This is how to run it using some example input: ``` perl simpleshooter.plx 7 "3,S2,N 5,P,N 3,S0,N -2,S3,N" ``` [Answer] # Spock, in Python 3.x This code is more of a though experiment (hence named after Spock because... he's a vulcan, and they're pretty good at these sort of things) but was fun building it nonetheless. The main reasoning behind all this code are assumptions a good, logical being, like Spock, would do, if given the game's rules: --- The objective of this game is to **maximize** score, which would be done by everyone just standing still, which isn't possible, due to the truck. * One of the directives Spock has to follow is to prevent the truck from appearing, making sure that everyone but one is dead before the truck appears. The way Spock plays in the rest of the game can be summed up by his famous quote: "*The needs of the many outweigh the needs of the few*". In other words, Spock has to make sure that the least amount of damage is suffered, by killing those that do it. How he does it: * If no player has prepped a grenade, target the least healthy player that's still playing. * If there are players that prepped grenades, from those target the least healthy. The reasoning is that, by targeting the weakest players, we are terminating sources of damage. The reasoning behind the grenades is that they are going off regardless and they do less damage if they aren't thrown. --- And so this bot works. I haven't tested extensively for input failures (so please warn me if something goes awry) but I'm confident I worked out most of the kinks. I based a small part of the code from the HanSolo bot but for the most part it's a tangled mess of code. Enjoy. ``` def IsAlive(player): return int(player[1].split(",")[0]) > 0 def IsTarget(player, target_health): return int(player[1].split(",")[0]) < target_health def HasGrenade(player): max_range = max(-4,-current_turn) for foo in range(-1,max_range,-1): if "P" in player[1].split(",")[foo]: for bar in range(-1,foo-1,-1): if player[1].split(",")[bar] not in ["T0", "T1", "T2", "T3"]: return True return False import sys info_list = sys.argv[2].split() current_turn = len(info_list[0].split(",")) action = "N" def Startgame(): global action target = 1 target_health = 5 grenade_list=[] for player in zip(range(1,4),info_list[1:]): if HasGrenade(player): grenade_list.append(player) if not grenade_list: foo_list = [] for player in zip(range(1,4),info_list[1:]): foo_list.append(player) target_list = foo_list else: target_list = grenade_list # Choose the least healthy player for player in target_list: if IsAlive(player) and IsTarget(player, target_health): target = player[0] target_health = int(player[1][0]) action = "S" + str(target) def Endgame(turn): global action if turn in [47, 49]: # Check if in 2 moves he can do enough damage rem_health = 0 for player in zip(range(1,4),info_list[1:]): if IsAlive(player): rem_health += player[0] if rem_health < 5: Startgame() # It's lazy, but it should work return else: action = "P" return if turn in [48, 50]: # If Spock shot someone before, it needs to shoot again if info_list[0].split(",")[-1] in ["S0", "S1", "S2", "S3"]: Startgame() return else: # There's no rule against throwing grenades to dead bodies, so if # possible it will be thrown there. target = 1 target_health = 5 foo_list = [] for player in zip(range(1,4),info_list[1:]): foo_list.append(player) target_list = foo_list for player in target_list: if IsTarget(player, target_health): target = player[0] target_health = int(player[1][1]) action = "T" + str(target) return if current_turn > 46: Endgame(current_turn) else: Startgame() print(action) ``` Run it like: ``` python spock.py ``` 2014-08-12 - Minor bugfix regarding grenade detection 2014-08-14 - Minor bugfix regarding endgame, thanks to isaacg for pointing it out before [Answer] ## Politically Correct Gunman Very politically correct, as it doesn't discriminate against anything. Thus it isn't very smart. ``` import random array = ["P", "N", "S0", "S1", "S2", "S3", "D1", "D2", "D3", "T1", "T2", "T3"] print(array[random.randrange(0,11)]) ``` It... doesn't really matter what arguments get passed to it how. `python politicallycorrectgunman.py` [Answer] # Straight Shooter He's a trained part of the cavalry and talks in many languages but, being blinkered, Straight Shooter can only see the one enemy in front of him. Being a horse, he doesn't understand that you have to wait between shots. ``` print('S2') ``` Perl, Python 2/3, Ruby: this horse really is a polygot entry. > > I'm winning anyway. I can't lose. You can shoot me but you can't kill me. Mister Ed ain't got shit on me! > > > For an answer that has a little more thought (and some functional paradigm) put into it, see [Twenty-Fourth and a Halfth Century](https://codegolf.stackexchange.com/questions/35988/four-man-standoff#36051). [Answer] # Anti-grenadier Grenades are bad. Very bad. So if anyone is preparing one, best thing to do is shoot them. Otherwise, we'll just hang out. ``` -- Antigrenadier local args = {...} -- command line arguments match = args[2] -- store the set of matches -- why this isn't standard in Lua.... function string:split( inSplitPattern, outResults ) if not outResults then outResults = { } end local theStart = 1 local theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart ) while theSplitStart do table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) ) theStart = theSplitEnd + 1 theSplitStart, theSplitEnd = string.find( self, inSplitPattern, theStart ) end table.insert( outResults, string.sub( self, theStart ) ) return outResults end -- set up the players players = match:split(" ") -- search other players for someone who pulled a grenade for i=2,#players do moves = players[i] -- test if person is alive if moves:sub(1,1) ~= "-" then -- cycle through all elements of the string for j=#moves,2,-1 do -- if found, shoot! if moves:sub(j,j) == "P" then print("S"..i-1) os.exit() end end end end -- otherwise we just relax print("N") ``` [Answer] # Ricochet - Perl Simple strategies seem to do decently in this challenge, so here's another. It shoots a random living player. It has the added feature of committing suicide at the end to avoid the truck. ``` @history = map([split(",",$_)],split(" ",$ARGV[1])); $health = $history[0][0]; @options = (); for(1..3){ if($history[$_][0] > 0){ push(@options,$_); } } $target = @options[int(rand(~~@options))]; if(~~@{$history[0]} == 50){ $target = 0; } print"S$target"; ``` Run like so: ``` perl ricochet.plx 5 "-2,S0 -2,S1 -2,S2 5,N" ``` [Answer] ## Aggressor Pulls on round one, throws at highest health opponent on round 2, shoots at highest health opponent thereafter. ``` #include <cstdio> #include <cstring> int main(int argc, char** argv){ char* t; t = strtok(argv[2]," "); int len = strlen(t); int max = -50, maxP; for(int i=1;i<4;i++){ int cur; t = strtok(NULL," "); if(t[0]=='-'){cur = -1*(t[1]-'0');} else{cur = t[0]-'0';} if(cur>max){ max = cur; maxP = i; } } if(len == 1){printf("P\n"); return 0;} if(len == 3){printf("T%d\n",maxP); return 0;} printf("S%d\n",maxP); return 0; } ``` Run this like ./agg ID "5 5 5 5". [Answer] # Ninja Just dodges randomly trying to avoid getting hit. ``` math.randomseed(os.time()) print("D"..tostring(math.random(4)-1)) ``` run as ``` lua ninja.lua ``` Args are unnecessary, but can be added w/o issue. [Answer] **Name**: PriorityTargets **Shell Command**: ruby PriorityTargets.rb 5 [game\_state] **Language**: Ruby V2.1.2 **Description**: PriorityTargets attempts to find common playstyles. It then decides, based on those playstyles, who it wants to attack and what weapon to use. **Note**: First Code Golf submission! Much larger than the other submissions because I went a little crazy. ``` #!/usr/bin/env ruby class PriorityTargets class PlayerAction SHOOT = 'S' DODGE = 'D' PREPARE_GRENADE = 'P' THROW_GRENADE = 'T' NOTHING = 'N' attr_accessor :action, :target def initialize(action_string) @action = action_string[0, 1] @target = self.has_target? ? action_string[1, 1].to_i : false end def to_s string = @action string << @target.to_s if self.has_target? string end def has_cooldown? [SHOOT].include? @action end def is_aggressive? [SHOOT, PREPARE_GRENADE, THROW_GRENADE].include? @action end def has_target? [SHOOT, DODGE, THROW_GRENADE].include? @action end end class Player attr_reader :identifier, :health, :history attr_accessor :playstyles def initialize(player_identifier, player_string) @identifier = player_identifier @playstyles = [] player_info = player_string.split(',') @health = player_info.shift.to_i @history = parse_history(player_info) end def has_attacked?(player, round = nil) round ||= self.history.length - 1 player.history[0, round].each do |turn| did_attack = true and break if turn.is_aggressive? && turn.has_target? && turn.target == player.identifier end did_attack ||= false end def is_holding_grenade?(round = nil) round ||= self.history.length turn_history = self.history[0, round] is_holding = false turn_history.each_with_index do |turn, curr_round| if turn.action == PlayerAction::PREPARE_GRENADE && curr_round >= round - 3 is_holding = true if turn_history.drop(curr_round).select{|turn| turn.action == PlayerAction::THROW_GRENADE }.length == 0 end end is_holding end def is_dead?; self.health <= 0; end def is_on_cooldown? return false if self.history.length == 0 self.history.last.has_cooldown? end def turn_at_round(round); self.history[round-1]; end private def parse_history(history_array) parsed = [] history_array.each {|action_string| parsed << PlayerAction.new(action_string) } parsed end end class PlayerList include Enumerable def initialize(player_list = [], filter_list = false) @list = player_list @filter = filter_list if filter_list end #Enumerable Methods def each list = @list.select{|player| @filter.include?(player.identifier) } if @filter list = @list unless @filter list.each {|player| yield(player) } end def <<(player); @list << player; end def [](key) player = @list.select{|player| @filter.include?(player.identifier) }[key] if @filter player = @list[key] unless @filter player end def length list = @list.select{|player| @filter.include?(player.identifier) } if @filter list = @list unless @filter list.length end def empty?; self.length == 0; end def not_empty?; self.length > 0; end def create_filtered_list(player_ids) new_player_list = PlayerList.new(@list, player_ids) new_player_list end #PlayerList Methods def includes_playstyle?(playstyle) (self.with_playstyle(playstyle).length > 0) end def have_executed_action?(action) action_found = false self.each {|player| action_found = true and break if player.history.select {|turn| turn.action == action}.length > 0 } action_found end def direct_damages(round = nil) round ||= self.first.history.length damage_list = {} @list.each {|player| damage_list[player.identifier] = 0 } if round >= 1 @list.each do |player| player.history[0, round].each_with_index do |turn, curr_round| if turn.has_target? target_player = @list.select{|curr_player| curr_player.identifier == turn.target }.first target_turn = target_player.turn_at_round(curr_round) damage_list[turn.target] += 8 if turn.action == PlayerAction::THROW_GRENADE if turn.action == PlayerAction::SHOOT damage_list[turn.target] += 2 unless target_turn.action == PlayerAction::DODGE && target_turn.target == player.identifier end end end end end damage_list.select! {|key| @filter.include? key } if @filter damage_list end def filtered_with_condition(&condition_block) player_ids = [] self.each {|player| player_ids << player.identifier if condition_block.call(player) } create_filtered_list(player_ids) end def on_cooldown; filtered_with_condition {|player| player.is_on_cooldown?} end def not_on_cooldown; filtered_with_condition {|player| !player.is_on_cooldown?} end def dead; filtered_with_condition {|player| player.is_dead?} end def not_dead; filtered_with_condition {|player| !player.is_dead?} end def with_playstyle(playstyle); filtered_with_condition {|player| player.playstyles.include?(playstyle)} end def not_with_playstyle(playstyle); filtered_with_condition {|player| !player.playstyles.include?(playstyle)} end def with_max_health(round = nil) round ||= self.first.history.length player_damages = direct_damages(round) filtered_with_condition {|player| player_damages[player.identifier] == player_damages.values.min } end def with_identifier(identifier) matches = self.with_identifiers([ identifier ]) return nil if matches.empty? matches.first end def with_identifiers(identifiers) create_filtered_list(identifiers) end end class PlayerTypes GRENADIER = :GRENADIER COWBOY = :COWBOY SKIDDISH = :SKIDDISH AGGRESSOR = :AGGRESSOR DEFENSIVE = :DEFENSIVE ANTI_GRENADIER = :ANTI_GRENADIER PLAYSTYLE_ORDER = [GRENADIER, COWBOY, SKIDDISH, AGGRESSOR, DEFENSIVE, ANTI_GRENADIER] def initialize(player_list) @players = player_list end def analyze_playstyles return if @players.first.history.length == 0 PLAYSTYLE_ORDER.each do |playstyle| check_fnc = "is_"+playstyle.to_s+'?' @players.each {|player| player.playstyles << playstyle if self.send(check_fnc, player) } end end def is_GRENADIER?(player) #Grenade on first turn #Used more than one grenade #Never used gun, only grenade shoot_count = player.history.count {|turn| turn.action == PlayerAction::SHOOT } grenade_count = player.history.count {|turn| turn.action == PlayerAction::PREPARE_GRENADE } profiled ||= true if player.history.first.action == PlayerAction::PREPARE_GRENADE profiled ||= true if grenade_count > 1 profiled ||= true if shoot_count == 0 && grenade_count > 0 profiled ||= false end def is_COWBOY?(player) #Never used grenade, only gun shoot_count = player.history.count {|turn| turn.action == PlayerAction::SHOOT } grenade_count = player.history.count {|turn| turn.action == PlayerAction::PREPARE_GRENADE } profiled ||= true if grenade_count == 0 && shoot_count > 0 profiled ||= false end def is_SKIDDISH?(player) #Dodged more than once #Never hurts anybody dodge_count = player.history.count {|turn| turn.action == PlayerAction::DODGE } attack_count = player.history.count {|turn| turn.is_aggressive? } profiled ||= true if dodge_count > 1 profiled ||= true if attack_count == 0 && player.history.length > 1 profiled ||= false end def is_AGGRESSOR?(player) #Only shoots person >= most health profiled = false player.history.each {|turn| profiled = true if turn.is_aggressive? && turn.has_target? } player.history.each_with_index do |turn, round| if turn.is_aggressive? && turn.has_target? profiled = false if [[email protected]](/cdn-cgi/l/email-protection)_max_health(round).include? @players.with_identifier(turn.target) end end profiled end def is_DEFENSIVE?(player) #Only hurts people who hurt them first player.history.each {|turn| profiled = true if turn.is_aggressive? && turn.has_target? } player.history.each_with_index do |turn, round| if turn.is_aggressive? && turn.has_target? target_player = @players.with_identifier(turn.target) profiled = false unless target_player.has_attacked?(player, round) end end profiled ||= false end def is_ANTI_GRENADIER?(player) #After a Grenadier has been shown, only shoots grenadier shots_fired = 0 shots_fired_while_holding = 0 player.history.each_with_index do |turn, round| if turn.is_aggressive? && turn.has_target? target_player = @players.with_identifier(turn.target) shots_fired += 1 shots_fired_while_holding += 1 if target_player.is_holding_grenade?(round) end end (shots_fired > 0 && shots_fired/2.0 <= shots_fired_while_holding) end end def initialize(game_state) players_info = game_state.split(' ') @player = Player.new(0, players_info.shift) @players = PlayerList.new @players << @player enemy_identifiers = [] players_info.each_with_index {|info, index| @players << Player.new(index+1, info); enemy_identifiers << index+1; } @enemies = @players.with_identifiers(enemy_identifiers ) end def analyze_playstyles types = PlayerTypes.new(@players) types.analyze_playstyles end def find_dodge_target armed_aggressors = @enemies.with_playstyle(PlayerTypes::AGGRESSOR).not_on_cooldown().not_dead() if armed_aggressors.not_empty? return armed_aggressors.with_max_health().first if @players.with_max_health().include?(@player) && @players.with_max_health().length == 1 end return @enemies[Random.rand(3)] if @player.history.length == 0 nil end def find_target unarmed_aggressors = @enemies.with_playstyle(PlayerTypes::AGGRESSOR).on_cooldown().not_dead() anti_grenadiers = @enemies.with_playstyle(PlayerTypes::ANTI_GRENADIER).not_dead() grenadiers = @enemies.with_playstyle(PlayerTypes::GRENADIER).not_dead() cowboys = @enemies.with_playstyle(PlayerTypes::COWBOY).not_dead() skiddish = @enemies.with_playstyle(PlayerTypes::SKIDDISH).not_dead() defensive = @enemies.with_playstyle(PlayerTypes::DEFENSIVE).not_dead() if unarmed_aggressors.not_empty? return unarmed_aggressors.with_max_health().first if @players.with_max_health().include?(@player) && @players.with_max_health().length == 1 end return anti_grenadiers.with_max_health().first if anti_grenadiers.not_empty? return grenadiers.with_max_health().first if grenadiers.not_empty? return cowboys.with_max_health().first if cowboys.not_empty? return skiddish.with_max_health().first if skiddish.not_empty? return defensive.with_max_health().first if defensive.not_empty? return @enemies.with_max_health().not_dead().first if @enemies.with_max_health().not_dead().length > 0 nil end def find_weapon return PlayerAction::THROW_GRENADE if @player.is_holding_grenade? anti_grenadiers = @enemies.with_playstyle(PlayerTypes::ANTI_GRENADIER).not_dead() return PlayerAction::PREPARE_GRENADE if anti_grenadiers.empty? && @enemies.have_executed_action?(PlayerAction::PREPARE_GRENADE) PlayerAction::SHOOT end def make_decision dodge_target = self.find_dodge_target target = self.find_target weapon = self.find_weapon decision ||= PlayerAction.new(PlayerAction::NOTHING) if @player.is_on_cooldown? || @enemies.with_max_health().not_dead().length == 0 decision ||= PlayerAction.new(PlayerAction::DODGE + dodge_target.identifier.to_s) if dodge_target decision ||= PlayerAction.new(weapon + target.identifier.to_s) STDOUT.write decision.to_s end end priority_targets = PriorityTargets.new(ARGV[1]) priority_targets.analyze_playstyles priority_targets.make_decision ``` [Answer] # Coward -- Perl Acts very cowardly. When he feels healthy, he chooses an enemy who does not feel so and shoots him. Bonus points for those enemies which were shooting the last turn (because they are known to be doing `Nothing` this turn and so be absolutely defenceless). When he feels not so good, he runs for cover to save his hide in, occassionally shooting someone. ``` #!/usr/bin/perl @allinfo = map { [split/,/] } split / /, $ARGV[1]; @life = map { $_->[0] } @allinfo; @action = map { @$_>1 ? $_->[-1] : () } @allinfo; if($life[0] < 3 && rand() < .5 ) { printf "D%d", +(sort { ($life[$a]>0)*($action[$a] eq "N") <=> ($life[$b]>0)*($action[$b] eq "N") } 1..3)[2] } else { @score = map { $life[$_]>0 ? (5/$life[$_] + 2*($action[$_] =~ /S./)) : 0 } 1..3; printf "S%d", +(sort { $score[$a] <=> $score[$b] } 1..3); } ``` Pretty standard Perl code; save it in some file and then run `perl file argument argument [...]`. I have checked for syntax and it was OK, so I hope for no problems with this. E: eliminated a potential for division by 0 error. [Answer] # Bomberman Bot written in R, command line should be: `Rscript Bomberman.R arg0 arg1` I realized after starting to write this bot that Geobits already made a [grenadier](https://codegolf.stackexchange.com/a/35991/6741) but I think mine is significantly different, in that it checks its health is above 3 before preparing a grenade, throws it at the last shooter first, and the most healthy second, and if its health is below 3 it will dodge the dangerous player (neither dead nor shooter in the last round) or shoot one of the remaining player. ``` input <- commandArgs(TRUE) history <- do.call(rbind,strsplit(scan(textConnection(input[2]),"",quiet=TRUE),",")) health <- as.integer(history[,1]) last_shooter <- which(grepl("S",history[-1,ncol(history)])) last_prepare <- which(history[1,]=="P") if(!length(last_prepare)) last_prepare <- -1 last_throw <- which(grepl("T",history[1,])) if(!length(last_throw)) last_throw <- 0 most_healthy <- which.max(health[-1]) dead <- which(health[-1]<=0) inoffensive <- c(last_shooter,dead) danger <- which(!(1:3)%in%inoffensive) alive <- which(!(1:3)%in%dead) if(health[1]>3 & last_throw > last_prepare) out <- "P" if(last_throw < last_prepare) out <- ifelse(length(last_shooter),paste("T",last_shooter[1],sep=""),paste("T",most_healthy[1],sep="")) if(health[1]<=3 & last_throw > last_prepare){ if(length(danger)){ out <- paste("D",sample(danger,1),sep="") }else{ out <- paste("S",sample(alive,1),sep="") } } cat(out) ``` **Edit** There seems to be some communication problem between this bot and your controller since all logs that I looked showed that my bot only output `N`. So, here is the same bot but rewritten in Python, in the hope that if this one also have communications problem, someone will see it. To be called with `python Bomberman.py arg0 arg1`. ``` import sys,re,random history = sys.argv[2] history = [k.split(",") for k in history.split()] health = [k[0] for k in history] last_turn = [k[-1] for k in history] last_shooter = [i for i,x in enumerate(last_turn) if re.search(r'S[0-3]',x)] last_prepare = [i for i,x in enumerate(history[0]) if x=='P'] if not len(last_prepare): last_prepare = [-1] last_throw = [i for i,x in enumerate(history[0]) if re.search(r'T[0-3]',x)] if not len(last_throw): last_throw = [0] most_healthy = [i for i,x in enumerate(health) if x==max(health)] dead = [i for i,x in enumerate(health) if x<=0] inoffensive = last_shooter+dead danger = [k for k in range(1,4) if k not in inoffensive] alive = [k for k in range(1,4) if k not in dead] if health[0]>3 and last_throw[-1] > last_prepare[-1]: out = 'P' if last_throw[-1] < last_prepare[-1]: if len(last_shooter): out = 'T'+random.choice(last_shooter) else: out = 'T'+random.choice(most_healthy) if health[0]<=3 and last_throw[-1] > last_prepare[-1]: if len(danger): out = 'D'+random.choice(danger) else: out = 'S'+random.choice(alive) print(out) ``` [Answer] # Neo Dodge a living player who did not shoot last turn. If everybody alive shot last turn, shoot a random living player. Suicide when you see headlights. ``` import java.util.Random; public class Neo { public static void main(String[] args) { if(args.length < 2) return; String[] list = args[1].split(" "); if(list.length < 4) return; Random rand = new Random(); int turn = list[0].split(",").length; if(turn == 49){ System.out.print("S0"); return; } int target=0; for(int i=1;i<4;i++) if(list[i].length()<2 || (list[i].charAt(0)!='-' && list[i].charAt(list[i].length()-2)!='S')) target=i; if(target>0){ System.out.print("D"+target); return; } while(target<1){ int i=rand.nextInt(3)+1; if(list[i].charAt(0)!='-') target=i; } System.out.print("S"+target); } } ``` I don't expect much from this guy against grenade-chuckers, but against shooters it might work pretty well. We'll see. [Answer] # Twenty-Fourth and a Halfth Century This Python entry ducks and dodges until only passive players or a single aggressive player remains, then starts shooting. It hopes a passing martian takes care of grenadiers and drunken truck drivers. Unless I've done something wrong, this is functional Python. It certainly doesn't look like the kind of Python I wrote before Haskell and friends found me, and I don't think I've mutated anything in place. But if you know better, please do tell me. ``` #!/usr/bin/env python import sys import random ## ==== Move Types ================================================== ## def move_type (move): if "" == move: return "N" return move[0] def is_passive_move (move): if "N" == move: return True if "D" == move_type (move): return True return False def is_aggressive_move (move): return not is_passive_move (move) def passive_moves (moves): return [m for m in moves if is_passive_move (m)] def aggressive_moves (moves): return [m for m in moves if is_aggressive_move (m)] ## ================================================== Move Types ==== ## ## ==== Player Model ================================================ ## class Player: def __init__ (self, number, health, moves): self.number = number self.health = health self.moves = moves def last_move (self): if 0 == len (self.moves): return "" return self.moves[-1] def player_from (number, player_string): x = player_string.split (",") health = int (x[0].strip ()) moves = [move.strip () for move in x[1:]] return Player (number, health, moves) def players_from (game_state): return [player_from (n, p) for (n, p) in zip (range(4), game_state.split ())] def is_alive (player): return 0 < player.health def i_am_dead (me): return not is_alive (me) def can_shoot (player): return "S" != move_type (player.last_move ()) def is_passive (player): passive_move_count = len (passive_moves (player.moves)) aggressive_move_count = len (aggressive_moves (player.moves)) return passive_move_count > (aggressive_move_count + 1) def players_who_can_breathe (players): return [p for p in players if is_alive (p)] def players_who_can_shoot (players): return [p for p in players if can_shoot (p)] def players_who_stand_around (players): return [p for p in players if is_passive (p)] ## ================================================ Player Model ==== ## ## ==== Actions ===================================================== ## def shoot_randomly_at (possible_targets): chosen_target = random.choice (possible_targets) return "S{0}".format (chosen_target.number) def dodge_one_of_the (potential_shooters): chosen_shooter = random.choice (potential_shooters) return "D{0}".format (chosen_shooter.number) def do_nothing (): return "N" def pick_move (game_state): players = players_from (game_state) me = players[0] enemies = players[1:] if i_am_dead (me): return do_nothing () living_enemies = players_who_can_breathe (enemies) if 1 == len (living_enemies): return shoot_randomly_at (living_enemies) passive_enemies = players_who_stand_around (living_enemies) if len (living_enemies) == len (passive_enemies): return shoot_randomly_at (passive_enemies) potential_shooters = players_who_can_shoot (living_enemies) if 0 < len (potential_shooters): return dodge_one_of_the (potential_shooters) return do_nothing () ## ===================================================== Actions ==== ## if "__main__" == __name__: game_state = sys.argv[2] print (pick_move (game_state)) ``` Run as: ``` python twenty-fourth-and-a-halfth-century.py 0 "5 5 5 5" ``` [Answer] # Scared This submission is scared of everyone. But it's especially scared of some people. So it figures out who's the most dangerous, and shoots them. If multiple enemies look the most dangerous, it shoots at a random one. ``` import sys import random def is_alive(player): return int(player.split(",")[0]) > 0 # Anyone with a live grenade who is alive is dangerous def is_dangerous(player): return player.count("P") > player.count("T") and \ int(player.split(",")[0]) > 0 def health(player): return int(player.split(",")[0]) # Failing that, healthy people are dangerous def danger_rating(player): return 6 if is_dangerous(player) else health(player) enemies = sys.argv[2].split()[1:] highest_danger = max(danger_rating(enemy) for enemy in enemies) most_dangerous_enemy = random.choice( [enemy_num+1 for enemy_num in range(len(enemies)) if danger_rating(enemies[enemy_num]) == highest_danger]) print("S"+str(most_dangerous_enemy)) ``` This is python (2 or 3, same result in either.) Save as `scared.py`, run with `python3 scared.py` [Answer] # Manipulative Bastard – Python Prepares and throws grenades. If he thinks there's no time or there are too few enemies, he shoots. If he's alone he tries to outsmart the other guy. ``` import sys def health(p): return int(p[0]) def is_alive(p): return health(p) > 0 def can_act(p): return is_alive(p) and p[-1][0] != 'S' def can_throw(p): return is_alive(p) and p[-1][0] == 'P' def shot_first(p): if len(p) == 1: return False return p[1][0] == 'S' def act(a): print a sys.exit(0) player = sys.argv[2].split()[0].split(',') enemies = [e.split(',') for e in sys.argv[2].split()[1:]] healthiest = sorted(enumerate(enemies, 1), key=lambda e:health(e[1]))[-1] alive = sum(is_alive(e) for e in enemies) if alive == 1: i, e = healthiest if health(e) <= 2 and not can_act(e): act('S%d' % i) if can_throw(player): act('T%d' % i) if can_throw(e): act('S%d' % i) if can_act(e) and shot_first(e) and len(player) < 40: act('D%d' % i) if len(player) > 45: act('P') act('S%d' % i) if can_throw(player): i, e = healthiest act('T%d' % i) if len(player) > 45: act('P') if health(player) <= 2 or any(can_throw(e) for e in enemies) or alive == 2: i, e = healthiest act('S%d' % i) act('P') ``` [Answer] # Osama I've been trying this for a day or so, now it's time to post and see how the others have evolved in the meantime. ``` module Main where import Data.List import Data.Ord import System.Environment words' "" = [] words' s = s' : words' (tail' s'') where (s', s'') = break (==',') s tail' (',':r) = r tail' r = r nRound = length . words' lastAction = last . words' health :: String -> Int health = read . head . words' alive = (>0) . health grenadeAge :: String -> Int grenadeAge p | not (alive p) = 0 | otherwise = g 0 $ tail $ words' p where g n (a:b:r) | head a == 'S' = g (if n>0 then n+2 else 0) r g 0 ("P":r) = g 1 r g n (('T':_):r) | n>0 = g 0 r g n (_:r) | n>0 = g (n+1) r g n (_:r) = g n r g n [] = n prepared :: String -> Bool prepared p = alive p && head (lastAction p) /= 'S' nShotMe = length . filter (=="S0") . words' getPlayer = (!!) action players@(me:them) | not (prepared me) = "S2" -- bogus | nRound me >= 49 = "S0" | grenadeAge me >= 1 = 'T':(show $ maximumBy (comparing (nShotMe . getPlayer players)) l) | any prepared them && nRound me > 0 = 'D':(show $ maximumBy (comparing (nShotMe . getPlayer players)) l) | otherwise = 'S':(show $ maximumBy (comparing (health . getPlayer players)) l) where l = filter (alive . (getPlayer players)) [1..3] main = do players <- fmap (words . head . tail) getArgs putStrLn $ action players ``` Compile with `ghc -O2 osama.hs`, then run using `./players/Osama/osama`. [Answer] ## Sniper - Lua On the first turn it will shoot a random person, then it will shoot any players that it can kill (2 or 1 health). If neither of those work it will try to shoot the player that shot it last, otherwise it will shoot a random player. Run with `lua Sniper.lua` ``` turns = arg[2] health = string.sub(turns, 1, 1) --make random numbers random math.randomseed(io.popen("date +%s%N"):read("*all")) math.random(); math.random(); math.random() function Split(str, delim, maxNb) -- Eliminate bad cases... if string.find(str, delim) == nil then return { str } end if maxNb == nil or maxNb < 1 then maxNb = 0 -- No limit end local result = {} local pat = "(.-)" .. delim .. "()" local nb = 0 local lastPos for part, pos in string.gmatch(str, pat) do nb = nb + 1 result[nb] = part lastPos = pos if nb == maxNb then break end end -- Handle the last field if nb ~= maxNb then result[nb + 1] = string.sub(str, lastPos) end return result end enemies = Split(turns, " ") --first turn if #enemies[1] == 1 then print(string.format("S%i",math.random(1,3))) os.exit() end --kills if possible for enemy=1,3 do if (tonumber(string.sub(enemies[enemy + 1],1,1)) or 0) < 3 and string.sub(enemies[enemy + 1],1,1) ~= "-" then print(string.format("S%i",enemy)) os.exit() end end --shoots the last person that shot at it for enemy=1,3 do if string.sub(enemies[enemy + 1],#enemies[enemy + 1]-1) == "S0" and tonumber(string.sub(enemies[enemy + 1],1,1)) > 0 then print(string.format("S%i",enemy)) os.exit() end end --otherwise shoot a random alive person local aliveEnemies = {} for enemy=1,3 do if string.sub(enemies[enemy + 1],1,1) ~= "-" then aliveEnemies[#aliveEnemies+1]=enemy end end print(string.format("S%i",math.random(1,#aliveEnemies))) ``` [Answer] # Darwin Survival of the fittest means the least healthy must die. ### Rationale Looking at the batch of results from Tuesday (12th), there seem to be three distinct groupings: survivors; the effectively suicidal; and the worse than useless. The survivors share simple shooting-based strategies. While a couple of other bots (*Spock*, *Coward*) will target the least healthy enemy, they also complicate their strategies with other actions. This one does not. Like *Simple Shooter*, it has a clear definition of the target and sticks with it relentlessly. It'll be interesting to see where it fits into the results. ``` #!/usr/bin/env python import sys import random ## ==== Player Model ================================================ ## class Player: def __init__ (self, number, health): self.number = number self.health = health def player_from (number, player_string): x = player_string.split (",") health = int (x[0].strip ()) return Player (number, health) def players_from (game_state): return [player_from (n, p) for (n, p) in zip (range(4), game_state.split ())] def is_alive (player): return 0 < player.health def i_am_dead (me): return not is_alive (me) def players_who_can_breathe (players): return [p for p in players if is_alive (p)] def players_by_health (players): return sorted (players, key=lambda p: p.health) def least_healthy_players (players): sorted_living_players = \ players_by_health (players_who_can_breathe (players)) lowest_living_health = sorted_living_players[0].health return [p for p in players if lowest_living_health == p.health] ## ================================================ Player Model ==== ## ## ==== Actions ===================================================== ## def shoot_randomly_at (possible_targets): chosen_target = random.choice (possible_targets) return "S{0}".format (chosen_target.number) def do_nothing (): return "N" def pick_move (game_state): players = players_from (game_state) me = players[0] enemies = players[1:] if i_am_dead (me): return do_nothing () least_healthy_enemies = least_healthy_players (enemies) return shoot_randomly_at (least_healthy_enemies) ## ===================================================== Actions ==== ## if "__main__" == __name__: game_state = sys.argv[2] print (pick_move (game_state)) ``` This is a stripped-down, slightly modified version of my earlier *Twenty-Fourth and a Halfth Century*, and shares its invocation: ``` python darwin.py 3 "5 5 5 5" ``` [Answer] # Zaenille - C ## Priorities : 1. Shoot if it's a 1 on 1 left 2. Shoot grenadiers 3. Dodge 4. Nothing (just to confuse some) Compile with `gcc <filename.c>`. Run with `./a.out <parameters>`. ``` #include <stdio.h> #include <string.h> int main(int argc, char *argv[]){ char* input = argv[2]; int enemyCount=1; int aliveCount=0; int aliveEnemy=0; //default char action = 'N'; int target = NULL; const char delim[1] = " "; char *token; //first turn if(strcmp(input,"5 5 5 5")==0){ printf("D1"); return 0; } token = strtok(input, delim); token = strtok(NULL, delim); //skip to the first enemy while(token != NULL){ //if someone is alive : if(strstr(token,"-")==NULL && token[0]!='0'){ aliveCount++; aliveEnemy=enemyCount; //if that person did nothing this turn, take it as a tip that he will shoot next turn, and dodge if(strstr(token, "N")!=NULL){ action = 'D'; target=enemyCount; } //if that person prepared a grenade, shoot him down if(strstr(token, "P")!=NULL){ action = 'S'; target=enemyCount; } } token = strtok(NULL, delim); enemyCount++; } //if there is 1 enemy left, shoot him down if(aliveCount==1){ action='S'; target=aliveEnemy; } printf(action=='N'?"N":"%c%d",action,target); return 0; } ``` [Answer] # InputAnalyzer The key a game such as this is analyze how all your opponents are playing to respond accordingly. My bot will do just that using complicated algorithms that will result in using my opponents turns to my advantage giving a decisive victory! Edit: I now 1. dodge any player who has a live grenade 2. will no longer attempt to shoow/throw/dodge myself. --- ``` import System.Environment import Data.Char (ord) import Data.List.Split main = do args <- getArgs let secondArg = (last args) let opt = (argCount secondArg 0) let list = (splitOn " " secondArg) let enemysToCheck = [1,2,3] let target = (avoidShootingSelf (findTarget (last args) 0 0 0 0)) putStrLn (decide list enemysToCheck opt target) argCount :: String -> Int -> Int argCount (s:str) i |(length str) == 0 = i `mod` 4 | otherwise = (argCount str (i + (ord s))) --myPseudo takes number 0-3, and a possible target and translates it to a command myPseudo :: Int -> Int -> String myPseudo 0 b = "S" ++ (show b) myPseudo 1 b = "D" ++ (show b) myPseudo 2 b = "P" myPseudo 3 b = "T" ++ (show b) decide :: [String] -> [Int] -> Int -> Int -> String decide [] [] a b = (myPseudo a b) decide (x:xs) [] a b = (myPseudo a b) decide xs (y:ys) a b | (liveGrenade z 0) == True = "D" ++ (show y) | otherwise = (decide xs ys a b) where z = xs!!y --checks if a player has a live grenade liveGrenade :: String -> Int -> Bool liveGrenade [] a = a > 0 liveGrenade (s:str) a | s == 'T' = (liveGrenade str (a - 1)) | s == 'P' = (liveGrenade str (a + 1)) | otherwise = (liveGrenade str a) --findTarget picks a target by doing some irrelevant string processing on the 2nd argument findTarget :: String -> Int -> Int -> Int -> Int -> Int findTarget [] a b c d = ((maximum [a,b,c,d]) `mod` 4) findTarget (s:str) a b c d | s == 'S' = (findTarget str (a + 1) b c d) | s == 'D' = (findTarget str a (b + 1) c d) | s == 'P' = (findTarget str a b (c + 1) d) | s == 'T' = (findTarget str a b c (d + 1)) | s == 'N' = (findTarget str a b c (d + 1)) | otherwise = (findTarget str a b c d) --Makes sure I do target myself takes int 0-3 avoidShootingSelf :: Int -> Int avoidShootingSelf 0 = 1 avoidShootingSelf a = a ``` Compile the bot with the following command (Need to have ghc) > > ghc --make InputAnalyzer.hs > > > Shell Command to run should be the following > > ./InputAnalyzer > > > Note: I tested on windows so if you have any trouble regarding compling/running please say so in comment in and I will do my best to find out the correct command. [Answer] # Dog named Courage First thing - shoot the bad guys on sight. Then dodge randomly until someone prepares a grenade. Then when everyone shoots at him, prepare my own grenade and throw it on anyone. But the distraction man. Edit: Now implemented as I thought It should be. Before, the score was: 35.9 *Updated: Sometimes shoots instead of dodgeing* ### couragethedog.py ``` import sys from collections import defaultdict as ddict from random import choice args = sys.argv info = " ".join(args[2:]).strip('"').split(" ") players = ddict(dict) for i,s in enumerate(info): parts = s.split(",") players[i]["health"]=int(parts[0]) players[i]["last"]=parts[-1] players[i]["history"]=parts[1:] players[i]["turn"]=len(parts) me=0 others=[1,2,3] turn=players[me]["turn"] alive = filter(lambda p:players[p]["health"]>0,others) def act(): if turn is 1: return "S%d" % choice(alive) if "P" == players[me]["history"][-1]: targets = set(alive) for i in alive: if "P" == players[i]["history"][-2]: targets.remove(i) return "T%d" % choice(list(targets)) for i in others: if players[i]["history"][-1] is "P": return "P" if choice([True,False,False]): return "S%d" % choice(alive) return "D%d" % choice(alive) print act() ``` Run as ``` python couragethedog.py ``` [Answer] # MAD - Java The MAD bot trust in the power of intimidation through [mutual assured destruction](http://en.wikipedia.org/wiki/Mutual_assured_destruction). Whenever he doesn't have a ready grenade, he prepares one. He then dodges possible gunners until either someone tries to deal damage to him or his grenade is about to explode. From the moment he gets attacked, **he chucks grenades at whoever has *tried* to deal more damage to him this match so far.** If his grenade is about to explode, he bombs the leading player. MAD is not against taking a shot at someone when there's nothing to dodge or directly chuck a grenade at and his grenade is still good for at least one turn. ``` import java.util.ArrayList; import java.util.Random; public class MAD { public static void main(String[] args) { if(args.length < 2) { return; // nothing to do here } String[] players = args[1].split(" "); if(players.length < 4 || !isAlive(players[0])) { return; // nothing to do here } Random rand = new Random(); int grenadeExplodes = grenadeExplodes(players[0]); if(grenadeExplodes==-1) { System.out.print("P"); // I don't feel safe without a prepared grenade in my hand return; } int highestDamage = -1; int playerToShoot = -1; for(int i=1; i<4; i++) // did anyone try to hit me? { int damage = damageAttempted(players[i], 0); if(isAlive(players[i]) && (damage>highestDamage || (damage==highestDamage && rand.nextDouble()>0.5))) { highestDamage = damage; playerToShoot = i; } } if(highestDamage > 0) { System.out.print("T" + Integer.toString(playerToShoot)); // don't tell me I didn't warn you return; } int highestHealth = -1; int healthiestPlayer = -1; for(int i=1; i<4; i++) // who is doing too well for their own good? { int health = getHealth(players[i]); if(health>highestHealth || (health==highestHealth && rand.nextDouble()>0.5)) { highestHealth = health; healthiestPlayer = i; } } if(grenadeExplodes==0) { System.out.print("T" + Integer.toString(healthiestPlayer).charAt(0)); // get this hot head outta here!! return; } // I've got time to flaunt my grenade around ArrayList<Integer> playersToDodge = new ArrayList<Integer>(); for(int i=1; i<4; i++) // lets see who could shoot me { if(canMove(players[i]) && grenadeExplodes(players[i])!=0) { playersToDodge.add(i); if(grenadeExplodes(players[i])==-1) // players who have no grenade are more likely to shoot { playersToDodge.add(i); } } } if(playersToDodge.size()>0) { System.out.print("D" + Integer.toString(playersToDodge.get(rand.nextInt(playersToDodge.size() - 1))).charAt(0)); // what do we say to would-be gunners? return; } if(grenadeExplodes!=1) { System.out.print("S" + Integer.toString(healthiestPlayer).charAt(0)); // seems like I can take a free shot at someone } else { System.out.print("N"); // wouldn't want to end up with an exploding grenade in my hand while being unable to throw it. } } public static boolean isAlive(String player) { return player.charAt(0)!='-'; } public static boolean canMove(String player) { return isAlive(player) && player.charAt(player.length()-2)!='S'; } public static int grenadeExplodes(String player) { String[] actions = player.split(","); if(actions.length>3 && actions[actions.length - 3].charAt(0)=='P' && actions[actions.length - 2].charAt(0)=='T' && actions[actions.length - 1].charAt(0)=='P') { return 0; } else if(actions.length>2 && actions[actions.length - 2].charAt(0)=='P' && actions[actions.length - 1].charAt(0)=='T') { return 1; } else if(actions.length>1 && actions[actions.length - 1].charAt(0)=='P') { return 2; } else { return -1; } } public static int damageAttempted(String player, int target) { String[] actions = player.split(","); int damage = 0; char targetChar = Integer.toString(target).charAt(0); for(int i=0; i<actions.length; i++) { if(actions[i].charAt(0)=='S' && actions[i].charAt(1)==targetChar) { damage += 2; } else if (actions[i].charAt(0)=='T') { if(actions[i].charAt(1)==targetChar) { damage += 8; } else { damage += 3; } } } return damage; } public static int getHealth(String player) { return Integer.parseInt(player.split(",")[0]); } } ``` This Bot will likely perform poorly, but I liked the idea anyway. MAD would probably do better in a field with smarter bots that log the behavior of other bots and with more matches run between 4 bots. [Answer] ## Sadist python His priority is to cause pain and grenades hurt. He pulls first turn. He likes to kill when you can't attack. He toys with SSSs (single simple shooters) by dodging and pulling to prolong the domination. He even choses to attack those first who've done nothing to anyone. Because he uses grenades, he (and everyone else) will ususally not survive the second or third round. If he is paired up with another grenadeer, everyone will die. This means I don't expect to win but I wrote this to learn python (never used it before and I'm trying to get an introduction into a bunch of new languages). There are several other, "pull firsts" so if you feel it is too simular let me know. The others don't seem to be willing to pull and then dodge, however. ``` import sys def ident(thatguy): return int(thatguy.split(",")[0]) def health(thatguy): return int(thatguy.split(",")[1]) def shooter(thatguy): if(len(thatguy.split(","))<3): return 1==1 else: return thatguy.split(",")[2][0]=="S" def mosthealth(group): bigbad=group[0] for foe in group: if (health(foe)>health(bigbad)): bigbad=foe return bigbad def igotanuke(mine): return mine.count("P")-mine.count("T")>0 def guytonuke(allguys,fighters): backup=allguys[:] for Aguy in backup: if(health(Aguy)<4): allguys.remove(Aguy) if (shooter(Aguy)): fighters.remove(Aguy) if(len(allguys)==0): return mosthealth(backup) if (len(allguys)==len(fighters)): return mosthealth(allguys) else: for fighter in fighters: allguys.remove(fighter) return mosthealth(allguys) raw = sys.argv[2] player = raw.split(" ") thisisme=player.pop(0) turn = len(player[0].split(","))-1 guys=[] gunners=[] c=1 for dude in player: dude=str(c)+","+dude c+=1 if (health(dude)>0): guys.append(dude) if (shooter(dude)): gunners.append(dude) if (turn==0): print "P" elif(turn==49): print"S0" elif(igotanuke(thisisme))&( turn % 2 == 1): print "T"+str(ident(guytonuke(guys,gunners))) elif(len(guys)<2)&(len(gunners)>0) & (turn % 2 == 1): print P elif(turn % 2 == 0) & (len(gunners)>0): print "D"+str(ident(mosthealth(gunners))) elif(turn % 2 == 1) & (len(gunners)>0): print "S"+str(ident(mosthealth(gunners))) else: print "S"+str(ident(mosthealth(guys))) ``` ]
[Question] [ The Illuminati commands you (with their mind control) to output the following string: ``` ^ /_\ /_|_\ /_|_|_\ /_|/o\|_\ /_|_\_/_|_\ /_|_|_|_|_|_\ /_|_|_|_|_|_|_\ /_|_|_|_|_|_|_|_\ /_|_|_|_|_|_|_|_|_\ ``` # Rules: * Trailing spaces are allowed for each line. * Leading spaces in each line are required. * Trailing whitespace is allowed after the full required output. * Since this is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, the winner shall be the shortest program in bytes. * Since this is a [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'") challenge, hardcoded output is allowed. * [Standard Loopholes](https://codegolf.meta.stackexchange.com/q/1061/62402) apply. * Update: [You may use tabs instead of spaces, with each tab counting as 4 spaces. If you want for some reason.](https://codegolf.stackexchange.com/questions/146499/confirm-the-illuminati?noredirect=1#comment358486_146499) --- [Sandbox](https://codegolf.meta.stackexchange.com/a/14103/62402) (I would leave it for the full 72 hours recommended by the sandbox FAQ, but with 7 upvotes and next to no negative feedback, 38 should be fine) [Answer] # Vim, 40 bytes -2 bytes thanks to [DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) ``` 9i_|␛r\I/␛qqYPxR /␛q8@qr^4jhR/o\␛jr/2hr\ ``` 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) [![In action](https://i.stack.imgur.com/kiPwY.gif)](https://i.stack.imgur.com/kiPwY.gif) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 21 bytes ``` G¬χ|_¶_|↗⁹↙^M³↓/o¶\‖B ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z8gP6cyPT9Pw@rQGh0FQwMdBaWa@Ji8@BolTWuugKLMvBINq9CCoMz0jBIdBUuEmEt@eZ5PahpQUCkOpNQ3vyxVw1hHASwBV6aknx@TFxMDUhCUmpaTmlziVFpSklqUllOpoWn9//9/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` χ With sides of length 10 ¬ In the directions down and left G Draw a closed polygon (implicit side) |_¶_| Filled with |_ and _| on alternate lines ↗⁹ Draw a line of 9 /s ↙^ Draw a ^ and move the cursor down and left M³↓ Move down 3 characters /o¶\ Print the left half of the eye ‖B Reflect the canvas keeping the right edge ``` [Answer] # [V](https://github.com/DJMcMayhem/V), 37 bytes ``` 9i|_á\|r/òÄó_| >òC ^4jhR/o\j2hR\_/ ``` [Try it online!](https://tio.run/##K/v/3zKzJl768MKYmiL9w5sOtxzeHF/DZXd4k7NCnLRJVkaQfn6MdJZRRlBMvP7//wA "V – Try It Online") Hexdump: ``` 00000000: 3969 7c5f 1be1 5c7c 722f f2c4 f35f 7c0a 9i|_..\|r/..._|. 00000010: 3ef2 4320 5e1b 346a 6852 2f6f 5c1b 6a32 >.C ^.4jhR/o\.j2 00000020: 6852 5c5f 2f hR\_/ ``` Explanation: ``` 9i " Insert 9 copies of... |_ " '|_' <esc> " Return to normal mode á\ " Append a backslash | " Move to the first character r/ " Replace it with a forward slash ò " Recursively... Ä " Duplicate this line (upwards) ó " Remove one instance of.. _| " '_|' > " Indent this line with one space ò " End the loop C ^ " Change this line (previously '/_\') to ' ^' <esc> " Return to normal mode 4j " Move down 4 lines h " Move one character to the left R " Write this text over existing characters... /o\ " '/o\' <esc> " Return to normal mode j " Move down a line 2h " Move two characters to the left R " Write this text over existing characters... \_/ " '\_/' ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~31~~ ~~27~~ 25 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ^9∫Ƨ_|m└Κ}¹±§"/o¶\_”95žΓ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTVFOSV1MjIyQiV1MDFBN18lN0NtJXUyNTE0JXUwMzlBJTdEJUI5JUIxJUE3JTIyL28lQjYlNUNfJXUyMDFEOTUldTAxN0UldTAzOTM_) ``` ^ push "^" 9∫ } do 9 times, pushing counter Ƨ_| push "_|" m mold that to the counter └Κ prepend "/" ¹ collect the lines in an array - ["^", "/_", "/_|", ..., "/_|_|_|_|_"] ± reverse each ["^", "_/", "|_/", ..., "_|_|_|_|_/"] § reverse as ascii-art: [" ^", " /_", " /_|", ..., "/_|_|_|_|_"] "/o¶\_” push "/o \_" 95ž insert that at [9; 5] Γ palindromize horizontally ``` or a 24 byte version using `¼` (space to an antidiagonal) instead of `±§`: ``` ^9∫Ƨ_|m└Κ}¹¼"/o¶\_”95žΓ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JTIwJTVFOSV1MjIyQiV1MDFBN18lN0NtJXUyNTE0JXUwMzlBJTdEJUI5JUJDJTIyL28lQjYlNUNfJXUyMDFEOTUldTAxN0UldTAzOTM_) [Answer] # [Python 2](https://docs.python.org/2/), ~~103~~ ~~101~~ ~~98~~ 95 bytes -2 bytes thanks to Jonathan Frech -3 bytes thanks to ovs ``` for i in range(10):print(9-i)*' '+['^','/_%s\\'%['|_'*~-i,'|/o\|_','|_\_/_|_'][i%6/4*i%3]][i>0] ``` [Try it online!](https://tio.run/##Dce9DoMgFAbQV2Ehn1INVhuTOvgigDcd/LkLGOpiYnx1ZDtnP48t@DalJUTBgr2IP7/Oxbsphz2yP4pvzaWCwMtgQgVN8m8tpMFFUHfNFS4dbE4GWdKU6QzLXn8Uy85lj41L6QE "Python 2 – Try It Online") [Answer] # JavaScript (ES6), ~~95~~ 92 bytes ``` f=(n=9,s='')=>n--?f(n,s+' ')+s+`/${n-4?n-3?'_|'.repeat(n):'_|/o\\|':'_|_\\_/_|'}_\\ `:s+`^ ` ``` Or **91 bytes** with a leading new-line -- which I think is not allowed: ``` f=(n=9,s=` `)=>n--?f(n,s+' ')+s+`/${n-4?n-3?'_|'.repeat(n):'_|/o\\|':'_|_\\_/_|'}_\\`:s+`^` ``` ### Demo ``` f=(n=9,s='')=>n--?f(n,s+' ')+s+`/${n-4?n-3?'_|'.repeat(n):'_|/o\\|':'_|_\\_/_|'}_\\ `:s+`^ ` O.innerText = f() ``` ``` <pre id=O></pre> ``` ### Formatted and commented ``` f = (n = 9, s = '') => // n = line counter, s = leading spaces n-- ? // if we haven't reached the top: f(n, s + ' ') + // do a recursive call with one more leading space s + // append the leading spaces `/${ // append the left border n - 4 ? // if this is not the 4th row: n - 3 ? // if this is not the 3rd row: '_|'.repeat(n) // append the brick pattern : // else (3rd row): '_|/o\\|' // append the top of the eye : // else (4th row): '_|_\\_/_|' // append the bottom of the eye }_\\\n` // append the right border + line-feed : // else: s + `^\n` // append the top of the pyramid and stop the recursion ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ ~~122~~ ~~120~~ ~~119~~ ~~117~~ ~~115~~ 118 bytes -1 byte thanks to @xanoetux +3 missing the lowest level... ``` f(i){for(printf("%*c",i=10,94);--i;printf("\n%*c%s_\\",i,47,i^6?i^5?"_|_|_|_|_|_|_|_|_|"+i*2:"_|_\\_/_|":"_|/o\\|"));} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI1OzOi2/SKOgKDOvJE1DSVUrWUkn09bQQMfSRNNaVzfTGiYTkweUUy2Oj4kBKtAxMdfJjDOzz4wztVeKr0GHStqZWkZWIImYmHh9IB/E1s@PialR0tS0rv2fm5iZp6FZzaWgkKahac1V@x8A "C (gcc) – Try It Online") [Answer] ## Haskell, ~~110~~ 107 bytes ``` " ^\n"++do z<-[1..9];([z..8]>>" ")++'/':g z++"_\\\n" g 4="_|/o\\|" g 5="_|_\\_/_|" g x=[2..x]>>"_|" ``` [Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0kBBuJi8pS0tVPyFapsdKMN9fQsY601oqv09Cxi7eyUFJQ0tbXV9dWt0hWqtLWV4mNigKq50hVMbJXia/TzY2JqQDxTEA8oF68fD@ZX2EYb6elVgAwACvzPTczMU7BVKCgtCS4pUkj7/y85LScxvfi/bnJBAQA "Haskell – Try It Online") Those 9 space at the beginning hurt. How it works ``` " ^\n"++ -- first line, followed by do -- we use the "do" syntatic sugar for monads, -- here the list monad z<-[1..9] -- for all 'z' from [1..9] perform the following -- and collect the results in a single list ([z..8]>>" ")++'/' -- make the spaces for the current line and -- the left wall '/' g z -- call g to make the inner part "_\\\n" -- append '_', '\' and a NL g 4="_|/o\\|" -- line 4 and 5 are implemented directly g 5="_|_\\_/_|" g x=[2..x]>>"_|" -- all other lines are some copies of "_|" ``` Edit: -3 bytes thanks to @Laikoni: [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~109~~ 105 bytes ``` filter f{' '*$_+'/'+'_|'*(8-$_)+'_\'} ' '*9+'^' 8|f 7|f 6|f ' /_|/o\|_\ /_|_\_/_|_\' 3..0|%{$_|f} ``` [Try it online!](https://tio.run/##LYlBCoMwFET3/xRZpIwaagRB7V1C/yqhhYCigot8zx5j6cAb3jDLfPh1@/gYcw7fuPtVhQSFRrOBhQELmmp6aq6LO5x0ny@DN2iSQGNhKEDdsSx2dsKO/osd/xrUt20nj6RZwpnzBQ "PowerShell – Try It Online") *Saved 4 bytes thanks to Veskah.* [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~47~~ ~~42~~ 40 bytes ``` '/„_|ûûû«η'^0ǝ.∞.C":;<IJK"Çv"/o\\_/"Nèyǝ ``` [Try it online!](https://tio.run/##MzBNTDJM/f9fXf9Rw7z4msO7QfDQ6nPb1eMMjs/Ve9QxT89ZycraxtPLW@lwe5mSfn5MTLy@kt/hFZXH5/7/DwA "05AB1E – Try It Online") ``` '/„_|ûûû« # Push bottom left tier of pyramid. η # All prefixes of... '^0ǝ # Replace the tip. .∞.C # Mirror, Center. ":;<IJK"Ç # Push [58,59,60,73,74,75]. v"/o\\_/"Nèyǝ # Replace those indexes with the eye. ``` --- Stupid version: `„_|3×"_|/o\|".;„_|2×û"_|_\_/_".;` --- Other, less stupid version (but still worse): # [05AB1E](https://github.com/Adriandmen/05AB1E), 42 bytes ``` •~µÎт•η4¾ǝ•Σ}•4ǝ•3x1•5ǝεS"|_/\^o"sèJ}€.∞.C ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOiukNbD/ddbAKyzm03ObTv@FwQa3EtkDQBs40rDIGk6fG557YGK9XE68fE5SsVH17hVfuoaY3eo455es7//wMA "05AB1E – Try It Online") [Answer] # [Bubblegum](https://esolangs.org/wiki/Bubblegum), 48 bytes ``` 00000000: 5380 8138 2e18 4b3f 3e86 0bce ac01 72e0 S..8..K?>.....r. 00000010: 6c30 0fc6 d1cf 8f01 71e1 cae2 218a e12a l0......q...!..* 00000020: 6ba0 ea61 7c84 085c 0021 0417 4188 0100 k..a|..\.!..A... ``` [Try it online!](https://tio.run/##Lc6xDsIwDATQna84VgbLTtrUYgAxM7KyJMFhoAwgdePfQwI9yZN1z05LSrPdl2etvGaP0StDxSuciWJIvsCbBnDKhphZMDlj4EKkROfjgXretPkL0oyQPYNLDrhJLtDSS2KCHM3BiUaYuAjM/CvTq82WaLcarhspMiyG1sw6gHXMaBsBDzJhEFW0W@2PB1H8EF07cGpOrV8 "Bubblegum – Try It Online") [Answer] # PHP, 123+3 bytes +3 bytes for the weird tab counting. (it still moves the cursor 8 spaces in any console!) ``` for($i=10;--$i;)$r.=str_pad(str_pad(" ",$i)."/",20-$i,"_|")."\\";$r[48]=$r[65]="/";$r[50]=$r[63]="\\";$r[49]=o;echo" ^$r"; ``` Note: The first character after `echo"` is a tab character! Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/fbab51e242680fef041c3acacfdaf015e546a126). other version, same length: ``` for(;$i++<9;)$r.=str_pad(str_pad(" ",10-$i)."/",10+$i,"_|")."\\";$r[48]=$r[65]="/";$r[50]=$r[63]="\\";$r[49]=o;echo" ^$r"; ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~79~~ 73 bytes ``` /8x 8 $* +`^(.*)\Sx $1x¶$& x ^ /111x /1/o\|x /1111x /1x_/1x 1 _| x _\ ``` [Try it online!](https://tio.run/##K0otycxL/P@fS9@igsuCS0WLSzshTkNPSzMmuIJLQcWw4tA2FTUuBSA7jkvf0NCwAkjq58fUVIB5YG5FPBBzGXLF13BVcMXH/P8PAA "Retina – Try It Online") [Answer] # Ruby, 92 bytes ``` 10.times{|i|s=' '*(10-i)+(i<1??^:"/#{"_|"*~-i}_\\");i/2==2&&s[9,3]="/o\\_/"[i%2*2,3];puts s} ``` [Answer] # Excel VBA, 104 Bytes Anonymous VBE immediate window function that confirms the truth. **Version A:** ``` ?Spc(9)"^":For i=0To 8:[A1]=i:?Spc(8-i)"/_"[If(A1=3,"|/o\|_",If(A1=4,"|_\_/_|_",Rept("|_",A1)))]"\":Next ``` **Version B:** ``` ?Spc(9)"^":For i=0To 8:[A1]=i:?Spc(8-i)"/_"IIf(i=3,"|/o\|_",IIf(i=4,"|_\_/_|_",[Rept("|_",A1)]))"\":Next ``` [Answer] # [Python 2](https://docs.python.org/2/), 154 bytes ``` l=bytearray a,b=' _';g=[l(a*9+"^"+a*9)]+[l(a*(8-k)+"/%s\\"%"|".join(b*k+b))for k in range(9)] g[4][8:11]=l("/o\\") g[5][8:11]=l("\\_/") for r in g:print r ``` [Try it online!](https://tio.run/##TcvRCoIwFIDhe59iHBA3Vw2jwIw9iTPZwKYpm5x2I/Tua3bV1Q8f/OsWRu/OMS7SbGHQiHrL9MHIgvTF3cp2obq8cXgAT2Ud/wGtjzPjIPK3UpDDB04vPzlqypkbxp4eyUwmR1A7O9B0Zba9dG3dVFUnFwrCp40lvP6hUr1IuM@4z7ZZcXKBYIxf "Python 2 – Try It Online") -3 bytes using `bytearray` thanks to Rod -1 byte thanks to bobrobbob [Answer] # Javascript 90 bytes (if default parameter a=9 is required then 92 bytes) ``` A=(a,x=``)=>a?A(a-1,x+" ")+x+"/".padEnd(a*2,a^5?a^4?"_|":"_|/o\\|":"_|_\\_/")+`\\ `:x+`^ ` console.log(A(9)) ``` [Answer] # Java 8, 156 bytes ``` v->"".format("%1$9s^\n%1$8s/a%1$7s/ba%1$6s/bba /b/o\\|a /b_\\_/ba /bbbbba /bbbbbba /bbbbbbba/bbbbbbbba","").replace("a","_\\\n").replace("b","_|") ``` **Explanation:** [Try it here.](https://tio.run/##TVBdawMhEHzvr1ikAYVG6Us/CO0/aF4KfalNWI0ppp4ep3cQmvz2y5q7QsFlZmeXZcYDDrhMrYuH3c9oA@YMb@jj7w2Aj8V1e7QO1rUFeC@dj99g@UfyOxjEitQzFb1csHgLa4jwAuOwfGVM7lPXYOFscX/7nDc6Ej5lhQSPWZmKD4QG62lQRiWtTzjxrdZbdZ3QgrnuTITYTAz@EYPsjjEhO9cGcstZ7emCjv9FU8UTE@Nqctz2JpDj2fhQEzUUnE8hP78AxZz6mItrZOqLbGlUeJSWxz4EMX/AebwA) ``` v-> // Method with empty unused parameter and String return-type "".format( // Format the following String (`%1$Ns` = N spaces) "%1$9s^\n // ^ %1$8s/a // /_\ %1$7s/ba // /_|_\ %1$6s/bba // /_|_|_\ /b/o\\|a // /_|/o\|_\ /b_\\_/ba // /_|_\_/_|_\ /bbbbba // /_|_|_|_|_|_\ /bbbbbba // /_|_|_|_|_|_|_\ /bbbbbbba // /_|_|_|_|_|_|_|_\ /bbbbbbbba","") // /_|_|_|_|_|_|_|_|_\ .replace("a","_\\\n") // Replace all "a" with "_\" + new-line .replace("b","_|") // Replace all "b" with "_|" // End of method (implicit / single-line return-statement) ``` [Answer] # Julia, ~~152~~ ~~141~~ ~~139~~ ~~130~~ ~~127~~ ~~120~~ ~~113~~ 112 bytes ``` q="_|";a+b=" "^a*b;a\b=replace(a,q^3,q*b,1);~n=n<0?9+"^\n":~(n-1)*(8-n+"/$(q^n)_\\\n");print(~8\"/o\\|"\"_\\_/") ``` Explained: ``` #Define constant q to abbreviate this string q="_|"; #Redefine the addition operator to compactly provide whitespace #where needed a+b=" "^a*b; #Redefine the inverse division operator so we can substitute #"_|_|_|" with "_|"*b very compactly a\b=replace(a,q^3,q*b,1); #Redefine the bitwise not operator to generate pyramid layers #Defines them recursively, calling itself to generate previous #layers before appending its own. #The base case generates the tip. ~n=n<0?9+"^\n":~(n-1)*(8-n+"/$(q^n)_\\\n"); #Print to output print( #Pyramid with 8 body layers ~8 #Then patch in the eye \"/o\\|" \"_\\_/" ) ``` [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 174 153 bytes ``` ()=>string.Format(@"{1,10} {0,10}\ {0,9}{2}{3,10}{2}{0,7}|/o\{2}{3,8}\_/_{2}{0,5}{4} {3}{4} {3}|_{4}{3}|_|_{4}","/_","^",@"|_\ ","/_|_",@"|_|_|_|_|_\ ") ``` [Try it online!](https://tio.run/##NY/BasMwDIbP01MIn2zImrRd6UbWUhj01MFgh11CTfDMMLQ22O5gOHr2zE4oAn2/PnSQVHhUzuvxFoz9wc@/EPW1BXXpQ8CPBCH20Sg83qx6DdHnnT165yLucORit5/d4uj8tY/8wNKyWjYEqSnoCl8orSity1xCU21pqF03y2fqZC1nv6H0RIhpPTFjkDlMnBKrWC1zO7PqwAbZwSQGOY/3ylqMLdwP/3XmG997Y7mABA9vzgZ30Ysvb6I@Gat5eYYL0QIBjf8 "C# (.NET Core) – Try It Online") An inefficient way of building the pyramid, but interesting working through it. ### Acknowledgements -21 bytes thanks to @someone [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 144 bytes This one may seem quite boring, because it is quite boring. ``` ()=>@" ^ /_\ /z\ /z|_\ /_|/o\|_\ /z\_/z\ /z|z|z\ /z|z|z|_\ /z|z|z|z\ /z|z|z|z|_\".Replace("z","_|_") ``` [Try it online!](https://tio.run/##NY/NCgIhFEbX@RQXVwo1PsA0EQStCqIWbYZETEKYNNQJmp9nN6fGezfn@ziLe6VfSetUbL02D7h8fFDPEslGeA@nHvkggpawb41c@@CSswFnbYAKIqHVZoshzw1lYrzOzLqMrBtyzfjAbJ1jUvisJSfthH/6KTOmOlOqcXFWr0ZIRXCHl5gPHNNYonzv2@o7HIU2hKIeLXbWeNuo4up0UAdtFJl@IJSWaERj/AI "C# (.NET Core) – Try It Online") [Answer] # [Splinter](https://esolangs.org/wiki/Splinter), 124 bytes ``` H{\/}G{BB}F{\_DG}E{\ H}D{\\\ }C{A\|}B{\ \ }A{\_\|\_}GG\ \^\ GGHFBEADGBHCFE\_\|H\o\\\|FHA\\\_HADBECCADBHCCC\_DECCCADHCCCC\_\\ ``` [Try it online!](https://deadfish.surge.sh/splinter#SHtcL31He0JCfUZ7XF9ER31Fe1wgSH1Ee1xcXAp9Q3tBXHx9QntcIFwgfUF7XF9cfFxffUdHXCBcXlwKR0dIRkJFQURHQkhDRkVcX1x8SFxvXFxcfEZIQVxcXF9IQURCRUNDQURCSENDQ1xfREVDQ0NBREhDQ0NDXF9cXA==) [Answer] # JavaScript, 117 bytes I know for a *fact* I'm not beating any of the golfing languages, but at least I can give my own solution. ``` $=>[...Array(10)].map((e,i)=>' '.repeat(9-i)+(i--?`/${['_|/o\\|','_|_\\_/_|'][i-3]||'_|'.repeat(i)}_\\`:'^')).join` ` ``` Here's a demo: ``` var f = $=>[...Array(10)].map((e,i)=>' '.repeat(9-i)+(i--?`/${['_|/o\\|','_|_\\_/_|'][i-3]||'_|'.repeat(i)}_\\`:'^')).join` `; console.log(f()); console.log(f.toString().length); ``` Explanation: ``` $=> // outer function start [...Array(10)] // create an array to map .map(…) // map it (e,i)=> // mapping function start ' '.repeat(9-i) // spaces for padding +(i--?…:'^') // use the carat if at the top of the pyramid `/${…}_\\` // otherwise, make the sides + steps ['_|/o\\|','_|_\\_/_|'][i-3] // use the patterns for the eye, if in the correct rows ||'_|'.repeat(i) // otherwise, make the "bricks" structure .join` ` // join all the rows into a string (yes this part has a newline in it) ``` [Answer] # Javascript, 238 bytes My very first try at codegolfing :D ``` var f=()=>{let b=x=>' '.repeat(x),g='\\',h='/',i=1,st=[(b(9)+'^').split('')];for(;i<10;i++)st.push((b(9-i)+h+st.map(i=>'_').join('|')+g).split(''));st[4][8]=st[5][10]=h;st[4][9]='o';st[5][8]=st[4][10]=g;return st.map(s=>s.join('')).join('\n');} document.getElementById("display").innerHTML = f(); console.log(f.toString().length); ``` ``` <pre id="display"> </pre> ``` ]
[Question] [ Given two strings, output a third string that is not equal to either of the two inputs, but has the same length (in characters) as either of the inputs. There is guaranteed to be at least one valid output. # Test Cases Test cases are quoted to show they are strings. Outputs are one of many possible. ``` input, input -> output "test", "test" -> "tttt" "do", "don't" -> "dnut_" "ye s", "yes" -> "fals" "yes", "yes" -> "noo" "maybe", "mayue" -> "false" "false", "false" -> "truee" "false", "true" -> "fatr" "1", "" -> "0" "", "t" -> "s" "", "abcabc" -> "testst" "abcdefghijklmnopqrstuvwxyz", "aaaaaaaaaaaaaaaaaaaaaaaaaa" -> "zbcdefghijklmnopqrstuvwxya" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" -> "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" ``` ## Rules * You may chose your input domain, but it must be composed of at least printable ASCII, and your output domain must be the same as your input domain. * The input lengths may be the same or different. * The output must be valid with probability 1; that is, you may generate random strings until one is valid (and theoretically you might infinite loop), but you can't just output a random string and hope it's valid. Note that this means you output does not need to be deterministic. * Automatic trailing newlines allowed, but they do not count towards the length of the output. * Due to questions regarding Memory Errors, it must work within 60 seconds up to input lengths of `6`. An answer that works for that and theoretically works for longer strings is OK, but something that Memory Errors on modern computer for input length `4` is not valid. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins. [Answer] # Haskell, 43 bytes ``` x!y=[s|s<-(<$max x y)<$>"abc",s/=x,s/=y]!!0 ``` Takes the max (lexicographically later) string, which we know is nonempty; replaces all characters with one of "a", "b", and "c" using `<$`; and returns the first that is neither of the inputs. I think this is similar to [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/139625/19857) and/or [geokavel's CJam answer](https://codegolf.stackexchange.com/a/139627/19857). (I've lurked for a while but this is my first time answering on this site; hi!) [Answer] # Brainfuck, 97 bytes ``` +>+[-,[>>,]<<[<<]>]>>[>]<<<[<]>[<+>>[-<+<+>>][>]<[->+<]<[-]>>>++<[<]>[.>>]>[>>]]>[+[>]+[<]>[.>>]] ``` [Run code online](https://copy.sh/brainfuck/?c=IyBMZXQgKEtuKSBiZSB0aGUgbnRoIGNoYXJhY3RlciBvZiBLCiMgTGV0ICheKSBkZXNpZ25hdGUgdGhlIHBvaW50ZXIKIyBMZXQgRiBiZSB0aGUgZmlyc3Qgc3RyaW5nIGlucHV0dGVkCiMgTGV0IFMgYmUgdGhlIHNlY29uZCBzdHJpbmcgaW5wdXR0ZWQKCis-K1stICAjIFR3aWNlIGRvCixbPj4sXSAgIyBJbnB1dCBzdHJpbmcgKGNoYXJhY3RlcnMgc2VwYXJhdGVkIGJ5IDEpCjw8Wzw8XT4gICMgR28gdG8gbGVmdCBvZiBiZWdpbm5pbmcgb2Ygc3RyaW5nCl0-ICAjIEVuZCBvbiBmaXJzdCBjaGFyYWN0ZXIgb2Ygc2Vjb25kIHN0cmluZwojIElmIHNlY29uZCBzdHJpbmcgaXMgbnVsbCB3ZSB3aWxsIGVuZCBvbmUgdG9vIGZhciB0byB0aGUgbGVmdAo-Wz5dPDw8WzxdPiAgIyBJZiBmaXJzdCBzdHJpbmcgaXMgbnVsbCB3ZSB3aWxsIGVuZCB0aGVyZSB0b28KIyBXZSB3aWxsIHVzZSB0aGlzIHRvIGRvIGZsb3cgY29udHJvbAoKWyAgIyBPbmx5IHJ1biBpZiBib3RoIHN0cmluZ3Mgd2VyZSBub24gbnVsbAoKIyBUYXBlOiAgICBTMCAnIEYwICcgUzEgJyBGMSAnIFMyICcgRjIgJyBldGMKIyAgICAgICAgICBeCgo8Kz4-ICAjIExldCBGMCogPSBGMCAocGx1cykgMSAgKGlzIDEgYXMgb2Ygbm93OyBGMCB3aWxsIGJlIGFkZGVkIGxhdGVyKQpbLTwrPCs-Pl0gIyBMZXQgQSA9IFMwIChwbHVzKSBGMAojIEEgbWF5IG9yIG1heSBub3QgYmUgemVybwojIEYwKiBtYXkgb3IgbWF5IG5vdCBiZSB6ZXJvCiMgVGFwZTogICAgRjAqICcgQSAnIDAgICcgUzEgJyBGMSAnIGV0YwojICAgICAgICAgICAgICAgIF4KCls-XTxbLT4rPF0gICMgTGV0IEIgPSBBIG9yIEYwKgojIEIgbWF5IG9yIG1heSBub3QgYmUgemVybwo8Wy1dPj4gICMgQ2xlYXIgRjAqCiMgVGFwZTogICAgIDAgJyBCICcgMCAnIFMxICcgRjEgJyBldGMgICAgKGlmIEEgd2FzIHplcm8pCiMgICAgICAgICAgICAgICBeCiMgT1IgICAgICAgIDAgJyAwICcgQiAnIHMxICcgRjEgJyBldGMgICAgKGlmIEEgd2FzIG5vbnplcm8pCiMgICAgICAgICAgICAgICAgICAgXgoKIyBMZXQgQyA9IEIgb3IgMgojIEMgd2lsbCBiZSBndWFyYW50ZWVkIG5vbnplcm8gYW5kIHVuaXF1ZSBmcm9tIFMwIGFuZCBGMAo-Kys8WzxdPiAgIyBDcmVhdGUgQwpbLj4-XSAgIyBQcmludCAodXNpbmcgUyBvciBGOyBkb2VzIG5vdCBtYXR0ZXIpCgo-Wz4-XSAgIyBFbmQgb24gYSB6ZXJvIGNlbGxzIHdpdGggemVybyBjZWxscyBhbGwgdG8gdGhlIHJpZ2h0CiMgVGhpcyBpcyBuZWNlc3NhcnkgZm9yIHRoZSBjb21pbmcgZnVuY3Rpb25hbGl0eQojIGFsc28gYXMgdG8gbm90IGxvb3AKXSAgIyBFbmQgbm9uIG51bGwgYmxvY2sKCiMgTm93IHdlIGNvbnNpZGVyIGlmIG9uZSBvZiB0aGUgc3RyaW5ncyB3YXMgbnVsbAojIFRhcGU6ICAgIDAgJyBFMCAnIDAgJyBFMSAnIGV0YyAgICAoaWYgb25lIHN0cmluZyB3YXMgbnVsbCkKIyAgICAgICAgICBeCiMgVGFwZTogICAgMCAnICAwICcgMCAnICAwICcgZXRjICAgIChpZiBuZWl0aGVyIHN0cmluZyB3YXMgbnVsbCkKIyAgICAgICAgICBeCiMgV2hlcmUgRSBpcyBGIG9yIFMgKHdlIGRvbid0IGNhcmUpCgo-WyAgIyBFeGVjdXRlIG9ubHkgaWYgb25lIHN0cmluZyB3YXMgbnVsbAoKKyAgIyBMZXQgQSA9IEUwIChwbHVzKSAxCiMgQSBtYXkgb3IgbWFueSBub3QgYmUgemVybwojIFRhcGU6IDAgJyBBICcgMCAnIEUxICcgZXRjCiMgICAgICAgICAgIF4KCls-XStbPF0-ICAjIExldCBCID0gQSBvciAxCiMgQiBpcyBndWFyYW50ZWVkIG5vbnplcm8gYW5kICE9IEUwCiMgVGFwZTogMCAnIEIgJyA_ICcgRTEgJyAwICcgRTIgJyBldGMKIyAgICAgICAgICAgXgoKWy4-Pl0gICMgUHJpbnQKCiMgRW5kIG9uIHplcm8gY2VsbCBhcyBub3QgdG8gbG9vcApdICAjIEVuZCBudWxsIGJsb2Nr) (note that "dynamic memory" must be selected in the bottom-right) Awesome challenge! I thought it would be trivial but it ended up being really difficult. I keep coming back to it because I feel like there *should* be some elegant 20-or-so-byte BF solution. At this point, I'm pretty happy I (seemingly) got it to work at all in BF. Input is taken as `str1` + `\0` + `str2`, where strings are consecutive non-zero 1-byte characters. Returns `(first str1 + first str2) or (first str1 + 1) or 2`. This algorithm was thought up by the brilliant @ØrjanJohansen, (presumably) based on my (broken) original one. Commented: ``` # Let (Kn) be the nth character of K # Let (^) designate the pointer # Let F be the first string inputted # Let S be the second string inputted +>+[- # Twice do ,[>>,] # Input string (characters separated by 1) <<[<<]> # Go to left of beginning of string ]> # End on first character of second string # If second string is null we will end one too far to the left >[>]<<<[<]> # If first string is null we will end there too # We will use this to do flow control [ # Only run if both strings were non null # Tape: S0 ' F0 ' S1 ' F1 ' S2 ' F2 ' etc # ^ <+>> # Let F0* = F0 (plus) 1 (is 1 as of now; F0 will be added later) [-<+<+>>] # Let A = S0 (plus) F0 # A may or may not be zero # F0* may or may not be zero # Tape: F0* ' A ' 0 ' S1 ' F1 ' etc # ^ [>]<[->+<] # Let B = A or F0* # B may or may not be zero <[-]>> # Clear F0* # Tape: 0 ' B ' 0 ' S1 ' F1 ' etc (if A was zero) # ^ # OR 0 ' 0 ' B ' s1 ' F1 ' etc (if A was nonzero) # ^ # Let C = B or 2 # C will be guaranteed nonzero and unique from S0 and F0 >++<[<]> # Create C [.>>] # Print (using S or F; does not matter) >[>>] # End on a zero cells with zero cells all to the right # This is necessary for the coming functionality # also as to not loop ] # End non null block # Now we consider if one of the strings was null # Tape: 0 ' E0 ' 0 ' E1 ' etc (if one string was null) # ^ # Tape: 0 ' 0 ' 0 ' 0 ' etc (if neither string was null) # ^ # Where E is F or S (we don't care) >[ # Execute only if one string was null + # Let A = E0 (plus) 1 # A may or many not be zero # Tape: 0 ' A ' 0 ' E1 ' etc # ^ [>]+[<]> # Let B = A or 1 # B is guaranteed nonzero and != E0 # Tape: 0 ' B ' ? ' E1 ' 0 ' E2 ' etc # ^ [.>>] # Print # End on zero cell as not to loop ] # End null block ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` żḟ@€ØAZḢ ``` **[Try it online!](https://tio.run/##AR4A4f9qZWxsef//xbzhuJ9A4oKsw5hBWuG4ov///0H/QUE "Jelly – Try It Online")** ### How? ``` żḟ@€ØAZḢ - Link: list of characters, a; list of characters, b ż - zip a and b ØA - uppercase alphabet ḟ@€ - filter discard for €ach (swap @rguments) Z - transpose the result Ḣ - head ``` [Answer] # [Python 3](https://docs.python.org/3/), 62 47 57 54 51 bytes **Edit:** - 5 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) **Edit:** +10 bytes to fix a bug **Edit:** -3 bytes thanks to [@betaveros](https://codegolf.stackexchange.com/users/19857/betaveros) **Edit:** -3 bytes by using max instead of pop ``` lambda x,y:max({*"abc"}-{x[:1],y[:1]})+max(x,y)[1:] ``` [Try it online!](https://tio.run/##K6gsycjPM/6fYxvzPycxNyklUaFCp9IqN7FCo1pLKTEpWalWt7oi2sowVqcSRNZqaoPkgGo0ow2tYv8XFGXmlWjkaCgp6SgZFippav4HAA) [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes ``` FEα×ι⌈⟦LθLη⟧¿¬№⟦θη⟧ιPι ``` [Try it online!](https://tio.run/##LYkxDoMwDAD3vsKjI5kXdOxKmFgAMVgIGksJgZAgfu@C1JtOd5PjNEX2qktMgJY3ZIJWwnygEFi@JJSAQz2v3@xwNwR/dWY0NyALYBMzfmJZMw47gRsJ5Fm2@CxbkruLeat23avvtTq1OvwP "Charcoal – Try It Online") Link is to verbose version of code. Generates all strings of uppercase characters repeated to the length of the longer input and overprints all those that don't appear in the input. In other words, the output is normally `ZZZ...` unless that is one of the inputs, in which case it's `YYY...` unless that is the other input, in which case it's `XXX...`. [Answer] # Mathematica, 111 bytes ``` (c=Characters;a=#2;While[f=Alphabet[]~RandomChoice~Length@#;f==#||f==c@a]&[#&@@c@{##}~MaximalBy~Length];""<>f)& ``` [try it online](https://sandbox.open.wolframcloud.com/app/objects/) (paste code with ctrl+v, place input at the end and hit shift+enter) input > > ["test","me"] > > > *thanx **@Not a tree** for checking and golfing -21 bytes* [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~38~~ 30 bytes ``` {(1 x.max.comb...*∉$_).tail} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rDUKFCLzexQi85PzdJT09P61FHp0q8pl5JYmZO7f/ixEqFNI1oJUNDQyUdIGmkFKtpzQUTtQSKWRgYoIgp6SgolaQWl6AIggWAEmDB/wA "Perl 6 – Try It Online") Anonymous codeblock that takes input as a list of two strings, and returns the first number from `1111...` with a non-empty amount of 1s that isn't in the input. ### Explanation: ``` { } # Anonymous code block 1 x.max.comb # String multiply 1 by the size of the non-empty string ... # Create a sequence increasing by 1 *∉$_ # Until the number is not in the input ( ).tail # And take the last number ``` [Answer] # [Zsh](https://www.zsh.org/), ~~51~~ ~~47~~ ~~37~~ 36 bytes ***-4** bytes by using builtin array `argv`, **-10** bytes by using prefix removal and `RC_EXPAND_PARAM`, **-1** byte by inlining the brace expansion.* ``` <<<${${${:-{1..3}${^@#?}}:|argv}[1]} ``` [Try it online!](https://tio.run/##LcjRCoIwGIbh813Fhwn/kcLqzAZ1H1Gw2l8OxiZOFFy79qUQ78nLs8a@LL11jJG1gbOezzBB8KwdIk9oGlT1zlVRStVpr2uSbNtTrtPjerjk3H31@JnzTd5zMcFzkTgKIkghQSToHQKeeiT8b92MvYkANlvs1CMO@sUbkPgB "Zsh – Try It Online") First, this was an awesome challenge, I went through a ton of ideas before landing on this one. ``` <<<${${${:-{1..3}${^@#?}}:|argv}[1]} ${:- } # empty fallback ${ @#?} # remove first character from each parameter ${^@ } # enable brace expansion (set -P) {1..3}${^@#?} # expand to 1foo 2foo 3foo 1bar 2bar 3bar ${ :|argv} # Set difference with 'argv' ${ [1]} # The first found element <<< # print to stdout ``` `@` and `*` are not identifiers, so `${ :|@}` and `${ :|*}` don't work, hence the use of `${ :|argv}` > > This method will work up to 93 inputs and find a 94th which is unique. Simply replace the `{1..3}` with the maximum possible range `{~..!}`. > > > # [Zsh](https://www.zsh.org/), ~~48~~ 47 bytes\* ``` for ((;$#i<${#${1:-$2}}||$@[(I)$i];i++)): <<<$i ``` [Try it online!](https://tio.run/##qyrO@P8/Lb9IQUPDWkU500alWlml2tBKV8WotramRsUhWsNTUyUz1jpTW1tT04rLxsZGJfM/EBgaAAA "Zsh – Try It Online") Completely new method courtesy of JoKing's Perl 6 submission, but doesn't work on large strings (n>20) due to integer size restrictions. `$@[(I)$i]` is reverse array lookup to largest index, it will output zero (falsy in arithmetic expansion) if $i is not found in the command line parameters. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ 7 bytes ``` øvAyм¬? ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8I4yx8oLew6tsf//Pzk/JZUrPT8nDQA "05AB1E – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 12 bytes ``` c"1Y2@X-1)&h ``` Input is a cell array of strings containing printable ASCII chars. The output is formed from the letters `'ABC'`, and so belongs to the input domain. [Try it online!](https://tio.run/##y00syfn/P1nJMNLIIULXUFMt4///avXEpGR1HQV1RydnF1f1WgA "MATL – Try It Online") ### Explanation The output is as long as the longest input string. Its *n*-th character is the first letter from `'ABC'` that is different from the *n*-th character of both input strings. ``` c % Concatenate the two strings vertically. If one is shorter it is % right-padded with spaces. Gives a 2-row character matrix " % For each column 1Y2 % Push the string 'ABC...Z' (the upper-case letters) @ % Push current column X- % Set difference 1) % Get first character &h % Horizontally concatenate the results so far % End (implicit). Display stack (implicit) ``` [Answer] ## Haskell, ~~56~~ ~~52~~ 48 bytes ``` x#y|_:t<-max x y=[c:t|c<-"abc",c:t/=x,c:t/=y]!!0 ``` [Try it online!](https://tio.run/##VYy9DsIgFIV3n@L2doGEqnNT3kAnx6ZpAGs0FtIgJJD03RHRDi7n58vJuYvXc5rnlEId17F1XaNFgACR96p1q@oaFFIhy@XAw9fiUFXHpMXDAActlvMIZPHu4uzJ7L1R3tpIakqh3wEAQTHdkOE1K2U/8rlEmXUjyLIV/r/BnDciCykbGNIb "Haskell – Try It Online") Replace the first char of the maximum of the two input strings with `a`, `b`and `c` and pick the first one that is different from both input strings. [Answer] # [Ruby](https://www.ruby-lang.org/), 53 bytes ``` ->a,b{([?a,?b,?c].map{|e|e*[a,b].max.size}-[a,b])[0]} ``` [Try it online!](https://tio.run/##bcxLCoMwEAbgvacIKlRLlPYArQexLhKdgFAfmAi16tltxidqZ5HM/80wVc2bwRaP1@A9GeWtEwaMBpwGceRnrGw76OAa6gnGjy/TL/TemN3wFvVDAoIokMrR5BpEV1krSUwRWi3z01yWEKueEqvla4rIQ2dbTGcXNQ3IE8PAY8TE16TzP1tSoCRFflmpASIRG5AbHSVjDQc03dSwqGBvOerUHFVV2yrDQpyaf3pCjrXoHWVdGce7FO/SeoyfN5cw7Q0/ "Ruby – Try It Online") Basically generates the strings `a...a`, `b...b`, and `c...c` and selects the first not in the input. [Answer] # ES6, 54 bytes ``` a=>b=>(a[0]+b[0]|0?'a':9-(a[0]^b[0]))+(a||b).substr(1) ``` [Answer] # Pyth, 7 ~~8~~ bytes ``` hC-LG.T ``` *1 byte thanks to Jakube* [Test suite](https://pyth.herokuapp.com/?code=hC-LG.T&input=%22test%22%2C+%22test%22+-%3E+%22tttt%22%0A%22do%22%2C+%22don%27t%22+-%3E+%22dnut_%22%0A%22ye+s%22%2C+%22yes%22+-%3E+%22fals%22%0A%22yes%22%2C+%22yes%22+-%3E+%22noo%22%0A%22maybe%22%2C+%22mayue%22+-%3E+%22false%22%0A%22false%22%2C+%22false%22+-%3E+%22truee%22%0A%22false%22%2C+%22true%22+-%3E+%22fatr%22%0A%221%22%2C+%22%22+-%3E+%220%22&test_suite=1&test_suite_input=%22test%22%2C+%22test%22+%0A%22do%22%2C+%22don%27t%22+%0A%22ye+s%22%2C+%22yes%22+%0A%22yes%22%2C+%22yes%22+%0A%22maybe%22%2C+%22mayue%22+%0A%22false%22%2C+%22false%22+%0A%22false%22%2C+%22true%22+%0A%221%22%2C+%22%22+%0A%22abcdefghijklmnopqrstuvwxyz%22%2C+%22aaaaaaaaaaaaaaaaaaaaaaaaaa%22&debug=0) We use `.T`, length preserving transpose, rather than `C`, truncating transpose, so that it works on inputs where one string is empty. Given two strings as a tuple, we transpose them (`.T`), then map the resulting pair of characters or single character by subtracting the character(s) from the lowerase alphabet with `-LG`, then transpose the resulting list of strings of unused characters with `C`, then return the first such string with `h`. This consists of the first letter alphabetically that is not in either string, for each position. [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~100~~ 73 bytes -27 bytes thanks to @Nevay's magical touch! :) ``` a->b->{b=b.length<1?a:b;if(a.length<1||(b[0]^=2)==a[0])b[0]^=1;return b;} ``` [Try it online!](https://tio.run/##ZZJRb4IwEMef56e4kJjBosTCmwjLsmRve9qjuqRoURy2pC0uRPnsrrXo3I2kubvfXf@9cLejBzoWNeO79de53NdCatgZFja6rMKi4StdCh4@JYO6yatyBauKKgXvtORwHAD0VGmqjTmIcg17k/M/tCz5Zr4EKjcquJQCvPVys9WWyvlyhGNnsgyK9EzHWT7OjnmahxXjG72dkWc6zZOy8OmNnE5@Pp8sP9MoSFNqvMCFJJFMN5JDnnTn5PL2tSHTkmZKK0hNUw9HzwbeCJztRhathQVrwR@vpGWgLGuZuhEE9rTNmUXGaVgPC1qpC3QOglq6Qrh8R49YeA9sTO7BxBuZg8C/igiDGL3yV4NgDYI1CNaIsEaENSKsEWGNGGvEWCPGGvG9RufmWgj5u2x2iFM33@vOmcm3SrN9KBod1qZOF7638IZqYf6uszDOem/IDbTXzRb1DjEOZ9/9/vhFSOu6av2@KNTi1Szti5S09YPgPklwMghcx93Anu78Aw "Java (OpenJDK 8) – Try It Online") Input domain = Printable ASCII + codepoint 127. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [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, takes input as a 2-element nested list. ``` ⊃¨⎕A∘~¨,⌿↑⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKNdIe3/o67mQyse9U11fNQxo@7QCp1HPfsftU0ECoDk/3OmcWmoOzo5q2tqqLu4uqlrcoFFUvJBAin5eerqJTAxR5AQjANiAwUA "APL (Dyalog Unicode) – Try It Online") [Answer] # Ruby, 56 bytes ``` ->a,b{a,b=b,a if a<b;a[0]=([?a,?b,?c]-[a[0],b[0]])[0];a} ``` [Answer] # [Pyth](https://pyth.readthedocs.io), 23 22 bytes ``` +.)-.{<G3.{,<Q1<KE1t|K ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2B.%29-.%7B%3CG3.%7B%2C%3CQ1%3CKE1t%7CK&input=%22abc%22%0A%22abd%22&test_suite=1&test_suite_input=%22test%22%0A%22test%22%0A%0A%22do%22%0A%22don%27t%22%0A%0A%22ye+s%22%0A%22yes%22%0A%0A%22yes%22%0A%22yes%22%0A%0A%22maybe%22%0A%22mayue%22%0A%0A%22false%22%0A%22false%22%0A%0A%22false%22%0A%22true%22%0A%0A%221%22%0A%22%22%0A&debug=0&input_size=3)** # [Pyth](https://pyth.readthedocs.io), 22 bytes ``` +eS-.{<G3.{,<Q1<KE1t|K ``` **[Test Suite!](https://pyth.herokuapp.com/?code=%2BeS-.%7B%3CG3.%7B%2C%3CQ1%3CKE1t%7CK&input=%22abc%22%0A%22abd%22&test_suite=1&test_suite_input=%22test%22%0A%22test%22%0A%0A%22do%22%0A%22don%27t%22%0A%0A%22ye+s%22%0A%22yes%22%0A%0A%22yes%22%0A%22yes%22%0A%0A%22maybe%22%0A%22mayue%22%0A%0A%22false%22%0A%22false%22%0A%0A%22false%22%0A%22true%22%0A%0A%221%22%0A%22%22%0A&debug=0&input_size=3)** --- # Explanation ``` +.)-.{<G3.{,<Q1<KE1t|K - Full program. <G3 - Yields the String "abc"; Alphabet[:3]. .{ - Set formed by the above. .{,<Q1<KE1 - Set formed by input_1[:1] and input_2[:1] - - Set subtraction. .) - Pop the last element. + - Append. t|K - input_1[1:] or input_2[1:], relying on the result of Logical OR. ``` [Answer] # Perl 5, ~~82~~ 79 bytes ``` sub{$_=$_[0];$_=$_[1]||$_ if/^(xz*)?$/;s/[^z]/z/||s/./y/;$_ eq$_[1]&&s/./x/;$_} ``` Takes input as two separate arguments and returns the third string. The subroutine attempts to produce a string very similar to the first string but with the first non-`z` character replaced with a `z`. Then it deals with corner cases by replacing the first character with `y` or `x`, as needed, if it finds that one of the inputs was in fact a sequence of all `z`'s. [Answer] # [Perl 5](https://www.perl.org/), 68 bytes ``` sub{$_="a"x length $_[0]||$_[1];$_++while $_ eq$_[0]||$_ eq$_[1];$_} ``` Explanation: * starts with (string of letter "a" as long as first string) or second string if that is false i.e. zero-length * keeps incrementing that until it's different from both first and second Starting from "a"s was to avoid incrementing to point where Perl lengthens the string; with only two strings to avoid being same as, it couldn't overflow. Execute with: ``` perl -e '$s = ' -E 'sub{$_="a"x length $_[0]||$_[1];$_++while $_ eq$_[0]||$_ eq$_[1];$_}' -E ';say $s->("z", "true")' ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~70~~ ~~65~~ ~~73~~ ~~67~~ 61 bytes The function needs the provided strings to be mutable (i.e. either arrays or dynamically allocated). ``` f(a,b)char*a,*b;{a=*a?a:b;*a=*a>70?33:99;*a+=*a==*b;puts(a);} ``` [Try it online!](https://tio.run/##nY1BbsIwEEX3PsXIG@I0lahYVMEKHKTqYuzYkJbEqe3Quoizpw5CqmpRgfDK/81/M/JxI@U46gwLweQWbY5FLvgBqxzXuBQ8n36r5/l6sViWZYwPMVdV7PSDdxkyfhybzkOLTZftTVMzOJBpEWhjXsryFSqgXjlPCxBo/xBOAHQWe6cR4yRm563swwnS2lBWnEEsTKCbecp@vYtaUOASMSh3g3aP1WIQKvEiG9RVU@POpeaZ3WF6e8PJp0S6KqCQtdKbbfP2vms7039Y54f951f4Tjbhv@/iDav8YDuYc3Ik4w8 "C (gcc) – Try It Online") Works for the standard ASCII range Explanation: ``` a=*a?a:b // If a is empty, point to b instead *a=*a>70?33:99 // Choose a different value for the 1st character of a, // while giving enough space to increment it without // going back to its previous value *a+=*a==*b // Increment the 1st character of a if the arbitrary // chosen value is equal to the value of the 1st // character of b puts(a) // Outputs a ``` [Answer] # R, ~~89~~ 67 bytes *@Giuseppe saved 9 bytes, @user2390246 saved 13 bytes* ### function ``` function(x,y)sub("^.",letters[!letters%in%substr(c(x,y),1,1)][1],x) ``` ### demo ``` # define function f <- function(x,y)sub("^.",letters[!letters%in%substr(c(x,y),1,1)][1],x) # test cases f("test","test") [1] "aest" f("do","don't") [1] "ao" f("ye s","yes") [1] "ae s" f("maybe","mayue") [1] "aaybe" f("false","false") [1] "aalse" f("false","true") [1] "aalse" f("1","") [1] "a" f("art","bug") [1] "crt" ``` [Answer] # Java 8, 119 bytes Lambda (curried) from `String` to lambda from `String` to `String`. Assign to `Function<String, Function<String, String>>`. ``` s->t->{String r=s.length()>t.length()?s:t;while((s+t).contains(r))r=r.substring(1)+(char)(Math.random()*128);return r;} ``` [Try It Online](https://tio.run/##jVJNj9owED1nf8U0EpJdwIJeWm02VFXV3va0x10OJhhimjjUMwEhNr@djmOCqHqpZMnPz/Px5mOnD3ra7I3brX9d9u2qsgUUlUaEZ20dnB@SvbcHTQaQNPHnjh1US7ZSm9YVZBunfl7B0wt567aT/7KJ92IBVFq/ji/ILzhd0HRxvr59jqoybkulkAu6wa/4SNmxtJURAsckVdE4YrkovJQ@9wrbFfYRxFyORVFqL8WzplJ57dZNLeTH@acvMvOGWu/AZ90lyR641Fj/tdJDY9dQc1gR1bwuQfstytCUZKCYLDQahBycOcIdHaySc0oGKZ1AvLtJJGt9WpnAMmjNjX5rZ7PPPd@jTfzogrRk03i4E/Kdk8JjzB0VJS8nJFOrpiXFM3NUDcIV@9aaRDrCCYyQ3UbISfoYr7PlgOaM7oah9H5fncRgJf96z5dSyiyIu2kLXYaC@zDL@HoC7nAA4xzmg8A4VF6r@2aJAINz6FnR9VEHU66Fbf8VZd0gJ02jg92ACJUPKwIfOC@8v4cQyvxudYXB66okodI3x17EN0Tjw2b@8L7xIkbr@sr4dJc/) ## Ungolfed lambda ``` s -> t -> { String r = s.length() > t.length() ? s : t; while ((s + t).contains(r)) r = r.substring(1) + (char) (Math.random() * 128); return r; } ``` This solution rotates random ASCII characters into the longer string until the required conditions are satisfied. Inputs are UTF-8 and outputs are ASCII. I don't know the gritty details of Unicode, but it seems plausible to me that this solution could fail when an appended `char` joins the preceding code point to form a single code unit. If someone who knows more about this can verify this, I'll change the input domain to ASCII. # Java 8, 126 bytes Same type as above. ``` s->t->{String r;for(byte[]o=(s.length()>t.length()?s:t).getBytes();(s+t).contains(r=new String(o));o[0]%=128)o[0]++;return r;} ``` [Try It Online](https://tio.run/##jVJNj9owED1nf8U0EpIjwIJeWm02qdqqvfW0R5aDCQZMg009E1aIzW@n4zihVL1UiuTnl/l48zx7dVJTd9R2v/55PTar2lRQ1QoRfihj4fKQHL05KdKApIh/7jlBNmRquWlsRcZZ@b0HT8/kjd1O/ismnmUJtDN@HW9QXHFa0rS89Hefb5wXqzPpxdIVAmWt7ZZ2IivpBj/hI2Vyq@kLh6HIcoFjJipniSdA4QurX/t2wmVZ7haz5aiYv/@YBTQe515T4y03a69J/sATRxv6gU/OrOHApUSssViC8lvMgjfJQDFZKdQIBfzp1tEhKrmkLI3SCcSznUTyoM4rHVgGjb7RL81s9qHjO7SJP9ogLWE/4E7IV24Kj7F3VJQ8n5H0QbqGJD@dpXoQLjn3oEikI5zACDlthNykq8FGDGjO6O5NpDoe67MYorK/7vNlxoYGcTdt1U55qNiHWc7HE7DPAYwLmA8C49vydt2bJQIMycGzqu2qDqE8C8f@K8rYQU6axgSzAREmH5YD3nFfeHsLJaT@1agaQ1avJKGdd6@diM@I2ocF/eY9r1ys1naT8ddefwM) ## Ungolfed lambda ``` s -> t -> { String r; for ( byte[] o = (s.length() > t.length() ? s : t).getBytes(); (s + t).contains(r = new String(o)); o[0] %= 128 ) o[0]++; return r; } ``` This increments the first byte of the longer string, wrapping within ASCII, until the required conditions are met. Inputs and outputs are ASCII strings. [Answer] # Bash, ~~115~~ .. 77 bytes Replaces first char of the first (non-empty) input string with 1,2,3 until no match is found to either input. [Try it Online!](https://tio.run/##dYxBDoIwEEX3PcVPbTK6wKSww5h4D@MC6JgSsRCLigHOjkVjogtn@d@bl2feTndbVowLZwZV6XgDUwu@ZRU8t4giSDXPcuq2UvU6jVQ8SnGsL/AoHXq9XidjIF2qw95jv4fy2GK3VHpQ8QqHwzDkIX/ajIILW4egl9PVzflujghTO56IQHxu2gfh@xYg/VoFsTMeCNq9bC18kxXs6SW8gfj809@EDjD@pW8hIfEE) ***-9, -12, -9, -8*** bytes all thanks to [GammaFunction](https://codegolf.stackexchange.com/users/86147/gammafunction) ``` x="${1:-$2}" for s in {1..3}"${x:1}" { [[ $s = @($1|$2) ]]||break;} echo "$s" ``` (quite an improvement over the [original...](https://gist.github.com/roblogic/c856c9607b5d29ff856d1c45c8807a75)) [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes ``` ∋l~lℕṫ.&≡ⁿ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FHd05dzqOWqQ93rtZTe9S58FHj/v//o5UMDZR0FICkgVLs/wgA "Brachylog – Try It Online") ### Explanation There may be a better way to do this, but I've been fighting Brachylog strings for a while now and this solution works. ``` ∋ For some element of the input list l get its length ~l That is also the length of ℕ some positive integer ṫ Converting that integer to a string . is the output & Also: ⁿ It is not true, for any X in the input list ≡ that the output equals X ``` Outputs strings like `"100"`. If `"100"` is already in the input list, goes to `"101"`, etc. [Answer] # [Perl 5](https://www.perl.org/), 79 + 1 (-p) = 80 bytes ``` $"=<>;chop;$_=length($,=$_)>length$"?$_:$";s/./chr$&+65+$i++/e while/^($"|$,)$/ ``` [Try it online!](https://tio.run/##JcexCoMwFAXQ3a8o4VKU2L7JDo1R7Ic0gzyaQDDBBFz67X0dPNvJvMdBBMqOk1l9ygbORt4@1bfoLVw3nYOa4Z5QptCdVr/jqh@DRtCa@HL4EJneLdQXfQcSeZXaLFzqL@Ua0lbklv8 "Perl 5 – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt), 17 bytes ``` ;B¬£ñl g1 çXÃkU v ``` Repeats the letters `A-Z` to the length of the longer input, removes the values in the input, and get the first item in the array. [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=O0Kso/FsIGcxIOdYw2tVIHY=&input=WyJhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eiIsICJBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQSJdCi1R) ## Old solution, 18 bytes ``` ;@!UøX}a@ñl g1 çBö ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=O0AhVfhYfWFA8WwgZzEg50L2&input=WyJCIiwgIiJdCi1R) Chooses a random character from the alphabet and repeats it to the length of the longer input string, until it is not present in the input. [Answer] # Python 3, 74 73 bytes -1 byte thanks to Step Hen ``` def f(x,y,i=1): while i*10<10**len(x or y)or str(i)in x+y:i*=2 print(i) ``` Prints lowest integer with the same length as the first of the inputs that has nonzero length. [Answer] # Python 2, 77 bytes ``` a=input() b=ord(a[0][0])+1 if b==ord(a[1][0]):b+=1 print unichr(b)+a[0][1:-1] ``` I think it has some potential. The idea is that it adds 1 to the 1st char in the 1st string, then checks if the other input's 1st char is the same. \*\*Note, ^ doesn't handle 0 length strings, so it doesn't really work at this length. Here's a super long solution that works with 0 length # 146 Bytes ``` a=input() def c(i):print unichr(ord(a[i][0])+1)+a[i][1:];exit(); for x in range(2):if len(a[x-1])<1:c(x) if a[0]==a[1]:c(1) print a[1][0]+a[0][1:] ``` Any improvements would be appreciated! [Answer] # CJam, ~~31~~ ~~30~~ 23 bytes ``` q~:A:e>,3,sf*{A\f=:+!}= ``` Takes printable ASCII as input. Outputs either a string of 0's, 1's, or 2's that is the same length as one of the input strings. The logic is that one of those can't be either of the input strings! [Try it Online](http://cjam.aditsu.net/#code=q~%3AA%3Ae%3E%2C3%2Csf*%7BA%5Cf%3D%3A%2B!%7D%3D&input=%5B%22000%22%20%22111%22%5D) ``` q~:A e# Store input array as var 'A' :e>, e# Take the length of the lexicographically greater string in the input array 3,s e# Generate "012" f* e# Repeat each number as many times as the longer string length, yielding something like ["000","111","222"] { e# Search array of number strings for first that returns true for this function A\f= e# Map each string in the input array to whether it equals the current number string (0,1) :+! e# Add up the array of bits and take the logical not. This returns true iff both array values were not equal to the current number string. }= e# Return the first number string that returns true. ``` ]
[Question] [ In this challenge you are to write a program or function, that takes a string as input and outputs one of two possible values. We will call one of these values *truthy* and one *falsy*. They do not need to actually be *truthy* or *falsy*. For an answer to be valid it must meet four additional criteria * When you pass your program to itself it outputs the *truthy* value. * If you pass your program as input to any older answer it should output the *truthy* output (of the program you are passing to). * If you pass any older answer to your answer as input it should output the *falsy* output (of your program). * There must be an infinite number of strings that evaluate to *truthy* output in all answers on the challenge (including your new answer). What this will do is it will slowly build up a chain of answers each of which can determine if other programs in the chain come before or after it. The goal of this challenge is to build up a list of source restrictions that are applied to the successive answers making each one more challenging than the last. ## Example A chain (written in Haskell) could start: ``` f _ = True ``` Since there are no older programs, the criteria do not apply to this answer it need only output one of two possible values, in this case it always outputs `True`. Following this could be the answer: ``` f x=or$zipWith(==)x$tail x ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwja/SKUqsyA8syRDw9ZWs0KlJDEzR6Hif25iZp5tQVFmXolGmlKaQryCrUJIUWmqkg6Ih0uXkuZ/AA "Haskell – Try It Online") Which asserts that there is a character twice in a row somewhere in the string. The first answer doesn't have this property while the second does (`==`). Thus this is a valid next answer. ## Special rules * You may use any language you wish (that has a freely available implementation) as many times as you wish. * If you were the last person to answer you must wait at least 7 days before posting a new answer. * Your program may not read its own source. * Since the 4th rule is exceedingly difficult to verify if cryptographic functions are involved, such functions are disallowed. ## Scoring criterion Each time you add an answer you will get as many points as its place in the chain. For example the 5th answer would gain it's writer 5 points. The goal is to get as many points as you can. The last answer will score its answerer -∞ points. This will probably be more fun if you try to maximize your own score rather than "win" the challenge. I will not be accepting an answer. > > Since this is [answer-chaining](/questions/tagged/answer-chaining "show questions tagged 'answer-chaining'") you may want to [sort by oldest](https://codegolf.stackexchange.com/questions/159629/does-it-lead-or-follow?answertab=oldest) > > > [Answer] # 14. X86 Assembly (gcc 6.3), 324 bytes ``` .TITLE "a"#"a" ELTIT. .data i:.fill 25,1,0 s:.string "%25[^\n]" t:.string "->Hi, Retina!" f:.string "Bye Retina!" .global main main: pushl $i pushl $s call scanf addl $8, %esp pushl $i call strlen addl $4, %esp sub $21, %eax jz y pushl $f call printf addl $4, %esp jmp en y: pushl $t call printf addl $4, %esp en: ret ``` [Try it on ideone!](https://ideone.com/q6Nwrm "Try it on ideone!") Note: *this **will** return a runtime error because the exit code is not zero. Running this in the ideone editor will display all stdout output regardless of how the program concludes.* * **Truthy** output: `"->Hi, Retina!"` * **Falsy** output: `"Bye Retina!"` **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. **The first line is exactly 21 characters long (not including newline).** **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`. * The last non-empty line does not have any duplicate characters. * **The first line is a palindrome of length = 21** [Answer] ## 9. [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes ``` .->0`Hi, Retina! ``` [Try it online!](https://tio.run/##XY/dSsMwFIDv8xQxMkxGGhrLQCgNCoIWBEHFGxVWt9MZ7dKapbMtCF7uJXyNPcAeZS9S0116Lg4f3zmcHwtOm0z2ZLfdbcmIXk17Eahweq05vjvUjvr@kuf8nEuEhGBCIMHSpUBEkER4hfY/vwAeoqfjE1iDefEcQohLiyurjaMFGKpNVTvK2HgsJiOZJCHzXfD9nHX3MsKHmHiTvc7mkC/e9PtHsTRl9WlXrl5/NS1SmCjiczoMuigKpBSW@83mdIDb2nmLo2FzoLq4SSxk8xttYEVZ3CaPMHOl1R3Q2uVnD2VqHKMNizPT0oWFqqAkUIQ3bLjq3/t/ "Retina – Try It Online") If you want to try your own program, simply append it to the input field, separated by two linefeeds. (If your program contains two linefeeds, you'll have to change the separator between all programs and in the TIO header.) **Satisfies:** 2. The first character is a `.` 3. It contains an `e` 4. Its length is even 5. Its length is a perfect square 6. It contains an `a` 7. It contains a `>` character 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. Sorry, but you kinda forced me to pad to length 16... **Without redundant requirements:** * The first character is a `.` * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. ### Explanation Starting with `.` is fine, it just means that we suppress Retina's implicit output (provided the first line has a configuration, but I didn't want a two-line program). That means we need it explicit output, but the option for that is `>`, so we're in luck. The `-` can go in front of it because it doesn't do anything. Now we can get to the program itself. The simplest thing to do is to match a literal string. That's guaranteed to show up in our program, we can easily make sure that it isn't part of any existing program, and it gives us a number as the result. However, it could potentially return a number greater than 1 (so more than two different values). We avoid this with the `0`-limit which only looks at the first match and counts that if it exists. So the `0` ensures that the output is only ever `0` or `1` (depending on whether the input contains the literal string). As for the literal string... well, we still need to include an `e` and an `a`... and we need the string to have at least 11 characters, so that we match the length requirements (getting to an even square). `Hi, Retina!` happens to satisfy those requirements. [Answer] # 13. [Perl 5](https://www.perl.org/), 64 bytes ``` .1;";1. \"Hi, Retina!->";$_=<>;chop;print y///c>5&&reverse eq$_; ``` [Try it online!](https://tio.run/##K0gtyjH9/1/P0FrJ2lCPK0bJI1NHISi1JDMvUVHXTslaJd7Wxs46OSO/wLqgKDOvRKFSX18/2c5UTa0otSy1qDiVK7VQJd6achMA "Perl 5 – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. **The first line is a palindrome of length > 5.** **Summary for future answers:** * First character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10th character is a `"`. * The last non-empty line does not have any duplicate characters. * **The first line is a palindrome of length > 5 (in *characters*).** [**Verification Ruby script**](https://tio.run/##dVNNl5MwFN3nVzyxdmDspKBWnYPtLJyFLnSh7moPJ4XXNkcmwSSonZbfXhPA08wc2QB53Htz35eq1/tTgRtgQv9GFYoJjDciIgAlu1sXDA5wrJTcHiEcbRgvYQ5G1ZhCVRsNwXspCm64FPD0IBpYK/kDRRBBLUrUGjZi6cgraAiKghB3kZBZUVclz5nBLN8xxXKDSoc6SkFTF9CUleUNHI750UVkLUyYRzCfQ9Kk4ISczppvMxSy3u6yipVcFEreYa@i@T3CAmYwHtuTwl/2AnQC@swvUWzNLnT@LMe96HpvsCN3MJL/S0/bvJenvkYvonNV3HMZr5x2QANoJqQHvXwEotYh/oEAfdArD@T7odaxuPGAswHg5WVMZ/AMEmcgprFHeT1ggPkG3gyAFj7o7QDo6gHqegD1gU/gCxou2BMfnsQePuzLSKUq4HlX1KQ9RTa5WZucz00ed@C67cBFcOGj/D4NTV3rVBvFK2pnCPXyKllFvojfx/@PXCvRkW0GrZZTOK2I@2MH5@u324@f7RSyBxNFkeU7p@1CR7twAO6rWxjSENJt2Cc0YNcBzkRbxn692o080SQN0oSS736pbW/SUTZ/t0jznazSSnFhYD@dTvPFbDzuN4Lgz1GW/gU) [Answer] # 5. [Python 3](https://docs.python.org/3/), 64 bytes ``` .012 import sys print(len(sys . stdin . read()) ** 0.5 % 1 == 0) ``` [Try it online!](https://tio.run/##K6gsycjPM/7/X8/A0IgrM7cgv6hEobiymKugKDOvRCMnNU8DyFPQUyguScnMA9JFqYkpGpqaClpaCgZ6pgqqCoYKtrYKBpqUmwAA "Python 3 – Try It Online") Checks if the length of the input is a perfect square. **This had been updated by the time 18 answers were present to support multiline input.** **The update does not hurt the chain.** --- **Satisfies:** 2. starts with a `.` 3. contains an `e` 4. has an even length 5. has a perfect square length [Answer] # 25, [Octave](https://www.gnu.org/software/octave/), 196 bytes New requirement: To avoid the tab versus spaces discussion, tabs can no longer be used for indentation. Each line still needs a tab, but it can't be the first character in the line. ``` .6;%+->?|" "|?>-+%;6. f=@(x)1&&cellfun(@(C)any(C==' ')&1&&find(C==' ')>1,strsplit(x,char(10))); % % % % % % %Henry Jams?Hi, Retina! % % % % % % % % % % % % % % % % % % % ~ ``` [**Verify all programs online!**](https://tio.run/##3Rddc9tE8Nn9FYeILV0sqz45No2F5KZp2gZKW9q0tE3ScpHPzTmyLCS5sYPp8AT8BB7gR/DK8EQf@RX0j5SVdKcPN2HKDDPMcLEd3X7v7d7uaurG9CV7@9boWfVmyxkslZqyHDitZt3qGZdG9lVtjkmj4TLPG8187aq2jam/0LZtW62puAGoEfeHcu8QPYrDKPB4rM1195iGGmljjK1L9do7n1vMDxfoEzqJBre4ju6zmPv0g9p5pO/1efU2@Jp8g2ykXtdH@lWdqNal4GszgeyrhoENQ9URaetINfDuJN8ohmIb6mFC2xG0EvXm258Zy1AbAtXZ/1BV2UvmH2bwroC3WRtNQxSE3I81j/ka94NZrGG8vm5068S22zhj6AkG9s0BjYyzB6SDYHUz5EcCSY/cIRu9OObjE2/iT4OvwiievTydL87UzDIHKY4izXTQbqJsy/NyiIPImx9@MEv7u7MYaFAnBaXKrkjTW86ZNbdDRoe3uc8iDVsL@xFz42nIz5g2i0dX9qa7fowhFawk@C9CFnia0nIUfY6FW5tCWMtpf1mKZoYkbYElLaeERLvI4ycM3QiZ7x6j/vXUNqSryv1HnmcNjeM@9YcohJ/pBMEJjEYonk6lUCKFQhJqke0oJdFgW6MR7W8eQl6qiqoKK4nMBuJ53s0nj24pSvD6xwrf69/@@M5Y//2X7OjU1z8@a68JZpkexFIskifJwYpea@25/bFjucfTwErTAS0uX77sOt1GI4TECSMmOdlXa88tIVvm197u3u0dpFDlQ/iinduwL9J2SGMqN7xvjLjnIbOrE70toVHfgAvI/RdIqZvd/WcH/mGeJnGBq4RBEKijAn9twVaxxgtvekQ9NKHcF6DksY@KJcDBLDr20BqvbiOxdSkYHbnUHwkAHQ4BfUVHdRYF54vIeOIQ7lWFaaPCFM2O0JpJEhidC9j4DC2qMkdlmWl8Rn8jczwJUK500a@Kiv@RKOb3ZSRCFouwy/JBIMc1QtYVRVknRBv6tEiwSnrBMQMNTsg9OjkaUhT1lUEeY@6jSOa6rDTEyBYklHgqZIM4uJN0v6TjsMAN9lvE3NCMpUPxIIdvbOb3Wtar5SD7U5qKeFqCisTrqvGqvql3zARR/qhI1jshVlamnqUwCk0JLgO0JMoU6El52X43g8H9STANYxQtIgkpCjIAIb@H3DeSSqdhI2tTyoGvYOyYvSbBwASlbUJjLTFM3yA4UbRMlpK5s2GYwsbN3EbRN1nRN6XyrH1Cdmg8mrDJEQs1tXwiqpoU0EY0mxQELmg39U6n3@npGz19k/Q3O7oKCye0H/cac82Ef@1GIlY7seca6acteG7bidW4RTC27ZHHA@0EqnNqdl3Vy46ZPZw6Ybbfw4lKBNvE7Gx0ex9d2ZTo8yFFB/2p1Oahn/756/fZAZpF@c6WAn9i5boHy2alVE0DOs1Dy3nAuctp5DLK3CDgEeVuXghpwAEeuS7AE0JYee1kLpByPqaMZRgOAgpOxtg4w8AjkMIm52QJIgOzsZCbG0RTwWOWr3EJmShMTZZkJc5UJJPc44y0zClWIaCwNgNKflYWK7lyY/g4KFsreQAXpM5W/Mw8F8ZU/Cy7mBxVciQlzlRkmSQXOw4KrSAkqOhcYRuv6Fw9P9jmOgMuwRljIrhqUK4tPaOKn2V1q35WFI6rYmUKCKnnx/M8seOyunFmb6EzVTYOStcmP9sjNx0KTytDoUTCcCjL6OlMUuRpIsZHQfFK3EHzPe5/pWKVrFJVa6XOwWg4T@atbShWOa6@5S/Q9kBsiyqEoFGbXVGH8smqud1yltDiagpCS6e13SxqQa2WT7O1ZPIADijtLKRujGIWxQU22aEI8NHx9BRp7jFzT5DmJbMtdEdcEGYYGyX9W2Mem6CYHpXwsANsPN3xZxOU17fa/@OhHMocVupNEiZzRU6o1nrLaS5pTZkrNbpsOq11q4jRHNnpi89/BLDW0XluPUb27p17D/dywN2He7BF9s097cHu0x3tMdZNgmvkwuOS338/DswfFsCta9vXd27cvLX7yae3P7tz997n9x/sPXz0xeMnTy9@I0z673sFsLt62WsXTSwXvPCD0Suv/Cnkwpf@vATUEgsujbIRWVO3/OiUhX1U58n3AMbrfdKHK8Y8LcAWKlTPMRrBj44CfIjf/gU "Octave – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line --- **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The first line is a palindrome of length 21. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. * Its length is an even perfect square. * It is at least 28 lines long. * The ninth line must have at least 22 characters, excluding the newline. * The last non-empty line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. **Explanation:** It was actually a bit hard to keep this at 196 bytes, since there are many bytes that are now mandatory on each line. The first line is simply a scalar that's not outputted, followed by a comment. The second line is an anonymous function that takes a string `x` as input and makes the following operations: ``` strsplit(x,char(10)) % Split at newlines. Can't use a literal newline, or [10,''] due to previous rules cellfun(@(C) ... ) % Perform the following operation on each line: any(C==' ') % Make sure there is at least one tab character 1&&find(C==' ')>1 % Make sure the index is higher than 1 1&&cellfun( ... ) % Check that this is true for all lines. ``` It's lucky that the short circuit operation `&&` takes precedence over `&`, and that `1&&find` doesn't require parentheses. Otherwise I wouldn't manage to golf this down to 196 bytes. [Answer] # 11. JavaScript (ES6), 36 bytes ``` .11&&(s=>"Hi, Retina!->"&&s[9]=='"') ``` [Try it online!](https://tio.run/##hZLRbtowFIbveYqzTIOYBpfA2NqiRKtUTaOatAmq7oIg4SUOuDh2ajuMIE3aZV9iL9cXYS5tQ7jakWwfW59@n6Pz35E10bFiuekImdBdGuyw7zebrg5C5wvzYEwNE@RNJ3SaTT09nwVBy2mhXSyFlpxiLhfutAFw2gbwMVwmyckJvEb7FOZXXup98vy59wL1MNwoRsSi4EQxU@4hjBG2a5ThSDjYCXCF9zFcU87LI01LPf75S2lFvccwMSRe0aRO9advW3RNxaziBhi@l2YpBfRrXNfvRYJluVQGdKkjkSsmjMupcO0VMGiTMGFPRUniIgTtNnTxAN6BD0EAXVTpf3jWh@Nq6e8oIhpvJ/7@10GFf8TwY8l0TpWu4eRnnNB0sWR3K54Jmd8rbYr1r025jUQITug8HSORF@aSc5uH4D8@PPT22bfC2HfoR6L65AzDGOrx3HMn3A43wVNHX5mg2kXDMrilsZGKbalbmPTsRo6EQe4GDYko3YWiOXcd6wNvgw4dn@MXhxypd8JuNK@55xX3u3ZQMsvocTF@J6zBMALOVhQ@KyriJVxcWU@MbzkfJnh5QUQCym4ys1Mp0hSMlAd568Bra@jJ3tAH@f/7ed6YNXBGcjdFaPcP "JavaScript (Node.js) – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. **The 10-th character is a `"`.** **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`. [Answer] # 23, [Literate Haskell](https://www.haskell.org/onlinereport/literate.html), 196 bytes New requirement: Indentation is great, so each line needs to contain at least one tab character. ``` .1+C->| " " |>-C+1. > main = interact test > test s = show (check (lines s)) > check = all (elem tab) > tab = toEnum 9 Henry Jams? Hi, Retina! ~ ``` [Try it online!](https://tio.run/##3Y8xCsJAFETr3VOMqSIxgZQWiUUQxNIbrOFDlvzdQP4XEYJXjxs8ga1MMcybaWZwMhJzyV5pdkrrWtVFV7YLkJkMWNqyK@rKGmNbE5yPaODjtu0VSqIJbwZJhQzTE3k/UD8iZx9JIPt9WnxRA8eMnJgC1N23IlnCOp3jI@BozS@6UJxfuLogpxT8ATdSH93Omvd/vPgA "Literate Haskell – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. **Each line contains a tab character.** --- **For future answers:** * The first line is a palindrome of length 21. * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. * Its length is an even perfect square. * It is at least 28 lines long. * The last non-empty line does not have any duplicate characters. * Contains the exact sequence `->`. * Contains the exact strings `Hi, Retina!` and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains a tab character. * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. [Answer] # 27. [GolfScript](http://www.golfscript.com/golfscript/), 144 bytes ``` . ;'>-C+"1"+C->'; . ' z y x w v u Hi, Retina! Henry Jams?';; t s r q o m l k j i h g f e d c b n /:^,27>^^^|=lynn * n~ ``` [Try it online!](https://tio.run/##zc67DYJQAIbR@vunUJubiGi0MZGIBQ2xdAASREAULwr4wBhXxzU8E5y8KrMmqYtr2/dT8IzvBs5oPnIC1zceTGXQG3XohZ7oge4oLCaDXdoWNh4SprbuBtv40myM56lFDarRDVXogkp0RidUoCPKUYZSdEAJ2iPLbBVNFks/iqLPuuys1Rj7/b/RDw "GolfScript – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. **There are at least 28 lines, and they are all distinct.** --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and **all lines are distinct**. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".#$[\]` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * The program ends with: `tab`, *(whatever)*, `~`. [Answer] # 12. [V](https://github.com/DJMcMayhem/V), 36 bytes ``` .1lllGYVH""pØHi, Retina!->üˆ.*± Ø^0$ ``` [Try it online!](https://tio.run/##K/v/X88wJyfHPTLMQ0mp4PAMj0wdhaDUksy8REVdu8N7DnXoaR3ayHV4RpyBCglKAQ "V – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. **The last non-empty line does not have any duplicate characters.** **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`. * The last line non-empty line does not have any duplicate characters. [Answer] # 21. [Alphuck](https://github.com/TryItOnline/brainfuck), 676 bytes *Surprisingly, most of the code is not padding.* ``` .11111111"1"11111111. ?|+->Hi, Retina!opaos iipiiciasceaecppisaic sapiceasccpisipiiiiia ecsaiiijaeepiiiiiiaec saeeejeepiiiaeecsajee eeeepiaeecsaejipiiiii iaecsaijeeeeeeeeeejii iiiijiipiiiaecsaijiii piaeeeecsaijeejiiijii iiiiiiiiiiijiipiiiaec saijiipiaeeeecsaejiii iiiiiiijeeeeeejiiijpi iaeeeeecsaeeejpiiaeee eeeecsajeejiiijiiiiii iijeeeeeeeeeeejeeepia eeecsaeejeeeeeeeeeeee jpiaeeeeecsaijepiaeee csaeejeeeeeeeeejiiiii iiiiijiipiiiaecsaiiij epiiiiaecsaeeejiipiae eeecsaijepiaeeecsaeje eeeeeeeeeejiiiiiiiiii iijiipiiiaecsaiijpiae eecsaejipiaeeecsajiii piaeeeecsajiiiiiiiiii ijeeejiiiiiiiijejiipi iiaecsajpHenry Jams?a bcefghiwklmnopqrstuvw xyzabcdefghwuklmnopqr stuvwxyzabcdefg~ ``` [Try it online!](https://tio.run/##7VJBUsMwDLzrFYUr0Bk@QK8djvxANYJKbVNRN4QyDF8vsmUnaV7AocolWu2uV4lxq@s2bM7n@WOpW3tKzWHxc/fwtOT72QsducGbveI@ArMyB8YYCCmockQOEFHZgBiCAYlhhUDBhsyCRA6xSYxLROKQvRrHGjDMEO9JigUkgXkI9SUJTaY5SJ0nblZT5YtzgIcaJOCaQZHplSv9SSyaM1SWgZpDe16PXk7yvOOoacm0E1T1eEYgOjibzDuYEKX6Tle2FvyrYo3mC8HEMW/neceWfd4LUykO9ScUg8n3vXCQsaV4CiiGoktqDqfZM@7iAmEV6O19zd1mu2v2@nGIx/azg6/TN67Caxp1bR1Bng2j3@stvd7S/39L/wA "Alphuck – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. --- **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The first line is a palindrome of length 21. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. --- * Its length is an even perfect square. * It is at least 28 lines long. * The last non-empty line does not have any duplicate characters. --- * Contains the exact sequence `->`. * Contains the exact strings `Hi, Retina!` and `Henry Jams?`. * It contains `|` and `+`. --- * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. [Answer] # 26. [Self-modifying Brainfuck](https://esolangs.org/wiki/Self-modifying_Brainfuck) (SMBF), 256 bytes The third-to-last character must be a tab. ``` .1111111 "1" 1111111. x x x x x x x x Hi, Retina!Henry Jams?C|xxxxxxxxxxxxxxxxxxxx x x x x x x x x x x x x x x x x x <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< x +>>>->>+>>->>+>>->>>>>>>>>>>+>>>>>->>->>>> x >,Z>,^<Z-^<Z-^<---------Z>+.>^ ^ x~ ``` Prints out `\x00` for truthy and outputs `\x00\x01` for falsey. Always terminates with an error due to an unmatched bracket. This prevents any input from being dynamically executed. This program only works in the [Python interpreter](https://ideone.com/L2byRe). **DOES NOT WORK ON TIO.** This is because the Python interpreter EOF is NUL. To use the Python interpreter, paste this code into the line where the `data` is set. This had to be done, because TIO has no easy way to type or input NUL bytes, so I still use Ideone. Then uncomment `sys.stdin = MySTDIN("<[.<]")` and replace the custom input with whatever input you are testing against. **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. --- **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The first line is a palindrome of length 21. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. * Its length is an even perfect square. * It is at least 28 lines long. * The ninth line must have at least 22 characters, excluding the newline. * The last non-empty line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. * The third-to-last character is a tab. [Answer] # 28. [Literate Haskell](https://www.haskell.org/onlinereport/literate.html), 256 bytes ``` . |+xx<<<"a"<<<xx+| . > g x=elem '<'x&&e%x==e > e=tail(show 0) > ('<':a)%('>':b)=a%b > a%('<':b)=('<':a)%b > a%('>':b)='<':e > a%(x:b)=a%b{->Hi, Retina!Henry Jams?-} > a@(_:_)%_=a > a%b=e a b C d e f g h i j k l m n o ppppppppp q 3~ ``` [Try it online!](https://tio.run/##5ZDBToNAEIbP/zzFtgkFUiEm3giLJl4aj74AGXQKaxdaC4lrrL46LlSewjlMMt/8/2RmGu4PYm1izSBnHmQcU1y2zuV5vua1z85tL0hJAVSgVk6LlVaFeeg2Gwmc1uK56IGNjfrm@KFu40kZeUXGcRCFRZhVseag8pSDmft66S/0qpqgXIn7c30lxc7cqGcZTMernXTnT/XEbX@ffE/Ch6jMyjgoNc@2yq@jQAyqQI@gV5CA9qAa1IAM6A10AFlQC@pAR9BpCdA77n5G8pNaNp023fSTl2G@K63jf/@aXw "Literate Haskell – Try It Online") [Test Driver](https://tio.run/##5RjbVtvK9XnmK6YTjCXAYyQwFxuJQJJzwllp6EpoVrsI0LE9sgWypEgy2MRknaf2fMJ5aD@ir119ah77Fc2PuHtGNpZvB3LiPtUspJm998zs@96aKo@b/X6NJ8QmYRQ0It5iSSfBWNSaASn4hC4ZlACS1@thqFAjjKkwSeRyv9H2eOQm3QmKDUVxKTxvErOpMHHCa1eiPoErKVzYTZqBvzGB27rHTSC2FeKm6cahiOIREn50aUch3yioFJa5fthOWOIGxB7CR1vtKupIJK7PJ1AfjfU7KhkPWi0xhTMU7pJf87gWuWEyRWAqgusp@IaCA@NeaRzntsIgSkjcjSuOBYSlu0oYuX6iORrAWJzUXZ9Fgtc1XdfpSGvm1BFb6ogPbR4loJ@EO84UybYiARUmIg55bVq@nbvMEZOW@WimqlHWnjrfTEVs8vgK8MxrxmPY9OhG4DmzNWfu3GFsoxZ3fQvEFxGvJVrcDG5YQ8/sa6qNMT6wlrQBm6QYhElRua98rq6ysEsKhXbiwNNxPTFybbKXcQwdH/7aTe7H@kgEo0wodh1yCtIcUGJZ8D6k5KxCkqbwMVGENORxTLHwYjGEONz1KHbcGTKNBV7xZCwMgb2puHxIvF@x3xQsI7G5EIkVZ8ql0idx2qN8MkOih@jvxxlON76Z03T@Ns1mxI2JHyTE9eV6Uo/caxExip8Q0VHR/Pr4@YuL3x2cvLRosR1HRc@tFv2gLi5aQb3tiViSynlqlkGOHL7ZZZxNm2MqSFU2keB6w4DNZtRUWZIyA5xHeq@o0jcratqL5UQ9pI8N8/pDrjpv0XCY4Xnrf8DzsMrcDyQb2dLzEP@P2SA7zcizvbiwiopV1y@@STNuWgUHB6mKaRMSwJ5RpjymcDsLP5y924giw/vOt9siBbxRtXluoLUCP0gVnRbxYkrPREdkyvqM0Ina1e4g6mSBT58sqo7q/QzLPmrR/ThbE9YXlHh@uO84ZquEkKN8HWrktSBJQG4gWYtMlyKJg6guIols8StB3AS0qBTyzlKCXQ8SgpnKeV2UhVj6rGplSKFNCs6UXr5m7fWkahZTPWRHJbe/76zIrMicRXQ/yTK1qELxh50tAkSiVYUCNbBY4JOTo2P6uBRujnL4IC5la0jnEo5EKC2@D8n2lGMTaeTJhvOhzPi1m02CsrJuLS5Vjpri4o16TbTJ8zqRR6wbB2T5X0yqf8iXZvcDcxqCyY7A2FlQSBzXEpme5mT0X24Fza/tBc1sMzgZIuaisvKBFzbbtau5Mj1a8KjtD75vst9PMyvRHMLMLCvpwhrf18eHx6@@TdDBTr89/G4@Sdo@vzp4/b0l/Ivfvx25xejLMTOUNXj8k3Kekzx@@Tggq8zFROu0Cc05xh7/Opa5f87aLJPfHK79PkO91U5nb2@PcgrPTme1hxgmCMH3eYN0LOGJFsnv5TvLyyLXsSwBcGElsIH6YCfruqTUgKLM9ZyWt/Plqm7xXBWgPKfgMB/ih9CUSgJFCukMVn0s2C/dNZJ2eL95KfyoS37grXi/cCcJn2oX5Qs9d2FxtawK7BCEOcJVhJ8hXEdYIOwg3EC4ibCL8CXCVwh7CLcQ9hEOEA6HP4Q/oI1P/edrztrTNQMvOTYdjCk@7jOmM4aZftRimDJqsT7DX378mxB9tnH6JC@uhX@Gn5YdjPNsQ0hQ3sytW2d54pCgnfTZumHi0X0PTu95POHLmx7CiLrrgffgtoesrJB1ViI5Ykgzrut9Ju7e85jdvjU25K1Xqc94tVYXTqPpXl55LT8IP0CdbF/fdLq32CbUpvA8kk514HkYunrjy08/mXJw3E4ASjYwMFWwbysdSx76yvVFrOmVrvVO1JIgcm@F1k6cnZPgyE90raNXuN/VGpEIPY0WbLrW0YGpgr3@p4yB@swYMxg5Ip4LLed3kfBrTVJ@jumbd55XqbNmmft1EsEjaIHwbceB/jSQGxjLy1ps2TSzDRy3vByf7p5ZVp7m4VjD87zv//juJaXh55/HCD//899/Ziv/@jv@/PP5@hJQVmjFYPj9xHaVpQtrz66A94fplRvpFovFml1aXo7AlhHEhviwdFHps5Ojk1cvCETDE/gnL17BHPygzhOO3TJzXAhHs7RmrK3juMziBPZqEJozS6fn7/0zipMRcEwzEG4jzGFXjOCs4QVV7hHZSGP5KEt7QwCG7bjpkSV3OIhxjcPpcY37Dub1OoB21kgOuo0RaUqRROBoA5LNAUncrpIl05Az3sGXt6Q7XOWkq5RanIlVl62QwFbd8pA4@QVi4ZcxfJCBnxlgZ80wViilK4ah1X0ONhmziLzIpVSXdB5vVeucxGW6D9nMJ7E0OEt/YIPBCDaANeBu/DSz0RkA908LhrmpsZ7N9f0zvLkr/bK3n/7RVToY9SY5kPthIhMIAnUjqXT5J6cKRjBgcUqlIJIUxsM47LOtChW8YO@Dr@zbBS5oZQuyxZjV56WAscteFoeem2j0vU913Ta3Vg0dP/ZHe/JH8SYz@5Kj3Cow1KOC9oCl1ZzkaExsyEsbm6Wt7Z1dPDGce8SXH/@aycSQBf/zj7/04TBj9VnB7oEhESWkZxeerYKRVOWQbkwsMrzbJdASJwCWLxIDQpUOrdYU0FBpnsxEYHUdKFKQRaSPaar2JLwqEfACcBK88NstsovR1/xlmIfJSBkYfepLORCq5CX31KBSonwFQQnMI3yLcBfhDsI3CF8j3EZZTWZ3zVcqOEE4RjiSVUWWmZaqOleqArmqGjVUZRKqStVUxfJRsXy@Zm7b5@fnPcvr@j5eQf6n//ua/F8) **Satisfies** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. There are at least 28 lines, and they are all distinct. 28. **There must be a `>` in the code and angle braces must be balanced** --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and all lines are distinct. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * `#$[\]` may not appear in the program. * The program ends with: `tab`, *(whatever)*, `~`. * **Angle braces must be balanced** [Answer] ## 29. [PHP](https://php.net/) with `-r`, 256 bytes ``` .6|0&"123' '321"&0|6. < 0 ; + eval( ~ preg_replace ('Hi, Retina!'^'g5X|<J' , '' ^'Henry Jams?' ,'×× ×  ×ÝÅÐÐÝÖÓÎÖÖÁÇÇÀ«Å¹ÖÄ'));?>->/45789:@ABCDEFGHIJKLMNOPQ * a b c d e f g h i j k m n o p~ ``` Not being able to use `$` made this quite tricky, in my original solution I misunderstood the rule, but I think I have everything covered now. I've used high-byte characters, `~` and `eval` to work around the lack of decent variables for PHP. I nearly made the minimum number of unique code points 96, but I thought that might make it a little too hard for some languages. Here's a reversible hex dump for verification too. ``` 00000000: 2e36 7c30 2622 3132 3327 0927 3332 3122 .6|0&"123'.'321" 00000010: 2630 7c36 2e0a 2a09 0a30 090a 3b09 0a2b &0|6..*..0..;..+ 00000020: 090a 6576 616c 2809 0a7e 090a 7072 6567 ..eval(..~..preg 00000030: 5f72 6570 6c61 6365 090a 2827 4869 2c20 _replace..('Hi, 00000040: 5265 7469 6e61 2127 5e27 6735 587c 3c4a Retina!'^'g5X|<J 00000050: 2709 0a2c 090a 2727 090a 5e27 4865 6e72 '..,..''..^'Henr 00000060: 7920 4a61 6d73 3f27 090a 2c27 9b96 9ad7 y Jams?'..,'.... 00000070: 9c90 8a91 8bd7 9c90 8a91 8ba0 9c97 9e8d ................ 00000080: 8cd7 9996 939a a098 9a8b a09c 9091 8b9a ................ 00000090: 918b 8cd7 dd8f 978f c5d0 d08c 8b9b 9691 ................ 000000a0: ddd6 d3ce d6d6 c1c7 c7c0 abc5 b9d6 c427 ...............' 000000b0: 2929 3b3f 3e2d 3e2f 3435 3738 393a 4041 ));?>->/45789:@A 000000c0: 4243 4445 4647 4849 4a4b 4c4d 4e4f 5051 BCDEFGHIJKLMNOPQ 000000d0: 090a 3c09 0a61 090a 6209 0a63 090a 6409 ..<..a..b..c..d. 000000e0: 0a65 090a 6609 0a67 090a 6809 0a69 090a .e..f..g..h..i.. 000000f0: 6a09 0a6b 090a 6d09 0a6e 090a 6f09 707e j..k..m..n..o.p~ ``` [Try it online!](https://tio.run/##rRfRctvG8fnuKy5nkQBEEiZISRYJApIjO7ZcN05t2XVsieoRPIqgQBAmQAtUGY870zSZNm2cyYzjunGn733qYzt5Ih/7FfWPsHsAIYK05KQzPfAOe3u7e7t7u3tgg/nt6dQ3ViR1Y1TMUq1U3g9LV/bDYkW8yyWNZoujDRUQrBZji6yYAHoC5BKAP2WOnEyeJYDX50eHfe45zOIJThbyb9p5cpcHtss@ENO6GI7WH45qt@ZaFFk@AWLkfCGiv8nd/pDcYl1/a4lJTCoN6BvQgbkp5hZ0MGAT5hUN3o2L8cLQCC/WQfHNJnRrRl@ZyS3HsiPazRhe4C3O5VVSshM5TSGzFe8h3tY64IpxFzQRX2KDFtM3AW7CvsKZEQzdgjXryqwDL2vEshqV2fqa8Iei6Ftmwby8tn5ls1LdvvrhzrXrH924uXvrZ7d//vGdT36ROG81AVgCNBLASoDm2ZknQCsBjhKgnQB2AnQS4DgBugngJkBPAN4zScfcavcIXfHpDCy40Wx0YpGCpeNWr08YsQVym@qk2cNoTsboyGt7pNCfCYiWdNzsuRxPp9OzeJeQdBbmuIZwEWEd4RzCUSwj/AzhdPwiLEupsJXqUhywEsJ5hCV41aVUSAq0NP7L@OX49eS78ffjF@Pfj78Z/yENj/8G8Hfjv47/OP4K8H8G2m/HrwH7CsZ49UVE9zoagWbyZvw1cHw9@XzyYvJi/BVgxQ7fTN5MXk6@nfwJxpeT30y@gOf5@O@Tz8f/hPlvpR87fYRXEWYINxC2EG6CBxBuIXyEcBthG@EOwscIdxF2Ee4h79lURaNcGNZqNcoojGGYGyEVE4SwiY5IaHCHd4lUk8JslmdCw@CA50bAbEf2270TUlQEpQwUVaZkZMmUqg3FYJkGYFkmwsM8WU@wMZVA8hgTzrh@XTBTJ5M6hMJngnBbPqweKplDg0VsDVCHJPbuXGyvMzcZe0lD@AkqCwcgXTILOzmq0dxOwZR0BA6AMz9FeIhwiPAJwk8RHiCc0gyl40PXcYCwj3BfyBSbdKM9j6P97UiXo0gvHuloRfq66HK1ni9dMev1@shwhq4LZ@eCQht6Jlcwt0YU0REcdi6jQ1S3jG05VLRs1uKO0xq48ra8ozB3KO8YBoS/koWllu02k7mp5f2g73uOHchh3mqzvqwVFQgfnEHv/FLGpG08j/Qn/cAIfbVg5kYM0ZAiNsqZhVVdxSgkhu16g@D/A@mrJKU5Rg@JsfvxJ/f3MLpzfw/exLixJ9/bfXRdfqjkS5qCNIwufLgLJ4PeSai79/buP/jlw08fsYbV5K2jtt05drpuz3vS94PB05NweAoFaA2jlOOwcIAmgmlECJwiISMRYBo4QCRLl0G5M6DmBbzPrIAE3A8ALV7Eh4Uor2Srza1jIju2y33iKwpQxCiDMMchcpSYAWuIBXgBOuhddwddUnmPkec8Cx58x4i4IcgNNINVkRLn/c7P251ReE67SMZ7frUfa0CTM00ojmYuNZ61XDQWZkggNvOPzHy99qgQ90LSHpk51azjOgrTuchTuSidbypcdnGWirSEUintSCLdrrpDsrOFL2iZuZc18LJ25uWtUW6hFvY81vOxbXu2bdnMtzjjlufZPrMt7DPPBoRvWYAQFNAYXLewaNsdxnmMsoEFaDnnnRgFINDABAMOMPGcd2YisGAAGR1@1joCK4RGiiTrgjbi5gl9J6bB9rzNWXDMM@eIyBPaztlOdseLdEioAOlFSsf6xqrPdor1TasqjBQ24YQ7vcZxx5tLBrZ4hpcIO4ncZZNhimOvskS12CC8JDGyLtY3LfJM3wWhnZmE5BBmApb8uyChkxbZibXAM4EdLxWdDDesqH6dLNQvDAUsKW0ng2QJJ7VttnRRJqTis2AWRSFc34APE7wEXhT8@O3z71Mqvn3@5j//@uKCrWap5Tiy7Xd5t8H7ix9x@VBRsv6gO1@Ga48FcilfLlfLG/m1jXxFq1bKeQk@opTaRjaUS/AqZoVI@dgIZa0aXaCQuVoxrykFTVEMo@XYnnwM5TeD/4cmbKCcgRH0EgUTGKfCBppSmGK76/X6UPKHPnydwm0gO9yVYab6QdN21T5nTVlR4yuc7rtUUczSRk5TfrIWdCQaxWtqaaqOtuKH5ugMGi2dH1nmJ0lgQIlS4wZfiTMIShQhRCuY7HFKygEgtx4XtNKarI5Mpmwd4LUK@wAEMHCtpq1SSlc1TW66TFveHu5KShVB57Buo8mIX6Vb4CYXrr@pure7d/s6gf0vQSfXb8NcxWqTBQzbVbVlw51YWs9r@SL2q@BBcOgRoZnS@uP6vntAcTBHLpRVilvzlQ@HfI5Xj5xegzlEXNdYDFUyb9gb@G2HrNgJ4GNLXMu@xdwWZs0moDbzJMN9b04aUwR9OOcZydqMxB80yEpJEzMW4s4pGSZcrZgrCpDWElen6xEQNawmxMF7iLlbxX0ewEnoVAff79MF71N95dComTr8wfL0SAAZXr582TLXs9k@f8r7PhSmJyuHOghwHOfGpw9uUupNXi0Imfzw79@pq@N/4MmrenFFXGzZrOwb5tJW2az/uHIAFySV4GC1hfMgu8Sxjzn5qM9dq02q1zC9@8Bx9KbarkJokD4MvS54cdBqwRdPD0ILKs@vUhKmarFgnuqhIRLotvh8khV9aDzgVtDr26dcHgStzb3erhsoUFB0cVkfiT@GMgQGFVVkql78rYdNQk0K4674AL3qONg0ifb2yy9LArgzCABLypD//LN95qun97SyCJd1UEorXZjxRCVRzsM7znqFrK6SorpOMkQjhgH/sqZq@fElCQ7CPZiqUDffcD5VVUWFHFB2u1BaVGqo02v5Vn47r/0X "Bash – Try It Online") [Test driver](https://tio.run/##7Rldc9vG8Rn3K65nSSAkESRAUZZIAbLkT7mKldqqJx1ZUo/kgYQEAjAASqRMedyZpsm0aeNMZhzXjTt971Mf2@kT@ZhfUf8Rdg8gRfArkiP2rcTocLe7d7dft7s4Fahf6XSKNMA6dj2n7NGqHNQDhFix4uCkjcmMQjAgaankuiGqj1FDTOCZ1C7XLOqZQWOIIhNSHDHLGsYshRg/oMVjVhrCZUOc2wgqjp0Zwi1f4IYQN0PEacX0Xeb5fST8yMxKiHwcQrmwsmm7tUAOTAfrPXh/qdWQ2mOBadMh1AslfU444061ykZwSog7oifUL3qmG4wQqCHByQg8E8KBcSs7iDOrruMF2G/4eUMDwux53vVMO0gYCYDJflAybdljtJSQJIn0taaObLEcbvG8Rr0A9BNQwxghuRmSgAoD5ru0OCrfynlsi2HLvFAj1YTWHtlfjUSsUP8Y8LJV8Qew0dZlxzLGa05dOUdIF6rUtDUQn3m0GCT8inMql6XYuurIwqsRy5XId9GGNpPo8o9TjhukQr/m7cKC7DZwMlkLDGgN02J9n8drMY@R0OZPXeSiL/V5VHKYINPAe8DuBsGaBu9NgvfzOKgwG@GQkLjU9wlils96EIOaFkGGOUamgROZ2h04n8DeyIG9TLyfsN4ILCaxOhWJQ85CX4tabNT6gWaMRJfRX/RjnGauzWk0fhKFOWz62HYCbNp8Pi555gnzZIJuYFYPj/mjnTt3Dz/d2H2gkVTN91KWWUjZTokdVp1SzWI@J@XjyCzd4Nl7y0d@PJ4OqCBS2VDka/ZOcjzURsrilDHgJNILRWWvrahRL@aDsOE@1gv4l7nqpEm9bozn5f8Bz730c9HhbMRz0mX8X2WB@DAmz83pHSsvVTDt1OMoFEfpsbtRmEp1jB1Y04vlzQiux@Gb41frU8R4X7m@LSLA4zBpTzxoVcd2IkVH2T0V0cuszmL5fszR8WqFRvfU8cwftbJX6BcCYyx7pUkX/XhOSE8p8Dy8KEXGqwTjLbEEyfOE4cDBpxCsWax84cSOV2IeR1bpMcNmAFoMFfJUCwU76QYENZLzJMUzNPfZsMbByRpOGiN6@Zi5J8OqmU724KUWX/6i5MLjTuY4ootBnKlpJYrPVpYxELFqARJU12KOjXe3dsjVQrjaj@Hdc8lrRjKRsC9Cdvp1SLzYHBhwIw9XopdFxo9dbBgUl3V5eqGyXy2nTsPXUP08qRK5wrxBQJz/6YT6y3xpfD0woSAYrgiUlSkdiZ1iwMPThIj@46Wg@rG1oBovBoePiDqtqLxhuZVa8XiiTFcW3KvZ3Q@f@IfV2Ew0gTA2iks6tcL30c7mzvb1BO2u9MnmvckkUfm8vfHovsbsw18@6btF/5My1uU5ePBbc5KTXH36ICCuzOmc1lETqhOMPfjZzGP/hLlxJlemE/4rLk56vc/tcSF9mKDbi7Oyel1WOh15uZmeg1ohIwpiRlXIXLq5LKM1AaUFlBfQgoDYCbUSAnopINdj5UOPuRYEWgElxAfmIo7Kwp@JB2I5@1lz7aEooEUBifA6EB8w22vgh7Tqr3Ow2PpL603rXfu71vet163ft75p/SHeb/0N@t@1/tr6Y@srgP8ZaL9tvQPoW2gj7OuQ7l3YAk37fetrmPF1@/P26/br1lcA5Tt8037fftP@tv0naN@0f9P@Ap5Xrb@3P2/9E8a/FSUpv64n9dRS9ubKau7WxubtO3fv3X@w9fDn25882vn0FwKaFxAVUEFARQGVQAMCMgRUFlBFQKaAjgR0LKCqgGwBOYL7snNn0Vi8taigGUMn3T5BOx1ZlmQZydJWVUZEJprckdGHV@8Z68iZvRsiO2H2PrqVMxAS5QzjIFGdTWv7IjawUws6clpRUf9aC0XXWRaz@YUWlnF4pQXv7qUWnp/HaTmLZ7HCPSEtdWR2/oz68tkTJcMv97IdmRaKJWaUK@bRsVW1Hfc5ZP3ayWm9cYZ0THQC7RZ3ww3LQvCNonz48kuVd3ZqAUBxBgFTSf0sX9f4ptumzfyElG9oT1kxcDzzjCVqgbGy62zZgZSoS3lqNxJl7jEJktTJYl0CppJ6@tcxz@nISlKPjfEWtkwooO95zC5WcO4OIo@fWla@JFdy1C5hDxqnCsLXDAOqbYcvoMzNJXxNJ7FlYLu5OX9vdV/TRCLCtoplWfd/9fQBIW777QBh@98//E6eb/0Dtd8epGeAMk/yioyeDS2XnznU1vQ8HCA3ulnEjVQqVdSzc3Me2NKD48WezxzmO/Lu1u72XUwouQF/@O42jMEPSjSgyMzJhgnBRc0uKotp5OdkP4C1ypjMqtm9g2f2PkFBHzigGTixfcxmg/XhctlyCtTC/LMA8SbH7S3Aia35FQvPmL2Oj4oUdveL1DYQLZUAtLKIZ6F26pNGFIEHjtYlWeqS@LUCnlEVPqJ1dHSGG71ZRjQrVIsxNOuo6mJYqpHrEQc/QszsHILPS/AzBeycUJR5Qsi8oiRKNgWbDFiE31cTInE6i1YLJYr9HFmHgGhjnxtcjn5gg24PFoA54G50L7bQPgDX95KKupSQmzqV1vfR0ir3y@Z69JAF0u01hzng6yF4BCSAugWudP7wYQjDCLAoogohnBT6vXMI4TdPGE3q6@ArEJQoI3kIv2TA6pNCwMCdtuy7lhkkyDObSJKuLi8oErrqjzT5j6AlWeUJIT@7AAw1CSNNYGlhlnM0IDbEpcxSdhmiJxrqTtziw6vvY9kAouB//vVFBzZTFm4n9SYYUiAYN/Xk7QUwEugvusDGGu5dYWMo8AMA8xf2AcGvtHGiWGFQHiYsHonA6hJQRCANcx9LMItVcUALHAEvAAfOXbtWxatI@JgnxjwM@spAwssOl0MQ8iLnniiESyTmBUFGkPTOBNQQUF1ApwI6EVBNiGsyvqqYz6NAQL6APAE954mFZxgrTDVHYdqphCnICNNRKUxNBZ6CUrmDRfWmfnBw0NSshm1D8rJfAkPNhXp9bW0NvB/aen2hCQzhULNlXNdCvYhrYn1ujs3WNY0BnGkB1AXh/woge3DKBFDkqDSbEHUxV5A0OlsAKJ0N4TDu4XvQiIoDWQSpd2e9GAhkMbGT55zwVuIwdyjNHmo0nFYAdnAvBd@enIKtfhZGbu/HtZd5@f@65vp1zX8B "Bash – Try It Online") **Satisfies** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. There are at least 28 lines, and they are all distinct. 28. There must be a `>` in the code and angle braces must be balanced. 29. **There must be more than 88 distinct code points in the program.** --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and all lines are distinct. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * `#$[\]` may not appear in the program. * The program ends with: `tab`, *(whatever)*, `~`. * Angle braces must be balanced. * **There must be more than 88 distinct code points in the program.** [Answer] # 30. [><>](https://esolangs.org/wiki/Fish) with `-v 0 -v 0`, 324 bytes `1` is truthy, empty string is falsey ``` .1|-<<<< "C" <<<<-|1. >i:0(?v' '~ v >}@@:' '=0=?;@ v >:0(?va=?v&1+&>' '~ >{r0&/ v >&}0&^ >&}rv < >l3(?v@:}@@=?;{' '~ ->1n; Hi, Retina! ABDEFGIKLMNOPQSTUVWXYZ b c d fg h jk o p * * * q * * * u * * * w xz 2 45 6 78 9 Henry Jams?%- _~ ``` [**Try it online!**](https://tio.run/##7VDJUsJQEDx3f0WkyoeFBl/cDeQl7rjv60ErKkhcogaNC4Rfx5eEg5ZXj/Zhlp7pnqppBK1mr1e2OmZVA4WFAtLC7FhlqsCWQ25cRLHL2EihEs@zde9Ix614jMGczvZ8x42FNSxUJlDtSIrRdJpKlUikOO@v5xqRRFpf/c5l/P249vJsfUnfaGdexi@YygorYC0YMfbqL0HoD4Bz84tLyyur6xubW9s7u/sHh0fHJ6dn4CWueA02bsAmeHsHPoJPKOVOOpX4jLzoU3z9MX0D3z/BMXBiEpwCp2cwy1o9jD6MNf@h5Q6auOj@f/FPvmjGhszCFw "><> – Try It Online") **Satisfies** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. There are at least 28 lines, and they are all distinct. 28. There must be a `>` in the code and angle braces must be balanced. 29. There must be more than 88 distinct code points in the program. 30. **The third-to-last character is a tab (#26) AND adjacent lines must have different lengths** --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and all lines are distinct. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * `#$[\]` may not appear in the program. * The program ends with: `tab`, *(whatever)*, `~`. * Angle braces must be balanced. * There must be more than 88 distinct code points in the program. * **Adjacent lines must have different lengths** [Answer] # 32. [Io](http://iolanguage.org/), 256 bytes New requirement: The codepoint sum has to be a perfect square, just like the bytecount. (TBH it did take me a whole day to write a program that satisfies my new requirement, hope you enjoy this requirement!) ``` .1// |+|?"'"?|+| //1. //Hi, Retina! Henry Jams? C := method(a , a sum sqrt %1== 0) // e@ // // ? // {f // &FO`FC*EU/2345678XYZ^ // B // DE // F // Gh // Ig // JKh // L // MN // O // PQ // jklm // ST // bci // V ~ :=9; // Apqrstuvwxyz{} // defgh // <-> ~ ``` [Try it online!](https://tio.run/##5Rhdc9pI8nnmV8yxAUkgCQS2EyMkcIiTOOvNp@NLHIIziAGEhZCRcMDGrlzV7e0@XV3VVe3uw@UX3NM93tU9hcf7Fbd/JNcjgS0gzmar9u0GTY@mp7vV09PdM4Pd//hR1bJZNMlMygkhUYYWZbOairPZ@7ZMnrLAdunv0H3mDsbkAe35ZVxFRYP0WNDpN0WKZUSJP@wR/3gQkKRmGCQnATNiFQ55LXNw1uIwdffRm7vV9PbzbL6wtr5x89aLlwd1PnCbgzvbHN7l4F6Hw502hw@@Dju7HHzzkMNHHDx@wmH3yOnx9tkehw3L5s0@vgAdN3X@vuUdD/xgePJ2ND49O@eYJmu1Q4klxcSIXHysiok7ckuuyFpCIt7AdgPHxRiwqiqpKlalnZ6Kawm1ljDUZQr887v3jC1jC6@@EtgJc18vD@S0PLZ7Xh9s5Y99HI6JDnNF6BGV@EHTdqEdMNoUJYmk0ySnrpMk0Uho2GVxtGGFs7G5Gdx@bKrYJLWEWUtAu@N6w2DLcbBpEu3n77/P85dHwwCwpICXRbLzWo366ukzrUCgrK/MQDFP9ZHBNdy1XeaLkj429pkV9Af2KROHQevWXn/HDSRxJOnUHYvtAfMcsZZQQBt5JK3MQTFzb2KutjysKWZslOwQxz5i5O6AuVaHFO/Aujzddxy9qXaK1G2SAYA@eGMwbLVI0O@vytNSKdE3QJmYWK5bKuW/2nxtGEItIawoqTmOc@/l/v1aopbwpj8tsE7//Z8/qekP/8DTn@q5Gyucei2hQzzVaitf1G8cGiVTtzp9Tw95yDibzVrmeio1AO8Z@Ayz4xuH@rLIvZ293W1YXlpLfBVCsr0LOPDUJg0ototqy3Yckl@XNTmH/aLqB8DeBo5kfv1Vvea@Br8IYugFE8NYKzZ2e8xiI2rb6TeoQ3rUdjEHRXJVsDf0Ow65Yc9ffGxRUMS3qNvCtNkE1C2ZJJnvXZFGFMEAgmBGsjYj8YcNciOv8R4d4e4pGc@5WhFXaJTWEle35xEQNS7OiYPPEDO3iAcsWFkzcCJR09J8tWuJtKaJTZfCGi6sH0w4Gpc4tUN7jSZkwmItUQY7QRT7q06kRiVcs9k7SAVB4OT0VUz6a0CWXylafk1UJyaVyq/x2uZqbEzK0a@WyMBnZ71lNbl8HMIIfK7gpRcMjBjP@3GAyTz3LCu1AQ7PqGKWQ@8smwpl4OobPIMuetl1eVANs6Aa5UDV9xw7gPRRq7lgasnMb2Q0CX9pqSUmvMDX1tT8qqbJDOgJo6DhBDTNJLmeLaMCuQt8RrT9Hus12EAUYpoLPImlYMu7Gh7JFg3EvFwoFAsb8tqGvKkVNwuyIEiSVNpIjcQ8NLkUFykeGSNRK7Zs8JmRYWg5WZMUTZIMo@XYnngkSTiJf0X5wjktuARsQtHuu4mXXq/9zM/v/hY7AsCe999/fbeaWaNSS/BnVlQMR4qF/NL3aN/Htu3ZtmVT32KUWZ5n@9S2sE89GxC@ZQGCU0ChmFkwaNtdyliEsoEFaBlj3QgFr0ADHQw4wER91p2JwJwBZHTZZelyLBcaKjIf57QhN5vTdyMabF@VKxYc8VxxhORz2u7ll@yuF@owpwKkFyod6RupPvtSpG9cVT5JPic8546PMdz1riQDW9TDS4TdudzlKUMXR1alc9WiCeElieHsIn3jIi/1XRDanUmYL8JMwJJ9FyR04yK7kRZ4JrDrxZyP4oYVnnneLpx5MBx65inp7XA@hOfnodnQxRfGSzzgY98W9Hl2gIMNhK9QFSQdJ7fcMamWr4ud5MU1kYLCSEGXkTJCn3w@rUp1MvpEuU7GZ57SLxWgyZimqZhmJgYvSyaEygwJxKZ8YMr10oESVWVeDsyMatZxHY1WDZKpKuaEb6hgE0ImplLNgEEQwibipwxiEKBmA2oFJGB@AGjeEB8G/E7/LRGtDrOOiOjwIylsvRJQRCiD8N1fZA7rkYA2@AA0gA762y7cWzYx@jW/@EUovjIYrUxKTytmZkJhRiOYF51kTCWtw6RGxLD5kfy3edPTZEGnF8TYefj4@R5Gj57vQUuMe3vis52DbfGFJOc1CWmfmR5zm9Bs3a7e2b577/7Og693v3n46PGTp8/2nu//Hu5q1983@D7ySwa5ijW0ut/CsdxijtMaumJFrIYBVoUAQ4KUgqFwv5z1TU2G82J0LoCdt0MHopaDnRYCEa08MdvE77OfIv2iZ2VSCOkCd9cwlrkbCzpCkEAQPkV4HMbYW4RPEB4ifM2NWtB1HCDsIzxA@BjhPsI9hB2EjxDuImwj3EG4jXALFghhWCEL4QbCLsoW63L@plmv1yeGM3ZdnEbuqoKTzGgEYRyeOqEdjeCKD6fOMLjaZGSEoSGUhFEqxZKQ1BjgmRFQ2xHD2MpJnFIEiiKVkqJgCsWGZNBkA7A0GeKhPx@fYyMqjmQRZjTjOls4DcTMoJxzwop4WDyUkocGDdkaoA5BmIYzroazZ6El2qFV7NBCR6G1etwk3HjevHBrFlbdcJJLwWrlCwIhQiEPy5bKTcAPS/xgm@NA5yDDATuhjshfLsL7zYC1D/l1llosPAYvHgzrQnv9xaT0QCBY5qMCfADXhfhKA0IWpj9OfyTwQJ2@n347/Qv83k9/mP51@meAP0z/MP0Ofu8@/H367Yd/Qv@PcI7UIVzM7No6nNSKlZUABbFp/kXKQYMDi4NmOAUOWhy0OehwYHPQ5eCIgx4HLgd9AN5qep4ofCOAqK1C7PJXZQLp2bSLObF8AjF5gU/C@4J5XqkUoW/kjLJe4V4foUM6apRPUlomZYYM5tkgl8ryUc5qps5zqTqKXVAAMwD@Elq6tJhOAWRVivAl@MZZKGv1IqOYmqsvBhzeus2NtjMz2TylcceyuFu1Io/qHkU@hNKRJGjS4EbRywwFsRwfhfgeQbDnEV5bR3gD4Zu30CaOLXtSQYefzIYl5TIbKqVrbx@d/uCUXzAKBbmwxq8XAkmmBEGU0hnZyF4d4Yt6CdJr5fr0XT98c30GP5ucXwgSv9zoPNHBVp5E@8Lx8Mlm@9ZQqLSyKWFLYrvPdO9NIJwdvDxZe1qglAJVowHAgtpsfi7hMqitFoA21E4HgA212wVwBNVxAPSgQh5Loj5UzwNwDHUwAOBDDQIAQ6gnJycA6aqnzv7KrCWE2v/ln5lXBvn4Pw "Io – Try It Online") 2. It starts with a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. There are at least 28 lines, and they are all distinct. 28. There must be a `>` in the code and angle braces must be balanced. 29. There must be more than 88 distinct code points in the program. 30. The third-to-last character is a tab (#26) AND adjacent lines must have different lengths 31. All printable ASCII characters that are not previously forbidden must be part of the code. The complete list is: `!"%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~` **32. The codepoint sum must be a perfect square.** --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and **all lines are distinct**. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * `#$[\]` may not appear in the program. * The program ends with: `tab`, *(whatever)*, `~`. * Angle braces must be balanced. * There must be more than 88 distinct code points in the program. * Adjacent lines must have different lengths * It contains all printable ASCII that are not previously forbidden. The characters are: `!"%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~`. * The codepoint sum is a perfect square. [Answer] # 1. [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 7 bytes ``` D,f,@,1 ``` [Try it online!](https://tio.run/##S0xJKSj4/99FJ03HQcfwv0qanRKUrcTl/x8A "Add++ – Try It Online") Might as well get Add++ in before things start getting difficult. This is very simply a translation of the first example into Add++. `D,f,@,1` defines a function which, no matter the argument given, returns `1`. [Answer] # 4. [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 10 bytes ``` .3[#'even] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/X884Wlk9tSw1L/a/g1UaF5e6nnEqSEjdSNXANlZdIU0hv7TkPwA "Stacked – Try It Online") Checks if the length of the program is even. Anonymous function which returns `1` for "true" inputs and `0` for "false" ones. **Satisfies:** 2. starts with a `.` 3. contains an `e` 4. has an even length [Answer] # 24, [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 256 bytes ``` .;*->+|a "x" a|+>-*;. x =input x =input x =input x =input x =input x =input x =input x =input;* Henry Jams? X =INPUT OUTPUT =GT(SIZE(X),21) 1 end ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234 Hi, Retina! ~ ``` [Try it online!](https://tio.run/##K87LT8rPMfn/X89aS9dOuyaRU6lCiTOxRttOV8taj4uzQsE2M6@gtIQ6LGstBY/UvKJKBa/E3GJ7Ls4IBVtPv4DQEC5O/9AQIK1g6x6iEewZ5aoRoaljZKjJacjFiROm5qUAKUcnZxdXN3cPTy9vH18//4DAoOCQ0LDwiMioxKTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyipDI2MTLk6PTB2FoNSSzLxERS7OutEQAAA "SNOBOL4 (CSNOBOL4) – Try It Online") Prints out `1` for truthy and outputs nothing for falsey. **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. --- **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The first line is a palindrome of length 21. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. * Its length is an even perfect square. * It is at least 28 lines long. * The ninth line must have at least 22 characters, excluding the newline. * The last non-empty line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * It contains `|`, `+` and `C`. * Each line contains a tab character. * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. [Answer] # 2. [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 17 bytes ``` ..).. .)Im. "."=. ``` [Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PU0@PS0/TM1ePS0lPyVYPixAA "Triangularity – Try It Online") Checks whether the first character is a dot (`.`). [Answer] # 8. [R](https://www.r-project.org/), 64 bytes ``` .0->z;x=readLines();y=Vectorize(utf8ToInt)(x);any(grepl("->",x)) ``` [Try it online!](https://tio.run/##K/r/X89A167KusK2KDUxxSczL7VYQ9O60jYsNbkkvyizKlWjtCTNIiTfM69EU6NC0zoxr1IjvSi1IEdDSddOSadCU/O/XmJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RSWXnYKSnRKQ9MwrKC1xzMnhsrNTMHzU0WEEYviXlgBFFYz/AwA "R – Try It Online") Satisfies: 2. The first character is a `.` 3. It contains an `e` 4. Its length is even 5. Its length is a perfect square 6. It contains an `a` 7. It contains a `>` character 8. Contains the exact sequence `->` in one of its lines. [Answer] # 10. [Somme](https://github.com/ConorOBrien-Foxx/Somme), 64 bytes ``` .1->Hi, Retina! I like French :D "RVll;d.h:and random stuff too! ``` [Try it online!](https://tio.run/##K87PzU39/1/PUNfOI1NHISi1JDMvUVHBUyEnMztVwa0oNS85Q8HKhUspKCwnxzpFL8MqMS9FoQhI5OcqFJeUpqUplOTnK1JuAgA "Somme – Try It Online") **[Verify it online!](https://tio.run/##dZJPTwIxEMXv/RTjqgQINAuKfzBgjMTIxQMaL4RDl86yG0pL2l0Vgc@O3WWVSrKXSdv85vVN5uk0WO3OAq3mKKEHIRMGCccQmDSfqKuyAZVQ1ohgi4AzWMNmqdVsQ1Ip0BgI5Ti7TwjAQSTRKdqHZZoY8B6V5HESKwmna7mFPeQRlJxs85r/JlDOkqiaadVIVmmwStBQE39jTk1/ZYz9YLwr3LVrf44gq2N/Ar0eeNSDbYMU0MURRGPJ8Qs8dKFLB3LNUPxAee@AnRKwXvdpB86hlRnwqe@0XJUYYK6B6xKo70I3JVDzH3VbQj3HDRhhEkt24uIt/5ifRkybsU9pe0IXbFmtdJXmNWrShR2wkw9o@3eTfFN2H69vg@EL1cjsNg@LosimUaacPW1sIACyUxGYLSH7gDwIATOluPVUhKpI0o62mn3HMwxBxHOEJ43SCncHxBu9C3HHadRlkoO2RS3AJGkYQqLUyQ8)** **Satisfies:** 2. The first character is a `.` 3. It contains an `e` 4. Its length is even 5. Its length is a perfect square 6. It contains an `a` 7. It contains a `>` character 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. **For future answers:** * The first character is a `.` * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. [Answer] # 6. [Pyth](https://pyth.readthedocs.io), 16 bytes ``` .e}\as.zS13 5 ``` [Try it here!](https://pyth.herokuapp.com/?code=.e%7D%5Cas.zS13++++5&input=.e%7D%5Cas.zS13++++5&debug=0) Checks if the input contains an `a`. Outputs either: * `[True, True, True, True, True, True, True, True, True, True, True, True, True]` for truthy * or `[False, False, False, False, False, False, False, False, False, False, False, False, False]` for falsy **Satisfies:** 2. starts with a `.` 3. contains an `e` 4. has an even length 5. has a perfect square length 6. contains an `a` [Answer] # 7. [Whispers](https://github.com/cairdcoinheringaahing/Whispers), 66 bytes ``` .abcdefghijklmnopqrstuvwxyz > ">" > InputAll >> 1∈2 >> Output 3 ``` [Try it online!](https://tio.run/##K8/ILC5ILSr@/18vMSk5JTUtPSMzKzsnNy@/oLCouKS0rLyisorLTkHJTglIeuYVlJY45uRw2dkpGD7q6DACMfxLS4CiCsZc1DADAA "Whispers – Try It Online") Outputs either `True` or `False`. Note the trailing new line. **Satisfies:** 2. The first character is a `.` 3. It contains an `e` 4. Its length is even 5. Its length in characters is a perfect square 6. It contains an `a` 7. It contains a `>` character [Answer] # 3. [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` . ”ee ``` [Try it online!](https://tio.run/##y0rNyan8/1@P61HD3NTU/3AWAA "Jelly – Try It Online") Checks whether the input contains a `e` character. Changed from `”` to `e` because that seemed unfair to languages without that character. And, to verify, here's a hexdump: ``` 00000000: 2e0a ff65 65 ...ee ``` **Satisfies:** 2. Starts with a `.` 3. Contains an `e` [Answer] # 18. [Python 3](https://docs.python.org/3/), 144 bytes ``` .6;"ea->?"#"?>-ae";6. "Hi, Retina!" import sys print(len(sys.stdin.read().split("\n"))>26+1) "|||||" 4.2 ``` [Try it online!](https://tio.run/##K6gsycjPM/7/X8/MWik1UdfOXklZyd5ONzFVydpMj0vJI1NHISi1JDMvUVGJKzO3IL@oRKG4spiroCgzr0QjJzVPA8jTKy5JyczTK0pNTNHQ1CsuyMks0VCKyVPS1LQzMtM21OQiFijVgIASl4me0eBzEQA "Python 3 – Try It Online") Outputs `True` if the input is at least 28 lines long, `False` otherwise. **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`, and so is the twelfth character (palindromic rule). * The last non-empty line does not have any duplicate characters. * The first line is a palindrome of length = 21 * It contains a `?`. * It contains a `|`. * It contains a `+`. * It is at least 28 lines long. [Answer] # 16: [Quarterstaff](https://github.com/Destructible-Watermelon/Quarterstaff), 64 1 is truthy, ``` .1......."a".......1. 1->a[Hi, Retina!] ?[-124(.|>a)?] 49a! ``` [Try it online!](https://tio.run/##KyxNLCpJLSouSUxL@/9fz1APApQSlaAsQz0uBQUFQ127xGiPTB2FoNSSzLxExVigoH20rqGRiYZejV2ipn0sl4lloiKyCXpkmQAA "Quarterstaff – Try It Online") the indentation doesn't do anything, by the way. **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|` **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`, and so is the twelfth character (palindromic rule). * The last non-empty line does not have any duplicate characters. * The first line is a palindrome of length = 21 * It contains a `?`. * It contains a `|` [Answer] # 15. Python 3, 64 bytes ``` .1and(11*"""*11(dna1. Hi, Retina!-> """)and(lambda s:"?" in s) ``` [Try it online!](https://tio.run/##fVTdbts2FL7nU5wyjiO5MmPadZtak7oM/XMRoEUSZC2stKMlylZCUapIp5aBArsa@gi96UPsflfL5d6iL5JRkg03BVoBIqhzvu/88HxiXup5Jgc38UKGXnBDKJORRWkHY9yh1IokowQ9Txw45jqR7E7XBwDjtCucYOk0YqBG@BFGiQRl3@RFIrU1qcJZyoY4K0CBcU3QDlACh1F09y7Cj53Y@dWh2DHWPoHTImFythCsSHSJTHRCbEIQsccpQZhgjxhbhR0QeMGFaDDo659fOF977hE40Sy85JEhDCY7e/yKy/PaNSTwqu4SBsbX4z0wRTV1Ci6tROYLbdl2p0OGu9TzenbNut@wDIN/DAK2OqEDqJ9h7X5A4Pd5onJeqLoYNg0jHs/mycWlSGWWvy@UXlx9WJYr5AP2sVnHVaJDIZDvA/366VO/2rxcaGOtKmv6OCBwXFXZ9Vfu0is4i44SyZVlu6V3xkOdFcmKWwsdH5xmY6lta2m7TJbWrOC5sALc9QPsLO2mh4dkPTYTsev3/vhmjrWf9sypZWnK6xZo1/8GAGMQySWHpwWX4RxGjxE@PhPCjch8ZGYPhVmyFEyXcQw6y@6sG6Bmyi/YFTsJiyTXJjGl7balPFPXLRkFuN1Wk4fnnrcX4L2mXmq0cNbUIoR49ubsOcb59edbvOt//vuLdP79G11/fttrbZIaYbzihYBhw3axa2QbfJcSu6133i@@G86z3K0FAOX@/n7oD9vtwuilUBzx96137iaqEdXrg/twqBRPp2vVnY5Pj54ABrxjXnhyZL6NUiOmGUpGJE6EgP7QoU4PqRFR2mSZAd7tDydvA6NHpLfGW8eNUbz1/FbyrZ3MRDZlAlKWSFQtI9g@KF@ouYBWstkoFDJTggqZjBGLImM6cGCXq3wLbRC6MOpfQ@6tIWoxhVafVl9siS5WUG5YccOqTy3@jnWR5mBClaMNWP8EzOUIFVxvjvjWz1mNbnP/BD@9gIIf3kAmCDo/t2/@Bw "Python 3 – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. **For future answers:** * The first character is a `.`. * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4. * The 10-th character is a `"`. * The last non-empty line does not have any duplicate characters. * The first line is a palindrome of length = 21 * It contains a `?`. [Answer] # 31. [Octave](https://www.gnu.org/software/octave/), 324 bytes New requirement: All printable ASCII that are not previously forbidden must be part of the code. The complete list is: `!"%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~`. ``` .6;%+<-?|" "|?-<+%;6. f=@(x)all(ismember(horzcat(33,34,46,' %&''()*+,=/0123456789:;<->?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~'),x)); % >> % V'quQ9g8u'@f/&'A)eLS;p`t'{ZYv4R3aaa % bb % c % dd %Henry Jams?Hi, Retina! % e % ff % g % hh % i % jj % k % ll % m % nn % o % pp % q % rr % s % tt % u % vvv % a~ ``` [Try it online!](https://tio.run/##3Tprd@PGdZ@xv2ICLwlABCmClLQrUoSklXe9crZeZ1/xrlbaHZJDEhQIQABIkStqj9PGsZs48Tppbcex0/SVtEn6SB9Jk6btOQS/9Vc0f8S9g8cMIHFd9xz79JxCwujivubOzJ175yG75eMR@eQYu5ZhdZHd6XxSWqvnChvFzakoiNPN4kYhV18rXeg0tuSxgk1TNrwBGTSJK/ds90kL@3K1qlZX1JU1VUK5vCTJylJBbSyXtUp1ZXXt0uX1Wn2jqG9ubV/ZefHqtZeu77785Ru/98rNV79y6/adu/e@@tr9BwePHuNmq0063Z7RPzQHlu0cuZ4/HB2PJ09OpqdPJUUdK0pduJATdB2Ke9LR8Cvr3ctDaauznJe2FXLjdt157EsnD@6PVm5VMcbA1WxC0YK33b6Qu04sd4JexgNv87qholvENyz8JaqRwNvpQNGFt9eDwoC334fiEF7ThGIAr2VBYcPrOFAcweu6UHjw@j4UQ3hHoxGU@Oknzol2ihpIelHtqFuqJtUvOCcVitmTSiWlVJJUpJVVJJWU3QH7EEtioyTtU95qzJuQfvf6x4REpJWYVN17QZLIiFj7EX41xpdJGdkuclzD8mWTWLJhOUNfVpSlpdJqTms0ykoksBYLkNOH2Cs9ua1VETyrEfFSTHz@wEiRZToSdTExU0e7tLJt02QYHWm/e@utSur75tAHHlQNUWFllxPTi/qT@rjhEty@YVjEk5X6pHGPtHzbNZ4Qeeh3Lt@xdy1fAVesY2sid13imLJY1EXqIJHl67Gyol5@nBrqiKiVY6pW1FNEtItM45Cgay6xWj1UezG0DamSeOueadbbpV4NW23kQmEPEPRAp4N8206UaolSLZ@XvYYuplSDbfm8t7e@32hIkihJsZVa4g2aaZov3b93XRSd4IOMXPDb//xGaWn2i6jrpOCDg/LFWDhxD60u1jXmJA/P1Fu/@KixoddbPduph@6AJsvLyy19NZ93wXFcjySS5Ojio3qsO/GvO7t3blxFIhZfgBddvQHf3G3b2MfJh1ErdQzTRJVVVVPLCdarlTzfpUFFzFVW9w4eWvvMTXxOywxDzCB1OP3KhJyllrqm3cQmGmDDilEUrCH@xGhn6PVMdNHIfnrxZwuiGfJa2OrECNxuA/myinLEcxariGR8F@ZVRmglI@QNm@hiRaM4PI5x/SdoktXZSesMx6fzKTr7AwexSie1rCr/f6WKWLVkJFzix8OehA8NfFzWtCVRFJc0TW5bmDtYxr2gm4FHoewmHjTbGHk1cZONsWEhL/H1JNJopegBh4ohrhvUwZzEe6k69jltc6@oVVbk0lTHyibDr6yzeZ3Eq@lm9CMWxBiaQhW01VnjJXVdrVYoIf0roSTexWqTyLRWFwmGLAaTYVMvYiJCTmRh@7wHQ/MHju36yJt4CYYHZECCf7cNq0QjnayUPMc0fFl8aImKolfWCpoCQhDaBpBdqWHqiqbQiqb0EaPmrJQqsY3rzMZcAUycigTytl4M83ZS@YL0LaV7RJJoAM17wwFnoLm9olarteoaze7rWm29qkrwhNl4Yy0/livwp5ynauXDxljWah0D3GHcaFCrlaKmKI1GxzQc@RCic2h2TlLTDausKWEjKuXP0IjMCPL1RUJejOEZ9KPUGgDy6X/95s2oAys8fEePCD/xw@renBYyocp2sM2G1jAcw2gZ2GsRTFqOY3jYaLFAiB0D8F6rBXjKCA@LnaQFrIbRx4REFAMUcElCSD@iAAis8MEkCSVEaNKP9TKDcKi4T9jTTxFphaHJCVtKMlRJEul@xJqWjB@ugFsbIRN5klabSDFjjL6TtjaRAZoTNjbTzqjlsTGZdqabSLuKdklKMlSZZmFq@w6vFZQ4mTrPiPXP1Hm2/@CT1ekYCToSpIqzBrHawj7KtDNd3dl2ZirsZ9UmLhBrXTyei9T209X1I3t5nWFlfSc1bVjfNlvhovA4syhMiLA4TMLo8TDhYG4SLx9jjqfxHKx8hvmfiVgpqySpfibOwdJwTNdbOxCsGC23bU3Qzmb8yaMQgkRdWY3jEFtZFXaK@hRSnCAiNNWLOwUeCwSBrWYFuvIACQjtxMUtH/nE8zmVfiEP6F7PPkZyq0dah0g26doWsqPCGSNKA9H8LROTDJCPmyk6fAHVt69awwFi8U34/wGkh5LhUrkpwSW@kqxQ60tFvTDFgjgWBTwt6MWlOh@jMWqEG5//I0R9CS1q1muosfvKq3fvMMTNu3fgEzVeuiPf3n1wVX5NUSuaImjP7a7k/fzHgVhtjnz@bv35O0Kafz/TAK6enezC81YssKFqEdPsDC15S94JJ/YOndgCTOw8EMP1BsPomgpr82g1NVZbPezC/FaUVAgQqAXUhLVszhcg5wtnc/5Y@HygxVFrZzpe8HzedX9x0Mb/9HDWgq7rRV0vpEr2FMKyGCO5jK4@0NWDjQfF6C0mzwO9UNIPEr4DYfw0GdJkCyAIdUmiERvGlEZxSA@CkEoirA1PGDRZ0MJjBo0YNBQWrEWFbCpizuYzZo9BLoOOGGQzaMAgk0GHDOozyGBQj0FdBnX4jGYQn9ktBjUZZAnLtQO1ckk/ODiYNsyJZSWUJcFi/ZvshYRpYTyG8YVdHJTjcWHKexelc2MXjRthLpOkDUka5/MkB1mZcAbS8LFhymFyLCspSTmUqGElBxAMYK2pNHCuyRlwLmYBAmc@yxBLRnSSIY5jlSeZVX1qJIunKf4t@VHtkZJ71MBpJU3eFsSMxwv6d2fBOJAF49VdMK7GgvE/XOAng9RonvcsJ3lS/ldlI8t2kNNyXqR7JhpNqxVNzJenPCJvMNkyg@oMKvCWjbAps6@n3AaXdB/RAzvc4o0/uw09kKTu6mvTjZdT81QV@ORNoYE1M/M4vyTNfjB7b/Zh8P7so9mz2Tdn786@lYZnPwL4/dkPZ9@evQ347wPv92YfAvYDKCPqs5Dvw7AEnuDj2Tsg8U7wRvAseDZ7G7C0hneDj4P3gu8F34HyveBrwZvw8/rsZ8Ebs1/D99chJSl1SGz68soqPQg/fwYu8In2aQ7U@sIcaLHbOIlrVNl56bRIY7og7ohh5C9OeZ7UjVpZ3hyFXvOUBc3wIE4/3dqqhYRGubFZ3zofUiO2UAFubI7yWiGvZzXpJ245v0zZqE49f1rOH2TFIx35U5er3VjAEXKZVahpqwZ2gT0n2ZrQuaeoa1Z9YdBPcNtX6IjuxuOZLJJSY9g6P3SdRePUP1w0b4WlyBD4s8SnbvQdU3hyWsDLs9iYp7sKg1ZWGbjGoEuXBbbFSM2wXFF4xPyCnZnEZy4iPQ68fGltdQXiBvMM3x0StLHcJqNlawhbm@Rklh589GyYzxyxi/yePez2fHRM4NclqIdH9AjY8wkekDZqmWAE57/ZU5Flo10E@@E2Y@oBTx3d6WHfQ8dQAj08EwV8c@h2ieuhlBH37eE5clrTZpqXeCoyQC2GrWPXsC1soraBTQKbvoTnbq/YG4JdYc0R12a6vrtAQ0PH87FP0CvkGN233cMU/RYBYyZ19FVY8qpod4A6rj1Ad32jhVVELyB2RwRZ9Oge9Qh224Cb2BZBQ49A7xHk9FwMoCSlG0E7@Uyv@bBfTdRadh3t0mZZaNtsgkJExhCpPQ@MT4@OR0gd0Q47tOxjlVbnkXS/YRixo6EBDfOMgWFiF3aroVE23ewCMKEDShD0zJfdoedP0JVQ8qxtdfQq9A5sp9vo9qFhWcARV1FHN8026mDQPoHebRkOYbLXbDczcig7ctAHeR0t8kOjE27Z0eMWGBYyhCezaIoG7VUPNttT2tVtVGyhlcfg8o9Dxy1CZ8FwTBL/geYNsvW3iefQzqA90AkPBqhPhN1Ae8pujgx76EFDuq5hmiC1sMI6sxMkrXSjKEzGho/KqTllwpAs4tE4rmNw@Pq17SvX7qa@@VxnuJ0CpwfvBt@FZPdHwR9Dcns/@CD4fvBh8IPgI0iCPwz@JPhR8KfBnwV/HvxF8JfBj4OfBH8V/HXw0@Bnwc@Dvwn@Nvi74O@DXwT/EPxj8E/BPwe/DH4V/Evw6@A3wb8Gvw3@Lfj34D/mr8@/Nv/9@R/Mvz5/Y/6N@Zvzt@Z/OP/m/Fvzt@ffnn9n/s782fzd@Xe5Nduplqav8jYgaGeGmnEdAYxZsE8iWfrk6ey196ccn5@//Y6uv7@YC/DkBpxvZPleid6Hswvx6EY8dSWeuhPnAs0mh1scbLcZ/Jz7cs5LONjpcLjLwV6PwwYH@30OH3KQXxnnhAEH@VYkJ9gcdBwOH3HQdTnscdD3OTzk4Gg04h84Sm2d6PZMlrYtD7JQDeUqBhTGQ7BjT6tZwwExZUepI34sMVZQBwoVOcq@cuHCGNzJOSFW@7R@oW14jrwnXcder0bdEMQrnu/K1JN6gJQlmPT06kXWaitKoyFdXsNrsGgEPbHoNr1vHDaj61DvnJI9fp2TOXABc1KU9EFUhgKbY0Dspyt80eh0IPtaPjKJ1fV75@tsA0dU8NsehT5cyV3LOILMT09gsvKW9UQehkTosbTE1aMhJFRgA7uQ3YF01DVJVpZeTtFT3Q0Jeir50KG3INJtFNFOeIQ6wNaQJlHUgYzQxCa2WkRKVWNBcO@CWqbV8AitWh7LMGTFvYpa3lfUvXXwi8papmMgxTSNdptYaemn9ESK9@cLF/ce7odXaSnBmxaYs3quKUxqrEpfKolSRmYHeg6yBlnQfaCcxnbDo4QTiWZz6fTkqewduX7C0Gh0jHEGo@TzA7sdf6kVhf4byCndbViI/g8J8qATXNpTn/w3 "Octave – Try It Online") 2. It starts with a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` 23. Each line contains a tab character. 24. The ninth line contains at least 22 characters, excluding the newline. 25. The tab character can't be the first character on a line 26. The third-to-last character is a tab. 27. There are at least 28 lines, and they are all distinct. 28. There must be a `>` in the code and angle braces must be balanced. 29. There must be more than 88 distinct code points in the program. 30. The third-to-last character is a tab (#26) AND adjacent lines must have different lengths 31. All printable ASCII characters that are not previously forbidden must be part of the code. The complete list is: `!"%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~` --- **For future answers:** * The first line is a palindrome matching `.␣␣␣␣␣␣␣␣"␣"␣␣␣␣␣␣␣␣.` (you are free to fill in the ␣s). * The second character is one of `',16;`, or a tab, or one of `\x04\x0e\x13\x18\x1d`. * Its length is an even perfect square. * There are at least 28 lines, and **all lines are distinct**. * The ninth line must have at least 22 characters (excluding the newline). * The last line does not have any duplicate characters. * Contains the exact strings `->`, `Hi, Retina!`, and `Henry Jams?`. * Each line contains at least one tab character, but it can't be the first character on a line. * `!".` are banned except where necessary: + Only `!` in `Hi, Retina!` and the two `.` and two `"` in the first line are allowed. * `#$[\]` may not appear in the program. * The program ends with: `tab`, *(whatever)*, `~`. * Angle braces must be balanced. * There must be more than 88 distinct code points in the program. * Adjacent lines must have different lengths * It contains all printable ASCII that are not previously forbidden. The characters are: `!"%&'()*+,-./0123456789:;=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz{|}~`. [Answer] # 20. [Jelly](https://github.com/DennisMitchell/jelly), 100 bytes This code checks whether or not `Henry Jams?`. Returns `1` for truthy, `0` for falsy. ``` .6;%+->?|"e"|?>-+%;6. Hi, Retina!->0123456789 0123456789 0123 “Henry Jams?”ẇ ``` [Try it online!](https://tio.run/##y0rNyan8/1/PzFpVW9fOvkYpVanG3k5XW9XaTI/LI1NHISi1JDMvUVHXzsDQyNjE1MzcwpILjcmFCzxqmOORmldUqeCVmFts/6hh7sNd7f/paRkA "Jelly – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * Its length is an even perfect square. * Contains the exact sequence `->`. * Contains the exact string `Hi, Retina!`. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60. * The 10-th character is a `"`, and so is the twelfth character (palindromic rule). * The last non-empty line does not have any duplicate characters. * The first line is a palindrome of length = 21 * It contains a `?`. * It contains a `|`. * It contains a `+`. * It is at least 28 lines long. * The following characters can only be used five times in total: `!"#$.[\]`. + Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. * Each program must contain `Henry Jams?` as a continuous substring. [Answer] # 22, [Octave](https://www.gnu.org/software/octave/), 100 bytes Executive summary: There must now be an uppercase `C` in the code. ``` .6;%+->?|"e"|?>-+%;6. 'Hi, Retina!Henry Jams?'; f=@(x)any(x=='C'); %Any C? %~ ``` [Try it online!](https://tio.run/##lVbLcts2FN37K1DEEkibogXqEUuMqDzbuJOZzqSZzHRkJ4Up0AZDkQhJxZKjZLpq8wlZtB/RbaerZtmvaH7EBUmAD8XppKAexH2cewBcXCByU/KKXl2ZQ7u133GmG0jhZup09lv20NxBD5kBHtOUheSrhzSM1@BbskimyN7xJre1lU7CtbaaTNA9pNs7rTvhGtyb7nymtd5eXZA4ZOEZiDxvh7/Gb8AEoPuGZ9w2sIDkr61MMkOmqZsmMgDuGgCZ@tGi7EATTkx0ktn2pK1SffzpN0oLVV@qerMbCNFXNDwp5AMp79IuiGLAYxamWkBDjYV8mWq6vrdnDlp4MunqhcNQOtA3xyQxL7/HPSDaoFDelEpy6s6pd3bO/BfBIoz4yzhJl68uVutLVDBzAHSgoumAoyzYnSAoJQ7AH9@9s2r975apsAG9XJQHO1TUO86lvZrElMwfsZAmmm6vJ0@pm0Yxu6TaMvUOn0RHYaqLxbGz1TmLKQ802HGgsdLlsEYSrON0f6wtcKHEXanFHaemBEcgYC8o@DqmoXsOxvdzbsBA8PHTILDn5vmYhHMQi59oAcQMeB5Io0iBYgWK220tmTiwBi24tdvJbHQiEglBhCRLrLIBB0HwzQ9PH0LIP7xv@H348@@fzb2/fi@mDn14/6y7K51VemAb2rhMkuOtuPbu88ktx3bPI27n6QDWBwcHrjNot2OROHFClSd9ufvcltgqv54cPXn0AEACb4gvePBI9Ku0nZOUqA4bmx4LAmANDGx0lTQZm0kaZ/sBtqzB7NlxeFKmSVrpGssgDZBX6e@u6bbWPAuiUxKABWGhFGWvY1A1KebL5DwAu6zZTWTXJYJ04pLQkwIynwv1oQFaNOHXQxQ@aSz2VcOp33BKlqdg18KZjKykzL8E6yamV8fM18f7D0x/wUEZdD1uQqX/C4qGY7USMU3lsqvygUWOaxjvQQj3MNbmIakSrJFeYpqFjZ6ZB2RxOicgGcNpucYsBInKdVVpsFk0kVDyrcIWcGJPklktxkmlm8462Opr5sYh@rSU90flvlb1ajMtHrgP5dtGhMhG3SSPjJHRszJF/YOAqncSVlWmoQ0pEQeI2Azi@CAUivOjLNufZrAY/oJHcQqSdaIkVUEWQpHfcxaaWaXTdDPhAUs1eBxCXXes4T7WhZMobQuSahkxo4/1LNAma7AYTt@0JMdRyfHTM04FlwdaEGgsWdDFKY01VJ8RhLIC2k6Wi8rAFdEto9cb94ZGf2iM8HjUM5BoemZ7a9heaT3x1y34tJBRZ2wN9Zyd1f0Cdo2l6WKr1x8Mbx6OlPp6SXU0/lo7vMVB@c8fvxQzY1V1uWhQPLKVsaeb/UYNijiJyjVjjDPmMpK4lFCXc5YQ5pYVjnAm5InrCnlmKFpZFKkrTBnzCaWFhgmAypNS6hca8SpMRaf0pJmiEFNf4paESA7s07L5NWUWMKeszGqeOSRV3n5hWveUrQKo2BZC5U/rsMqrJMN8XmerfISO54NtjLMYuSTTGGd9iNlUZVNS88wh6yYlrM@rqAKEN2JuuflbMbfnT3TLmJwpceGYATcJldHyOWqMsx5ue5yNgH4TVqWARL1@Pa@D9evh/IJvFTMP5vPatinn9tTNb3sXjdueUopbn6qPF0tlUaaJvBdKi7dyD1pfsP/R527iyN4qYPJGLq7k4k6udPJqLrtVFQLiBLYGWR3ameFxuFzQQOO6DVwaBN4y1DJE4IkfA3D95Opf "Octave – Try It Online") **Satisfies:** 2. The first character is a `.`. 3. It contains an `e`. 4. Its length is even. 5. Its length is a perfect square. 6. It contains an `a`. 7. It contains a `>` character. 8. Contains the exact string `->`. 9. Contains the exact string `Hi, Retina!`. 10. The sum of the first two Unicode code points is a multiple of 5. 11. The 10-th character is a `"`. 12. The last non-empty line does not have any duplicate characters. 13. The first line is a palindrome of length > 5. 14. The first line is exactly 21 characters long (not including newline). 15. It contains a `?`. 16. It contains a `|`. 17. Contains a `+`. 18. It is at least 28 lines long. 19. The following characters are used five times in total: `!"#$.[\]` and the codepoint of the second character is less than 60. 20. Contains `Henry Jams?` as a continuous substring. 21. The last character is `~`. 22. It contains a `C` --- **For future answers:** * The first character is a `.`, and so is the 21st character (palindromic rule). * The 10th character is a `"`, and so is the 12th character (palindromic rule). * The first line is a palindrome of length 21. * The second character's Unicode code point, mod 5, is 4, **and** its code point is lower than 60 (the printables are `',1;6` and tab). * The last character is `~`. --- * Its length is an even perfect square. * It is at least 28 lines long. * The last non-empty line does not have any duplicate characters. --- * Contains the exact sequence `->`. * Contains the exact strings `Hi, Retina!` and `Henry Jams?`. * It contains `|`, `+` and `C`. --- * Each program is now allowed only the 2 `.` and 2 `"` in the first line, and the `!` in `Hi, Retina!`. Those characters cannot be used anywhere else, in addition to no uses of `#$[\]`. ]
[Question] [ This is a follow up to [How slow is Python really? (Or how fast is your language?)](https://codegolf.stackexchange.com/questions/26323/how-slow-is-python-really-or-how-fast-is-your-language). It turns out it was a bit too easy to get a x100 speedup for my last question. For those who have enjoyed the challenge but want something harder where they can really use their low level skills, here is part II. The challenge is to get a x100 speedup for the following python code as tested on my computer. To make it more difficult I am using pypy this time. The current timing for me is **1 minute and 7 seconds** using pypy 2.2.1. **Rules** 1. The first person to submit code which I can run, is correct and is x100 times faster on my machine will be awarded a bounty of 50 points. 2. I will award the win to the fastest code after a week. ``` import itertools import operator import random n = 8 m = 8 iters = 1000 # creates an array of 0s with length m # [0, 0, 0, 0, 0, 0, 0, 0] leadingzerocounts = [0]*m # itertools.product creates an array of all possible combinations of the # args passed to it. # # Ex: # itertools.product("ABCD", "xy") --> Ax Ay Bx By Cx Cy Dx Dy # itertools.product("AB", repeat=5) --> [ # ('A', 'A', 'A', 'A', 'A'), # ('A', 'A', 'A', 'A', 'B'), # ('A', 'A', 'A', 'B', 'A'), # ('A', 'A', 'A', 'B', 'B'), # etc. # ] for S in itertools.product([-1,1], repeat = n+m-1): for i in xrange(iters): F = [random.choice([-1,0,0,1]) for j in xrange(n)] # if the array is made up of only zeros keep recreating it until # there is at least one nonzero value. while not any(F): F = [random.choice([-1,0,0,1]) for j in xrange(n)] j = 0 while (j < m and sum(map(operator.mul, F, S[j:j+n])) == 0): leadingzerocounts[j] +=1 j += 1 print leadingzerocounts ``` The output should be similar to ``` [6335185, 2526840, 1041967, 439735, 193391, 87083, 40635, 19694] ``` You must use a random seed in your code and any random number generator that is good enough to give answers close to the above will be accepted. **My Machine** The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. **Explanation of code** This code iterates over all arrays S of length n+m-1 that are made up for -1s and 1s. For each array S it samples 1000 non-zero random arrays F of length n made up of -1,0 or 1 with probability of 1/4, 1/2,/14 of taking each values. It then computes the inner products between F and each window of S of length n until it finds a non-zero inner product. It adds 1 to `leadingzerocounts` at each position it found a zero inner product. **Status** * **Perl**. 2.7 times slowdown by @tobyink. (Compared to pypy not cpython.) * **J**. 39 times speedup by @Eelvex. * **C**. 59 times speed up by @ace. * **Julia**. 197 times faster not including start up time by @one-more-minute. 8.5 times speed up including start up time (it's faster using 4 processors in this case than 8). * **Fortran**. 438 times speed up by @semi-extrinsic. * **Rpython**. 258 times speed up by @primo. * **C++**. 508 times speed up by @ilmale. (I stopped timing the new improvements because they are too fast and iters was too small.) --- It was pointed out that timings below a second are unreliable and also some languages have a start-up cost. The argument is that if you are to include that you should also include the compilation time of C/C++ etc. Here are the timings for the fastest code with the number of iterations increased to 100,000. * **Julia**. 42 seconds by @one-more-minute. * **C++**. 14 seconds by @GuySirton. * **Fortran**. 14s by @semi-extrinsic. * **C++**. 12s by @ilmale. * **Rpython**. 18s by @primo. * **C++**. 5s by @Stefan. ## **The winner is.. Stefan!** Follow-up challenge posted. [How high can you go? (A coding+algorithms challenge)](https://codegolf.stackexchange.com/questions/26459/optimize-this-algorithm-for-larger-inputs-a-codingalgorithms-challenge) . This one is harder. [Answer] # C++ x150 x450 x530 Instead of array I used bits (and dark magic). Thanks @ace for the faster random function. How does it work: the first 15th bits of the integer `s` represent the array `S[15]`; the zeroes represent -1, the ones represent +1. The array `F` is build in a similar way. But with two bit for each symbol. * 00 represent -1 * 01 and 10 represent 0 * 11 represent 1 Cause `S` and `F` have a different representation I have to interleave `S` with itself to be comparable with `F`. * 0 (-1) became 00 (-1 in the representation of `F`) * 1 (+1) became 11 (+1 in the representation of `F`) Now we can simply use Carnot to compute the inner product. Remember that one variable can only assume value 00 or 11 0 . 00 = 11 (-1 \* -1 = +1) 0 . 01 = 10 (-1 \* 0 = 0) 0 . 10 = 01 (-1 \* 0 = 0) 0 . 11 = 00 (-1 \* +1 = -1) 1 . 00 = 00 (+1 \* -1 = -1) 1 . 10 = 10 (+1 \* 0 = 0) 1 . 01 = 01 (+1 \* 0 = 0) 1 . 11 = 11 (+1 \* +1 = +1) Looks like a not xor to me. :) Sum the ones is just a game of shift and mask, nothing really complex. ``` #include <array> #include <ctime> // From standford bithacks // http://graphics.stanford.edu/~seander/bithacks.html inline int32_t interleaveBit(int32_t x) { static const uint32_t B[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF }; x = (x | ( x << 8)) & B[3]; x = (x | ( x << 4)) & B[2]; x = (x | ( x << 2)) & B[1]; x = (x | ( x << 1)) & B[0]; return x | (x << 1); } inline int32_t sumOnes(int32_t v) { static int b[] = { 1, 0, 0, 1}; int s = 0; for( int i = 0; i < 8; ++i) { const int a = 3&(v>>(i*2)); s += b[a]; } return s; } inline int32_t sumArray(int32_t v) { static int b[] = { -1, 0, 0, 1}; int s = 0; for( int i = 0; i < 8; ++i) { const int a = 3&(v>>(i*2)); s += b[a]; } return s; } uint32_t x, y = 24252, z=57768, w=1564; //PRNG seeds int32_t myRand() { uint32_t t; t = x ^ (x<<1); x = y; y = z; z = w; w = w ^ ( w >> 19) ^ t ^ (t >> 8); return w; } int main() { std::array<int, 8> leadingZero{0}; x = static_cast<int32_t>(time(nullptr)); // seed PRNG const int maxS = 1 << 15; for(int s = 0; s < maxS; ++s) { const int32_t x = interleaveBit(s); for(int i = 0; i < 1000; ++i) { int32_t random; do { random = 0xFFFF & myRand(); }while(sumOnes(random) == 0); int j = 7; while( j >= 0 ) { const int32_t h = (x >> (j*2)); const int32_t l = 0xFFFF & (~(random ^ h)); // inner product if(sumArray(l) == 0) { leadingZero[j]++; } else { break; } j--; } } } for(int i = 7; i >= 0; --i) { printf("%d ", leadingZero[i]); } printf("\n"); return 0; } ``` Here a sample output: ``` 6332350 2525218 1041716 438741 192917 87159 41023 19908 real 0m0.372s user 0m0.371s sys 0m0.001s ``` The program has been compiled with: ``` gcc -std=c++11 -O3 -msse4.2 -Wall -lstdc++ 26371.cpp -o fastPy ``` on Fedora 20 with gcc 4.8.2 The Cpu is a i7 8core. Probably I can gain some ms tweaking compiler parameters. While this is the OP solution time on my machine: ``` time pypy 26371.py [6330609, 2523914, 1040885, 439303, 192708, 86987, 40710, 19498] real 0m53.061s user 0m53.016s sys 0m0.022s ``` --- Edit: Just adding openmp and change the order of the for I have a x3 gain, leading to a x450 performance improvement against OP code. :D In this case the `leadingZero` array must be atomic. The random global... are random, they will be more random. ``` #pragma omp parallel for for(int i = 0; i < 1000; ++i) { int32_t random; do { random = 0xFFFF & myRand(); }while(sumOnes(random) == 0); for(int s = 0; s < maxS; ++s) { const int32_t x = interleaveBit(s); int j = 7; while( j >= 0 ) { const int32_t h = (x >> (j*2)); const int32_t l = 0xFFFF & (~(random ^ h)); // inner product if( sumArray(l) == 0 ) { leadingZero[j]++; } else { break; } j--; } } } ``` need to add `-fopenmp` to the compiler flag --- Edit:2 As suggester by user71404 I changed the sumOnes and sumArray functions and now it's uber fast. ``` real 0m0.101s user 0m0.101s sys 0m0.000s ``` With openmp is slower, cause the atomics add too much overhead. ``` real 0m0.253s user 0m1.870s sys 0m0.001s ``` Without atomics is even faster, but I get wrong result. 2137992 1147218 619297 321243 155815 70946 32919 15579 ``` real 0m0.048s user 0m0.338s sys 0m0.001s ``` To understand sumArray consider that 16 bit represent and array of 8 numbers. 00 have no 1 and represent -1 01 and 10 have one 1 and represent 0 11 have two 1s and represent 1 So that built-in count the number of bit set to 1 [[http://en.wikipedia.org/wiki/Hamming\_weight]](http://en.wikipedia.org/wiki/Hamming_weight%5d) and to each group we remove 1. Cool. sumOnes is just black magic. Here the latest compile flags and code. gcc -std=c++11 -mfpmath=sse -O3 -flto -march=native -funroll-loops -Wall -lstdc++ ``` #include <cstdint> #include <cstdio> #include <ctime> inline int32_t interleaveBit(int32_t x) { static const uint32_t B[] = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF }; x = (x | ( x << 8)) & B[3]; x = (x | ( x << 4)) & B[2]; x = (x | ( x << 2)) & B[1]; x = (x | ( x << 1)) & B[0]; return x | (x << 1); } inline int32_t sumOnes(int32_t v) { /* 0xAAAA == 0b1010 1010 1010 1010 */ return !!(0xAAAA & (v ^ ~(v << 1))); } inline int32_t sumArray(int32_t v) { return __builtin_popcount(v) - 8; } uint32_t x, y = 24252, z = 57768, w = 1564; //PRNG seeds int32_t myRand() { uint32_t t; t = x ^ (x << 1); x = y; y = z; z = w; w = w ^ ( w >> 19) ^ t ^ (t >> 8); return w; } int main() { int leadingZero[8] = { 0 }; x = static_cast<int32_t>(time(nullptr)); // seed PRNG const int maxS = 1 << 15; for( int i = 0; i < 1000; ++i ) { int32_t random; do { random = 0xFFFF & myRand(); } while(sumOnes(random) == 0 ); for( int s = 0; s < maxS; ++s ) { const int32_t x = interleaveBit(s); int j = 7; while( j >= 0 ) { const int32_t h = (x >> (j * 2)); const int32_t l = 0xFFFF & (~(random ^ h)); // inner product if( sumArray(l) == 0 ) { leadingZero[j]++; } else { break; } j--; } } } printf("[%d, %d, %d, %d, %d, %d, %d, %d]\n", leadingZero[7], leadingZero[6], leadingZero[5], leadingZero[4], leadingZero[3], leadingZero[2], leadingZero[1], leadingZero[0]); return 0; } ``` [Answer] # C++ bit magic ## ~16ms multithreaded, 56ms singlethreaded. ~4000 speedup. (speedup is based on multithreaded code on my i7-2820QM and the 1 min 9 seconds mentioned in the question. Since the OP's system has worse single threaded performance than my CPU but better multi threaded perfiormance i expect this number to be accurate) The multithreaded part is quite inefficient due to the spawning of threads. I could probably do better by leveraging my custom job library but that one has bugs under unix systems.. For an explanation and almost identical code without threading refer to <https://codegolf.stackexchange.com/a/26485/20965>. ### edit I gave each thread it's own RNG and cut down the bit length to 32 which reduced the runtime by a few ms. ``` #include <iostream> #include <bitset> #include <random> #include <chrono> #include <stdint.h> #include <cassert> #include <array> #include <tuple> #include <memory> #include <thread> #include <future> #include <string.h> #ifdef _MSC_VER uint32_t popcnt( uint32_t x ){ return _mm_popcnt_u32(x); } #else uint32_t popcnt( uint32_t x ){ return __builtin_popcount(x); } #endif void convolve() { static const unsigned threadCount = 32; static const unsigned n = 8; static const unsigned m = 8; static const unsigned totalIters = 1000; static_assert( n <= 16, "packing of F fails when n > 16."); static uint32_t fmask = (1 << n) -1; fmask |= fmask << 16; std::array< uint32_t, m * threadCount > out; std::vector< std::future<void> > threads; for( int threadId = 0; threadId < threadCount; threadId++) { threads.emplace_back( std::async( [&, threadId] { std::random_device rd; std::knuth_b gen(rd()); uint32_t nextRandomNumber = gen(); const unsigned iters = totalIters / threadCount; std::array< uint32_t, m > leadingZeros; for( auto& x : leadingZeros ) x = 0; for( unsigned i = 0; i < iters; i++ ) { // generate random bit mess uint32_t F; do { // this funky looking construction shortens the dependancy chain of F F = nextRandomNumber & fmask; nextRandomNumber = gen(); } while ( 0 == ((F % (1 << n)) ^ (F >> 16 )) ); // Assume F is an array with interleaved elements such that F[0] || F[16] is one element // here MSB(F) & ~LSB(F) returns 1 for all elements that are positive // and ~MSB(F) & LSB(F) returns 1 for all elements that are negative // this results in the distribution ( -1, 0, 0, 1 ) // to ease calculations we generate r = LSB(F) and l = MSB(F) uint32_t r = F % ( 1 << n ); // modulo is required because the behaviour of the leftmost bit is implementation defined uint32_t l = ( F >> 16 ) % ( 1 << n ); uint32_t posBits = l & ~r; uint32_t negBits = ~l & r; assert( (posBits & negBits) == 0 ); uint32_t mask = posBits | negBits; uint32_t totalBits = popcnt( mask ); // if the amount of -1 and +1's is uneven, sum(S*F) cannot possibly evaluate to 0 if ( totalBits & 1 ) continue; uint32_t adjF = posBits & ~negBits; uint32_t desiredBits = totalBits / 2; uint32_t S = (1 << (n + m -1)); // generate all possible N+1 bit strings // 1 = +1 // 0 = -1 while ( S-- ) { for( int shift = 0; shift < m; shift++ ) { uint32_t s = (S >> shift) % ( 1 << n ); auto firstBits = (s & mask) ^ adjF; if ( desiredBits == popcnt( firstBits ) ) { leadingZeros[shift] = leadingZeros[shift] + 1; } else { break; } } } } memcpy( out.data() + (threadId * m), leadingZeros.data(), sizeof( leadingZeros[0] ) * m ); } )); }; std::array< uint32_t, m > leadingZeros; for( auto& x : leadingZeros ) x = 0; for( auto& thread : threads ) { thread.wait(); } for( int i = 0; i < (threadCount * m); i++ ) { leadingZeros[i % m] += out[i]; } for( auto x : leadingZeros ) std::cout << x << ", "; std::cout << std::endl; } int main() { typedef std::chrono::high_resolution_clock clock; int rounds = 100; // do some rounds to get the cpu up to speed.. for( int i = 0; i < rounds / 10; i++ ) { convolve(); } auto start = clock::now(); for( int i = 0; i < rounds; i++ ) convolve(); auto end = clock::now(); double seconds = std::chrono::duration_cast< std::chrono::microseconds >( end - start ).count() / 1000000.0; std::cout << seconds/rounds*1000 << " msec/round" << std::endl; return 0; } ``` Sample output: ``` 6317312, 2515072, 1034368, 434048, 190144, 85200, 39804, 19168, 6226944, 2481408, 1031168, 438080, 192896, 86816, 40484, 19490, 6321152, 2524672, 1045376, 442880, 195680, 88464, 41656, 20212, 6330624, 2517504, 1031104, 430208, 187696, 83976, 38976, 18708, 6304768, 2510336, 1030720, 433056, 190880, 86824, 40940, 19840, 6272512, 2494720, 1028160, 432352, 189168, 84752, 39540, 19052, 6233600, 2507520, 1046912, 447008, 198224, 89984, 42092, 20292, ``` [Answer] # Julia: 0.7s, 120x faster As user20768 demonstrated, a straightforward port of the code to Julia is about twice as fast as PyPy. But we can do a lot better than that. ``` function pleadingzerocounts(; n = 8, m = 8, iters = 1000) @parallel (+) for S = 1:2^(8+8-1) leading_counts = zeros(Int, m) F = Array(Int, n) for i = 1:iters flag = 0 while flag == 0 for i = 1:n v = (1-(rand(Int8)&3))%2 @inbounds F[i] = v flag += v & 1 end end for j = 1:m sum = 0 for i = 1:n @inbounds sum += S & (1 << (j + i - 2)) > 0 ? F[i] : -F[i] end sum == 0 ? (leading_counts[j] += 1) : break end end leading_counts end end function main() # Warm up the JIT pleadingzerocounts() # Then go for real println(@time pleadingzerocounts()) end ``` You can run this using `julia -p 8 -e 'require("golf.jl");main()'` (the 8 is the number of processes, you might want to play around with it). On the latest Julia prerelease this takes 0.7s vs. 1m22s for PyPy. If you have enough cores on your computer, and perhaps spin up a few AWS instances, you should be able to shave off some more :) [Answer] ### C, 1.210s **With OP's code running 1m45.729s on my machine.** Compilation: ``` gcc -O3 -march=native -fwhole-program -fstrict-aliasing -ftree-vectorize -Wall ./test2.c -o ./test2 ``` Special thanks: @dyp for compilation flags and ideas for optimisations. ``` #include <stdio.h> #include <time.h> #define n (8) #define m (8) #define iters (1000) int leadingzerocounts[m]; // declared as global so initialised to 0 unsigned int x,y=34353,z=57768,w=1564; //PRNG seeds /* xorshift PRNG * Taken from https://en.wikipedia.org/wiki/Xorshift#Example_implementation * Used under CC-By-SA */ int myRand() { unsigned int t; t = x ^ (x << 11); x = y; y = z; z = w; return w = w ^ (w >> 19) ^ t ^ (t >> 8); } int dotproduct(int*F, int*S) { unsigned int i; int sum=0; for(i=0; i<n; i++) { sum+=F[i]*S[i]; } return sum; } int main() { unsigned int i, j, tmp; x=(int)time(NULL); //seed PRNG int S[n+m-1]; for(i=0; i<(1<<(n+m-1)); i++) { tmp=i; for(j=0; j<n+m-1; j++) { S[j]=(tmp&1)*(-2)+1; tmp>>=1; } for(j=0; j<iters; j++) { int F[n]; unsigned int k, flag=0; do { for(k=0; k<n; k++) { F[k]=(1-(myRand()&3))%2; flag+=(F[k]&1); } } while(!flag); for(k=0; k<m&&!dotproduct(F, S+k); k++) { leadingzerocounts[k]++; } } } for(i=0; i<m; i++) printf("%d ", leadingzerocounts[i]); return 0; } ``` Sample output: ``` 6334411 2527506 1042239 439328 192914 87005 40847 19728 ``` [Answer] **Perl** This is nowhere near as fast as the C solution, but is pretty fast for a high-level interpreted language I think. It shaves about 40% off the running time of the Python implementation. ``` #!/usr/bin/env perl use v5.10; use strict; use warnings; use Algorithm::Combinatorics qw( variations_with_repetition ); use List::Util qw( any sum ); use constant { N => 8, M => 8, ITERS => 1000, }; my @leadingzerocounts; my $variations = variations_with_repetition([-1, 1], N + M - 1); while (my $S = $variations->next) { for my $i (1 .. ITERS) { my @F; until (@F and any { $_ } @F) { @F = map +((-1,0,0,1)[rand 4]), 1..N; } my $j = 0; while ($j < M) { last if sum map $F[$_]*$S->[$j+$_], 0..N-1; $leadingzerocounts[$j++]++; } } } say join ", ", @leadingzerocounts; ``` The Algorithm::Combinatorics is available in Ubuntu (`sudo apt-get install libalgorithm-combinatorics-perl`). The other modules used are core Perl modules, so should already be installed as part of the base Ubuntu installation. [Answer] # Julia: 4.66x slower! I am really beginning to doubt [the statistics on their website](http://julialang.org)... Note that the following Julia code is effectively a direct transcription of the OP's Python code without any optimisations. I use the `time()` function to exclude Julia's slow startup time... ``` srand(27182818284590) t = time() require("Iterators") n = 8 m = 8 iters = 1000 bothzero = 0 leadingzerocounts = zeros(m) for S in Iterators.product(fill([-1,1], n+m-1)...) for i = 1:iters F = [[-1 0 0 1][rand(1:4)] for j = 1:n] while all((x) -> x == 0, F) F = [[-1 0 0 1][rand(1:4)] for j = 1:n] end j = 1 while j <= m && sum(map(*, F, S[j:j+n-1])) == 0 leadingzerocounts[j] += 1 j += 1 end end end println(leadingzerocounts) t = time() - t println("$t seconds") ``` Julia: 5 m 32.912 s OP's code in PyPy: 1 m 11.506 s Julia output: ``` 6332170 2525472 1041522 438761 193119 86873 40705 19662 ``` [Answer] **Julia: 1 min 21.4s (2.2x faster)** (modification of Arman's code) **Op's code in PyPy: 3 min 1.4 s** Both done in the REPL, not including time to load packages. ``` function foo() n = 8 m = 8 iters = 1000 bothzero = 0 leadingzerocounts = zeros(Int,m) P=[-1,0,0,1] for S in Iterators.product(fill([-1,1], n+m-1)...) Sm=[S...] for i = 1:iters F = P[rand(1:4,n)] while all(F==0) F = P[rand(1:4,n)] end j = 1 while j <= m && dot(F,Sm[j:j+n-1]) == 0 leadingzerocounts[j] += 1 j += 1 end end end println(leadingzerocounts) end ``` There are some problems with Arman's code making it very slow: It uses a lot of anonymous functions and higher order functions unnecessarily. To test if all of a vector F is zero, why not just write all(F==0) instead of all(x->x==0,F)? It is shorter, and a literally a thousand times faster. It also uses sum(map(\*,x,y)) as the dot product instead of simply dot(x,y). The first version **650 times slower** for a vector of 10k doubles. And the dot product function is implemented as a for loop in pure Julia. Also, array comprehensions are slow. It is better to write [0,1,0,-1][rand(1:4,n)] instead of [[-1 0 0 1][rand(1:4)] for j = 1:n]. Finally, global variables are bad juju in Julia. Julia is only fast if you write code in such a way that allows the JIT and type inference to work. A big part of this is type stability: The compiler must be able to be sure that a variable's type will not change while inside a loop, for example. [Answer] ## RPython 0.187s (258x faster) Original Source w/ PyPy2.2.1: **1m 6.718s** Now with threading, back-support for standard Python has been dropped. The number of worker threads can be specified as a command line parameter, default is two. ``` from time import time, sleep from math import fmod from rpython.rlib.rthread import start_new_thread, allocate_lock, get_ident class Random: __slots__ = ['s'] def __init__(self, s=1): self.s = s def init_genrand(self, seed): self.s = seed def genrand32(self): # xorshift PRNG with period 2^32-1 # see http://core.kmi.open.ac.uk/download/pdf/6250138.pdf self.s ^= (self.s << 13) self.s ^= (self.s >> 17) self.s ^= (self.s << 5) return self.s class ThreadEnv: __slots__ = ['n', 'm', 'iters', 'counts', 'running', 'lock'] def __init__(self): self.n = 8 self.m = 8 self.iters = 1000 self.counts = [0]*8 self.running = 0 self.lock = None env = ThreadEnv() truth = [-1,0,0,1] def main(argv): argc = len(argv) if argc < 4 or argc > 5: print 'Usage: %s N M ITERS [NUM_THREADS=2]'%argv[0] return 1 if argc == 5: num_threads = int(argv[4]) else: num_threads = 2 env.n = int(argv[1]) env.m = int(argv[2]) env.iters = int(argv[3]) // num_threads env.counts = [0]*env.m env.lock = allocate_lock() for i in xrange(num_threads-1): start_new_thread(run,()) env.running += 1 env.running += 1 # use the main process as a worker run() # wait for any laggers while env.running: sleep(0.01) print env.counts return 0 def run(): n, m, iters = env.n, env.m, env.iters counts = [0]*m sbits = [0]*(n+m-1) random = Random() seed = int(fmod(time(), 2147483.648)*1000) ^ get_ident() random.init_genrand(seed) for S in xrange(1<<n+m-1): i = 0 sbit = 0 while not sbit: sbits[i] ^= 3 sbit = sbits[i] i += 1 for i in xrange(iters): f = 0 while not f: F = random.genrand32() G, x = F, 0 for k in xrange(n): x += truth[(G&3)^sbits[k]] f |= x G >>= 2 if not x: counts[0] += 1 for j in xrange(1, m): G, x = F, 0 for k in xrange(j, n+j): x += truth[(G&3)^sbits[k]] G >>= 2 if x: break counts[j] += 1 # passing True stalls until a lock can be obtained env.lock.acquire(True) for i in xrange(m): env.counts[i] += counts[i] env.running -= 1 env.lock.release() def target(*args): return main, None ``` [RPython](http://pypy.readthedocs.org/en/latest/coding-guide.html#id1) is a restricted subset of Python, which can be translated to C and then compiled using the [RPython Toolchain](http://pypy.readthedocs.org/en/latest/translation.html). Its expressed purpose is to aid in the creation of language interpreters, but it can also be used to compile simple programs like the one above. Most of the 'fancier' features of Python, such as `itertools` or even `map` are not available. To compile, make a local clone of the current [pypy repository](https://bitbucket.org/pypy/pypy/src), and run the following: ``` $ pypy %PYPY_REPO%/rpython/bin/rpython --thread convolution.py ``` The resulting executable will be named `convolution-c` or similar in the current working directory. I've parameterized the input variables, so the program should be run as: ``` convolution-c 8 8 1000 ``` to match the sample code. --- **Implementation Notes** `S in itertools.product([-1,1], repeat = n+m-1)` becomes `S in xrange(1<<n+m-1)`, interpreting `S` as a bit map: [`0`, `1`] → [`-1`, `1`] Likewise, `F` is also a bit map, with each two bits representing a single value: [`00`, `01`, `10`, `11`] → [`-1`, `0`, `0`, `1`] A truth table is used to lookup the product, rather than performing a mulitplication. Because 32-bit signed integers are used, `n` may be no larger than 15, and `n+m` no larger than 31. Arbitrary integer support can be achieved with the `rpython.rlib.rbigint` module, if necessary. The first iteration of the dot-product loop is unrolled, and combined with the nullity test of `F`. A homebrew PRNG is used, source listed. The author of the paper demonstrates a period of 232-1, and claims that it passes all Diehard tests save one, although I haven't personally confirmed this. The random seed changes every millisecond, which is as about as good using a timestamp will allow. Additionally, each worker thread `xor`s their process id with this value, to ensure that they each have a different seed. --- **Sample Timings** 2 worker threads: ``` $ timeit convolution-c 8 8 1000 2 [6331845, 2526161, 1042330, 440018, 193724, 87147, 40943, 19603] Elapsed Time: 0:00:00.375 Process Time: 0:00:00.687 System Calls: 6927 ``` 4 worker threads: ``` $ timeit convolution-c 8 8 1000 4 [6334565, 2527684, 1043502, 440216, 193225, 87398, 40799, 19338] Elapsed Time: 0:00:00.218 Process Time: 0:00:00.796 System Calls: 3417 ``` **8 worker threads:** ``` $ timeit convolution-c 8 8 1000 8 [6327639, 2522483, 1039869, 437884, 192460, 86771, 40420, 19403] Elapsed Time: 0:00:00.187 Process Time: 0:00:00.734 System Calls: 3165 ``` OP's original source: ``` $ timeit pypy convolution-orig.py [6330610, 2525644, 1041481, 438980, 193001, 86622, 40598, 19449] Elapsed Time: 0:01:06.718 Process Time: 0:01:06.718 System Calls: 11599808 ``` --- **Timing for 100000 iterations:** ``` $ timeit convolution-c 8 8 100000 8 [633156171, 252540679, 104129386, 43903716, 19307215, 8709157, 4072133, 1959124] Elapsed Time: 0:00:16.625 Process Time: 0:01:02.406 System Calls: 171341 ``` [Answer] # Nimrod ``` import times, locks, strutils, unsigned const N = 8 M = 8 iters = 1000 numThreads = 8 type SVec = array[0..N+M-1, int] FVec = array[0..N-1, int] ComputeThread = TThread[int] var rngSeed = int(epochTime()*1000) totalLeadingZeros: array[0..M-1, int] lock: TLock type RNGState = object x, y, z, w: uint32 proc newRNG(seed: int): RNGState = result.x = uint32(seed) proc random(rng: var RNGState): int = let t = rng.x xor (rng.x shl 11) rng.x = rng.y; rng.y = rng.z; rng.z = rng.w rng.w = rng.w xor (rng.w shr 19) xor t xor (t shr 8) result = int(rng.w) proc initVecRand(v: var FVec, rng: var RNGState) = const values = [ -1, 0, 0, 1 ] var rnd = rng.random var bitAcc = 0 for i in 0 .. <len(v): let val = values[rnd and 3] rnd = rnd shr 2 v[i] = val bitAcc = bitAcc or val if bitAcc == 0: initVecRand(v, rng) proc convolve(s: SVec, f: FVec, offset: int): int = for i in 0 .. <len(f): result += s[i+offset]*f[i] proc iterate(v: var SVec) = for i in 0 .. <len(v): if v[i] == -1: v[i] = 1 return v[i] = -1 proc mainThread(id: int) {.thread.} = const numS = 1 shl (N+M-1) var s: SVec f: FVec leadingZeros: array[0..M-1, int] rng = newRNG(rngSeed + id) for k in 0 .. <len(s): s[k] = -1 for i in 1..numS: for j in countUp(id, iters, numThreads): initVecRand(f, rng) if convolve(s, f, 0) == 0: leadingZeros[0] += 1 for k in 1 .. <M: if convolve(s, f, k) == 0: leadingZeros[k] += 1 else: break iterate(s) acquire(lock) for i in 0 .. <M: totalLeadingZeros[i] += leadingZeros[i] release(lock) proc main = let startTime = epochTime() var threads: array[1..numThreads, ComputeThread] initLock(lock) for i in 1..numThreads: createThread(threads[i], mainThread, i) for i in 1..numThreads: joinThread(threads[i]) echo("Leading zeros: ", @totalLeadingZeros) let endTime = epochTime() echo("Time taken: ", formatFloat(endTime - startTime, ffDecimal, 3), " seconds") main() ``` Example output: ``` Leading zeros: @[6333025, 2525808, 1042466, 439138, 192391, 86751, 40671, 19525] Time taken: 0.145 seconds ``` Nimrod compiles to C, therefore the choice of C compiler for the backend matters, too. Using clang, compile with: ``` nimrod cc --threads:on --cc=clang --passc:-flto -d:release conv.nim ``` Using gcc, compile with: ``` nimrod cc --threads:on --cc=gcc --passc:-flto -d:release conv.nim ``` Omit `--passc:-flto` if you have an older C compiler that doesn't support LTO. Omit the `--cc=...` option if you are fine with the default choice for the C compiler. The code requires [Nimrod 0.9.4 or 0.9.5](http://nimrod-lang.org/download.html). On my quadcore iMac (2.66 GHz core i5), the code runs in about .15 seconds with gcc 4.9, .16 seconds with clang, compared to 88 seconds for PyPy 2.2.1 (i.e. a 500+ times speedup). Unfortunately, I don't have access to a machine with more than four cores that also has PyPy installed or where I could easily install PyPy, though I get about .1 seconds (with a lot of measurement noise) on a 64-core AMD Opteron 6376 1.4 GHz (according to /proc/cpuinfo) with gcc 4.4.6. The implementation tries to be faithful to the original rather than optimizing code at the cost of readability, while not forgoing obvious optimizations. Interestingly enough, tail recursion in `initVecRand()` is a bit faster than a loop with a break instruction with both gcc and clang. Manually unrolling one iteration of the `convolve` test loop inside the main loop also produced a speedup, presumably due to better branch prediction. [Answer] # Java I translated the above C++ solution to Java: ``` import java.util.Random; import java.util.Arrays; public class Bench2 { public static int[] bits = { 0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF }; public static int[] oneValues = { 1, 0, 0, 1 }; public static int[] values = { -1, 0, 0, 1 }; public static int n = 8; public static int m = 8; public static int iters = 1000; private static int x,y=34353,z=57768,w=1564; public static void main( String[] args ) { x = (int) (System.currentTimeMillis()/1000l); int[] leadingzerocounts = new int[ m ]; Arrays.fill( leadingzerocounts, 0 ); int maxS = 1 << 15; for( int s = 0; s < maxS; s++ ) { int x = interleaveBit( s ); for( int i=0; i<iters; i++ ) { int random; do { random = 0xFFFF & fastRandom( ); } while( sumOnes( random ) == 0 ); int j = 7; while( j >= 0 ) { int h = ( x >> (j*2) ); int l = 0xFFFF & (~(random ^ h)); if( sumArray( l ) == 0 ) { leadingzerocounts[ j ]++; } else { break; } j--; } } } for( int i = 7; i >= 0; --i ) { System.out.print( leadingzerocounts[ i ] + " " ); } System.out.println( ); } public static int interleaveBit( int x ) { x = (x | ( x << 8)) & bits[3]; x = (x | ( x << 4)) & bits[2]; x = (x | ( x << 2)) & bits[1]; x = (x | ( x << 1)) & bits[0]; return x | (x << 1); } public static int sumOnes( int v ) { return (0xAAAA & (v ^ ~(v << 1))); // int s = 0; // for( int i = 0; i < 8; ++i ) { // int a = 3 & ( v >> (i*2) ); // s += oneValues[ a ]; // } // return s; } public static int sumArray( int v ) { return Integer.bitCount( v ) - 8; // int s = 0; // for( int i=0; i<8; ++i ) { // int a = 3 & ( v >> (i*2) ); // s += values[ a ]; // } // return s; } public static int fastRandom( ) { long t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (int)( w ^ (w >> 19) ^ t ^ (t >> 8)); } } ``` On my machine I get following output for the java program: ``` time java Bench2 6330616 2524569 1040372 439615 193290 87131 40651 19607 java Bench2 0.36s user 0.02s system 102% cpu 0.371 total ``` The OPs program runs about 53 seconds on my machine: ``` time pypy start.py [6330944, 2524897, 1040621, 439317, 192731, 86850, 40830, 19555] pypy start.py 52.96s user 0.06s system 99% cpu 53.271 total ``` The c++ program executed only about 0.15 seconds: ``` time ./benchcc [6112256, 2461184, 1025152, 435584, 193376, 87400, 40924, 19700] ./benchcc 0.15s user 0.00s system 99% cpu 0.151 total ``` That is about 2.5x faster than the corresponding java solution (I didn't exclude VM startup). This java solutions is about 142x faster than the program executed with PyPy. Since I was personally interested, I set `iters` to 100\_000 for Java and C++ but the factor of 2.5 didn't decrease in favor of Java if anything got bigger. EDIT: I ran the programs on a 64bit Arch Linux PC. EDIT2: I want to add that I started with a rough translation of the python code: ``` import java.util.Random; import java.util.Arrays; public class Bench { public static int[] values = { -1, 0, 0, 1 }; public static int n = 8; public static int m = 8; public static int iters = 1000; private static int x,y=34353,z=57768,w=1564; public static void main( String[] args ) { x = (int) (System.currentTimeMillis()/1000l); int[] leadingzerocounts = new int[ m ]; Arrays.fill( leadingzerocounts, 0 ); int[] S = new int[ n+m-1 ]; Arrays.fill( S, -1 ); do { for( int i=0; i<iters; i++ ) { int[] F = new int[ n ]; do { randomArray( F ); } while( containsOnlyZeros( F ) ); for( int j=0; j < m && check( F, S, j ); j++ ) { leadingzerocounts[ j ] += 1; } } } while( next( S ) ); System.out.println( Arrays.toString( leadingzerocounts ) ); } public static void randomArray( int[] F ) { for( int i = 0; i<F.length; i++ ) { F[ i ] = (1-(fastRandom()&3))%2; } } public static boolean containsOnlyZeros( int[] F ) { for( int x : F ) { if( x != 0 ) { return false; } } return true; } public static boolean next( int[] S ) { for( int i=0; i<S.length; i++ ) { if( ( S[ i ] = -S[ i ] ) == 1 ) { return true; } } return false; } public static boolean check( int[] F, int[] S, int j ) { int sum = 0; for( int i=0; i<n; i++ ) { sum += F[ i ] * S[ j + i ]; } return sum == 0; } public static int fastRandom( ) { long t; t = x ^ (x << 11); x = y; y = z; z = w; return w = (int)( w ^ (w >> 19) ^ t ^ (t >> 8)); } } ``` This program ran about 3.6 seconds: ``` time java Bench [6330034, 2524369, 1040723, 439261, 193673, 87338, 40840, 19567] java Bench 3.64s user 0.01s system 101% cpu 3.600 total ``` Which is about 14 times faster than the PyPy solution. (Choosing the standard random function over the fastRandom function leads to an execution time of 5 seconds) [Answer] **Python 3.5 + numpy 1.10.1, 3.76 seconds** The tests were run on my Macbook Pro. OP's code took ~6 mins on the same machine. The reason I'm answering this question in fact is because I don't have 10 reputations and can't answer Part I :-p For the past few days, I have been trying to figure out how to perform massive convolutions efficiently with numpy (without relying on a third-party package, even scipy). As I came across this series of challenges during my research, I decided to give it a try. I may have come to this game to late, but here is my attempt using Python 3.5 and numpy 1.10.1. ``` def test_convolv(): n = 8 m = 8 iters = 1000 ilow = np.ceil(0+n/2).astype(int) ihigh = np.ceil(m+n/2).astype(int) leadingzerocounts = np.zeros(m) # Pre-compute S & F S = np.array(list(itertools.product([-1,1], repeat = n+m-1))) choicesF = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n*iters).reshape(iters,n) imask = ~np.any(choicesF, axis=1) while np.any(imask): imasksize = np.count_nonzero(imask) choicesF[imask,:] = np.random.choice(np.array([-1, 0, 0, 1], dtype=np.int8), size=n*imasksize).reshape(imasksize, n) imask = ~np.any(choicesF, axis=1) for i in np.arange(iters): F = choicesF[i, :] # This is where the magic is: by flattening the S array, # I try to take advantage of speed of the np.convolve # (really numpy.multiarray.correlate). FS = (np.convolve(S.reshape(-1), F, 'same').reshape(S.shape))[:, ilow:ihigh] jmask_not = (FS[:, 0] != 0) leadingzerocounts[0] = leadingzerocounts[0]+np.count_nonzero(~jmask_not) for j in np.arange(n-1)+1: jmask = (FS[jmask_not, j] != 0) leadingzerocounts[j] = leadingzerocounts[j] + np.count_nonzero(~jmask) jmask_not[(jmask_not.nonzero()[0])[jmask]] = False print(leadingzerocounts) ``` I pre-computed the S and F arrays, and flattened the S array while performing the convolution, which (based on my experiments) could take advantage of the speed of np.convolve. In other words, as I didn't find a vectorized convolution routine, I fake-vectorized the code by flattening the whole array and hoped np.convolved would do the vectorization under the hood for me, which seemed to be working. Note I used mode='same' and trimmed the leading and trailing elements that were useless. On my Macbook Pro, the test results give **3.76 seconds**. When I ran OP's code (modified to Python 3.5), I got about **6 minutes**. The speedup is about 100 times. One drawback is that because the S and F arrays are to be stored, the memory requirement can be a problem if the sizes are too big. I used the same method for Part I and I got a ~ 60-100x speedup on my laptop. As I did everything on my Macbook Pro, if someone could test my code and let me know how it goes on your machine, I would appreciate it very much! [Answer] # J, 130x~50x speedup? ``` n =: m =: 8 len =: 1000 S =: (] - 0 = ])S0=: #:i.2^<:+/n,m k =: (n#0) -.~ (_1 0 0 1) {~ (n#4) #: i.4^n sn =: (]-0=])#:i.2^n ku =: ~. k M =: 0=+/"1 sn *"1/ ku fs =: (ku&i.)"1 k snum =: n #.\"1 S0 run =: 3 : 0 r =: n#0 for_t. (snum) do. rn =: fs{~? len # #k r =: r + +/"1*/\rn{"1 t{M end. r ) echo run 0 exit'' ``` Times on a random debian: ``` u#>time j slowpy.ijs 6334123 2526955 1041600 440039 193567 87321 40754 19714 real 0m2.453s user 0m2.368s sys 0m0.084s u#>time python slow_pyth.py [6331017, 2524166, 1041731, 438731, 193599, 87578, 40919, 19705] real 5m25.541s user 5m25.548s sys 0m0.012s ``` I think there is room for improvement. [Answer] **C++: x200 (4-core i7, should scale to x400 on 8-core)** Trying for a more straightforward **C++11** (Tested with VS 2012, gcc and clang) solution with parallelization. To get this to compile and run under Linux with gcc 4.8.1: > > g++ -O3 -msse -msse2 -msse3 -march=native -std=c++11 -pthread > -Wl,--no-as-needed golf.cpp > > > Under Linux we also need `std::launch::async` to force multiple threads. I was missing that in an earlier version. In Visual Studio (2012+) this should just work but make a release build for timing... On my oldish dual core i3 this runs in **~0.9** seconds. On my i7 quad core this is 0.319s vs. pypy 66 seconds. On an 8-core i7 this should in the x400 speedup range. Switching to C style arrays would speed it up but I was interested in staying with C++ containers. For me it's interesting to see the speedup you can get while staying relatively close to the problem domain and at a relatively high level, something I think C++ is really good at. Also of note is the relative ease of paralleization using C++11 constructs. @ilmale's bit solution is very cool and works for -1/1/0. One could also throw SSE at this and maybe get a significant speedup. Beyond the parallelization there's another "trick" in there which is reducing the number of summations. Sample results: 6332947 2525357 1041957 438353 193024 87331 40902 19649 ``` #include <vector> #include <iostream> #include <thread> #include <future> #include <time.h> #include <ctime> #include <algorithm> using namespace std; // Bring some of these constants out to share const size_t m = 8; const int nthreads = 16; const size_t cn = 15; const int two_to_cn = 32768; static unsigned int seed = 35; int my_random() // not thread safe but let's call that more random! { seed = seed*1664525UL + 1013904223UL; // numberical recipes, 32 bit return ((seed>>30)&1)-!!((seed>>30)&2); // Credit to Dave! } bool allzero(const vector<int>& T) { for(auto x : T) { if(x!=0) { return false; } } return true; } // Return the position of the first non-zero element size_t convolve_until_nonzero(size_t max_n, const vector<int>& v1, const vector<int>& v2) { for(size_t i = 0; i<max_n; ++i) { int result = 0; for(size_t j = 0; j<v2.size(); ++j) { result += v1[i+j]*v2[j]; } if(result!=0) { return i; } } return max_n; } void advance(vector<int>& v) { for(auto &x : v) { if(x==-1) { x = 1; return; } x = -1; } } vector<int> convolve_random_arrays(vector<int> S, int range) { const int iters = 1000; int bothzero = 0; int firstzero = 0; time_t current_time; time(&current_time); seed = current_time; vector<int> F(m); vector<int> leadingzerocounts(m+1); for(auto &x: leadingzerocounts) { x = 0; } for(int i=0; i<range; ++i) { for(int j=0; j<iters; ++j) { do { for(auto &x : F) { x = my_random(); } } while(allzero(F)); leadingzerocounts[convolve_until_nonzero(m, S, F)]++; } advance(S); } // Finish adding things up... for(int i=m-1; i>0; --i) { leadingzerocounts[i] += leadingzerocounts[i+1]; } vector<int> withoutfirst(leadingzerocounts.begin()+1, leadingzerocounts.end()); return withoutfirst; } int main(int argc, char* argv[]) { vector<int> leadingzerocounts(m); for(auto &x: leadingzerocounts) { x = 0; } clock_t start = clock(); vector<int> S(cn); for(auto &x : S) { x = -1; } vector< future< vector< int > > > fs; // The future results of the threads // Go make threads to work on parts of the problem for(int i=0; i<nthreads; ++i) { vector<int> S_reversed = S; // S counts using LSBs but we want the thread start to be in MSBs reverse(S_reversed.begin(), S_reversed.end()); fs.push_back(async(std::launch::async, convolve_random_arrays, S_reversed, two_to_cn/nthreads)); advance(S); } // And now collect the data for(auto &f : fs) { vector<int> result = f.get(); for(int i=0; i<result.size(); ++i) { leadingzerocounts[i] += result[i]; } } for(auto count : leadingzerocounts) { cout << count << endl; } return 0; } ``` [Answer] # Fortran: 316x Okay, Fortran: I've got it up to **106x** **155x** **160x** **316x** speedup when using an Xorshift RNG and OpenMP on a 4 core i7 CPU. Other than that, there are no big tricks. For the iterator to construct S, I just use the binary representation of the 16-bit integer i. You'll note that apart from the inline RNG and the "iterator"/mapping from i to S, the code is just as high-level as the Python code. Edit: removed the "if" in the Xorshift, now using "r = abs(w/...)" instead of "r=w/...". Goes from 106x to 155x. Edit2: This generates 15x as many random numbers as the C++ solution. If someone has a zero-overhead solution for converting a random int into an array of 0s and 1s in Fortran, I'm all ears. Then we could beat C++ :) Edit3: The first edit introduced a bug, as Lembik pointed out. This is fixed now, with a tiny improvement in speedup. I will try to use the suggestion by Eelvex to get more speedup. Edit4: Profiling indicated that converting to real and back to integer with nint() was slow. I replaced this with one integer division doing both scaling and rounding, going from 160x to 316x speedup. Compile with: > > gfortran -O3 -march=native -fopenmp golf.f90 > > > ``` program golf implicit none integer, parameter :: m=8, n=8 integer :: F(n), S(m+n-1), leadingzerocounts(m) integer :: j,k,bindec,enc,tmp,x=123456789,y=362436069,z=521288629,w=88675123 integer*2 :: i real :: r leadingzerocounts=0 !$OMP parallel do private(i,enc,j,bindec,S,F,k,tmp,x,y,z,w,r) reduction(+:leadingzerocounts) schedule(dynamic) do i=0,32766 enc=i ! Short loop to convert i into the array S with -1s and 1s do j=16,2,-1 bindec=2**(j-1) if (enc-bindec .ge. 0) then S(j-1)=1 enc=enc-bindec else S(j-1)=-1 endif end do do j=1,1000 F=0 do while (.not. any(F /= 0)) do k=1,n ! Start Xorshift RNG tmp = ieor(x,ishft(x,11)) x = y y = z z = w w = ieor(ieor(w,ishft(w,-19)),ieor(tmp,ishft(tmp,-8))) ! End Xorshift RNG ! Just scale it inside the nint: !F(k)=nint(w/2147483648.0) ! Scaling by integer division is faster, but then we need the random ! number to be in (-2,2) instead of [-1,1]: F(k)=w/1073741824 end do end do do k=1,m if (dot_product(F,S(k:k+n-1)) /= 0) exit leadingzerocounts(k)=leadingzerocounts(k)+1 end do end do end do !$OMP end parallel do print *, leadingzerocounts end ``` Example output: > > $ time ./a.out > > 6329624 2524831 1039787 438809 193044 6860 40486 19517 > > ./a.out 1.45s user 0.00s system 746% cpu 0.192 total > > > OP's code: > > $ time pypy golf.py > > pypy golf.py 60.68s user 0.04s system 99% cpu 1:00.74 total > > > ]
[Question] [ Given an unsigned 16-bit integer ***N***, your task is to determine whether its binary representation mapped inside a 4x4 matrix is matching a [tetromino shape](https://en.wikipedia.org/wiki/Tetromino), and if so, which shape it is. ## Matrix Each bit of ***N*** is mapped inside a 4x4 matrix, from left to right and from top to bottom, starting with the most significant one. **Example**: ``` N = 17600 binary representation: 0100010011000000 matrix: [ [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ], [ 1, 1, 0, 0 ], [ 0, 0, 0, 0 ] ] ``` ## Tetromino shapes **Base shapes** There are 7 tetromino shapes, identified by the letters *O*, *I*, *S*, *Z*, *L*, *J* and *T*: [![tetrominoes](https://i.stack.imgur.com/wq6SC.png)](https://i.stack.imgur.com/wq6SC.png) **Rotations and translations** If a shape is translated and/or rotated within the 4x4 matrix, it is still considered a valid variation of the same tetromino. For instance, 17600, 1136, 2272 and 1604 should all be identified as *J* tetrominoes: [![valid J examples](https://i.stack.imgur.com/pTuGj.png)](https://i.stack.imgur.com/pTuGj.png) **Don't wrap!** However, the shapes can't wrap around or be shifted beyond any boundary of the matrix. For instance, *neither* 568 *nor* 688 should be identified as *J* tetrominoes (let alone any other shape): [![invalid J examples](https://i.stack.imgur.com/oQaWi.png)](https://i.stack.imgur.com/oQaWi.png) ## Clarifications and rules * You may take input as an integer, or directly as 16 binary digits in any reasonable format, such as a 2D array, a flat array or a delimited string. * The input is guaranteed to be an unsigned 16-bit integer (or its equivalent representation as an array or a string). * When a valid shape is identified, you must print or return the *letter* identifying the shape, in either lower or upper case. * If no shape is identified, you must print or return a value that doesn't match any tetromino letter. You may also choose to return nothing at all. * To be considered valid, the matrix must contain the exact tetromino shape without any additional cells (see 1911 and 34953 in the test cases). * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Test cases You can [follow this link](https://pastebin.com/QYwERVWz) to get the test cases as 2D arrays. ``` 0 -> false 50 -> false 51 -> 'O' 1911 -> false 15 -> 'I' 34952 -> 'I' 34953 -> false 1122 -> 'S' 3168 -> 'Z' 785 -> 'L' 1136 -> 'J' 568 -> false 688 -> false 35968 -> 'T' 19520 -> 'T' ``` [Answer] # [Python 3](https://docs.python.org/3/), 124 bytes ``` def f(n): while n&4369<n/n:n>>=1 while n&15<1:n>>=4 return'TJLZSIO'["rēȣc63ıGtIJȱᄑ@'̢̑@@@@Ȳq".index(chr(n))%7] ``` [Try it online!](https://tio.run/##TU4xTsNAEOyvoaQ9RQKfC0M257vYUYjSIRASBamCEIqcMz4JbcxxEUnPByJ@QF6QvMGFi3yCl5h1GhitZmdmV9ot175YoGyaucl5LjAcMP5R2FfD8TyWOh3iJQ5wNLqCvxzUEI5ZzLgzfukwmNzeTR9u7oPHjqu@6m2mT2S1u/bVvt79fG7GweH7sBkT6v3baefC4tysRFY4uhee9Z@afOH4M7fI3QxfjADVvsG9W7eN89JZ9CIXLVssl16EBBqZVWZK/38piKLMzd6LKArCpssUFTBIgUgxGaeqd2TJAHokQSesnyhyUjNFRicJkyolBbTb/QU "Python 3 – Try It Online") Expects an integer **n** representing a 4 × 4 binary matrix. Throws if no tetromino is found. Line 2 slides the shape to the right until a 1 is in the rightmost column. (4369 is `0001 0001 0001 0001` in binary.) Line 3 lowers the shape until a 1 is in the bottom row. Together this turns e.g.: ``` 0 1 0 0 0 0 0 0 1 1 1 0 into 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 ``` Then we look for the index of `n` in this list: ``` [114 275 547 99 54 15 51 305 71 116 306 561 4369 64 39 802 785 64 64 64 64 562 113 23] # T J L Z S I O ``` Each column of indices equivalent modulo 7 corresponds to a tetromino shape. 64 (`@`) is used as a padding value as `n` cannot be 64 at this point in the code. **NB.** An exception is thrown for input `0` by computing `n/n` instead of `1`. [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~95~~ ~~94~~ ~~93~~ ~~89~~ 87 bytes -2 thanks to [Zacharý](https://codegolf.stackexchange.com/users/55550/zachar%c3%bd) Requires `⎕IO←0` which is default on many systems. Takes Boolean matrix (of any shape!) as argument. Returns nothing if the given number of bits is not four, and a blank line if the four given bits do not form a tetromino. ``` {4=+/,⍵:'OIZSJLT'/⍨∨/1∊¨(((2 2)4⍴¨1),(0 1⌽¨⊂K⌽2⊖J),(⍳3)⊖¨⊂J←1,⍪K←3↑1)∘.⍷⍵∘{⌽∘⍉⍣⍵⊢⍺}¨⍳4} ``` [Try it online!](https://tio.run/##bY/BSsNAEIbvPsXeusFqMrvZNRF8gKRCD/bkraCIUJsi9SAlF5ESoyt6UDxrD4t4qyIIXvIo8yJxUg@C2cvOv9/u/8/McDLaODgfjrKjGm8fkj7O74J6cDg9zU6OxxndZuHOut9F87Hd6Sf7e@nuoOOjsVhYH7AoK8s5F0x4IZr3yoLX5QEDvPmuLJYXPRICy8eUMJql9EivHlJKBkp97ZGQOL8HD4unTTSf1InUjIxU0FyheWlQ@YzmKyevWYZ5nYwnZ9NmOJqZCpo3vL781SFrJuGg6RTUb0Hu/G8jtrKygLG1/0wRdFBwUYgBHFS5/sowVsJJZTsBhHAkgI7adCtSrslAascWFNCmOnJRqWIdOTZWIvgB "APL (Dyalog Unicode) – Try It Online") Works by creating all four rotations of the input, then looking for each tetromino in each rotation. `{`…`}` anonymous function where the argument is represented by `⍵`:  `,⍵` ravel (flatten) the argument  `+/` sum it  `4=` is four equal to that?  `:` if so, then (else return nothing):   `⍳4` first four **ɩ**ndices; `[0,1,2,3]`   `⍵∘{`…`}¨` apply the following function on each, using the input as fixed left argument    `⍺` the left argument i.e. the input    `⊢⍺` yield that (separates `⍵` from `⍺`)    `⌽∘⍉⍣⍵` mirror and transpose (i.e. rotate 90°) `⍵` times   `(`…`)∘.⍷` outer "product", but using Find\*, of the following list and the rotations:    `3↑1` take three elements from one, padding with zeros; `[1,0,0]`    `K←` store that as `K`    `⍪` table (make into column vector); `[[1],[0],[0]]`    `1,` prepend a one; `[[1,1],[1,0],[1,0]]` ("J")    `J←` store as `J`    `(`…`)⊖¨⊂` rotate the entire J vertically, each of the following number of steps:     `⍳3` first three **ɩ**ntegers; `[0,1,2]`    we have `[[[1,1],[1,0],[1,0]],[[1,0],[1,0],[1,1]],[[1,0],[1,1],[1,0]]]` ("J", "L, "T")    `(`…`),` prepend the following list:     `2⊖J` rotate `J` two steps vertically; `[[1,0],[1,1],[1,0]]` ("T")     `K⌽` rotate the rows of that by 1, 0, and 0 steps respectively; `[[0,1],[1,1],[1,0]]` ("Z")     `0 1⌽¨⊂` rotate the entire array vertically, no times and once; `[[[0,1],[1,1],[1,0]],[[1,0],[1,1],[0,1]]]` ("Z", "S")     `(`…`),` prepend the following list:      `(2 2)4⍴¨1` reshape a one into each of a 2×2 matrix and a 4-element list; `[[[1,1],[1,1]],[1,1,1,1]]` ("O", "I")   `1∊¨` for each, is one a member?   `∨/` horizontal OR reduction (i.e. across rotations; one Boolean for each shape)   `'OIZSLJT'/⍨` use that to filter the string \* Find returns a Boolean array of same shape as its right argument, with ones indicating the top left corner of all subarrays identical to the left argument. [Answer] ## JavaScript (ES6), ~~242~~ ~~212~~ ~~172~~ 164 bytes ``` x=>[...'OISZLJT'].filter((z,y)=>x.match(`^0*(${'99,33825|15,51|2145,195|561,2115|57,1059|135,71|1073'.split`,`[y].replace(/\d+/g,C=x=>x?x%2+C(x>>1)+x%2:'|')})0*$`)) ``` Was supposed to be just to get the ball rolling, but I'm a little late for that ¯\\_(ツ)\_/¯ Takes a string of bits, with rows separated by `0`s (`'0001000110001000000'` representing `0001 0011 0010 0000`) and returns an array containing the character representing the tetromino, or an array containing nothing. This works by checking each rotation of tetromino to see if the input at any point contains the tetromino, surrounded entirely by zeroes on either side. Each tetromino is represented by one or more binary numbers: ``` 0 0 0 0 -> 0000 0110 1100 0000 0 1 1 0 -> 0000001100110000000 1 1 0 0 -> 110011 0 0 0 0 -> 51 0 1 0 0 -> 0100 0110 0010 0000 0 1 1 0 -> 0100001100001000000 0 0 1 0 -> 100001100001 0 0 0 0 -> 2145 ``` So to check if the input contains an S tetromino, we simply check whether it contains the binary representation of either `51` or `2145`, with only `0`s on either side. A few of the tetrominoes have 4 orientations. If you look at the binary representations of these, each has 2 representations which are simply the mirror of the other two. To save space, the binary representation is built up forward and backward simultaneously with the recursive `C` function, allowing us to only put two of the orientations in and have the other two implied. --- Alternate approach with charcodes: ``` x=>[...'OISZLJT'].filter((z,y)=>x.match(`^0*(${[...'÷,êÿ,óî,ûÝ,ëúüÏ,çöïþ,ßýíÞ'.split`,`[y]].map(c=>(C=n=>n?'1e'+(n%4+2)%5-0+C(n>>2):'')(c.charCodeAt())).join`|`})0*$`)) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~54 43 42~~ 41 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Erik the Outgolfer (move transpose inside repeated chain) ``` T€FṀ⁸ṙ€Zµ⁺F ZU$3СǀḄṂ“çc3Ð6'G‘i’ị“¥Çıƭ⁵» ``` A monadic link taking a 2D array of integers (`1`s and `0`s) and returning a lowercase letter `oiszljt` for the respective tetromino or `w` if invalid. **[Try it Online!](https://tio.run/##y0rNyan8/z/kUdMat4c7Gx417ni4cyaQE3Vo66PGXW5cUaEqxocnHFp4uB0o@HBHy8OdTY8a5hxengwUNVN3f9QwI/NRw8yHu7uBooeWHm4/svHY2keNWw/t/v//f3S0oY6hjoGOQSyXTrSBDpgDYRogRCHMWAA "Jelly – Try It Online")** or see the [test suite](https://tio.run/##y0rNyan8/z/kUdMat4c7Gx417ni4cyaQE3Vo66PGXW5cUaEqxocnHFp4uB0o@HBHy8OdTY8a5hxengwUNVN3f9QwI/NRw8yHu7uBooeWHm4/svHY2keNWw/t5jq6B6xHJRJIAJE3EGc9atx3aNuhbf///4@OjjbQAcNYHbwsIBOnvKGOIZxFvEpDDJWGcHl0Fj4zISxDJJWGSKK4WcSqxOZOZBcb4PS7IQ6V2MMTETYGKCz8thsSMBPVdEMCKg3R3IEZSoYYoYRquyFWv6OpjAUA "Jelly – Try It Online"). Also see [this program](https://tio.run/##y0rNyan8/z/kUdMat4c7Gx417ni4cyaQE3Vo66PGXW5cUaEqxocnHFp4uB0o@HBHy8OdTY8a5hxengwUNVN3f9QwI/NRw8yHu7uBooeWHm4/svHY2keNWw/t5jI0Czo6Odnk0FZrQ/OHO9c83DmtGMgBmnJ0D9gwlUggAUTeIIN3zjo8L@tR475D2w5t@/8fAA "Jelly – Try It Online") which lists all 1820 possible 2D binary arrays with exactly four bits set along with their outputs, sorted by those outputs. ### How? This first takes all four rotations of the input. Then it shifts the set bits of each as far to the right and then as far to the bottom as possible and converts the results to binary numbers. It then looks up the minimum result in a list of the minimal such representations of each valid tetromino and uses the decremented result to index into the two concatenated dictionary words `zoist`+`jowl`, yielding `w` when no match was found. ``` T€FṀ⁸ṙ€Zµ⁺F - Link 1, shift set bits right & then down : list of lists of bits µ⁺ - perform the following twice, 1st with x=input, then with x=result of that): T€ - truthy indexes of €ach F - flatten into a single list Ṁ - maximum (the index of the right-most bit) ⁸ - chain's left argument, x ṙ€ - rotate €ach left by that amount Z - transpose the result F - flatten (avoids an € in the main link moving this into here) ZU$3СǀḄṂ“çc3Ð6'G‘i’ị“¥Çıƭ⁵» - Main link: list of lists of bits (the integers 0 or 1) 3С - repeat this 3 times collecting the 4 results: $ - last two links as a monad: Z - transpose U - upend (reverse each) -- net effect rotate 90° CW Ç€ - call the last link as a monad for €ach Ḅ - convert from binary (vectorises) Ṃ - minimum (of the four results) “çc3Ð6'G‘ - code-page indexes = [23,99,51,15,54,39,71] - ...the minimal such results for l,z,o,i,s,t,j shapes i - 1-based index of minimum in there or 0 if not found ’ - decrement “¥Çıƭ⁵» - compressed words: "zoist"+"jowl" = "zoistjowl" ị - index into (1 indexed & modular, so -1 yields 'w', - 0 yields 'l', 1 yields 'z', ...) ``` --- **Previous method** (54 bytes) ``` Fœr0Ḅ“çc3Ðñ'G‘i ;Z$Ḅ©f“¦µ½¿Æ‘ȯ®¬S>2ȧZU$3СǀṀ’ị“¥Çıƭ⁵» ``` A monadic link taking a 2D array of integers (`1`s and `0`s) and returning a lowercase letter `oiszljt` for the respective tetromino or `w` if invalid. **[Try it online!](https://tio.run/##y0rNyan8/9/t6OQig4c7Wh41zDm8PNn48ITDG9XdHzXMyOSyjlIJftS05tCaYDujRLfgR417TBKjQlWASg4tPNwOlHm4s@FRw8yHu7uBeg8tPdx@ZOOxtY8atx7a/f///@hoAx0DHUMdg1gunWgQA840QGYCYWwsAA "Jelly – Try It Online")** This checks there are at least three empty lines (rows+columns) and that certain patterns of bits are not present in any line (specifically the numbers 5,9,10,11, and 13), these together assure the next step wont yield false-positives. It then flattens and then floor-shifts the binary number (by striping trailing zeros before conversion) of each of the four rotations, and looks up the minimal result in a list of numbers, using the decremented result to index into the two concatenated dictionary words `zoist`+`jowl`, yielding `w` when no match was found. [Answer] # [Retina](https://github.com/m-ender/retina), 125 bytes ``` s`(.*1){5}.* {s`.*1111.* I s`.*111(.{2,4})1.* $.1 T`234`\LTJ s`.*11(.{2,4})11.* $.1 T`2-90`S\OZ4-9 s`.*4.* O#$`. $.%` O#$^` ``` [Try it online!](https://tio.run/##TY5NCsIwEIX37xpGaVMNmebH5giK4EJXUmRcuHDjQt2FXMsDeLE6FRFDeLwvfDPkdn5crqdhWrFpoDQarqipe4LKVCwsgXAERaUtjK5MplhqKILJvkDNXs/hzpXRVOdQjAbynYXkCKzwBZlr577U46MyhD23znO/2a@/xk/4MxbJ8q7fHvwifSw/rt9OFBsxpjzWIw@DRZAr/0wkEeB8Cu0nHYhaqRQ7LLsg5CKCQOw6uJCkkbj2DQ "Retina – Try It Online") Link includes test cases plus a header to convert from integers to a 4×4 matrix. Explanation: ``` s`(.*1){5}.* ``` Delete the input if it contains 5 `1`s. ``` {s`.*1111.* I ``` Check all rotations of the input (see below). If the input contains four consecutive `1`s, it's an `I`. ``` s`.*111(.{2,4})1.* $.1 T`234`\LTJ ``` If it contains three consecutive `1`s plus a `1` on the next line underneath one of the three, then map the number of intermediate characters to the appropriate result letter. ``` s`.*11(.{2,4})11.* $.1 ``` Similarly for two adjacent `1`s adjacent to two adjacent `1`s on the next line. ``` T`2-90`S\OZ4-9 ``` But also keep count of the number of rotations using the otherwise unused `0`s. ``` s`.*4.* ``` And give up if too many rotations have been performed. ``` O#$`. $.%` O#$^` ``` Transpose and reverse the array, thus rotating it. [Answer] # [MATL](https://github.com/lmendo/MATL), 60 bytes ``` Itt6tIl7tl7H15vHe"4:"G@X!HYa]4$v@BIthYaEqY+4=aa]v'OSZLJTI'w) ``` Input is a binary 4×4 array (matrix), using `;` as row separator. Ouput is a letter or empty for no tetromino. [Try it online!](https://tio.run/##y00syfn/37OkxKzEM8e8JMfcw9C0zCNVycRKyd0hQtEjMjHWRKXMwcmzJCMy0bUwUtvENjExtkzdPzjKxyvEU71c8///aAMdBUMdBSBpYK2AzDZEFYcihVgA) Or [verify all test cases](https://tio.run/##y00syfmfEOFV8d@zpMSsxDPHvCTH3MPQtMwjVcnESsnLIULRIzIx1kSlzMHJsyQjMtG1MFLbxDYxMbZM3T84yscrxFO9XPO/up56hkvI/2gDHQUoUrBWIIoTy0VQkyEQIXPI0mSITZMhsjqsHCJsgnIMUTQZokkR5pChCZef0D1ogD/0DAlowhNPKKFsgMEhznmGRNqEYa0hkZoMsboVa5AbYg9yDOcZ4gs9LJoA) (output has a dot appended to allow identifying an empty result). ### Explanation The code builds 4 rotations of the input 4×4 array in steps of 90 degrees. Each rotated array is padded with 2 zeros up and down, which transforms it into a 8×4 array. The 4 arrays are vertically concatenated into a 32×4 array. The four rotated arrays within this concatenated array are "isolated" thanks to the zero-padding. Each of the 7 possible patterns is tested to see if it is present in the 32×4 array. A loop is used for this. Each pattern is defined by two numbers, which expressed in binary give the appropriate 0/1 mask. For example, numbers `3`, `6` define the "S" shape. The 7 sets of 2 numbers are arranged into a 2×7 matrix, from which the loop will pick each column sequentially. The matrix is defined by pushing all numbers to the stack, contatenating them into a vector, and reshaping into a 2-row matrix. Since the "I" shape is defined by number 15 followed by 0, putting it at the end allows the 0 to be implicitly filled by the reshaping function. The mask is then padded with 3 zeros in the four directions. This is necessary so as to detect unwanted values in the input. To see if the mask is present in the 32×4 array, the latter is transformed to bipolar form (i.e. −1/1 instead of 0/1) and convolved with the mask. Since the mask has 4 ones, matching occurs if some entry in the convolution result equals 4. At the end of the loop, 7 false/true results have been obtained, at most one of which is true. This is used to index into a string containing the possible output letters. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 53 bytes ``` ZL0ẋW⁸tZµ⁺ZU$3С“©©“œ“Ç¿“¦©¦“ƽ‘;Uḃ2$’¤iЀṀị“÷¶Ė¡µỵỤ» ``` [Try it online!](https://tio.run/##y0rNyan8/z/Kx@Dhru7wR407SqIObX3UuCsqVMX48IRDCx81zDm08tBKIHV0MpA43H5oP0hoGVBwGYjfdmjvo4YZ1qEPdzQbqTxqmHloSebhCY@a1jzc2fBwdzdIxfZD245MO7Tw0NaHu4FoyaHd////j4421FEwgKBYHQUuBVL4sQA "Jelly – Try It Online") Full program. Takes a 4x4. Prints `m` if not a tetromino, otherwise prints lowercase. [Answer] # [APL (Dyalog)](https://dyalog.com/), 66 bytes `{'TIOJSLZ-'[(¯51 144 64,,∘+⍨12J96 ¯48J64)⍳×/(+/-4×⊢)⍵/,0j1⊥¨⍳4 4]}` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/0NSS4ryczPz8oG8avUQT3@vYJ8oXfVojUPrTQ0VDE1MFMxMdHQedczQftS7wtDIy9JM4dB6EwsvMxPNR72bD0/X19DW1zU5PP1R1yKgwFZ9HYMsw0ddSw@tAMqaKJjE1v73zCsoLQGZDrQUSD3qXfOou0UHwgGqeNS7RcPQDEgaaT7qWgI0ohbhJgWwXgUDBQUudDFToCAWUUNsooaWhoZYRE2xqTU2sTQ1wipqjGmCoZERFhMMzSwwRc0tTLG5zNDYDIsvgAZgippZYBM1NrU0s8DiY1MjAwA) The arg is a boolean vector. Computes signed distances of the dots to their centre of gravity as complex numbers (real and imaginary part are ∆x,∆y) and multiplies the complex numbers together. This turns out to be a good enough invariant to distinguish among the tetrominoes. [Answer] # [Perl 5](https://www.perl.org/), 197 + 1 (-p) = 198 bytes ``` s/(0000)*$//;1while s/(...)0(...)0(...)0(...)0/0${1}0${2}0${3}0${4}/;$_={51,O,15,I,4369,I,54,S,561,S,99,Z,306,Z,547,L,23,L,785,L,116,L,275,J,113,J,802,J,71,J,114,T,562,T,39,T,609,T}->{oct("0b".$_)} ``` [Try it online!](https://tio.run/##Zc89T8MwEAbgv9JGkZqgi@/OX2kUtQMbiI8BJhCtoCo0atVETRFDZH465sKKh8fvvYOt67ang4vpepF9HrvXzT65NDqBMc3uZpCu88V3jysa2AfEj9OkeZ/i6pn45SLFOvaYkZxcBqz5a9ccthPplFI5/RcpHTgIesSM2IC1fD44hntgB1dgja/kchYewHkWqwqewJAXnS3hBrQRyrkTmf1YlA6uJRtxTlos@a@w8CiPaNFUgicxFMuh3ZyzhN4SJQuGGDXZn7Y7N@2xj8WtU8QUi@4X "Perl 5 – Try It Online") Takes a 16 bit string as input. Outputs nothing if input is not a single tetromino. **How?** The two substitutions "move" the input shape to the bottom right corner. The resulting bit string is converted to an integer, then checked for in a hash of valid integers. ]
[Question] [ Let's make an ASCII art clock and calendar that tells us the current month, day of the month, day of the week, hour, minute, and whether it's night or day (but not the year or second). At any particular time the calendar will look something like this: (it looks better with less line spacing) ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | ___ | | | | _( ) | | | | (___)__) -.- | | | | | | | | | | | | -.- | | | | -.- | | | | ___ | | | | _( ) | | | | (___)__) | | | | | | | | ___ | | | | _( ) | | | | _ (___)__) | | | | /|\ | | | | / | \ | | | | /__|__\ | | | |____|____ | | | |\_______/~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-~~-~~~~~| | | |____________________________________________________________| | |/______________________________________________________________\| ``` It is always a 66 by 23 character "picture frame" whose border never changes. The image within the frame tells us the time and date: * During the day (6:00am - 5:59pm) the month is determined by the number of birds (`-.-`) in the sky. January = 1 bird, February = 2 birds, etc. * During the night (6:00pm - 5:59am) the birds are replaced with 3 times as many stars (`*`). January = 3 stars, February = 6 stars, etc. Birds and stars are never in the sky at the same time. * The day of the month is determined by the number of characters between the two dashes (`-`) on the water. e.g. `~~-~~~~-~~` means it is the fourth day of the month. Depending on the minute, the boat may need to be between the dashes (the dashes do not loop around). * The day of the week is determined by the number of clouds in the sky (all clouds look the same). Sunday = **0 clouds**, Monday = 1 cloud, ..., Saturday = 6 clouds. * The hour is determined by the level of water (and the boat). At its lowest (as above) it is 1 o'clock, during 2 o'clock it is one character higher, and so on up to 12 o'clock, then back to 1 o-clock. (It's a 12 not a 24 hour clock.) * The minute is determined by the horizontal position of the boat. At the top of the hour the boat touches the left edge of the frame (as above). At each subsequent minute the boat moves right by one character. In minutes 51 to 59 it loops from the right side of the frame back to the left. So, given that the example above has 3 birds, 3 clouds, 2 chars between dashes, the water at the lowest level, and the boat on the far left we can tell that the date is Wednesday March 2nd, and the time is 1:00pm. Here is another example from Sunday April 25th, at 3:58am: ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | | | | | * * | | | | * * * | | | | * | | | | | | | | * | | | | * * | | | | | | | | * | | | | | | | | * | | | | _ | | | | /|\ * | | | |/ | \ | | | |__|__\ /| | | |__|____ __| | | |______/~~~~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~~-~~~~~\_| | | | | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` # Goal Your goal is to write the shortest program possible that outputs these ASCII art "calendars" to stdout using the time when the program is run. Every run of the program should output one time-scene. Updates should not be automatic (or animated). The clouds, stars, and birds, should be placed randomly in the sky (so every run, even ones at the same time are likely to be different). They should never overlap the boat or each other. (Also the water dashes should not overlap the boat hull.) Notice that nothing I have described appears underwater. This is for you to do. During one predetermined hour of every week (your choice), something *interesting* should be drawn underwater. It could be a sea monster or sunken ship or anything, it's up to you. During that hour you may even alter the design of the rest of the scene (staying in the frame bounds). # Scoring This is a code-golf popularity-contest combo. Your score is `(bytes in program) - 4 * (upvotes - downvotes)`. The lowest score wins. Use <http://mothereff.in/byte-counter> as a byte counter if you use non-ASCII characters. # Notes and Updates * You may use buoys instead of dashes, since, lets face it, they're much more appropriate: ``` | | ~~(_)~~~(_)~~ (3rd of the month) ``` * The dashes (or buoys) do not have to be random but it would be nice if they were. * Your "special hour" should last 60 minutes from the top of the hour to 1 minute before the next hour. * During the special hour the things you draw underwater may move and may alter the surface and the sky when it makes sense (e.g. sea monster eating the boat, black hole forming at the sea floor, etc.) [Answer] ## Ruby, At World's End, ~~1260~~ ~~1070~~ 967 bytes Anyone remember that Pirates of the Caribbean film? ``` c=(" #{?_*60} ")*2 c+="| |#{' '*60}| | "*19+c [67,132,-2,-66,-67,-69,-71,-132,-134].map{|i|c[i]=?|} a=c[68]=c[-3]=?\\ e=c[131]=c[-66]=?/ [1,2,-4,-65,63,64].map{|i|c[i]=?_} t=Time.now w,_,n,l,d,m=t.wday,*t.to_a p=l>11 q=(l-1)%12+1 h=(20-(l-1)%12)*67+3 c[h,60]=?~*60 f=(n+9)%60 f=f+d>58?n>d+2?0:n-12:f c[h+f]=c[h+f+d+1]=?- s=l==18&&w==0 z=->s{s.chars.map(&:to_i)} b={?_=>z['5410110125'+g='020304050607121315161718222326'],e=>z['08213243'],a=>z['00273645'],?|=>z['14243444'],?#=>[3,3,3,5]} b={?_=>z[g+'272855140824'].map{|i|i-1},a=>b[e],e=>b[a],?|=>z['142434']}if s b.each{|k,v|v.each_slice(2){|j,i|c[h-67*j*(s ?-1:1)+(i+n)%60]=k}} r=->(m,t){k=0 (x=rand(53) y=rand(19-q) m.values.flatten.each_slice(2).any?{|j,i|c[h-(y+j)*67+i+x]!=' '}? next: m.each{|k,v|v.each_slice(2){|j,i|c[h-(y+j)*67+i+x]=k}} k+=1)while k<t} r[{?(=>[1,0,2,2],?)=>z['141726'],?_=>z['111213151621333435'],?#=>z['232425']},w] r[l>5&&l<18?{?-=>[1,0,1,2],?.=>[1,1]}:{?*=>[1,0]},m] puts c.tr(?#,' ') ``` There's still a lot of room for improving the golfitude there, but it's a start. Now what's with the movie reference? Apparently that Green Flash happens a lot more often than Jack Sparrow wants us to believe. In fact, it happens about once a week instead of once every ten years. Every Sunday at sunset, the Black Ruby (hrhr) does one round in the land of the dead: ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | * * * | | | | * * | | | | * * * _______ | | | |-~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~/_______\~~~~~~~| | | | ___|___ | | | | \ | / | | | | \ | / | | | | \_/ | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` [Answer] # Java - Cute Kraken (A lot of bytes) EDIT: Further improvements to birds/stars bring up top and clouds, now the most busy calendar (12pm, Saturday, December) works about 70% of the time. Other 30% I get a (get ready for this) Stack Overflow error because I use recursion. New pics of busiest possible calendar and new Kraken pic, which shows off the lows/highs of stars/clouds. Now better handles situations in which the random scattering of stars/birds prevents the random insertion of clouds. When things are too crowded and it doesn't work after 200 tries, we re-do the stars/birds in hopes that the next configuration will allow the clouds some personal space. Who's a cute wittle kwaken? Who's a cute wittle kwaken? You are! You are! Minor edits, still no golfing. Kwaken shows up on the 9s because he knows everyone expects him at midnight. He's small and shy now, but one day he hopes to eat the ship. Clouds have a tendency to be low in the sky, while stars and birds like to fly above them; things tend to get a little crowded around 8 o'clock though. ``` import java.text.SimpleDateFormat; import java.util.Calendar; public class TimeFlies { static char[][] frame = new char[23][66]; static char[] bird = new char[] {'-', '.', '-'}; static char[][] boat = new char[][]{ {' ', ' ', ' ', ' ', '_', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', '/', '|', '\\', ' ', ' ', ' '}, {' ', ' ', '/', ' ', '|', ' ', '\\', ' ', ' '}, {' ', '/', '_', '_', '|', '_', '_', '\\', ' '}, {'_', '_', '_', '_', '|', '_', '_', '_', '_'}, {'\\', '_', '_', '_', '_', '_', '_', '_', '/'}, }; static char[][] cloud = new char[][]{ {' ', ' ', ' ', '_', '_', '_', ' ', ' '}, {' ', '_', '(', ' ', ' ', ' ', ')', ' '}, {'(', '_', '_', '_', ')', '_', '_', ')'}, }; static char[][] kraken = new char[][]{ {' ', ' ', ' ', '_', '_', '_', '_', '_', '_', '_', '_', ' ', ' ', ' ', ' '}, {' ', ' ', '/', ' ', ' ', '_', ' ', ' ', ' ', '_', ' ', '\\', ' ', ' ', ' '}, {' ', '|', ' ', ' ', '|', '_', '|', ' ', '|', '_', '|', ' ', '|', ' ', ' '}, {' ', ' ', '\\', '_', '_', '_', '\\', ' ', '/', '_', '_', '/', ' ', ' ', ' '}, {' ', ' ', ' ', '/', '|', ' ', '|', ' ', '|', ' ', '|', '\\', ' ', ' ', ' '}, {'_', '_', '/', ' ', '|', ' ', '|', ' ', '|', ' ', '|', ' ', '\\', '_', '_'}, {' ', ' ', '_', '/', ' ', ' ', '|', ' ', '|', ' ', ' ', '\\', '_', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', '/', ' ', ' ', ' ', '\\', ' ', ' ', ' ', ' ', ' '}}; static int day, month, hours, minutes, weekday, attempts = 0; static boolean isFirstTime, birds = true; static String timeStamp; public static void main() { timeStamp = new SimpleDateFormat("MMddHHmm").format(Calendar.getInstance().getTime()); isFirstTime = true; retry(); } public static void retry() { day = Integer.parseInt(timeStamp.substring(2, 4)); month = Integer.parseInt(timeStamp.substring(0, 2)); hours = Integer.parseInt(timeStamp.substring(4, 6)); minutes = Integer.parseInt(timeStamp.substring(6, 8)); Calendar c = Calendar.getInstance(); c.set(2014, month, day); weekday = c.get(Calendar.DAY_OF_WEEK) - 1; int timeTemp = hours*60 + minutes; if(timeTemp < 360 || timeTemp > 1080) { birds = false; month *= 3; } if(hours > 12) hours -= 12; initiateFrame(); if(isFirstTime) { printFrame(); isFirstTime = false; } } public static void insertStuff() { for(int i = 0; i < boat.length; i++) for(int k = 0; k < boat[0].length; k++) { if(3+k+minutes > 62) frame[15 + i - hours][3 + k + minutes-60] = boat[i][k]; else frame[15 + i - hours][3 + k + minutes] = boat[i][k]; } boolean beganDayCount = false; for(int i = 0; i <= 22; i++) for(int k = 0; k <=65; k++) if(i == (20 - hours) && (k > 2 && k < 63) && frame[i][k] == ' ') { if(!beganDayCount) { frame[i][k] = '-'; beganDayCount = true; } else { if(day > 0) frame[i][k] = '~'; if(day == 0) frame[i][k] = '-'; else frame[i][k] = '~'; day--; } } putInBirdsOrStars(); putInClouds(); if(hours == 9) putInKraken(); } public static void putInKraken() { for(int i = 0; i < kraken.length; i++) for(int k = 0; k < kraken[0].length; k++) frame[i + 12][k + 20] = kraken[i][k]; } public static void putInClouds() { int x = (int)(Math.random() * 7) + (14-hours); int y = (int)(Math.random() * 54) + 2; boolean noFreeSpace = true; for(int i = 0; i < cloud.length; i++) { for(int k = 0; k < cloud[0].length; k++) { if(frame[x + i][y + k] == ' ' ) noFreeSpace = false; else { noFreeSpace = true; break; } } if(noFreeSpace) break; } if(x + 2 > 20 - hours) noFreeSpace = true; if(!noFreeSpace) { for(int i = 0; i < cloud.length; i++) for(int k = 0; k < cloud[0].length; k++) frame[x + i][y + k] = cloud[i][k]; weekday--; } attempts++; if(attempts > 200) { attempts = 0; retry(); } if(weekday > 0) putInClouds(); } public static void putInBirdsOrStars() { int x = (int)(Math.random() * 5) + (12 - hours); int y = (int)(Math.random() * 60) + 2; boolean freeSpace = false; for(int i = 0; i < bird.length; i++) if(frame[x][y] == ' ' && frame[x][y + 1] == ' ' && frame[x][y + 2] == ' ') freeSpace = true; if(x > 20- hours) freeSpace = false; if(birds && freeSpace) { for(int i = 0; i < bird.length; i++) frame[x][y++] = bird[i]; month--; } else if(freeSpace) { frame[x][y] = '*'; month--; } if(month > 0) putInBirdsOrStars(); } public static void initiateFrame() { for(int i = 0; i <= 22; i++) for(int k = 0; k <=65; k++) { if(((k == 0 || k == 65) && (i > 0)) || ((k == 2 || k == 63) && (i > 1 && i < 22))) frame[i][k] = '|'; else if((i == 0 && (k > 0 && k < 65)) || ((i == 1 || i == 21) && (k > 2 && k < 63)) || (i == 22 && (k > 1 && k < 64))) frame[i][k] = '_'; else frame[i][k] = ' '; } frame[1][1] = '\\'; frame[1][64] = '/'; frame[22][1] = '/';frame[22][64] = '\\'; insertStuff(); } public static void printFrame() { for(int i = 0; i <= 22; i++) { for(int k = 0; k <=65; k++) System.out.print(frame[i][k]); System.out.println(); } } } ``` Casual output ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | -.- | | | | -.- | | | | | | | | -.- | | | | | | | | -.- | | | | | | | | -.- -.- | | | | -.- ___ | | | | -.- _( ) ___ | | | | ___ (___)__) _( ) | | | | _( ) ___ _ (___)__) | | | | (___)__) _( ) /|\ | | | | ___ (___)__) ___ / | \ | | | | _( ) _( ) /__|__\ | | | | (___)__) (___)__) ____|____ | | | |-~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~~~~~~\_______/~~~~~~~~~~~~| | | | | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` super busy output ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | * * ** * * * * ** * * * * * * | | | |* _ * * ** * * * * * * | | | | /|\* ___ * ** * * * ___ * * | | | | / | \ _( ) ___ ___ ___ _( ) ___ | | | |/__|__\(___)__) _( ) _( ) _( )(___)__) _( ) | | | |___|____ (___)__) (___)__) (___)__) (___)__) _| | | |_______/-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~-~~~~~~~~~~~~~~~~~~~\| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` If we're to introduce our kraken by hard coding some values, we get... ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | | | | |* * * * * | | | | * * * * * | | | |* ___ * * * * | | | | _( ) _ ___ * * | | | | * (___)__)/|\* _( ) * * * ___ * * | | | | ___ / | \ (___)__) ___ _( ) ___ | | | | _( ) /__|__\ _( ) (___)__) _( ) | | | |(___)__) ____|____ (___)__) (___)__) | | | |-~~~~~~~~~~~~\_______/~~~-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| | | | ________ | | | | / _ _ \ | | | | | |_| |_| | | | | | \___\ /__/ | | | | /| | | |\ | | | | __/ | | | | \__ | | | | _/ | | \_ | | | | / \ | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` [Answer] ## Python3 - Pirates and Jellyfish: ~~1580~~ 1472 bytes Every Wednesday at midnight a pirate ship sinks our boat. The noise wakes up a giant jellyfish who randomly roams the frame for an hour. ``` from random import* from datetime import* l=len;r=range n=randint def f(s,p,*a): global c,o;j=l(s[0]) while 1: x=n(3,63-j);y=n(3,p);g=y+l(s);h=x+j if not(o[y][x]or o[g][h]or o[g][x]or o[y][h]):break if l(a)!= 0:x,y=a for w in r(l(s)): for m in r(j):c[y+w][x+m]=s[w][m];o[y+w][x+m]=1 E=datetime.now();D=(E.weekday()+1)%7 h=E.hour;M=E.month t=6<h<18;N=(3*M,M)[t] H=9if h==0 else 21-h%12 s=min(H-1,12) o=[[0]*66 for i in r(23)] c=[['']*66 for i in r(23)] c[0]=[' ']+['_']*64+[' '] c[1]=['|','\\']+['_']*62+['/','|'] for i in r(2,21):c[i]=['|',' ','|']+[' ']*60+['|',' ','|'] c[21]=['|',' ','|']+['_']*60+['|',' ','|'] c[22]=['|','/']+['_']*62+['\\','|'] for i in r(3,63):c[H][i]='~' Z=(D!=3or h!=0) B=([' _~_ ',' __)__)__ ',' )_))_))_) ','.--:--:--:-=/',' \\_o__o__o_/ '],[' _ ',' /|\\ ',' / | \ ',' /__|__\\ ','____|____','\\_______/'])[Z] j=l(B[0]);y=H-l(B)+1;x=E.minute while 1: b=n(3,63) if b<x or b>(x+j):break z=E.day+1;d=b+z if b<x<d:d+=j if d>63:d=b-z if d<x<b:d-=j c[H][b]=c[H][d]='-' for w in r(l(B)): for m in r(j): g=x+m;k=y+w if g>59:c[k][g-57]=B[w][m];o[k][g-57]=1 else:c[k][g+3]=B[w][m];o[k][g+3]=1 f(([" ,'', ",".°____°."," :::::: ",",';:::'."," ,';:'. "],[''])[Z],s,n(3,50),n(10,13)) f(([' o ° o °','°________°','/___°____\\'],[''])[Z],s,15,18) for i in r(D):f([' ___ ',' ( ) ','(___)__)'],s-3) for i in r(N):f(('*',['-.-'])[t],s) for w in r(23): for m in r(66):print(c[w][m],end='') print('') ``` --- Example at Tuesday Aug 19 23:27 ![enter image description here](https://i.stack.imgur.com/c90mb.png) On Wednesdays around midnight: ![enter image description here](https://i.stack.imgur.com/dtZvd.png) [Answer] # Cobra - 994 Without Bouys: 994 ``` class P def main r,d=Random(),DateTime.now h,y,t,a=(d.hour+23)%24+1,d.day,d.month,d.dayOfWeek to int u,i,q=18-(h-1)%12,List<of String>[](20),1-(h+7)%24//13 for p in 20 i[p],s=['| |\n'],'__' for x in 60,i[p],s=[if(p-u,'[' _'[p//19]]','~')]+i[p],s+'_' for g in 6,for c in 9,i[u-g][(d.minute+c)%60]='[r'\_______/____|____ /__|__\ /#|#\ /|\ _ '[g*9+c]]' while x,if'~'==i[u][p-=p-r.next(60-y)]==i[u][p+y+1],i[u][p],i[u][p+y+1],x='-','-',0 while g+c o,c,g=i,a,t+t*q*2 for z in 99,if if(c,o[y-=y-r.next(u-2)][x-=x-r.next(52):x+8]+o[y+1][x:x+8]+o[y+2][x:x+8],o[y-=y-r.next(u)][x-=x-r.next(60-3+3*q):x+4-3*q]).join('').trim==''and g,for m in 3-(p-=p-if(c,0,1))*2,for n in 8-p*5,o[y+m][x+n-p*n*q],c,g=if(c,'[' ___ _(###) (___)__)'[m*8+n]]',['['-.-'[n]]','*'][q]),c-(m+n)//9,g-p*n//2 print' _[s]_ \n|\\[s]/|' for l in o,for k in['| |']+l Console.foregroundColor=if(k<>'~'or h+a>1,7,9)to ConsoleColor Console.write(if(k=='#',' ',k)) print'|/[s]\\|' ``` With Bouys: 1084 ``` class P def main r,d=Random(),DateTime.now h,y,t,a=(d.hour+23)%24+1,d.day,d.month,d.dayOfWeek to int u,i,q=18-(h-1)%12,List<of String>[](20),1-(h+7)%24//13 for p in 20 i[p],s=['| |\n'],'__' for x in 60,i[p],s=[if(p-u,'[' _'[p//19]]','~')]+i[p],s+'_' for g in 6,for c in 9,i[u-g][(d.minute+c)%60]='[r'\_______/____|____ /__|__\ /#|#\ /|\ _ '[g*9+c]]' while x<>3,if''==(i[u][p-=p-r.next(58-y):p+3]+i[u][p+y+3:p+y+7]).join('').trim(c'~') i[u-1][p+1]=i[u-1][p+y+4]='|' for x in 3,i[u][p+x]=i[u][p+y+3+x]='['(_)'[x]]' while g+c o,c,g=i,a,t+t*q*2 for z in 99,if if(c,o[y-=y-r.next(u-2)][x-=x-r.next(52):x+8]+o[y+1][x:x+8]+o[y+2][x:x+8],o[y-=y-r.next(u)][x-=x-r.next(60-3+3*q):x+4-3*q]).join('').trim==''and g,for m in 3-(p-=p-if(c,0,1))*2,for n in 8-p*5,o[y+m][x+n-p*n*q],c,g=if(c,'[' ___ _(###) (___)__)'[m*8+n]]',['['-.-'[n]]','*'][q]),c-(m+n)//9,g-p*n//2 print' _[s]_ \n|\\[s]/|' for l in o,for k in['| |']+l Console.foregroundColor=if(k<>'~'or h+a>1,7,9)to ConsoleColor Console.write(if(k=='#',' ',k)) print'|/[s]\\|' ``` At 1am every Sunday, the endless expanse of the tilde sea on comes alive with a dazzling blue shine. Hope returns to the people of the desolate shell-world. ![enter image description here](https://i.stack.imgur.com/bSLDH.png) [Answer] ## C# ~~1124~~ 1128bytes Once a week, a shoddy ASCII submarine should appear for an hour below the waterline, and increase my byte count noticeably *hopefully this code will actually work now*. I dread to think what happens on Saturdays at 11:00 in December... ``` using System;class P{static string G(DateTime t){Func<int,int>K=new Random().Next;int i,j,D=t.Day,H=t.Hour,W=19-H%12,E=(int)t.DayOfWeek;var M=new char[60,19];Func<int,int,int,string,bool>T=(x,y,w,s)=>{for(i=0;i<s.Length;)if(M[(x+i%w)%60,y+i++/w]>0)return 0>1;for(;i-->0;)M[(x+i%w)%60,y+i/w]=s[i];return 1>0;};T(t.Minute,W-5,9,@" _ /|\ / | \ /__|__\ ____|____\_______/");while(M[j=K(59-D),W]+M[j+D+1,W]>0){}M[j+D+1,W]=M[j,W]='-';for(j=60;j-->0;)T(j,W,1,"~");for(;++j<E;)while(!T(K(53),K(W-3),8," ___ _( ) (___)__)")){}var N=H<6|H>=18;for(j=0;j++<t.Month*(N?3:1);)while(!T(K(60-(N?1:3)),K(W-1),3,N?"*":"-.-")){}if(H==18&E==4)T(K(59),W+2,17,@" __ __/ \_________ (_______________)");var res=" ________________________________________________________________\n|\\ ____________________________________________________________ /|\n| |";for(j=0;j<19;j++){for(i=0;i<60;i++)res+=M[i,j];res+="| |\n| |";}return res+"____________________________________________________________| |\n|/______________________________________________________________\\|";}static void Main(){Console.Write(G(DateTime.Now));}} ``` Somewhat formatted code (which re-draws every 15seconds because I mis-read the spec): ``` using System; class P { static string G(DateTime t) { Func<int,int>K=new Random().Next; int i,j,D=t.Day,H=t.Hour,W=19-H%12,E=(int)t.DayOfWeek; var M=new char[60,19]; Func<int,int,int,string,bool>T=(x,y,w,s)=> { for(i=0;i<s.Length;) if(M[(x+i%w)%60,y+i++/w]>0) return 0>1; for(;i-->0;) M[(x+i%w)%60,y+i/w]=s[i]; return 1>0; }; T(t.Minute,W-5,9,@" _ /|\ / | \ /__|__\ ____|____\_______/"); while(M[j=K(59-D),W]+M[j+D+1,W]>0){} M[j+D+1,W]=M[j,W]='-'; for(j=60;j-->0;) T(j,W,1,"~"); for(;++j<E;) while(!T(K(53),K(W-3),8," ___ _( ) (___)__)")){} var N=H<6|H>=18; for(j=0;j++<t.Month*(N?3:1);) while(!T(K(60-(N?1:3)),K(W-1),3,N?"*":"-.-")){} if(H==18&E==4) T(K(59),W+2,17,@" __ __/ \_________ (_______________)"); var res=@" ________________________________________________________________ |\ ____________________________________________________________ /| | |"; for(j=0;j<19;j++) { for(i=0;i<60;i++) res+=M[i,j]; res+="| |\n| |"; } return res+@"____________________________________________________________| | |/______________________________________________________________\|"; } static void Main() { for(;;) { Console.Clear(); Console.Write(G(DateTime.Now)); System.Threading.Thread.Sleep(15000); } } } ``` Example output (should read 3:31, Wednesday, 13th August): ``` ________________________________________________________________ |\ ____________________________________________________________ /| | | | | | | * * | | | | * | | | | * * | | | | * | | | | ___ * * | | | | _( ) | | | | *(___)__) * * | | | | * | | | | ___ * * | | | | * _( ) * ___ * | | | | * (___)__) _ _( ) | | | | * * /|\ (___)__) * * | | | | / | \ * * | | | | /__|__\ | | | | ____|____ | | | |~~-~~~~~~~~~~~~~-~~~~~~~~~~~~~~\_______/~~~~~~~~~~~~~~~~~~~~| | | | | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` [Answer] # Lua - more than stars I'm done! Well, not done done. I'm done with this code and challenge. It's not golfed, it's missing the month indicator. There's no avoidance... I'm only posting it so that in the off chance nobody completes this chalange, at least you saw something, got an idea. ``` --Halfed Assed Calender math.randomseed(os.time()) math.randomseed(os.time()) math.randomseed(os.time()) local bh=os.date("%I") local bm=os.date("%m") local wdm=os.date("%d") local cdw=os.date("%w") local bsm=os.date("%M") local hh=tonumber(os.date("%H")) local function tp(t) for i=1,#t do for k= 1, #t[i] do io.write(t[i][k]) end print() end end local function s2a(s) local ns = {} for i=1, table.getn(s) do local nns={} for k = 1, string.len(s[i]) do table.insert(nns, string.sub(s[i],k,k)) end table.insert(ns,nns) end return ns end function ca(bg, a, x,y) ntb={} lbg=#bg la=#a lax=#a[1] lbgx=#bg[1] if lbgx-((lax+y)-1)<0 then elseif lbg-((la+x)-1)<0 then else for i=1,la do for j = 1, lax do if " "==a[i][j] then else table.remove(bg[x+(i-1)],y+(j-1)) table.insert(bg[x+(i-1)],y+(j-1), a[i][j]) end end end end return bg end f=s2a({" ________________________________________________________________ ","|\\ ____________________________________________________________ /|","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| | | |","| |____________________________________________________________| |","|/______________________________________________________________\\|"}) boat=s2a({" _ "," /|\\ "," / | \\ "," /__|__\\ ","____|____ ","\\_______/ "}) ccc=s2a({" ___ "," _( ) ","(___)__)"}) water=s2a({"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"}) tblock=s2a({"xxx","xxx","xxx"}) temp=ca(f,water,19-bh,4) if hh<18 and hh>= 6 then n=bm sb = {{"-",".","-"}} else n=3*bm sb={{"*"}} end for i = 1,n do r1=math.random(14 -bh) r2=math.random(59) temp=ca(temp,sb,r1+3,r2+3) end if cdw==0 then else for i=1,cdw do r1=math.random(11-bh) r2=math.random(52) temp=ca(temp,ccc,r1+3,r2+3) end end temp=ca(temp,boat,14-bh, bsm) tp(temp) ``` You can take look at it [here.](http://codepad.org/SLqvjLYF) --- ``` |\ ____________________________________________________________ /| | | | | | | -.- | | | | | | | | ___ | | | | _( ) | | | | -.- -.- (___)__) | | | | | | | | -.- _ ___ | | | | -.- /|\ _( ) | | | | -.- / | \ (___)__) | | | | /__|__\ -.-.- | | | | ____|____ | | | |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\_______/~~~~~~~~~~~| | | | | | | | | | | | | | | | | | | | | | | |____________________________________________________________| | |/______________________________________________________________\| ``` ]
[Question] [ This is not a challenge but a question, I figured it was on topic because of > > Non-challenge questions that are related to solving programming puzzles or a particular type of challenge are also on topic. > > > Now on to the question: Is it possible to write any JavaScript code with only 5 letters? [JSFuck](http://esolangs.org/wiki/JSFuck) already does this with 6 symbols `!+[]()` but I wonder if the `!` character is needed. JSFuck works with a combination of casting to string (by adding an empty array), casting to number (by writing a + in front) and casting to boolean by negating. For example: ``` [] \\ Empty array +[] \\ Cast to number -> 0 !+[] \\ Negate -> true !+[]+[] \\ Cast to string -> "true" ``` From this string we can extract all it's letters using the square brackets with a number inside, and any number can be made by adding true together that many times. Like this a lot of letters can be found and can be concatenated to strings. The most important string to be able to create is `"constructor"` because it can be used to get the `Function` from any function, and this object can be used to execute strings as JavaScript: ``` []["find"] \\ the function Array.prototype.find []["find"]["constructor"] \\ the Function object []["find"]["constructor"](string)() \\ same as eval(string) ``` As you can see, `!` has 2 uses here: * Creating numbers to select letters from strings. * Casting to boolean to get `"true"` and `"false"`. The first one of these 2 can also be done using the `++` incrementor, not directly on `0`, but it can be used on elements inside an array: ``` +[] \\ 0 [+[]] \\ [0] [+[]][+[]] \\ [0][0] -> 0 ++[+[]][+[]] \\ ++[0][0]-> 1 ++[[]][+[]] \\ also works because ++ casts to number ``` So all numbers can be created without `!`. The second one is more difficult. The importance of `"true"` and `"false"` lays in the letters `"r"` and `"s"`, which both appear in `"constructor"`. I have already found all the other letters of `"constructor"` by means of `"undefined"`, `"Infinity"`, `"NaN"` and by casting functions to strings. So the ultimate question: (How) can you create booleans, or the letters `"r"` and `"s"` in JavaScript by only using `+[]()` ? The letter `"l"` might also help. It can be obtained form `null` but I havent been able to get that value with those 5 symbols. It can for example be used to get booleans if we already have `"s"`: ``` []["includes"]() \\ false [+[]]["includes"](+[]) \\ true ``` The letter `"l"` and `"k"` together would give access to `"r"`: ``` ([]+[])["link"]() \\ "<a href="undefined"></a>" ``` Any way to get a boolean, `null` or any of the letters `r s l k` would be very useful! A library of what we have: ``` Array.prototype.find: [][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])] Infinity: +((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[])) NaN: +[][[]] undefined: [][[]] 0: +[] 1: ++[[]][+[]] 2: (++[[]][+[]])+(++[[]][+[]]) 3: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 4: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 5: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 6: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 7: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 8: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) 9: (++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]) a: (+[][[]]+[])[++[[]][+[]]] c: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] d: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])] e: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] f: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] i: ([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] n: ([][[]]+[])[++[[]][+[]]] o: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] t: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] u: ([][[]]+[])[+[]] v: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]]))] y: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])] I: (+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[+[]] N: (+[][[]]+[])[+[]] " ": ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))] (: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))] ): ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))] {: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+(++[[]][+[]]+[]+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])))] }: ([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[+((++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+[]+((++[[]][+[]])+(++[[]][+[]])))] .: (+(++[[]][+[]]+[]+(++[[]][+[]])+([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+(++[[]][+[]]+[]+(+[])+(+[])))+[])[++[[]][+[]]] ,: [[]][([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+([][[]]+[])[++[[]][+[]]]+([][(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(([][[]]+[])[++[[]][+[]]])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])])]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]+(+[][[]]+[])[++[[]][+[]]]+(+((++[[]][+[]]+[])+(([][[]]+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])])+(++[[]][+[]]+[])+(+[])+(+[])+(+[]))+[])[(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])+(++[[]][+[]])]]([[]])+[] ``` [Answer] After [brainstorming](http://chat.stackexchange.com/rooms/36887/discussion-on-question-by-jens-renders-jsfk-with-only-5-symbols), the result seems to be that, on modern browsers at least, there’s no way to do this. I’ll try to summarize the entire process, adding some reasoning about why we’ve exhausted our options in any given domain before moving on. Then, barring some kind of amazing new insight (like, a corner case of JavaScript syntax everyone is forgetting about) it’ll be pretty clear that there’s no way to get the remaining letters. ## Literals The only *immediate* literals you can make with `+()[]` are the nested empty arrays `[]`, `[[]]`, `[[[]]]`, etc. From there, we can start casting values using `+`: * `+[]` gets zero, which Jens’s trick expands to arbitrary positive integers using `++`. * `[]+[]` is `""`. In fact, `[]+x` gets us a string representation of `x` in general. `[]`’s next use is indexing. Indexing an object out-of-bounds (`[][[]]`) gets you `undefined`. Casting that to a string and indexing the result gets you the letters `d e f i n u`; casting it to an integer first using `+` gets you `NaN`, from which the letters `a N` follow. Using the `++` trick on any non-integer value reached so far either gives `NaN` or an error. Also, none of the objects we can create are callable (yet), so `()` doesn’t help (except for grouping). The remaining tricks up our sleeve are casting and indexing. So the question is: which strings can we create using the characters `0123456789adefinuN` that either * are number literals we can round-trip cast to integer to get new strings, or * are property names of objects we can already reach? ### Number literals As an example of the second option, we can make the string `"1e1000"`, and then get `Infinity` from `+"1e1000"`, and casting that *back* to string gets us the letters `y` and `I`. Also, we can make `"11e100"`, cast to number and back to string, to get `"1.1e+101"`, from which we extract `.` and `+`. Using that `.`, in turn, we can make the string `".0000001"`, cast it to number and back, to get `"1e-7"`, winning us `-`. That’s basically all floats will get you: there aren’t any more interesting values other than `Infinity` and `NaN`, and there aren’t any more characters used in their usual string representations other than `-+.0123456789e`. ### Properties So we have the letters `-+.0123456789adefinuyIN`. Which properties can we reach? Let’s ask JavaScript. ``` >>> R = /^[-+.0123456789adefinuyIN]+$/ >>> [Array, Object, String, Number].reduce((h, f) => { h[f.name] = Object.getOwnPropertyNames(f.prototype).filter(x => x.match(R)); return h }, {}) { Array: [ 'find' ], Object: [], String: [], Number: [] } ``` Only `[].find`, which Jens already found. Let’s cast that to a string, reap all of its letters, and try again. The string representation is a bit different across browsers. On Chrome and Edge, `"function find() { [native code] }"` contains `acdefinotuv()[]{}` and a space; our full alphabet is now `+-.()[]{}0123456789INacdefinotuvy`. On Firefox, there are more spaces and newlines, but the letters are the same. We repeat our search: ``` >>> R = /^[+-.()\[\]{}0123456789INacdefinotuvy]+$/ >>> [Array, Object, String, Number, Function].reduce((h, f) => { h[f.name] = Object.getOwnPropertyNames(f.prototype).filter(x => x.match(R)); return h }, {}) { Array: [ 'concat', 'find' ], Object: [], String: [ 'concat' ], Number: [], Function: [] } ``` `String.prototype.concat` is deprecated: it does exactly what `+` does, which we can already do. So we got `Array.prototype.concat` and `Array.prototype.find`. What can we do with them? ## Functions `concat()` lets us create, for the first time, longer arrays. `[[]].concat([[]])` is `[[], []]`, and casting that to a string gets us `","`. (This doesn’t help us find new properties.) But `.concat` doesn’t modify our values, and it can never return `null` or anything like that. Calling `find()` doesn’t help us either: the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) says > > The `find()` method returns a value in the array, if an element in the array satisfies the provided testing function. Otherwise `undefined` is returned. > > > Both of those we can already do using indexing. --- And from here, there’s nowhere else to go. If you doubt anything I’ve written, let me know in the comments. [Answer] The 3 functions in [Lynn's answer](https://codegolf.stackexchange.com/a/75464/25180) weren't that useless. But the [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) in ECMAScript 5 foiled my plan. There is a quirk in the older versions of JavaScript / ECMAScript. If a method is called without an object, the global object `window` is assumed. So we can do this: ``` a = {f:function(){return this}}; a.f(); // Returns a. g = a.f; g(); // Returns window. window.g(); // Also returns window. ``` This is still true for modern browsers, but only if the function isn't defined in strict mode. And all built-in functions (with native code) seemed to be in strict mode. In older browsers when there isn't the strict mode yet, this also works for built-in functions. Assume we are using older browsers. Then if we want `window`, we have to find a built-in function that returns something containing `this`. Within the only choices we had, there is the function `Array.prototype.concat` doing exactly that. We can test it like this: ``` Number.prototype.concat = Array.prototype.concat; 1..concat(2); // Returns [1, 2] concat = Array.prototype.concat; window.concat(2); // Returns [window, 2] concat(2) // TypeError in modern browsers while // returning the same thing in older ones. concat.bind(window)(2) // A workaround in modern browsers. ``` So basically it doesn't care whether the object it is called upon is an array (but it must be an object for the least). It just wraps it in an array if not. If we had `window`, firstly we can get the string `[object Window]` by casting it to a string. With the new character `b`, we can get `r` and `s` using the following two lines respectively, and every character we didn't have in `constructor`: ``` window["atob"]("cuaa")[0] window["atob"]("cyaa")[0] ``` But the other problem is to remove the object reference from `[].concat`. Wrapping it in an array and extracting doesn't work, because `[].concat` already means `[]["concat"]`. The only way I know which could possibly be constructed using `+[]()` is to return it from a function. `Array.prototype.find` seemed to be able to do that: ``` [[]["concat"]]["find"](x=>1) // Returns Array.prototype.concat, where x=>1 can // be replaced with any always truthy function. ``` We had always truthy functions. `Array.prototype.concat` and `String.prototype.concat` both return truthy if the object is `window`. If we use the later one, we made use of all of the three available functions. **But,** unfortunately, `Array.prototype.find` doesn't exist in the old browser we are using. At least I didn't find one that works. And I didn't find another way removing the object reference. The complete code that is testable in modern browsers that returns `r` and `s`, with the `.bind(window)` workaround: ``` [[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0]["ato"+([]+[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0])[2]]("cuaa")[0]; [[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0]["ato"+([]+[[]["concat"]]["find"](""["concat"].bind(window)).bind(window)()[0])[2]]("cyaa")[0] ``` ]
[Question] [ In the game of Freecell, you are tasked with building four foundation piles in suit from ace to king, on a layout where you build downward in alternating colours. However, you can only build one card at a time, so you are given four "free cells" each of which can contain one card to help you move entire sequences. The idea is that you weave individual cards in and out of the free cells as required to help you solve the game. Your task is to build a program that will solve these games in the fewest moves possible. Your program will take as input a sequence of 52 cards, in the following format: ``` 2S 9H 10C 6H 4H 7S 2D QD KD QC 10S AC ... ``` Which will be dealt in the initial layout in this order: ``` 01 02 03 04 05 06 07 08 09 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 ``` And return a list of moves to solve the game. Each move will be in this format: * A number representing the pile number (`1` through `8`), or a free cell (`A` to `D`), representing the source pile. * Another number or letter representing the destination pile or free cell, or `F` for the foundation of that suit. The output will look something like this: ``` 18 28 3A 8B 8C 85 B5 35 4F etc. ``` Once a card is put into the foundation, it cannot be removed. Since only one card is moved at a time, moving a sequence of 3 cards requires 5 moves, and a sequence of 5 cards requires 9 moves. If a game is unsolvable, your program should indicate as such. However, your program must be able to solve any solvable game. Your program will be judged on the 32,768 deals found in the original Microsoft FreeCell program. In order to be valid, your program must successfully solve every deal except [deal #11,982](https://www.youtube.com/watch?v=UvDJoq5OsFk), which is unsolvable. Your score will be the total number of moves it takes to solve these 32,767 deals, with shorter code being a tie-breaker. --- A file with all the decks in the format required by the above specification is available for download here (5.00 MB file): <https://github.com/joezeng/pcg-se-files/raw/master/freecell_decks> [Answer] # C 64,643 bytes, Score: ~6.5 million The following Stack Snippet (courtesy of Mego) outputs all of the code as a single standalone C file: ``` $("#a").text(pako.inflate(atob('eJztPWt347ax3/UrsO6JTVrSVpKd1FlZzslJ2iZtzr233faT10eHoqg1E1lSRWrTbVb//WLwIB4EQJCSvOmGc3YpCcQMBsDMYAYv/y5dxcvdPEG3WT5P1y8f7zq/k5OW6UxLS6Jt/Kjn26art5DWwV93cY7oxzSOtvNp3vmlgzBkj+ttjkjSavc0ltLmSfzTuLMfdzr5+00yTxbIRIai5jgX+508bfL35OVYLzjLo/inouR0lSNcJMma0YIlktn98MsHV/GMGFrE/KupvDwpyhMZEfnM7m8elGIX2ySJk+Uyu79mL4BFaAaa4uQFCkLsc9x5t07nmOxqvUr/k9DXAc90SbOF4w6Qp6nx+mkTbZMgXq+yHBFsnG3YQ2rCKGSkKVa6SnMDWZ4Cr9NoOd1lyZazuJ7GQfwYbUl2kA+cv/gNOaJsSl8YCMs9DkRHm2S7lMgJWiQLvB1BvkBCxFUy5N+MdlMugzOMQCUQ/5Cz90h/XBbCOk0z/LFcQpVJ/t1oo1BRKyqJHZNO0veQZ5vgRp6gAAVBcMmy300uoosQnZ8jkXY7ufjPRRiir6S07sXXF32S9RUqEkNGPV2ggBKfIJwvJImUD4Btku+2KzSk0rYnz2SZJTLexV+saE48dPE3K+LIjfhXK+KVG3FoQwwuA9oy3WFIcg4uwq+Gg1fmGlCCdzjbiPUASbjFCV/i5rcUAXn6QFinac4/4Nn2HQxCgEDfueTAdy43JCnmUlNIC8miyApJUSSFpKhyQpIYpz8/pssEBQWDAEGMXuDqfkeomt68tr751vrmG+sbZH3zZlBucWC+2x0Xv4/aGnuhOTERle+YUJX7rhAYmvF1OePQmPHbcsaRMeM35YxXY1WuVK72nWojyeVJ5BOj0EtuvnCL6taMGswiJ7QZy0VElr7uSPxQ0sASEV0g9RRtplf3w+sHPKBh5F/QGTrrobOv4TGCxxU8ruHxOTy+gMcf4HEDjy/hMRzA8y/w+Bs8/nqGYGQ8iiXnNhqMALQCtgEDKknwCxuA4VVJGjG9Vbx5HxC6Ui0xxkMP3i6TVaClh9gOCfm91PkAeSadAMVXmBNb8QNj4QOPohWjyPoSUxJdSVuZ9nrhqpXb19W6VHqgelp1iPCXEGXDoFSYyM9IqpCiGOXs30nZNavPWRqG5rY9ey3hlrBGNqxvXVhXNqxvNCxLNrn25p7y9IQ050RufUpd1yvFWvRop58bPCOOS4c1bjgIQpeJJ5TfM3lVpmoZ/HwwJIPeAIxAwb/RoYU3uk8LaaPCJpI3rAD8bgiKqCaGhMjYmH1kyT6SvLF42L8rjOwdxhE/a3lnCp1bHzr9EiGT6mGyRDgpa9QB4Rl+URRLZU9QLrFJ6N360utbCbrxBjoa8axYiIOjLu8Qpzw+EjFgiFIUdxlmw5A2e4YNaymEHFnRRgqaPmYWrJ4zgT2nQkrk3yeyYzX4V4ZtM33Zv6MhZw/dYNXDmOtFIFgKe2obcdVTCBTRaQ9dFzRobbn2CnTOqCNOZEw+JU9ZkgcBZMctA696aFAUwLBCSrNBwMqKYc2LS4ufNgHOmI16xiII5oL4S5dZj3zk69dKBEfdmV46GfR+nAxEpI5Vj/8kLnUQT3DY0e2GssQrosspE59gwp17oY+YwgR84243Heuvgh9vr8/P08nkD+GHD8GPdxP664tQHS3L+lLQmAzGxhfd7o/mFyq7F29WF5jjUs59KQVnl911opj1JgnklodEnMamiuAr1rOnaLlcx8FowP0lTh93vOgh3KFjldCW595iIrSwkh7LBIkon2OirJgFGYgJF6FKqqC0WGMvFLd1dnszBmlgVlcxu9mLycBmF6kskdA+pCHR6kLt43L/wujaVTtR7RYtw17qR+A3xvyOY86sxjBnOlaYNjPCmJe4R/KkhqiQr9QaalauHefwknSGqcnsBcy2SfSTTwHGNlZ+MudEC8VEHMUhAHl6ySYFgyx8eEkHh3J6MV/5QFwN/C0cG9CLbJjB8rAoG0SiHsJbrJqD0/VQ0hdIkmcw8b9eMXlJfrAxBvOlTHBGZd9PvHyK/j0taoNJiLzMWFIeSGuArQ6ZIRgORteh0L8Iy3N0ez2OhP7xVikFjHS4o5xHRR3gm82/5eLGc+JRnUgd0oROeQ9zUMqMQ7bBNckXbKIKO/efXWVI/s/gu/5nwwy9Js9vyfMbeL5ZnfVK0id5/vowTgJE+VdYD32ooA/roo8U9FFd9CsF/UpHpy2Na2hIHRpTR8ZUTHhs6h0pdAHLjzur3+8j6T/uDT4eVCC+wS5vHzn+U1LUWZK1AYvQwDnCyKIZEGMIKmw2FCjEHr9C3jYc6TxUU7ZYIDLOMIXCzPOvt0oBRXK5WqTWpBEQVBxl6nAl8yxPKuB6VrPsMb7GUS5UFdLOQteAW5qXMBCtkBSwAWc9i2qwimR87ODVVexusS5Q5lF80+smRFmfESLGf8+C7mU8hZ7Lkn/tklWcTJ/W7xIxpwx5cMABcwVqGhjSpyJJniKir4yTRIwFSrBrDpAF+tCCProMOAXzjJAgMSp5bXzW/0oigrqoktKVldK1RKl7VUXn2krnc5nO5046dxP0eeVSy74jvIDNNnlHvfSMLh+CzkiJ1CbJA7fx5W4FkWUyl9/CxzafRjnNVlDP0yeO2qHrobPd22ma43Bhvcs3u1yQlV5RluUM3MXBbst6ucvT9apUkdILGnCul++SKbY2WrTNYlVa8CZ/lOfQiMpRVc3EurYlpsCFJz9T4sLxUeKWRQxuSMYWndl3ibhMvXjXQ3nytJmK0qizNRM/4keyxE44gdmEnGLQ7xDaUcJFL3B3l1he4ATGHPiEcQc+rWOPbm3hszT8WCMgzSXfSxJNgiegBjpxYxoiFhDLLGLs/C1i9wgh+BSeBUZn7jhRGI3NMh0Du4JZ9RvRw1jS5TI14COQdEQbYQwyi2WdCGN3qGYtZ2OOMp/IIc4zVg4DTX3Q0F7fkwIfSNCrRg/nfOFeQbfP13GBqyFfhRJQT6RazlSPvUC39QAL4eykWaRWEOoPwwek9ZMqXNSzhAQyJNOFtBCwQBaKZEnm+vKaBOWxPO0SFEYkBIZZ04/LGQurQFaZCiRbzRw5imbtDx/GR6SFGZN28TgJC7S+qa6Bgmxr+W4X6UJK+16ZZT0XlEyZH+l66NDwDvp/RrdISVR6pXwySFrvzugcS92o2gRoRWZ53pWI6v/884cffGdVpIEFN5LmGPSddTDPRfL2DpxMLxfpau7d5gASB90DmhbgXKp0de5anUEQzB3iM3VVCkYAzB3H29kwV7w3SzrB8J6EXpCVbtVNnJi8xzJFO1UAkwPaxfo5ujFoKAfVWxXTXyEe0slwKaul3mWXJq7N0mtoOq34e40QGEXNTdRBwwBvzTBOAJhavV/hleNYYfhF3U6gK0hKo2nlllqxpwm2ua4AVVGEVpKtJ8oph4s19nHAH9IiB2GGuJNmqR2U9wJmdWs2d33PzEap7KTJUG40AKNVcTN8gPtmItXIU7MpCQDx3DR/AWvKCLYCVXl0Hwb/JiWUdrbpcEABV6QAs5i4Wx6gvIKvg7mjTTqjp9QZYo4jBEcXgJN3/ok63t7p7g6v6lY9iN1L4ZopylajNKVrtABbD8tMQdCLiX2C4BQBlt4W3vGVHHHo9VQCmzZeaeMVDdp4BbXxShuv6NDGKwW08YoRnjFeqXJk2njiVxBPNO2k1uev9vkLpz872RqNEg0IfMcaYfPoT6biWjA0N7OymuKUOB2TBS0FAUe0I4r3EFqJCg13jCXAdgWnmOpyeo5AvIExjWvlvVU87SX5xlUGhEPWmcgOSlENz2UmsqHSi7W6oR+HWlEchyYRGwfvyI3DgWEGQO3ggSB5RnQc3IPV0SM8Dn6RHof6ER+HI0Z+HOpFgBwadSZB9I0IOZjdBwCrLwfgFgRHxCjKdWqexdX2K/7QiNKvFIBGESaH54o0OTiaXGOnQeTJwT8C5XDkSJRDdeedNDLlcJQIlYNdWU+pTgdGsjIf9ojWjxWAA/dKWWroCHU5uFrfL9UzEJD2+rFtlIXnMza+or6V7OPDVsQeSjPYPDxNcVttYb8jFui5kgw7GwVJtt0xf8QZ6HZHIpn0K9kEOUuW65+l/Y8yIzQMyNfTLc4UE8Eo2IbkRbpc0iTKLk+T2Faqqo4fxiMnamMRZmybDiN1z+GkFAyUBU/hxn72ay8bOLVHbFW48a8Cd5sjbW9nnQpQGhU1UI+rIXckWi7vkIi0KBOHiWiM4ltBDP8qB4zluE+Wc3HdgkYfN37cHWKSkVJApBdgbkyAQjN8wuKovGuRQ6FWXnSMYXVRdRaoFiRN0Spnu260KhE1h6yCsF/Iako92kyiLgUOc245kWhmZ2/yYLwnR4rJMZ1CZBZUelWNbbLCxHEtaYpNu2nlsquE6RRydKgIsdb0nqo2H22NfBscbMk8I7ZqTs5JzTOTDXHyS083ZtACtIcaOmfquQWjBMyth8eslYP5unl8qx2KmJdscT1eFX7trDJJndtm+XSomKsrSpTf9d1SK0PVvJ1E30eC1eaqiI2KKioem9u2KXgLiT8qIX00RHfYDazmjnLokwtA8w89urfrsES2yhQNLko6QZdzMBd3bCng4N/WpDV0kXCsEelgj2TUXN4y9kJj59jCBWUow/upWtUYyJATQJoSzWPQJA/rJEMpHiLX2QTGQsPbQAlAwvArS8ZXesaaXJnr3J+U2W1QXTXW86svxfGpMM95zBpbo1Mf4NfcmYSIXXxXix6CWxvNB4GVTu8bQm21kfrluoXoblKXGyQrQVzDugE41qxsYF3Lqk2Jhd8k/isroiUOrIIGNeK8zLCPNbu9Hs+alEvLboIFwKYYzEtrs6qZkufhEcARpvmA3zBXxmqEVnUGUPZ9bK+rT//VpeJx7k/DMR768wG7OGEmxLnp+t25b67sWKvRrWkc+ljqfvPrUHfe97PKWcXn4RCgVfaPo+xN6m+TJTuzs9obRWalTSJ1uWzQuWyaGBHDMRHOTn/Y3GTUxQA4WBwe/I6iR6FL9j5S88MSiWj5ePyM7f4Jn+Sv2xQNuq/RRisbHLIBywa1N2bZ4Ei7g0zQeO+PkVjNDV42OECbTrEhzAb1NorZoPkGMhucYGOZDZptOLPBUYWREKy7Qc0G9f0954Y2GzQTfI8NcDZoYHY9dvjYoFn1jrXB7rhcARy0Ic8Gz71RzwYNg5XjbOyzQf0NfzY40UZAGzQXsmfZOGiDo24otEF94/rfYLaOtJHRBn4bHG3QXByPd+SvCvz2SdqgiVCdJrfv+udhOU65X1QysdxsStsOHYe6Kg+ZmdEADt3ix5kt6NTZbxNPxIzAaIziO7jfuN+vu+um1g6+yh0K9XZeVWxnOdVOPoBT7OZzN/RJzpVUTBH7qhUAbBCMu7YF/OLvxVlmwx3HmderPF3tLM7U3npKlv3FQK/F3tLSLu7DW3lhNqZ/DyImhqB2Dfp9O/OmdNpYpVtcq0uqfU6Rb7wbk2139l137mI5z9U75TzXQyrF0lmhZtPN7ur9N00fVzZPrelgjxOKv63pXUfztudirUg1p03bc7HtuVgC7blYAu25WB3ac7EqtOdiZT4+zrnYKoof/1is9jf0/P7wRCkgd1yNCeB3PWa5HM6V13SKGV0qvno6pVE8WvOkm4k5wgq0xo3x+hwjbVtoV5H34NtnHPuJSgjWqOTQO2dq+9VNfepa/vSBjtuxLqesO2F3Ct/Z329u5jMf2V+u7ysfM+jxNR4ATe7/c/vElgG8YvB2H7s81Ad2j8WNfd/n9HsdftHh/m49X/cEfq67g07u3x7Nt7U5UMdViSP4sdU+rLtLjuu7VvutR/FMZde0vS9DTwFo78to78tg0N6X8cndl/GivTCjqFx7YYaA9sIML2gvzGgvzGgvzHBDe2FGe2FGe2FGLWgvzHCU3QQLoL0ww4nVCO1TOkPfqAHaCzOc3LQXZlRAq+wfR9mb1L+9MMMb2gszakB7YUYlrfbCjAOgvTCjvTCjGtoLMwpoL8w4SA7bCzOeOdRpL8xwst9emCGgvTDDDu2FGQ2gvTDDDe2FGe43B+zXe4btejJ66QYL2KgHtpjs39OvsTBfvVFj95SOrh4xMf81bMC0bFnqD80HP4ydIl9HQv+OW1f/q2h38jwRuWXD+ieOrRJRf5lLXs5ia6piCfg20Dlii6kiy6tylupD+pU7h2CWG8GqFqqc5642eMdfpvIzsp4z0U21H+ATnmdy1vvgRSLXYpCy6KNJN/Ykf11a4rUW1ERHDlvbeVYN+a2qiKvav66lFUcf/Qb7R1U04XiI9i68j27XuXe1vavEilRzxrq9q6S9q4RAe1cJgfauEh3au0pUaO8qkflo7yox/VJnmAx3sqrRhNpEz3spq05CuZMVNvGoEZ1p6sfUVnWu/KDzYYOxdHR1bD0r5YgPa8ygVA83x5s5qVYAj3iwrqwCfMIhhs9MYP0ZEovNbW9wIQg1Iov2BhcXtDe4lKC9waW9waW9wUWB9gYXqUInv8FFPFlpw3Fn34kfoy26RI/JcsM4RpPO2SLuk9ZF9+sN1BLr0WwNHuEiXSZvVmedM/L4fiEloxS0YL0FYdokcbpIkzkuKsJOOG6C1Ry8tHS12eUC/+t3UbqMljOM/L+0nFckvf+Iuez3gSmpMn00T7PNMnpP7lkhLKMsxh7QiiKlBCnNk21/vctxQToSZhG/jKAgkOhZskWYLyosmDWUvEu272kH4txY8HEpRD6TOSnB1YMw9xttNss0jqA669XyPbmzhrdkf57Mdm9RSFnNCKukJMFrH0XLbI3Yb2CXsvKcnJHH6/TtCrPyCgXVeBTt9fd//ufrvw9xFf4Pi1CeEe5ZE68XiNlIwvnPyTbhvGMtQgssf/kaZ5kn2+1LidoICar/wPKaSb3H2mi9+v16sTAhOZAvMtaQBiLwANOP64BHxXQVwJdo+zbuIaYo+Me7+4ewQ60DSdxlCTNB98PB6PqBDZp/+v6HP2IEUA2WwsdHaTAi9MVXrJksLyuY/SILl9u3k+EYP2+BIfjCwz9hqUhY9wLrcfy0CQir+PHQQ1ijzsIQffiAzG+Jqp3JdxGo1m8DvboIzj7LznqyrdDMWtmMCQMEjpaDv9TNn6TVDjaJRE4h75R1rnLrgTczmZsZWW/9uKE9X82ThZIWPXNbziQFqoF5A6cQJMPBecGsIE8sN4xa83Q1lsaIgptS1sV6k6wUutuzUEZdgNEPhFYUvomkKIOH0JAc/t6SE4pmZSzi5TpLApZSzEJRlZ5gvUnzNFpOBQU40hnLhTCd0mNe5aXJJZY9Yqvn+0QdXwP+peahhWVSuLLcg2AvDTyM+RhucIFYew84bdXLkewENTvqFjF6rgpK1Jwb9XyVNj0FUxBB8G6dzi9D3SmKHkKTpDtQQs6UXQoB2RwyUCuFgrPvUbzeLeeri5y2EHUY3kZPCZj5Qlg7CtJnKX5HHes8fZJYEVZt3/l/SfRivg=='), {to: 'string'})); ``` ``` <script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <pre id="a"> </pre> ``` [Download the original source here](https://github.com/Cis112233/MyLang/blob/master/freecell-solver-0.2.1.zip). Use GCC and run `make` then using the guideline in the readme. My formatting is bad (all the different files are in one code block) and this could be golfed more (12k bytes tho). Any help would be loved! Some of the code is not mine. I used it from a un-copyrighted source. I however fixed the input/output method to be within the challenge (a long task since I am horrible at C (5ish hours)). I also had to re-write much of the code and debug everything. Many thanks to my Dad for helping out and being a rubber duck (and pointing out my memory management errors) and for everyone on TNB who dealt with my angry rants about segfaults and C. [Answer] # Haskell, Score: 4.98M, 7564 Bytes ``` {-# LANGUAGE BangPatterns #-} import Control.Concurrent.Async (race) import Control.Concurrent.Async.Extra (sequenceConcurrently) import qualified Data.Vector as V import qualified Data.List as L import qualified Data.IntSet as S type Deck = String -- a line of the input, s.th. like -- JD 2D 9H JC 5D 7H 7C... type Card = (Int , Int) -- (Suit, Rank) type Cascade = [Card] -- bottom up, i.e. head is the accessible card type Board = V.Vector Cascade -- the whole Board: 16 lots of cascades -- 0..7:tableau, 8..11:cells, 12..15:foundation type Move = (Int , Int) -- 'from' and 'to' board index type Game = (Board, [Move]) -- a Board and the Moves to get there type Strategy = Int idxTbl, idxFnd, idxTblR, idxFrom :: [Int] idxTbl = [ 0.. 7] -- indices of tableau cascades idxTblR = [7,6..0] -- indices of tableau in reverse order idxFnd = [12..15] -- indices of foundations idxFrom = [ 0..11] -- all indices where a card can be moved from (@@) :: Board -> Int -> Cascade -- return cascade at index i (@@) = (V.!) (@!) :: Board -> Int -> Int -- return the rank of the top card at index i brd @! i = snd $ head $ brd@@i (//) :: Board -> [(Int, Cascade)] -> Board (//) = (V.//) -- update from Data.Vector solved :: Board -> Bool solved brd = all ((==13).(brd@!)) idxFnd -- -- -- main :: IO () main = print . sum =<< mapM solveDeck . lines =<< getContents -- applies different strategies and hash functions to a given deck -- does all the concurreny stuff solveDeck :: Deck -> IO Int solveDeck deck = do putStrLn $ "Playing Deck: " ++ deck mvs <- sequenceConcurrently -- try fast hash funtions concurrently [dfs hsh S.empty s startGame | hsh<-[hashCLS, hashCL], s<-[1..4]] let scores = [(length m, reverse m) | m <- mvs, not $ null m] if null scores then do -- unsolvable by fast hash functions, retry with slow hash function mvs2 <- race' (race' (dfs hashC S.empty 1 startGame) (dfs hashC S.empty 4 startGame)) (race' (dfs hashC S.empty 2 startGame) (dfs hashC S.empty 3 startGame)) let score2 = length mvs2 putStrLn $ "Solution: " ++ show (score2, reverse mvs2) return score2 else do -- at least one slow hash function succeeded, return best result let winner = minimum scores putStrLn $ "Solution: " ++ show winner return $ fst winner where !startGame = [(deal deck, [])] race' one two = race one two >>= either return return -- depth first search with a given strategy and hash function dfs :: (Board -> Int) -> S.IntSet -> Strategy -> [Game] -> IO [Move] dfs _ _ _ [] = return [] dfs hashFn seen strat ((brd,mvs):games) | S.member hBrd seen = dfs hashFn seen strat games --skip board if seen before | solved brd = return mvs --solution found | otherwise = dfs hashFn (S.insert hBrd seen) strat (newGames++games) --descend the search space where hBrd = hashFn brd newGames = nextGames mvs brd strat -- one step in search nextGames :: [Move] -> Board -> Strategy -> [Game] nextGames moves brd strategy | mv:_ <- autoMoves = doAuto mv | otherwise = checkMoves $ allMoves strategy where -- all possible from/to combinations except between freecells and only to -- first empty freecell. Based on strategy. allMoves 1 = [(f,t) | f<-fList, t<-tList idxTbl, f<8||f>11||t<8||t>11] allMoves 2 = [(f,t) | f<-fList, t<-tList idxTblR, f<8||f>11||t<8||t>11] allMoves 3 = [(f,t) | t<-tList idxTbl, f<-fList, f<8||f>11||t<8||t>11] allMoves 4 = [(f,t) | t<-tList idxTblR, f<-fList, f<8||f>11||t<8||t>11] allMoves _ = error "allMoves: strategy out of range" -- "from" indices are always ordered by minimum rank in respective cascade fList = L.sortOn (minimum.map snd.(brd@@)) $ filter (not.null.(brd@@)) idxFrom -- order of "to" indices is foundation before freecell before tableau -- * only tableau is subject to strategy -- * only first empty freecell (if any) -- * foundation is "12" for all suits, we'll unravel that later tList idxs | null $ brd@@ 8 = 12: 8:idxs | null $ brd@@ 9 = 12: 9:idxs | null $ brd@@10 = 12:10:idxs | null $ brd@@11 = 12:11:idxs | otherwise = 12: idxs -- checks which moves from 'allMoves' are actually legal and executes -- them returning a list of games checkMoves [] = [] checkMoves (mv@(f,t):mvs) | t == 12 = if fitsFnd then doFnd else checkRest -- to foundation | t < 8 = if fitsTbl then doTbl else checkRest -- to tableau | otherwise = doCell -- to cell (alway empty) where !cscdT = brd@@t !cscdF = brd@@f !cardF@(suitF,rankF) = head cscdF (suitT,rankT) = head cscdT fitsTbl = null cscdT || rankT==rankF+1 && odd (suitF+suitT) fitsFnd = rankF-1 == brd@!(12+suitF) doTbl = (brd // [(t, cardF:cscdT), (f, tail cscdF)], mv:moves) : checkRest doCell = (brd // [(t, [cardF]), (f, tail cscdF)], mv:moves) : checkRest doFnd = (brd // [(t+suitF, [cardF]),(f, tail cscdF)], (f,t+suitF):moves) : checkRest checkRest = checkMoves mvs -- a list of all greedy automoves autoMoves = [(f,12+s) | f <- idxFrom, -- keep all 'from' indices let cascade = brd@@f, not $ null cascade, -- if there's a card in the cascade let (s,r) = head cascade, r-1 == brd@!(12+s), -- and it fits on its foundation let (j,k) = if even s then (13,15) else (12,14), r-4 <= min(brd@!j)(brd@!k) ] -- and it's not too greedy doAuto mv@(f,t) | fCrd:fCrds <- brd@@f = [(brd // [(t,[fCrd]),(f,fCrds)], mv:moves)] | otherwise = error "nextGames: automove from empty cascade" -- -- parsing and dealing decks -- deal :: Deck -> Board deal = foldl putCard emptyBoard . zip (cycle idxTbl) . parse emptyBoard :: Board -- foundation is initialised with dummy cards emptyBoard = -- of rank 0, so that aces fit on them nicely foldl (\b i -> putCard b (i+12, (i,0))) (V.replicate 16 []) [0..3] putCard :: Board -> (Int,Card) -> Board putCard brd (i,crd) = brd // [(i, crd : brd@@i)] parse :: Deck -> [Card] parse [] = [] parse (' ':cs) = parse cs parse ('1':'0':s:cs) = (chrToSuit s , 10) : parse cs parse (r:s:cs) | Just i <- L.elemIndex r " A23456789 JQK" = (chrToSuit s, i) : parse cs parse _ = error "parse: invalid deck" chrToSuit :: Char -> Int -- parity important: reds are even, blacks odd chrToSuit c | Just i <- L.elemIndex c "DSHC" = i chrToSuit _ = error "chrToSuit: invalid char" -- -- hash functions -- hashCLS, hashCL, hashC :: Board -> Int hashCLS brd = foldl (\h r -> h*16+r) c $ map (brd@!) idxFnd where c = foldl (\h l -> h*32+l) 0 $ L.sort $ map (length.(brd@@)) idxTbl hashCL brd = foldl (\h r -> h*16+r) c $ map (brd@!) idxFnd where c = foldl (\h l -> h*32+l) 0 $ map (length.(brd@@)) idxTbl hashC brd = foldl (\h r -> h*16+r) c $ map (brd@!) idxFnd where c = foldl (\h s->h*26633+s) 0 $ L.sort $ map (hCscd.(brd@@)) idxTbl hCscd cList = foldl (\v (s,r) -> (v*26633+s)*94291+r) 0 cList ``` The list of games is read via stdin. For each game the output is a pair of the number of moves and a list of moves as (from,to) pairs, where both 'from' and 'to' are indices of board positions. 0 to 7 are the eight cascades, 8 to 11 the four free cells and 12 to 15 the four foundations. E.g. ``` Playing Deck: KS 8S 3C 9D QS 4D JD QH 5C 10H 5D 10C 4H 3D 7H AD KC 6S 2S 8D AH 7C QD 6C 7S KH 8C 6H 2C 9C JH KD 4S 5S AC 10S JS 3S 9S 5H AS 4C 8H QC 6D 2H JC 10D 7D 2D 3H 9H Solution: (85,[(0,8),(0,13),(2,9),(2,10),(2,15),(4,11),(7,6),(2,3),(2,13),(9,0),(4,9),(4,15),(4,14),(5,14),(0,14),(4,14),(5,13),(0,13),(7,14),(5,6),(11,5),(1,11),(5,0),(1,2),(0,5),(1,13),(5,0),(8,3),(7,8),(7,3),(7,12),(11,12),(2,11),(2,3),(2,15),(11,15),(5,11),(5,12),(5,12),(3,12),(0,12),(0,5),(0,2),(0,15),(3,15),(3,12),(11,15),(3,15),(6,15),(1,11),(1,13),(5,13),(3,5),(9,7),(3,9),(6,7),(1,6),(1,13),(3,1),(3,14),(3,12),(3,15),(3,12),(7,12),(6,7),(6,15),(6,13),(1,13),(6,4),(6,3),(6,14),(6,12),(3,12),(8,12),(10,14),(5,14),(7,14),(4,14),(7,13),(4,13),(0,13),(7,14),(9,15),(2,15),(11,14)]) ``` At the end the total number of moves is printed. How it works: The basic approach is a depth first search. As the quality of the search (both number of moves and search time) heavily depends on the search order, I try several orders concurrently and pick the result that finishes first: * two different nested loops + for each available card look where it can be placed + for each position look if a card from elsewhere fits on it * when looping over the destination try in order + foundation before free cell before tableau from left to right + foundation before free cell before tableau from right to left That's four different orders (or strategies as I call them) in combination. Source order is the same for all strategies: sorted by minimum rank of all cards in the respective cascade/freecell. There's also autoplay, i.e. if a card can safely be placed in the foundation it's the only move in this situation. It turns out that a greedy autoplay leads to slightly better results, so I autoplay up to two additional ranks (e.g. autoplay 8s even if 5s of opposite color are still around). However, all this is not good enough (5 games do not finish within reasonable time; about 14.7M moves for the rest), but I had a lucky find: somehow you have to keep track of the boards visited so far to prevent infinite loops during the search. The above method uses a hash which is calculated by rolling through the cascades and including suit and rank of all the cards along the way. Now we are just hashing the length of each cascade plus the top foundation cards (i.e. two boards result in the same hash if (and only if) the foundations are equal and all cascades in order have pairwise the same length). Yes, we do get a lot of collisions but they restrict the search space at pretty good spots and lead to far fewer moves in far less time. In fact, the search is so fast that we can afford to finish all four strategies and pick the best result. A similar hash function where for collision the matching length of a cascade can be anywhere in the tableau and not necessarily at the same index produces even better results - at least on average. Now we can try 8 variants (2 fast hash function with 4 strategies each) and pick the best result. Note: not all variants can solve every game but just one success is enough to get a result. There are 11 games (including the unsolvable #11982) which none of the variants can solve. In these cases I switch back to the slow hash function and pick the fastest result. Using 4 cores on my laptop this solves all games in about 1.5h and a total of 4.98M moves. Remarks * The total number of moves can vary by a few hundred, because the result of the games with the slow hash function depends on how the OS assigns CPU time to the strategies and in different a run a different strategy might finish first. But that's just for 10 games. * If I let all 12 variants (3 hash functions with 4 strategies each) race agains each other and pick the fastest result I get 7.25M moves in 250 sec. * The source code is not golfed at all. Removing unnecessary things like comments, types, type annotations, whitespace, error handling and switching to single letter names easily brings the byte count to a third and then we can still apply the usual golfing tricks. ]
[Question] [ Write a program that creates a two-state [checkbox](https://en.wikipedia.org/wiki/Checkbox) that people can interact with using a mouse. Specifically, your program should achieve all of the following: 1. Have a 8×8 pixel (or larger if desired) region of the screen that is the clickable area of the checkbox. Henceforth this region is simply called the checkbox. 2. When the mouse cursor is moved within the checkbox and the default\* mouse button is pressed, the checkbox should toggle states. Checked becomes unchecked. Unchecked becomes checked. 3. The checkbox should not move when it is toggled. 4. In the checked state, the checkbox may be any colors. 5. In the unchecked state, the checkbox may be any colors **as long as at least 16 pixels are visually distinct from the checked state**. 6. In a single program instance, all checked states should be visually identical to one another and all unchecked states should be visually identical to one another. 7. Don't end the program until it's explicitly terminated (e.g. via exit button or Alt+F4), so a user can click the checkbox as much as they want. \*You may assume the default mouse button is always left click, but it's also fine to use the default as defined by mouse software or the OS, which may not actually be left click depending on the user. # Notes * It does not matter what is outside of your checkbox region. It could just be the desktop. It could be a portion of a console that changes on every toggle. * It does not matter what state your checkbox starts in. * The checkbox region may have any dimensions at or above 8×8 pixels. It need not be square. * You may make minor allowances for settings that are out of your control such as console font size, browser zoom, monitor resolution, etc. As long your program works in a reasonable test setting it should be valid. * If your program opens a window, you may assume it has been dragged to an appropriate location on the screen if necessary (e.g. top left corner). * You may use markup languages such as HTML or other languages [we usually don't consider](http://meta.codegolf.stackexchange.com/q/3610/26997) as full-fledged programming languages. * Your checkbox *must* be be toggleable using the default mouse button. It's alright if it also toggles for other forms of input (e.g. right mouse button), **with the exception of mouse motion**. i.e. the state should not change if the mouse is merely moved within the checkbox. * **Screenshots of your checkbox in action are highly encouraged!** # Scoring The shortest code in bytes wins. # Example A canonical HTML example in 23 bytes. ``` <input type="checkbox"> ``` For me in Google Chrome, this makes a 12×12 pixel checkbox and about 30 pixels clearly change between checked and unchecked states. I make the allowance that browser zoom is at 100%. [Answer] ## Mathematica, 10 bytes ``` Checkbox[] ``` Assumes Mathematica's [notebook environment](http://meta.codegolf.stackexchange.com/a/7844/8478). The two states look like this: [![enter image description here](https://i.stack.imgur.com/xAOnK.png)](https://i.stack.imgur.com/xAOnK.png) [Answer] ## HTML, 20 bytes Don't know how valid this will be as an answer. HTML requires the tag to be closed to legally validate, but modern browsers will automatically close them so it's executable. ``` <input type=checkbox ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~67~~ ~~55~~ ~~50~~ ~~35~~ ~~32~~ 31 bytes ``` :()(read -p$[i^=1] ›?9h -sn6 :) ``` The code contains a CR byte (first newline) and a CSI byte (small right angle bracket with the Windows-1252 encoding). It requires xterm (or equivalent) and the ISO-8859-1 encoding (or similar). The code defines a function named `:`, which alternately displays a white **1** or **0** in a black rectangle. There are exactly 24 differing pixels with xterm's default settings. ([proof](https://i.stack.imgur.com/Xovkr.png)) For an older version that toggles the color of the entire terminal, check [revision 10](https://codegolf.stackexchange.com/revisions/109186/10) of this answer. *Thanks to @ais523 for suggesting* xterm, *which saves 4 bytes!* ### How it works `:(...)` creates a function named `:` that executes `...`. The *read* command does the actual magic. * `-p` specifies an input prompt, which is printed to STDOUT. + `$[i^=1]` is an arithmetic expansion which XORs the variable **i** with **1**. **i** may initially be unset; when this occurs, it will be treated as **0**. + The carriage return places the cursor back at the beginning of the line. + `›?9h` captures the mouse in supported terminals. Each click will send six characters to the terminal, namely `←[Mbxy`, where `←` represents the ESC byte (**0x1b**). `←[` indicates an escape sequence, `M` the mouse, `b` the button (**0x20** + the button number), `x` the **x** coordinate of the click (**0x20** + coordinate), and `y` the **y** coordinate. + `-sn6` makes *read* silent (the mouse input won't be echoed to STDERR) and stops after reading exactly 6 bytes. It saves the input in the **REPLY** variable, but we're not interested in the output it produces. Finally, once *read* finishes (after exactly one mouse click), `:` recursively calls itself, entering an infinite loop. ### Creation and invocation ``` $ echo $':()(read -p$[i^=1]\r\x9b?9h -sn6\n:);:' > checkbox.sh $ xxd -c 17 -g 1 checkbox.sh 0000000: 3a 28 29 28 72 65 61 64 20 2d 70 24 5b 69 5e 3d 31 :()(read -p$[i^=1 0000011: 5d 0d 9b 3f 39 68 20 2d 73 6e 36 0a 3a 29 3b 3a 0a ]..?9h -sn6.:);:. $ LANG=en_US xterm -e bash checkbox.sh ``` ### Output ![screencast](https://i.stack.imgur.com/slje9.gif) [Answer] # GitHub Flavored Markdown - 6 bytes ``` - [ ] ``` (There is a trailing space) In a gist : [![check/not check](https://i.stack.imgur.com/h5pfU.gif)](https://i.stack.imgur.com/h5pfU.gif) [Answer] # HTML + JavaScript, ~~32~~ ~~30~~ 25 chars ``` <p onclick=innerHTML^=1>0 ``` [Answer] # Processing, ~~78~~ ~~66~~ ~~65~~ ~~63~~ 61 bytes *2 bytes saved thanks to @TuukkaX by using `-a%2` instead of `a%2*-1`* *2 bytes saved thanks to @TuukkaX by using `a=-a`* ``` int a=1;void draw(){background(a);}void mousePressed(){a=-a;} ``` The checkbox alternates between being black and white. ### Explanation ``` int a=1; //the variable that contains the state of the checkbox void mousePressed(){a=-a;} //if the mouse is pressed, change the sign of a ``` Now there are many other alternatives like using an if-statement to process this, but then it gets weird and constantly changes the background while the mouse is being pressed. I first tried `mouseButton`, but then I would need more conditions and more code that will just end up much more verbose. Now for `mousePressed()` to be called forever (otherwise it would just stop after the program has just started), we need a `draw()` function. ``` void draw(){ //loop infinitely background(a); //set the sketch's background to -a%2 //if a == 1, the background colour is set to almost black //if a == -1, the background colour is set to white } ``` [![enter image description here](https://i.stack.imgur.com/dlqoF.gif)](https://i.stack.imgur.com/dlqoF.gif) --- A smaller checkbox would be 90 bytes (the checkbox is in the top left corner, so we can remove some mouse conditions): ``` int a=1;void draw(){fill(a);rect(0,0,8,8);}void mousePressed(){if(mouseX<9&mouseY<9)a=-1;} ``` [Answer] # Unix Shell (+x11-apps), 3 bytes **Disclaimer** The answer below is boring, borderline and "feels cheating" (at least to me). Yet, it does not seem to violate any of the challenge rules "as written", or "default loopholes", so I'm posting it. (If you can point a specific rule it breaks, please comment on !) **Golfed** ``` xgc ``` > > The xgc program demonstrates various features of the X graphics primitives. > > > The *xgc* screen is actually filled with various checkboxes: [![enter image description here](https://i.stack.imgur.com/ywEti.gif)](https://i.stack.imgur.com/ywEti.gif) and "sticky buttons" (which qualify as checkboxes, under this challenge rules): [![enter image description here](https://i.stack.imgur.com/bvZZe.gif)](https://i.stack.imgur.com/bvZZe.gif) [Answer] # [AHK](https://en.wikipedia.org/wiki/AutoHotkey), 25 bytes ``` Gui,Add,Checkbox Gui,Show ``` Output - [![Mouse pointer is not captured in this gif](https://i.stack.imgur.com/OOMDk.gif)](https://i.stack.imgur.com/OOMDk.gif) [Answer] # Scratch, 2 blocks ![enter image description here](https://i.stack.imgur.com/T77Vb.png) Put this script in the default sprite (which comes with 2 costumes) [Answer] ## Python REPL, 45 bytes ``` from tkinter import* Checkbutton(Tk()).pack() ``` [Answer] # [GeoGebra](https://www.geogebra.org/), 10 bytes ``` Checkbox[] ``` Entered into the input bar. Here is a gif of the execution: [![Program execution](https://i.stack.imgur.com/CYyFS.gif)](https://i.stack.imgur.com/CYyFS.gif) [Answer] # Tcl/Tk, 21 byte **Golfed** ``` grid [checkbutton .c] ``` [![enter image description here](https://i.stack.imgur.com/roKj6.png)](https://i.stack.imgur.com/roKj6.png) [Answer] # HTML with JavaScript - ~~136~~ ~~124~~ ~~120~~ ~~115~~ ~~113~~ ~~111~~ ~~109~~ 79 bytes ``` <p style=height:20;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''> ``` -2 with thanks to @KritixiLithos Reduced to 79 after some fantastic golfing from @Jan. Although the new version fits the requirements I have kept the old version for professional pride reasons. While it is perfectly valid to use built-ins, I thought it was more fun to create my own from scratch. Tested with Chrome and Firefox. `border:solid` is there for IE compatibility but I don't know if it is actually needed in newer IE versions - I don't have IE available to test. The `px` in the height is there for the benefit of "Run code snippet" so is not included in the "real" byte count. It works fine in the browser without it. ``` <p style=height:20px;border:solid onClick=t=this;t.innerHTML=(t.e=!t.e)?'x':''> ``` Previous version: ``` <p id=d style="width:20px;height:20px;border:solid 1px"onClick="d.innerHTML=d.innerHTML=='x'?'':'x'"align=center> ``` [Answer] # Minecraft 1.0.0, 1 byte A lever in Minecraft meets all the criteria for a check box. This answer is only valid for older versions of the game where punching a lever still toggles it. [![enter image description here](https://i.stack.imgur.com/eRnQ0.gif)](https://i.stack.imgur.com/eRnQ0.gif) [Scored using @Connor O'Brien's suggested byte count.](http://meta.codegolf.stackexchange.com/a/7397/44713) [Answer] ## Any version of Windows command line, 3 bytes **(cmd.exe, batch, powershell, start->run, whatever)** ``` osk ``` Opens the on-screen-keyboard which has several "checkboxes" such as shift, ctrl, alt, capslock keys Similar to the xgc answer, and inspired by the SmileBASIC answer screenshot. [Answer] # TI-Basic, 15 bytes ``` While 1:Shade(0,9:Input :ClrDraw:Input :End ``` Fairly straightforward. The checkbox covers approximately 40% of the screen and alternates between black and white. When checked, the screen will look something like this: > > [![screen](https://i.stack.imgur.com/1zC6X.png)](https://i.stack.imgur.com/1zC6X.png) > > > [Answer] # Octave, ~~36~~ 20 bytes ``` uicontrol('sty','c') ``` Thanks to @LuisMendo saved 16 bytes! [Answer] # [KV Lang](https://kivy.org/docs/api-kivy.lang.html), 8 bytes ``` CheckBox ``` [![enter image description here](https://i.stack.imgur.com/slR06.png)](https://i.stack.imgur.com/slR06.png) --- assuming a really basic Python environment for kv lang to even run: ``` from kivy.app import runTouchApp from kivy.lang import Builder runTouchApp(Builder.load_string('CheckBox')) ``` This works basically because `CheckBox` is a Kivy widget included in a [`kivy.Factory`](https://kivy.org/docs/api-kivy.factory.html) as each widget from the standard library. That simple string creates an instance of [`CheckBox`](https://kivy.org/docs/api-kivy.uix.checkbox.html) and because of `runTouchApp` expecting a widget to run I can use `Builder.load_string`. The background of `load_string` handles basically every kv string and if there is a single instance of a widget defined (e.g. `CheckBox`), then it is elevated to a **root** widget position, for example: ``` Application openGL Window root widget(mostly layout) main tree and some widgets ... ``` [Answer] # SmileBASIC, 49 bytes ``` @L O=T TOUCH OUT T,, X=T<O!=X KEY 1,""[X]GOTO@L ``` `` and `` are an empty box and a checked box in SB's font. Toggle the checkbox by touching the screen (the closest thing to clicking with a mouse) [![enter image description here](https://i.stack.imgur.com/F8RSi.png)](https://i.stack.imgur.com/F8RSi.png) [![enter image description here](https://i.stack.imgur.com/n6yWi.png)](https://i.stack.imgur.com/n6yWi.png) # Cheating answers: ### 0 bytes: (the on-screen keyboard has buttons that act like checkboxes, such as the caps lock and insert keys) ### 14 bytes: ``` EXEC"SYS/SBGED ``` Opens up the built in graphics editor, which has multiple checkbox-like buttons [Answer] ## C#, ~~124~~ 120 bytes saved 4 bytes thanks to grabthefish. [![checkbox checked and not checked](https://i.stack.imgur.com/M4YxN.png)](https://i.stack.imgur.com/M4YxN.png) note: because of edits, the picture doesn't exactly represent what the code makes, the "checkBox1" isn't displayed with the current code. ``` using System.Windows.Forms;class P{static void Main(){var a=new Form();a.Controls.Add(new CheckBox());a.ShowDialog();}} ``` ungolfed: `using System.Windows.Forms; class P{ static void Main(){ var a=new Form(); a.Controls.Add(new CheckBox()); ~~Application.Run(a);~~ a.ShowDialog(); } }` [Answer] # Excel VBA, ~~38~~ ~~32~~ ~~31~~ 29 Bytes Immediates Window function that inserts a checkbox of height=9 and width=9, at the cell `A1` on the first sheet of the active Excel VBA project ``` Sheet1.CheckBoxes.Add 0,0,9,9 ``` -6 Thanks to pajonk for replacing `[A1],[A1],9,9` with `0,0,9,9` -1 for replacing `Sheets(1)` with `[Sheet1]` -2 for realizing the above was stupid and using `Sheet1` instead [Answer] # Ruby with Shoes, 16 characters ``` Shoes.app{check} ``` Sample output: ![checkbox created with Ruby](https://i.stack.imgur.com/cAWXV.png) [Answer] ## HTML with JavaScript, ~~46~~ ~~33~~ 28 bytes ``` <body onclick=innerHTML^=1>0 ``` v2 ``` <body onclick=this.innerHTML^=1>0 ``` v1 ``` <body onclick=t=this;t.innerHTML=t.e=!t.e||''> ``` This is a variant on @ElPedro's answer: [Create a Checkbox](https://codegolf.stackexchange.com/questions/109155/create-a-checkbox/109167#109167) . Got down to 28 bytes with the help of @Albert Renshaw It could be further reduced, but that would make it identical to [Create a Checkbox](https://codegolf.stackexchange.com/questions/109155/create-a-checkbox/109295#109295) The whole application area is clickable. It will display `0` in the `off` state and `1` in the `on` state. Try it out at <https://jsbin.com/nuhetiyocu/1/edit> [Answer] # Powershell v5+, 94 Bytes ``` ($a=[Windows.Forms.Form]::new()).Controls.Add([Windows.Forms.Checkbox]::new());$a.ShowDialog() ``` [![enter image description here](https://i.stack.imgur.com/uwYtO.png)](https://i.stack.imgur.com/uwYtO.png) [![enter image description here](https://i.stack.imgur.com/OhQVI.png)](https://i.stack.imgur.com/OhQVI.png) This is pretty terrible, but I can't get the statements any shorter with either `Add-Type` or `using namespace` - and the variable is required, since I need to reuse the object to show the form, and `Controls.Add()` returns nothing usable. `ShowDialog` is required on my system to have the box be interactive after running this command, otherwise the form is frozen. also `System.Windows.Forms.Form` can only be shortened to `Windows.Forms.Form` before (at least my own) system stops auto completing it in a fresh session. [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 273 bytes **To show the checkbox:** ``` createDialog"b" ``` **But first it must be defined:** Save the following to a file named `description.ext` in the mission folder: ``` class b{idd=999;movingEnable=1;class controls{class c{idc=457;x=0.1;y=0.1;w=0.1;h=0.1;text="";action="if(ctrlText 457=={})then{ctrlSetText[457,{V}]}else{ctrlSetText[457,{}]}";type=1;style=2;colorText[]={1,1,1,1};font="tahomaB36";sizeEx=0.1;}}} ``` **The checkbox in action:** [![](https://i.stack.imgur.com/BbhSK.gif)](https://i.stack.imgur.com/BbhSK.gif) [Answer] ## VBA (Word), ~~74~~ 57 bytes -17 thanks to Taylor Scott ``` Sub a() f = a.FormFields.Add(Selection.Range, 71) End Sub ``` Filename of the document should be a. [Answer] # Pug, 20 bytes ``` input(type=checkbox) ``` [Answer] # Clojure, ~~201~~ ~~195~~ ~~145~~ 127 bytes ``` (ns c(:require[quil.core :as q]))(def a(atom nil))(q/defsketch b :draw #(q/background(if@a 0 99)):mouse-clicked #(swap! a not)) ``` -6 bytes by getting rid of the need for `m/fun-mode`. -50 bytes by removing the `:setup` and `:size` options, since they are defaultable and unnecessary in non-`fun-mode`. Also removed the unnecessary import for middleware. -18 bytes thanks to @ASCII-only. Changed to "smaller" colors, and removed an unnecessary space before the dereference operator (`@`). Creates a [Quil](http://quil.info/) sketch (a Clojure library that provides a layer over Processing), therefore, this requires the Quil library to run. ``` (ns bits.golf.checkbox (:require [quil.core :as q])) ; Mutable global variable to hold the toggle state (def a (atom nil)) (q/defsketch b ; Draw the background color to be either black or red depending on the toggle state. :draw #(apply q/background (if @a [0 0 0] [255 0 0])) ; Negate the state on mouse click :mouse-clicked #(swap! a not)) ``` [![enter image description here](https://i.stack.imgur.com/hmafV.png)](https://i.stack.imgur.com/hmafV.png) [![enter image description here](https://i.stack.imgur.com/cjTxf.png)](https://i.stack.imgur.com/cjTxf.png) [Answer] # [AutoIt](http://autoitscript.com/forum), 78 Bytes ``` GUICreate(0) GUISetState(GUICtrlCreateCheckbox(0,0,0)) Do Until GUIGetMsg()=-3 ``` Opens a maximized window that can be closed like any other windows window. The maximization and ... on-top-ness is a side effect of the golfing. [![enter image description here](https://i.stack.imgur.com/Er50U.png)](https://i.stack.imgur.com/Er50U.png) [Answer] ## Python, 62 bytes ``` from tkinter import* a=Tk() Checkbutton(a).pack() a.mainloop() ``` ]
[Question] [ Make a program that takes the word you input, and adds that word to the back of itself minus its first letter, then repeats until all letters are gone. For example, `cat` would become `catatt`, and `hello` would become `helloellolloloo`. **Input** Any of the 26 letters of the English alphabet. There may be multiple words separated by spaces, and the change should be applied to every word. **Output** The word(s) inputted, with each word put after itself with its first letter missing, and then with its second letter missing, and so on until there are no more letters to add. **More examples:** `ill eel` outputs `illlll eelell` `laser bat` outputs `laserasersererr batatt` `darth vader` outputs `dartharthrththh vaderaderdererr` This is code golf, so the shortest code wins. Clarification: You can treat the input or output as a list. You can separate words using newline instead of space. You can add a trailing space to the input. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~60~~ 56 bytes ``` ,[>++++++++[-<----<++++>>]<[>>]<[[<]>.[[-]>[.>]<[<]>]],] ``` [Try it online!](https://tio.run/##LYdBCoAgEAC/svfUFyz7kWUPJSuJoFEG/X7TaA7DzHauuaY7FjPHtPywRz/A2USC/IlRKDB7IQ7zx4o4MWsV@q7Q25EjtAT65KtrjQov "brainfuck – Try It Online") Requires a trailing space and prints a leading space. Both of these could be circumvented, but that ends up at [112 bytes](https://tio.run/##VYtLCoAwDESv0n0/Jwi5SMhCS8UitKIVvH1MpS4cSJiZ5M3HlMtyxU3EEdoh8uBV0D0iA72LgJG8DoUeR@IBfKyegvbsxgtpYbv7kQ5ZpBbT1mRa3XM0dTHpzmdLJaYH "brainfuck – Try It Online"). ### Explanation ``` ,[ Loop over each byte of input Tape: 32 w o r-32 d' >++++++++[-<----<++++>>] Subtract 32 from the character and add 32 to the previous char Tape: 32 w o r d-32 0' <[>>]< If the last character was a space Tape: 32 w o r d-32 0' or Tape: 32 w o r d' space-32 [ [<]>. Move to the end of the word and print out the space [ Loop over each letter [-] Remove the first letter (initially space) >[.>] Print the rest of the word <[<]> Move back to the first letter ] Tape: clear ] ,] Get the next byte of input ``` [Answer] # Japt `-m`, ~~6~~ 3 bytes Input and output are arrays of words. ``` £sY ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=o3NZ&input=WyJjb2RlIiwiZ29sZiJdCi1tUw==) --- ## Explanation ``` :For each word in the input array £ :Map each letter at index Y sY : Slice the current word from index Y ``` [Answer] ## Haskell, ~~36~~ 21 bytes ``` map$concat.scanr(:)"" ``` [Try it online!](https://tio.run/##XcsxCoAwDADA3VeE0EFBfYDQl6hDiK0txrRY3291dj24QOVwItXbpZ6UDSdlusfCpFc7dYifRgULW2oA8hX1BgMeZgxfS7j@NIpgD@ic4Fof9kJ7qQPn/AI "Haskell – Try It Online") Edit: -15 bytes, because of new IO format (list of words instead of space separated words) [Answer] # [Python 3](https://docs.python.org/3/), 49 bytes ``` d=lambda s:' '.join(n+d(n[1:])for n in s.split()) ``` [Try It Online!](https://tio.run/##VcixCsJADADQ3a8IXZogFMSt4JeIQ0pOGom5IxcEv/50Enzja@/cq5/HkIvxcxOGvs4wL4@qjn4U9OtpvdG9BjioQ196M00kGi3UEwUnNYNSbCI6/M64l4CN82@FI3d4sZT4/vgA) This takes advantage of the fact that `"".split()` returns an empty array so that acts as the check for the base case in the recursion. [Answer] ## Perl `-p`, ~~36~~ ~~25~~ 23 bytes ``` s!\b|\S!$'=~s/ .*//r!eg ``` [Try it online!](https://tio.run/##K0gtyjH9/79YMSapJiZYUUXdtq5YX0FPS1@/SDE1/f9/j9ScnHyF8PyinJR/@QUlmfl5xf91CwA) This is a single regsub. First, it matches all word boundaries or non-space characters: ``` [][H][e][l][l][o] [][W][o][r][l][d] ``` Note that each of these matches should be replaced with the rest of the word: ``` [→Hello][H→ello][e→llo][l→lo][l→o][o→] (...) ``` We can accomplish this with the special variable `$'`, which stores the part of the string after the match. However, we need to apply the nested regsub `s/ .*//` to it, which removes everything past the first space in `$'`, in order to get rid of the remaining words in the input. Thanks to [@nwellnhof](https://codegolf.stackexchange.com/users/9296/nwellnhof) for 2 bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` ḊƬ€ ``` [Try it online!](https://tio.run/##y0rNyan8///hjq5jax41rQEyNh1u9/7/Xz0lsagkQ6EsMSW1SB0A "Jelly – Try It Online") Don’t need the `K`s anymore since array input/output is now allowed. ``` ḊƬ€ € For each word: Ḋ Remove the first letter Ƭ until there are none left. ``` [Answer] # APL(Dyalog), ~~19~~ 9 bytes `{⌽∊,\⌽⍵}¨` *thanks to @H.PWiz for jogging my brain* This works because all strings in APL are character arrays. ``` {⌽∊,\⌽⍵}¨ ¨ - for each string ⍵} - string argument - ex. "hello" ⌽ - reverse - "olleh" ,\ - scan magic - "o" "ol" "oll" "olle" "olleh" ∊ - enlist(join together) "oolollolleolleh" {⌽ - reverse - "helloellolloloo" ``` [TIO](https://tio.run/##SyzI0U2pTMzJT///v/pRz95HHV06MSC6d2vtoRXYxDTUFdQfdcx41LngUVfbo65FmuoZqTk5@Qrl@UU5KepcxGjIzMlRSE3NIU5xTmJxapFCUmIJccpTEotKMhTKElNSi9QB) [Answer] # JavaScript (ES6), 33 bytes *Saved 1 byte thanks to @ShieruAsakoto* I/O format: array of words. ``` a=>a.map(g=w=>w&&w+g(w.slice(1))) ``` [Try it online!](https://tio.run/##bcpBDoMgEADAex8iu7GS@AD8SONhhZXSbMUAkedTzo3nmQ9dlG0KZ5mO6LjtppFZSH/pBG@qWeow1NFD1VmCZZgRsdl45CisJXrY4aWCiHoqZlEr4uNfhTKn7huVW3eUyrv7Ra6/PtoP "JavaScript (Node.js) – Try It Online") --- # JavaScript (ES6), 35 bytes I/O format: array of words. ``` a=>a.map(w=>w.replace(/./g,"$&$'")) ``` [Try it online!](https://tio.run/##bcpNDsIgEAbQvcdoGgeSSk9AL2JcfML0L2MhQNrjI2vj@r0dJ7JLWyyPI3ius62wE8wHUV12ukziKHCsRjMuQ9ffe@q0ri4cOQgbCYua1ZM2ERqIWeil9e1XBZlT8zfKX/dIZW1@wrfXRv0C "JavaScript (Node.js) – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~82~~ ~~75~~ 67 bytes ``` write(sapply(x<-scan(,""),substring,1:(y=max(nchar(x))),y),1,y,,"") ``` [Try it online!](https://tio.run/##FcrBCoAgDADQXwlPG6yD16iPWSoplMhmpV9v9M5Pxngl1QDKpZwd2jqr4wxkDJLeu1ZJ@SC7QN8ubpBdZIGGiNSRLHX65/AsNU4P@yDjAw "R – Try It Online") *Several bytes saved thanks to [JayCe](https://codegolf.stackexchange.com/users/80010/jayce)* Separates output with newlines. The `sapply(...)` expression generates a matrix/column vector of the appropriate substrings, padding with `""` as needed. `write` then prints the elements of the matrix, `y` per line, separating them with `""`. [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), ~~94~~ 93 bytes ``` -[-[-<]>>+<]>-<<+[[[-]<,[->+>+<<]>[-<+>]>>[-<->>+<]<]<<[>>+<<[-]]<[<]>[[.>]<[<]>[-]>]>>>>.<<] ``` [Try it online!](https://tio.run/##LYtRCoAwDEOv0v/ZnaD0ImUfOiYOYROd4O1nJhJoQvK6nHMu6x333tkgCaoOh0WcmXGQyVgdOpSYnQKA84dBYiMJyCA2GPP6Jw4DVvX47b0WaluiVo8cqa6Unny1VGKiFw "brainfuck – Try It Online") * Saved one byte thanks to [Nitrodon](https://codegolf.stackexchange.com/users/69059/nitrodon) -- golfing `.[-]>[.>]<[<]>` to `[.>]<[<]>[-]>`. # Explanation ``` [[[ (dynamic) tape layout: ... NUL STR ... STR CHR FLG BUF SPC NUL ... ]]] load a 32 into SPC -[-[-<]>>+<]>- while FLG <<+[ read a word [ clear FLG; read CHR [-]<, copy CHR to BUF (using FLG as a temporary) [->+>+<<]>[-<+>] subtract SPC from BUF and save SPC >>[-<->>+<] move tape layout one to the right < ] strip trailing space; set FLG to true << [>>+<<[-]] to STR's first character <[<]> print word in all reduced forms [ [.>]<[<]>[-]> ] print SPC; move to FLG >>>>.<< ] ``` [Try it online!](https://tio.run/##TVC7TsMwFN39FWejVUkG2KjlgUqFoUKoj8nK4DpOa5HEke1Q8vXh2mVAkRLH597zOntl@2bUX/MspcSinnrVWb1EVINBqyY3xheUZYmP0w6H4z6f03fzvsd294bX0xaHz03GE1ZVFWOtUzUUnp9g@@gSzgpJD6@EWNGrYOx2ta1JDIzzlWQM3uSdm/M1g2SAbo3yaWJ9x0iRbmVR8ceEumHKJog/eViMwfaXbEkF4ommG5xXflrmJbEiYVImDytR0VUYz9ErHbP5xrsus6i@RlDfJlsGRJovsmf66xwB/4qB602Sj1cDby/XSDOcgfIjRG8HkIBtk6swKG3WCCZmg2nHj4aBc8jEzikVKaSqjvuHgMb6EKGvKjk0ngYleWcYPPWZK6JiodqWmqlHbWo0znfh3pssRZXniVTc7dz3KNP6L4TLzVM@IUrOWTXPrs85ohushmtgfmyIptcGvw "brainfuck – Try It Online") # Attribution Esolang's [brainfuck constant collection](https://esolangs.org/wiki/Brainfuck_constants#32) was used for the initial space load. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` €.síJ ``` [Try it online!](https://tio.run/##yy9OTMpM/W/q9v9R0xq94sNrvf7r/I9WSk4sUYrlilbKSM3JyQezMnNylHQUlFJTc8DcnMTi1CKQQBJUZUpiUUkGSKAsMQUoEwsA "05AB1E – Try It Online") **Explanation** ``` €.s # push suffixes of each í # reverse each J # join suffixes ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~6~~ 4 bytes -2 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan) (taking input as a list)! ``` moΣṫ ``` [Try it online!](https://tio.run/##yygtzv7/Pzf/3OKHO1f///8/WiknsTi1SElHKSmxRCkWAA "Husk – Try It Online") ### Explanation Takes input as a list of strings and maps the following function: ``` Σṫ -- example argument: "abc" ṫ -- tails: ["abc","bc","c"] Σ -- concat: "abcbcc" ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes ``` ¶ . $&$%' ¶ ``` [Try it online!](https://tio.run/##K0otycxL/P9fgevQNi49LhU1FVV1EFPh//@UxKKSDIWyxJTUIgA "Retina 0.8.2 – Try It Online") Note: trailing spaces. Explanation: ``` ¶ ``` Split on spaces. ``` . $&$%' ``` Append its suffix to each letter. The `%` means that we only get the word's suffix. ``` ¶ ``` Join with spaces. [Answer] # [Vim](https://www.vim.org/), 47 bytes (38 key strokes) Start with your input as the sole line in a Vim buffer. ``` :s/<Space>/\r/g<CR>ggqaywPlxqqb99@aj0q99@bgg99J ``` ## Explanation This puts each word on its own line, iterates over each line, then rejoins them all. Breaks if words are longer than 99 characters or if your input has more than 99 words. 1. `:s/<Space>/\r/g<CR>` [replaces](http://vim.wikia.com/wiki/Search_and_replace) spaces with new lines (`\r`) 2. `gg` positions the cursor at the beginning of the first line 3. `qa` begins recording [macro](http://vim.wikia.com/wiki/Macros) *a*: * `yw` yanks the rest of the word * `P` [puts it behind the cursor](http://vimdoc.sourceforge.net/htmldoc/change.html#P) * `lx` removes the first letter of the latter word * `q` stops recording macro *a* 4. `qb` begins recording macro *b*: * `99@a` executes macro *a* ninety-nine times (introduces the character limit) * `j0` positions the cursor at the start of the next line * `q` stops recording macro *b* 5. `99@b` executes macro *b* ninety-nine times (introduces the word limit) 6. `gg` positions the cursor at the first line 7. `99J` [joins](http://vimdoc.sourceforge.net/htmldoc/change.html#J) the following ninety-nine lines with spaces (word limit again) For another 2 bytes (2 key strokes) you could extend the word limit to 999. Another 4 bytes, 9999, etc. [Answer] # [Pepe](//github.com/Soaku/Pepe/), ~~167~~ 153 bytes ``` REEerEeeEeeeeeRrEEEEerEEEEEeerEErEEeerreErEEeErreEREEEEEEEreereErEerEEEErEEeerrEEreRRErEEEEreREEreeereReeRerEEEEEErEEEeerreEerEEeerEEEEerEEeEreereErEeree ``` [Try it online!](//soaku.github.io/Pepe/#T!8g--gE0E!k@A!m@AE7*AC!q!k@E$-&!q$FG$/.&2-c@K!k-g!m*AC*) [Answer] # 16-bit x86 assembly code, 24 bytes ``` 47 inc di B020 mov al,20h l1: 3806 cmp [si],al 7212 jb l5 ;less means end of string 7401 je l2 ;equal means space was seen 4F dec di ;overwrite extra space l2: E80300 call l3 46 inc si ;move to next character in word 75F1 jne l1 l3: 56 push si l4: 3806 cmp [si],al A4 movsb ;copy character 77FB ja l4 ;until either zero or space is seen 5E pop si l5: C3 ret ``` Call with si = pointer to source string, di = pointer to output buffer. The source string requires a zero byte to end it. The code is the same in 16- or 32- or 64-bit (si/di become either esi/edi or rsi/rdi). 32-bit code is two bytes larger because of the expanded call. 64-bit code is three bytes larger still because the inc/dec of rsi/rdi attracts a prefix (but if it is known that they are within 32-bit memory space, then they can be esi/edi again to avoid that penalty). [Answer] # [MATL](https://github.com/lmendo/MATL), ~~18~~ 16 bytes ``` "@gXH"HX@Jh)]0&h ``` Input is a cell array of words. [Try it online!](https://tio.run/##y00syfn/X8khPcJDySPCwStDM9ZALeP//2r1nMTi1CJ1BfWkxBL1WgA) ### Explanation ``` " % Implicit input: cell array of strings. For each cell @g % Push content of current cell, that is, a word XH % Copy into clipboard H " % For each letter H % Push word X@ % Push iteration index Jh) % Index from that until the end into current word ] % End 0 % Push 0. Will be cast to char. Char(0) is displayed as space &h % Concatenate horizontally all elements so far. Implicit display ``` [Answer] # [K4](http://kx.com/download) / [K (oK)](https://github.com/JohnEarnest/ok), 9 bytes **Solution:** ``` ,/'(1_)\' ``` [Try it online!](https://tio.run/##y9bNz/7/X0dfXcMwXjNGXUMpJbGoJEPJWqksMSW1SEnz/38A "K (oK) – Try It Online") **Explanation:** ``` ,/'(1_)\' / the solution ' / apply to each \ / scan ( ) / do this together 1_ / drop first ,/' / flatten (,/) each (') ``` [Answer] # [C++ (clang)](http://clang.llvm.org/), 174 bytes ``` #include<map> #include<string.h> std::string r(std::string w){while(auto x=strchr(w.c_str(),32))return r(w.substr(0,x-w.c_str()))+" "+r(x+1);return w!=""?w+r(w.substr(1)):w;} ``` [Try it online!](https://tio.run/##hY5BbsIwEEX3OYVrNh4FUGl3iUmPUhnbwpYmTjSxcSTE2UMoVYTYZDf/zZvR132/06jCeZo2PmhMxspW9U2xpCGSD@e9a4ohmqp6RkbiNWW4ZufRCpVix8bjjLUjkff6dx4FbL@/AMjGRIE98JBOD/65HXeLA1ByxksSY3mA@l/OH0fOf3L5cnQAqHJ9W@oy6buZW9U2hQ@RtcoHAddnW92lKKUgwT0isxY5gJR/KxsM1u8WqsESO6m44hlF0bGLMpZWTL36y1nE7t25TXc "C++ (clang) – Try It Online") It's my first submission, and i didn't know if returning string instead of printing it is okay :) [Answer] # [Stax](https://github.com/tomtheisen/stax), 3 bytes ``` m|] ``` [Run and debug it](https://staxlang.xyz/#c=m%7C]&i=darth%0Avader&a=1) Explanation: ``` m Map over the lines |] Get all suffixes (suffices?) Implicit flatten and output ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ƛ[Ḣx+ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%5B%E1%B8%A2x%2B&inputs=%5B%27laser%27%2C%27bat%27%5D&header=&footer=) (IMO) this is a really neat recursive solution. Port of my JS answer that came out really nicely. ``` ƛ # Foreach value as n [ # If truthy (Not empty string) x # Call this function (The function we're mapping with) Ḣ # With n[1:] - remove first character + # Appended to the result ``` The "concatenation of suffixes" approach doesn't do any better: # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` ƛṘ¦∑Ṙ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B%E1%B9%98%C2%A6%E2%88%91%E1%B9%98&inputs=%5B%27laser%27%2C%27bat%27%5D&header=&footer=) ``` ƛ # Map... Ṙ # Reverse ¦ # Cumulative sums (prefixes) ∑ # Concatenated Ṙ # Reversed ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes ``` ⪫E⪪S ⭆ι✂ιμLι¹ ``` [Try it online!](https://tio.run/##LYpBCoAgEEX3nUJajVCL1p2gKAg8waCSA2YiU9efjNp8/uM9G7DYE6PIVigxzCclWDGDyZEYppQvNlzVDrpTrWrrfvxGVCGS9e85OrX4tHMAqs2g9d/rUcRh4aBudL400t/xAQ "Charcoal – Try It Online") Note: Trailing space. Link is to verbose version of code. Explanation: ``` S Input string ⪪ Split on spaces E Map over each word ι Current word ⭆ Map over each character and join ι Current word μ Current index ι Current word L Length ¹ Literal 1 ✂ Slice ⪫ Join with spaces Implicitly print ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-s`, 11 bytes ``` J_@>,#_Mq^s ``` Takes the space-separated list of words from stdin. [Try it online!](https://tio.run/##K8gs@P/fK97BTkc53rcwrvj//5zE4tQihaTEkv@6xQA "Pip – Try It Online") ### Explanation ``` s is space (implicit) q Read a line of stdin ^s Split it on spaces M Map this lambda function to each word: _ The word... @> sliced starting at index... ,#_ range(len(word)) This creates len(word) slices ["word" "ord" "rd" "d"] J Join those into a single string The resulting list of modified words is printed; the -s flag uses space as the separator ``` [Answer] # [Python 2](https://docs.python.org/2/), 63 bytes ``` lambda s:' '.join(map(g,s.split())) g=lambda s:s and s+g(s[1:]) ``` [Try it online!](https://tio.run/##TcrBCsIwDADQ@74ityQoAz0O9iXqIaNdV8m60gTBr6@34fXx6te3o9z7Oj@7yr4EAZsQcHwfudAuldLVRquanZh5SPO5DKQEsEsie9ymF/facnFYCbMqxKjIw0kqFhss4v8YpPkGHwmxIfcf "Python 2 – Try It Online") [Answer] # [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md) ``` ±[±]⇵] ``` [Try it here!](https://dzaima.github.io/Canvas/?u=JUIxJXVGRjNCJUIxJXVGRjNEJXUyMUY1JXVGRjNE,i=JTVCJTIybGFzZXIlMjIlMkMlMjAlMjJiYXQlMjIlNUQ_,v=8) [5 bytes](https://dzaima.github.io/Canvas/?u=JUIxJXVGRjNCJXVGRjNEJXVGRjNEJUIx,i=JTVCJTIybGFzZXIlMjIlMkMlMjAlMjJiYXQlMjIlNUQ_,v=8) with a crazy output format [Answer] # C#, 111 90 bytes ``` b=>string.Join(" ",(b.Split(' ').Select(x=>string.Concat(x.Select((y, i)=>x.Substring(i)))))) ``` [Try it Online!](https://tio.run/##hZDBSgMxEIbveYphL01gDXheW5CCgiiILXgQD9PssBtMkzXJlhbps69po3UpFP9DwvzzzTAzKlwp52nog7YNLHYh0rpi40jOnTGkonY2yHuy5LU6Ix61/TyzlrSN51brCetkyCWGj1AxZnFNoUNFME/NnaHbrrtmXwySlMEQ4Nm7xuP66GT/oBAxagUbp2t4Qm15iD71fXsH9E0QJ@6v4qC73qqbTJaQ/xkgTIfVdJZD@eBSswKKkq/kojM68glMhFzQ4QB8e@LSuAqT8ZvhuxK0mM6S0a8yw7U4akh7jqf42VS@eh0pHY448qIlY1whRPU/WqOPLWywJn@x4CXd@ciP8nuW3z0bvgE) By Changing input and output to arrays, I saved a few bytes: ``` b=>b.Select(x=>string.Concat(x.Select((y,i)=>x.Substring(i)))).ToArray() ``` [Try it Online!](https://tio.run/##nVGxasMwEN31FYcnG1xB59SGEGihtFAaQ4fS4SIfsagjpZKSxgR/u3uJ49Z4yNA3CN27p6d7kvI3yjrqdl6bNSwbH2gzE@NKLmxdkwraGi8fyJDTaqJ40uZrQhV0CFOqcoQlE7JA/@lnQhjckN@iIliwua1pvt3eiqMAhqrRe3hxdu1wc2Z6/gQfMGgFe6tLeEZtYh8c@75/ALq1T351fydOuN8ZdTcoUxh2OSBk0K2yfCWXdEoaH7K873J2o5CJoRM3qU6ynOvdqpfEOmHIws6dwyZOOs41vvWSTL45HYgfii7DykfLg0cQpRgb@ubZjxBVVNc2gpYdZ/93KdGFKkoh2mNJ7prdK3/I2W3Ub0W/tqL7AQ) [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~17~~ 13 bytes ``` {,/|:'|,\|x}' ``` [Try it online!](https://tio.run/##y9bNz/7/P81KSUFJv1pHv8ZKvUYnpqaiVv1/moKGUmZOjpK1UmoqiMxJLE4tAtJJiSVAMiWxqCQDSJclpgBFNf8DAA "K (oK) – Try It Online") Prefix anonymous function; Input is taken as a list of strings, which in turn are lists of characters. Thanks @streetster for 4 bytes. ### How: ``` {,/|:'|,\|x}' //Main function, argument x → ("ill";"eel") ' // For each element of the argument |x} // Flip it. x → ("lli";"lee") ,\ // Concatenate each element, keeping intermediates. x → (("l";"ll";"lli");("l";"le";"lee") | // Flip it again. x → (("lli";"ll";"l");("lee";"le";"l")) |:' // Now flip each element. x → (("ill";"ll";"l");("eel";"el";"l")) {,/ // Concatenation scan. x → ("illlll";"eelell") ``` [Answer] # [Common Lisp](http://www.clisp.org/), 179 bytes ``` (defun r(s)(cond((endp s)nil)((eql(first s)#\Space)(princ " ")(r(rest s)))(t(q s)(r(rest s)))))(defun q (l)(cond((eql(first l)#\Space)t)((endp l)t)(t(princ(first l))(q(rest l))))) ``` [Try it online!](https://tio.run/##TY9LDgIxDEOvEpUFznnYskFtRlSK@kmLOP4QZlDFzrGjZzlqHm3fkWR7FTIMRqwlAVJSo8ElK/vRFVu2Md253G/tEYXRLJdIgQLDYHKEzJjoLv4tN098J@jiL6Qu5ORfr37lPBvWF6OfTD2Yu1fEKhaFwlNUK72raQp09UnT8w8 "Common Lisp – Try It Online") This is my first try at golfing any edits are welcome [Answer] # [Lua](https://www.lua.org), 70 bytes ``` for i=1,#arg do x=arg[i]for i=1,#x do io.write(x:sub(i))end print()end ``` [Try it online!](https://tio.run/##yylN/P8/Lb9IIdPWUEc5sShdISVfocIWyIjOjIWLV4BEM/P1yosyS1I1KqyKS5M0MjU1U/NSFAqKMvNKNEDM////Z6Tm5OT/L88vykkBAA "Lua – Try It Online") ### Explanation The arguments in Lua are stored in the table `arg` starting at index 1. The unary operator `#` returns the size of the table and function `s:sub(a,b)` returns a substring based on string `s` delimited by integers `a` and `b`, if b is not passed it will return the rest of the string. I had to use `io.write()` instead of `print()` to avoid line breaking, and added `print()` at the end for the opposite reason. [Answer] # [Python 3](https://docs.python.org/3/), ~~79~~ 74 bytes *-5 bytes thanks to mypetlion* ``` print(*map(lambda x:''.join(x[n:]for n in range(len(x))),input().split())) ``` [Try it online!](https://tio.run/##DchBDkBADADAr/SmFXFx8xVxWLGoVNusFbx@OU0y/ubNtCvFE2vG@giOEo5pDvD0VdXuxorPoP24WAIFVkhB14gS/yeihtWvjNSeLvxLVMoWRQxuSzJ/ "Python 3 – Try It Online") A full program that takes input from stdin and outputs to stdout. ]
[Question] [ Write a function or program that takes as its input a string and prints a truthy value if the string is a [pangram](https://en.wikipedia.org/wiki/Pangram) (a sequence of letters containing at least one of each letter in the English alphabet) and a falsey value otherwise. Case of letters should be ignored; If the string is `abcdefghijklmnopqrstuvwXYZ`, then the function should still return a truthy value. Note that the string can contain any other characters in it, so `123abcdefghijklm NOPQRSTUVWXYZ321` would return a truthy value. An empty input should return a falsey value. --- Test cases ``` AbCdEfGhIjKlMnOpQrStUvWxYz ==> True ACEGIKMOQSUWY BDFHJLNPRTVXZ ==> True public static void main(String[] args) ==> False The quick brown fox jumped over the lazy dogs. BOING BOING BOING ==> True ``` This is code golf. Standard rules apply. Shortest code in bytes wins. [Answer] ## Pyth, 7 bytes ``` L!-Grb0 ``` Explanation: ``` L lambda (implicit b:) rb0 Convert b to lowercase G Lowercase alphabet, "abcd...z" - Set difference, all elts of first that aren't in second ! Logical NOT (The empty string is falsey) ``` Try the full-program, single-line version [here](https://pyth.herokuapp.com/?code=%21-Grz0&input=abcdefghijklmnopqrstuvwxyz&test_suite=1&test_suite_input=abcdefgLGHLS+SLKijkmnol+shai+heargpqrtuvwSIBN%2Cxyz%0Azyxwvutsrqponmlkjihgfedcba%0Azyxwvutsrrrrnmlkjihgfedcba&debug=1). [Answer] ## [Perl 6](http://perl6.org), 20 bytes ``` 'a'..'z'⊆*.lc.comb ``` usage: ``` my &code = 'a'..'z'⊆*.lc.comb; # the parameter is ^ there say code '123abcdefghijklm NOPQRSTUVWXYZ321' # True say code '123abcdefghijklm NOPQRSTUVWXY' # False ``` I used the 3 byte "french" version (`⊆`) of `U+2286 SUBSET OF OR EQUAL TO` operator instead of the 4 byte "texas" version (`(<=)`) which would have also required an extra space in front of it. [Answer] # JavaScript ES6, 51 ~~57~~ **Edit** 6 bytes save thx @user81655 ``` a=>new Set(a.toUpperCase().match(/[A-Z]/g)).size>25 ``` Test snippet ``` F=a=>new Set(a.toUpperCase().match(/[A-Z]/g)).size>25 function update() { O.innerHTML=F(I.value) } I.value='qwertyuiopasdfghjklzxcvbnm';update() ``` ``` input { width: 70% } ``` ``` <input id=I oninput='update()'> <pre id=O></pre> ``` [Answer] # GS2, ~~11~~ 9 bytes ``` ☺ 6ΘàB1." ``` *Thanks to @MitchSchwartz for golfing off 2 bytes!* The source code uses the CP437 encoding. [Try it online!](http://gs2.tryitonline.net/#code=4pi6IDbOmMOgQjEuIg&input=MTIzYWJjZGVmZ2hpamtsbSBOT1BRUlNUVVZXWFlaMzIx) ### How it works ``` ☺ Push 32 (code point of space). 6 Bitwise OR. Θ Make a block of these two instructions and map it over the input. This turns uppercase letters into their lowercase counterparts. à Push the lowercase alphabet. B1 Swap and apply set difference. ." Push the logical NOT of the length of the result. ``` [Answer] # R ~~50~~ ,~~46~~ 39 bytes ``` all(sapply(letters,grepl,readline(),T)) ``` Edit drops the need for `tolower` by adding `ignore.case=TRUE` (`T`) [Answer] # Python 2, ~~53~~ 51 bytes ``` f=lambda s,c=65:c>90or(chr(c)in s.upper())*f(s,c+1) ``` Alternate solutions: ``` lambda s:all(chr(c)in s.upper()for c in range(65,91)) lambda s:not set(range(65,91))-set(map(ord,s.upper())) ``` Thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) for pointing out that sets have an `<=` operator, for an alternate 51: ``` lambda s:set(range(65,91))<=set(map(ord,s.upper())) ``` [Answer] # O, 11 bytes ``` GQ_s{n-}dS= ``` [Try it online.](http://o-lang.herokuapp.com/link/R1Ffc3tuLX1kUz0=/VGhlJTIwcXVpY2slMjBicm93biUyMGZveCUyMGp1bXBzJTIwb3ZlciUyMHRoZSUyMGxhenklMjBkb2c=) Sadly, O does not have set difference :/ ## Explanation ``` G Pushes the alphabet to the stack Q Pushes input to the stack _ Converts the string to lowercase s Split string into char array { }d Iterate through array n Pushes current element to the stack - String subtraction S Pushes a blank string to the stack = Equals ``` [Answer] All of these regexes use their engines' respective case insensitivity flags, so that has not been counted towards the byte counts. Even though some use `\pL` (a shorthand for `\p{L}`) instead of `[A-Z]`, they still need the flag, due to comparing characters via backreference. Without it, they would need to apply the flag inline, `(?i)` inserted at the beginning, costing 4 extra bytes. # Regex (Perl 5 / PCRE / Boost / Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/)), 21🐌, 22🐌, 24, or 25 bytes Quite simply, this regex works by asserting that there are at least 26 alphabetical characters in the string that do not match with any character to the right of themselves. Each of these characters will be the last occurrence of a given letter of the alphabet in the string; as such, they are all guaranteed to be different letters, and asserting that there are 26 of them implies that the full set A-Z is covered. `(.*(\pL)(?!.*\2)){26}` (21 bytes) 🐌 - [Try it online!](https://tio.run/##fY9ta8IwEMff91PctNhG6kOF7YWxiqBjAycOHGwglLSmGk2TmrSKk@6rd5GxMRgMjnv83f@4jCp@W6VnsBWGC5cx4WB3sCmDwWS8HA9LK5HKtVnQxYMhNtFHF2CJ6aBLppjIobYSNVyCzSEAXUQ6N3jotXzPR/RwHcLoV79rJgj6YIfYAiMErllsNH4IbggfCerUne8D7hUJPqBjqw5DI2epCtoHcPrOPeHapA7CpRH7om2OoQzD6XwShpXbbrqrbIbc0U27ueohdOndlVVVhwURG0VSDS2Qgp@No5AywVLzv8k9iGhMCk0h3zINxrQEzeXJssbxdPO4f5LP@uX0Fk2Sh91MLNTy@PpuWXWYS9HK/mp7QKJI0SMjOV17EBP93wkSxWuabLZst@epkNlB6bw4fgI "Perl 5 – Try It Online") (Perl 5) Using `\pL` instead of `[A-Z]` to match alphabetical characters imposes the requirement that the input must be in ASCII, because `\pL` matches all Unicode alphabetical characters (including those that are extended ASCII in common codepages); so an accented letter, for example, would count towards consuming the target of 26 loop iterations. Some other regex engines only support this syntax in the form of `\p{L}` (which offers no advantage over `[A-Z]` for this particular problem, being equal in length) and not with the shortened syntax of `\pL`. This bare-bones version of the regex is extremely slow, due to an excessively huge amount of backtracking both for pangrams and non-pangrams, but will always give the correct result when given enough time. Its search for the 26 matches proceeds in the most pessimal way possible. Using a lazy quantifier speeds it up greatly when matching pangrams, but it's still incredibly slow to yield non-matches when given non-pangrams: `(.*?(\pL)(?!.*\2)){26}` (22 bytes) 🐌 [Try it online!](https://tio.run/##bVVrb9s2FP2uX3GTGLVdKG5ToPsQNw3Spa@gLRLMWzcgQEBJlESZIhWSsh5B9tezQ8n2AmyAAdvUfZx7zrlUxY18@1R2NDFLepA6ZpImr5b4e/bu8mJ18f4xSLWZTcTZ6@W790t8n8wfSKQ4mT9URihHh7fqcPlIE0lnZOvIOoTfhccn4cmc3/uHdP7s/DWezOmUJnfLgFCIZkh88WIfIRFxMld8ejTdNZj5kLO/6dXEvBLz8@nK1PyUaHo6/cSkxc/pfPmIYmP0RC7p8e7u44/Lu7un2eLl@ey2@jafnR8sXt6@mc8f3vzy@PR0RNdMZYaVNggu4o/Z1/V3fWN/b/6KLtMvxTd1bVabP/vg16aktNAmoYipNWWyq3JLG946uq9Fvwg@6ZZUV/pTVIv8abymQmx4Qg2TDiGfpYio0PHaDjljODnty1DSMJMugpshredV3hlLkdRN6B8LlVHCUkdXolwEX3SzPZTdttHwsOeRYZaKuqwOgu9mQVdoFtLqj7HfdX4ZAn5mKeUNyU61i@C3KheqJZ2iF0Od@5oZ14eokWSc4IaNbhbBKueUYhSK9AClET0zydhpBCC7RfDTjxmOY4UEs@xJyAaq6EOd7CZMQZfPtqREljvMwSKNBmPlRXAFMAlrLEl/ChyRyMjuwY4wAazRlBggU1ticy4rSlm7S9mK4xFyAEF2pLOB7A23KNhRyVy@DbuuIyli4ILCu5C8znytsaGH7asBEg7itedip1WhpfORDZpHHCNcez49DIzaCDQZGEx0D7BS3Nfgp6gzCw1AGECIfqBW1zJBaEs3NVtzQzoqeOyQisifOXJ7XUYCyJjxg4c7/oepR9mumfNqtCBVJf75hmMhsnDLUVqXEdhwELUSfc9GfUetIqMb9UwdsG@GSMn6DuAzFNaebivkmqquYCUcx9s4xxbB6l71SNb8X4WQW7AuRKvMm6INR5sO0DxdWnqaBzoPgoutAaaez4iE3a1HnA9wdrMKjzF7DlyrrqVMQ0D1/9DH/cKa4rfYMLriSokUId90xXvIZtXUYT0GUctxr3LueXRxTodXXFcA1h0chnQhgWhleMTXU0@n2q9YxkqkfOiweV6acree1tVJ542LTBFr3BAwDWZXxPxl1XPsa0eZMBKHcImF/qNTKslEAgbjNXe4EDgIxuNxbKj82WDWbr@QJSyDkg5rGkNLrLkXxJNQ6I3AjX5fc64W4HnvClrxFhKOrkJ4jXUkw6txF0DnGrIWvOHSdCPhY7O9Fn6rEOKbZEqXfI8SJ7g/WKX9gFiICzn0t05oBftaXzjqxrVoPMv4z9uKGwwKW/WjRQdLg1O/TdD2qlaIxh5x6QdAChTNQBQHnqrkuPdBs0@00AJE9l5DON3osvL3zFAvgf0cdpCT2GiDHa39BWH3bCl/sQ/C4CoS5X5Ww5n0wyCIuSEy4qx2Iq0lzNf4sTC4H0JZwFsEwRH90Oq42r5jaPbmLTzgHDd2Tse49CAShHE8wdXMY1ZbPzV8j49GfdMI6ws6w0sOABZvhCBgUZzwNMtFsS6Vru4N/LVp2q7fv8L@8wb7Bw "Perl 5 – Try It Online") (Perl 5) [Try it online!](https://tio.run/##fVd/U9TIFv0/n@ICVZLwwijs6lOR3UIcFyhAhOG5u2pNdZJO0jNJOnaSySSuX315pzvJOKi7lCVJ9/1x7rnndho/z3cj37/bCngoMk5Xx9fj/enxm1fj6e3l6WT67vTV5ISeWlsi85Mq4PQi9xXfH8W/WH7MFE3z9x/pkK43X9b13Pup@qNpfp/ET@rYvrNHO7/aH/Jzx/51Y7TzYd9xPu8/@XLnfGu56dJOfjjN/7N3sJamKAMhdZr1JSWy6P6akFjlLP3e7hdLZCXleCynXCmpbF9mRUkG9k7Ki4JF3PmMPM@f@zCgFy@oX9WPZp1nQXJAipeVymjv4Mt3IfW7LwPu0GeL8GOC91He7z9@8vHALIuQbMPbNOK967S3srW7S3ZH/O3xydH10x2n33SpEC2XoT3ApYfDypq94zgmi/65V86mMSKT7zlt/mOFxntVpdWVmTKR2UNd@XuQmvDMzp3dvY@Hjw6ogs1P@9OSpH7TDhEerBWGrgnYyKvygLridam0o/jwnrLSj7GalXxZ0k7/cH83YCVDu1bPXS7Fiyop3a60g161N6d/js1KGBYcm7IqATkq43sGO3LB/RJefdVQ74AuzUXC7Z7am6vJtZO7veuf4@s308n4@uL08mgyfjUsHx/djM/HNzf0V79wO3nt0gMDq//dg3nkfJXChkIne77X1WT@X7MbmDn8EV9TLLGS25e35@drAugskbK3TkQqyiGSSz/vP/v52ZP/7j977BzQw4ckFfgsuCpp0945P73AyF8cTY5PDgfDp8@cTWIleTwSWaZbKkPKWVlylZmka206/K5zPchpqGQ67b1sBV0b1F2lITCYQWq1kox4MCUJTiO7U7PI3E5HgNwe7g2aHFhqHcKenjx7@0O23UddcW08RzzNywZyfvCgC/X@0ceNw@2t7fVgnR60sO5XYgCvq6IL6U@hcdvpsY30XOq3R@bfVwpc6slfAzaA67O9gDq@wfGNxcZhr6/x9fWb6@nlG9MkOK3Lp7MFSWYxtDfH/eA7B1@IJwVfbbxmeDMb95J@YzVRFYzuWX1ZPYW1ElDfv1Kx5@p2ymoovfP@TiOh4tz@@o4CRDgo1vmR8o3DitW1w6XbwXStDu2OE5xpd1t0xbJIsbSwrCN/HJ3OL@Tb4rb@w3sVnszOsys1WfzeWsd1SuFMqoA8ls0pSpo8Lmihx/BTJdqR9VouKWtSvYponl715zQTCx5QzZISJr8lwqOZ9OeF8enMqZQ6DAU1U@HIemvcWp7HjSrIS2Tt6m09YAELSzoT6cg6kXW/mDR9IrPZck@xgmZVmm9YF2pEZ0jm0uR/Xb6rGAeUx6KCQl5T0mTLkXWTxyJb6uH1EoY4nyqmytZFjACfg7ShhaxH1iTmFKIU8qSBUouWqaDL1AFImpH1TpfpdmW5Zn4HEiJDFb2sgqHCEHRp74IyEcUl6mAeTuA@8sg6A5iA1QUlehU4PBFRsQLbwQSwWlKggCzriY15klPIloNL3xyNkAMIvD0ZGbIXvEDARo9k3JtdVV4ifOBChweTuIp0rC6hhq2jARIW/LnmYujVTGIgYVkjucdRwpXmU8NAqbVAEsNgIFuATcSnCvzMqqhAD0AYQIjWUCurJIDpkt5WbM4VSW@GDxNcYfkuhm8rU08AGVO6cHfg31Tdte2KlbobS5CaBXp/wfVX1@05CqvUAxslmpqLtmVdf7teeUrW2Vp3wL4ylglrG4CPEFhquguRzClvZiyF4vgS52wWQeq6615S8a8dgu@MNS5SRVoUS7eTqYGm6ZKJptnQuWEd9QLY1nx6JIphPPzYwBlqFRpjtA5cZs2SIokGZj@G3s0XxhTPYsHojOO7FcLkXOa8RduKbBvfM2aamnZzFXPNI84Y2jzjMgewZgP30qMEiCaKe3y@renMViMWsRQuLxtMnm5NOoxnUVZBo4ULT@FLnBAQDWrPiOlzteWY14YioRIsQiUF@t8pJU@YCMCgP@clDgQOgrHdlY0u/6ZQa7MayBSSQcgSY@qjlxhz3RBNwkwuBEvgxXk2As8rVdCEL9HCTlUwrzCOOB/zbhZA5xxtnfGaJ6rpCO@SrXqhpwomOkmUSdwkB5RYwfnBcqkLxEAcJSZ/UQrcuIkVOrDXdGNRa5bxzpc5bh3YTVnbSdRIGpzqaUJvzyr8OVJjjniiC4ALOhqBKA48ecpxYQDN2rFAL8y1GD3UXy/c4/Q5Y@IFkF@JGeQkFlJhRit9QBQrtjJ9sJvG4CgS6apWXFsSXQyMcPnRlh5nVSnCKoH4al0WCtdFZAXgjSxriy45U7t5/5Ehe/8xRKBvPIVDu0CDvz0kSgqABVovcOJnuIxbFvN8/PEVxWI2T9I0k7mCiBb1smn/9sMEp/jdbmI@cbtP/w8 "C++ (gcc) – Try It Online") (PCRE2 / C++, with backtrack limit adjusted) [Try it online!](https://tio.run/##bVVrb9NIFP3uX3Froo2NTKAVsIJsVJWlPKoCpXSXXW1RNLbH9iTjGTNjx7ERv717xk4CWu2HVs74Ps4959xxVVR3v51WRUUTQwvyH/o0o8rwfGl4JVnCg@nD2f3T5bJgsl4muqyE5OY2uA3nt9cP7TSiKf4yHC5z7gJUzVVtg@Xy1dvL8@UyjOg4REn/YSP8uSeUWFpeB36VGD6LWbKuDf4tpShF7UfkPz559vjZ019Pnj3xw7mXaRNMxOLRfCIXGerb4NPNy7fvw3n4jUQWTOQ/tjaSKzyFD46/LBb@rfJDBNsmxhscR4@iB8fhfIgWIU8K7ULmhKrHc49wTsGPGr/8gpKPvhwtpvemaDEpFwMVJauTIpiYCCFzckVGiiSz9ZIbA5Th0eLq@vz18v2H5fn19YfrU//cnT8n/3kwKU/9G9Pw54Rf/ismLR4xHn0HgKGaP5H@/Pt/SA7C@V0A7oPb6jIMTo9m929PwvDbydPvd3f36Iqp3LDSet5Zcp6/Xb/TH@0f7d/xy@zN6lJdmZvNX733e1tSttImpZipNeWyqwpLG76t6Wsj@pn3Sm9JdaU7RbXYnSZrWokNT6kFGIS8liKmlU7WdsgZw6nWrgylLTPZzPs4pPW8KjpjKZa6jdxroXJKWVbThShn3hvd7g5lt2s0vOx5bJilVVNWR947M6MLNIvo5s@x31XxMgL83FLGW5Kd2s68T1Uh1JZ0hl6wDwKZqfsINdKcU9nRRrcz76bgcOaGU6wHKK3omUnHTiMA2c28z27MaBwLTtbmQEI@UEUvmnQ/YQa6XLYlJfKixhws1mgwVp55FwCTstaSdKfAEYuc7AHsCBPAWk2pATK1I7bgsqKMbfcpO3EcQg4gyI51PpC94RYFO4Ili13YVRNLkQAXFN6HFE3uao0NHWxXDZBwkKwdF3utVlrWLrJF85hjhCvHp4OBUVuBJgODqe4BVoqvDfhZNbmFBiAMIEQ/UKsbmSJ0Sx8btuaGdLziSY1URH4ukNvrMhZAxowbPNrzP0w9ynbFaqfGFqSq1L3fcIPa0Y6jrCljsFFD1Er0PRv1HbWKjW7VT@qAfTNEStZ3AJ@jsHZ0WyHXVHUrVsJxfJsU2CJY3akey4b/UAi5K9ZFaJU7U2yj0aYDNEeXlo7mgc4j72xngKnjMyZh9@uRFAOc/azCYcx/Bq5Vt6VcQ0D1/9DH/cKa4llsGF1wpUSGkEtd8R6yWTWtsR6DqOW4VwV3POLKIv@C6wrAuiPcrWcSiG4Mj/l66uhUhxXLWYmUFx02z0lT7tfT1k3aOeMiUyQaNwRMg9kVMVyAoufY145yYSQO4RIL/Uen4NMhUjCYrHFpw1ggGK/HsaHya4NZu8NClrAMStZY0wRaYs2dII6Eld4IJpHFuZqB54Mr6IZvIeHoKoQ3WEfCJ2vcBdC5hqwr3nJpupHwsdlBC7dVCHFNcqVLfkCJE9wfrNJuQCzEmRz621poBftaVzjuxrVoHcv4zbcVNxgUtupHiw6WBqdum6DtRaMQjT3i0g2AFCiagygOPFWJT6aj2SVaaAEie6chnG7wMXD3zFAvhf1q7CAnsdEGO9q4C8Ie2FLuYh@EwVUkysOshjPphkEQq4fImLOmFlkjYb7WjYXB3RDKAt7M8@7Re87Mg2r3kaHg5AlMUNfc2NDzWJykPMsLsVrLslS6MnDKpt12/b8 "PHP – Try It Online") (PCRE2 / PHP, with backtrack limit adjusted) Changing the main loop to an atomic group allows the regex to also yield non-matches at a reasonable speed: `(?>.*?(\pL)(?!.*\1)){26}` (24 bytes) [Try it on regex101](https://regex101.com/r/4QdZEV/5) (PCRE1) [Try it online!](https://tio.run/##rVddc9u2En3nr1grD7Y6isZOP6b1Hd@Mm283aZ1r3/Zmkj6AJERCAgEGAEWRnf729CxByW5v7cRtn2yBwOLsObt7yLoLpTWff1BVbV0gJwu5SRydkJtMJh8OHv57/tnDg3f1y@nBw735Z@@OptNfHnz16wc8fHt0fP/o53@ROjlMFtaRJmXI1tIcHE6PEyK1IHVMtVMmHEz598lRXNXYoqckTE76LUKcnOy/M/vHpE/020OO@SfbDn/eO9m/t7@NJ01@Mrl0jTwmmvDmAffcS@Gy8sDNSM/GpRfPvv/hP08enV48mZLUXtLkqcCfY5owpqtoevrhHp0LUzhR@SQ5zZ4UL1av7Gv/3/ZN@njxfPnSnLvL9f/65FFb0WJpXU6pMCsqdFeXntZyE@h9o/p58tRuyHQVryJayqvZipZqLXNqhQ7Y8kyrlJY2W/nhTNxOwXIYylvhFvPk9XCsl3XZOU@ptu2MHytTUC4Wgc5UNU@e23Zc1N140fCwl6kTnpZNVe8lr9ycznDZjC5/jPedl49ngF94WsiWdGc28@SiLpXZkF3gLoE47xvhQj9DjLyQVHW0tu08uSwlLZAKpXaA0qpeuDzeFAHobp78xGnOYloz4urYklAMVNG3Tb7NcAG6@LQno4oyIA@RWlwQI8@TM4DJRetJ8ypwpKogvwMbYQJYayl3QGZGYkupa1qIzfbIKA4jlACC06ktBrLX0iNgR5UI5bjtvEm1yoALCm@3lE3BseKFDJujARIWshVzsdVqaXXgnS0uTyVSOGc@GQZSbRUuGRjMbQ@wWr1vwM@yKTw0AGEAofqBWtvoHFs39LoRK@nIpkuZBRzFzp9KnO1tlSogE44Tn235H7KOsp2LwGpsuqGP8HwtUfLFbORo0VQp2AgQtVZ9L6K@UavU2dZcUwfsu2GnFn0H8AUCW6bbK72iuluKChUnN1mJLkKps@qpbuSVQji7FN0MVxVcFJtZLNMBGtNlNdM80LmXnI4FsM98pqT8tj2ycoCzzVUxxuI6cGu6DRUWApo/hx77C22K/9Va0Jk0Ri2w5SXGVw/ZvNkPaI9B1Cr2VSmZx5CVNDmTtgawbm8yo1MNRJdOpnK1z3SaXYsVosKRbzt0HktTbdvThybvuHBxUmUWEwJFg9wNCR5HvUS/dlQop7GIKvHQP1ZKrYXKwWC2kgEDQYJgPI5pQ@VnDrl2u4asUDIIGdCmGbREm7MgTMLSrpXQOCWlmYPnXVXQpdxAwlhV2N6gHTFG69gLoHMFWZeyldp1kfB42U4L7ips4UsKYyu5Q4kVzA8Bi0GCaIhTPdzvg7IG5es5cNrFtmiZZfyWm1o6JIqy6mOJDiUNTrmboO1ZY7AbfSQ1J4AjULQAURJ46kqawDTzQQ8tQGTPGqLSna1qnjNDvBzlF9CDktTaOvRowwPC79gyPNgHYTCKVLXL1UmhORlsEmHYmUrRBLVoNIqv5bSQOCdhPODNk@QefQ9/ul@PJkMHD75EEYQgnZ8mg61cN5ShiAZXeWp5DN7sKv9nKruJtZagYDw2DraPuoo1H3WVOrqK/2RXKYDlU3zFNu4uvnJHWxmmwK2uMo72aC7z5PFtdmJb/RFLKUU12MqnOgobyinkWNxqKr8zlL/gJ@aT/YRQ10j4ylbG/hvsZPfyEjuPR3g0k/yObtILM7rJk9E6hrn3B1u5yUz8bW6yuNVLdmbJ9enQqfejs@xQu1V3zTD@iHtwGfaY4nYr@as@coOJ7OwDzzH@bjaRN9xMf99GMsy58I8YCezjykzu4iJbjPh9zUIut4Yw2of4vaWgaPzNpnJlIq9Ed2cPuSj/lolY84@ayOf3H3yx9RE0AnDRq9OLR5Ad@uGchLlcoBF8iYnEgmfMKerE1o0WjtxQCUOpxTYWmdIqxDnA4oAbvD6uhdIC/Y0@RTCNpQx1FYCd24kJkmiCNw@@w0QtLB0YxMt3BFRKa24NlAuurxuABUnFFEPWYnYihIfECBokaGVCLJ8tAExCF3ykclkh0MpYDG18ITSRr6Nvvj7E/ZjLWRPG3rWLhcrABvLlDxUZiz5jcdEgeaWM8sGJMAzNJqAASqWZElAKApYNFEQBY5@MqWXCI@/nUuTU1MMKDujxO4V/Bh5ugAyl9Pi@A20roYzf1o8wmeJyeuakXMUDeHLRpU4FTMrJC9xieORqKTyKBWMOdHgx3lCh12RUN5XDNHcyG1@bnkvX2wJzI23g2Px6P8FjFYD@OyBYKdBiAcC3w@xSftcoM/qxK2zwmHQo6NpyywiYlsyiUiaTdTiOc9oaZpb3bVSFpzmE0Xbokflv "Python 3 – Try It Online") (Python `import regex`) Adding an anchor is not necessary to make the regex yield correct results, but speeds up non-matches further, by preventing the regex engine from continuing to try for a match at every character of the string (because if it fails to match at the beginning, we know it's guaranteed not to match anywhere in the same string, but the regex engine can't know that): `^(?>.*?(\pL)(?!.*\1)){26}` (25 bytes) [Try it on regex101](https://regex101.com/r/4QdZEV/4) (PCRE1) [Try it online!](https://tio.run/##rVfvc9s2Ev3Ov2KtfLDVUTR2etfp@cbNuPntJq1z9rWXSdoZkARJSCDAAKAoqtO/PX1LULLbq5247SdbILB4@97uPrLpQ2XN5x9U3VgXyMlSrhNHJ@Qmk8mHnw4efjX/7OHBu@bl9ODh3vyzd0fT6c8PvvjlA56@PTq@f/Tjv0mdHCaFdaRJGbKNNAeH0@OESBWkjqlxyoSDKf8@OYqrGlv0lITJSb9FiJOT/Xdm/5j0iX57yDH/YNvhj3sn@/f2t/GkyU8ml66Vx0QT3jwAn3spXFYduBnp2bj04tm33/3nyaPTiydTktpLmjwV@HNME8Z0FU1PP9yjc2FKJ2qfJKfZk/LF8pV97f/bvUkfF88XL825u1z9b5M86moqFtbllAqzpFL3TeVpJdeB3rdqM0@e2jWZvuZVREt5NVvSQq1kTp3QAVueaZXSwmZLP5yJ2ylYDkN5J1wxT14PxzayqXrnKdW2m/FjZUrKRRHoTNXz5LntxkXdjxcNDzcydcLToq2bveSVm9MZLpvR5ffxvvPq8QzwS0@F7Ej3Zj1PLppKmTXZAncJxHnfChc2M8TIS0l1TyvbzZPLSlKBVCi1A5RObYTL400RgO7nyQ@c5iymNSOuji0J5UAVfd3m2wwL0MWnPRlVVgF5iNTighh5npwBTC46T5pXgSNVJfkd2AgTwDpLuQMyMxJbSd1QIdbbI6M4jFACCE6nthzIXkmPgD3VIlTjtvM21SoDLii83VK1JceKFzJsjgZIWMiWzMVWq4XVgXd2uDyVSOGc@WQYSLVTuGRgMLcbgNXqfQt@Fm3poQEIAwi1Gai1rc6xdU2vW7GUjmy6kFnAUez8ocLZja1TBWTCceKzLf9D1lG2cxFYjXU/9BGeryRKvpyNHBVtnYKNAFEbtdmIqG/UKnW2M9fUAftu2KnFpgf4EoEt0@2VXlLTL0SNipPrrEIXodRZ9VS38kohnF2IfoarSi6K9SyW6QCN6bKaaR7o3EtOxwLYZz5TUn7bHlk1wNnmqhhjeR24Nf2aSgsBzR9Dj/2FNsX/aiXoTBqjCmx5ifG1gWze7Ae0xyBqHfuqksxjyCqanEnbAFi/N5nRqQaiSydTudxnOs2uxUpR48jXPTqPpam37elDm/dcuDipMosJgaJB7oYEj6ONRL/2VCqnsYgq8dA/VkqjhcrBYLaUAQNBgmA8jmlD5WcOufa7hqxRMggZ0KYZtESbsyBMwsKulNA4JaWZg@ddVdClXEPCWFXY3qIdMUab2AugcwlZF7KT2vWR8HjZTgvuKmzhS0pja7lDiRXMDwGPQYJoiFM93O@Dsgbl6zlw2se26Jhl/JbrRjokirLaxBIdShqccjdB27PWYDf6SGpOAEegaAmiJPA0tTSBaeaDHlqAyA1riEp3tm54zgzxcpRfQA9KUivr0KMtDwi/Y8vwYB@EwShS9S5XJ4XmZLBJhGFnKkUbVNFqFF/HaSFxTsJ4wJsnyT36Fv50vxlNhg4e/BNFEIJ0fpoMtnLdUIYiGlzlqeUxeLOr/J@p7CbWSoKC8dg42D7qKtZ81FWa6Cr@k12lBJZP8RXburv4yh1tZZgCt7rKONqjucyTx7fZie30RyylEvVgK5/qKGwop5CjuNVUfmMof8JPzCf7CaGukfCVrYz9N9jJ7uUldh6P8Ggm@R3dZCPM6CZPRusY5t7vbOUmM/G3uUlxq5fszJLr06FT70dn2aF2y/6aYfwe9@Ay7DHl7VbyZ33kBhPZ2QeeY/zdbCJvuJn@uo1kmHPhbzES2MeVmdzFRbYY8fuahVxuDWG0D/FbS0HR@JtN5cpEXon@zh5yUf0lE7HmbzWRz@8/@MfWR9AIwEWvTi8eQXboh3MS5nKBRvAVJhILnjGnqBPbtFo4ckMlDKUW21hkSqsQ5wCLA27w@rgSSgv0N/oUwTSWMtRVAHZuJyZIognePPgGE7W0dGAQL98RUCutuTVQLri@aQEWJJVTDFmL2YkQHhIjaJCglQmxfLYEMAld8JXKZYVAS2MxtPGF0Ea@jv715SHux1zO2jD2ri0KlYEN5MsfKjIWfcbiokHyWhnlgxNhGJptQAFUSjMloBQELFooiALGPhlTy4RH3s@lyKlthhUc0ON3Cv8MPNwAGUrp8X0H2tZCGb@tH2EyxeX0zEm5jAfw5KJPnQqYlJMXuMXwyNVSeBQLxhzo8GK8oUavyahuKodp7mQ2vjY9l25jS8yNtIVj8@v9BI9VAPpvgGCpQIsFAN8Ns0v5XaPM6Pu@tMFj0qGgG8stI2BaMotKmUw24TjOaWuYWd63VjWe5hBG26FH5r8C "Python 3 – Try It Online") (Python `import regex`) [Try it online!](https://tio.run/##rVfvc9s2Ev3OvwJxPJXVUZQ4d725i5t43Do/6iYdZ@xrLzOZ84AkSEICARoARZEZ37@eewtQits7O3HbT7aABbD73r59UiOs@uZj3bNde8A@KJNxxXYfHuDj02@Pj86Pnl0lhbF7u/Lpo4Nvnx3g7/70A5MFVqYfGiu1Zzvv9c7BFdtV7Clzbeo8wi9mD/Zn@1NxSZvs8Nr6I@xM2RO2e3GQMFzE9nDwq6@2EQoR@1MtJvcnmwf2KOTpf9jDXftQTg8n57YVTxibPJm84Mrh38n04AqXxehddcCuLi6e/3R8cfHx33uHz@ZfH@69b15P9w7vzb9@vz@dfnj8t6uPH@@zU65Ly2uXJEfZ8/KH5Rvz1v2ze5ceF68Wr/WpPV/9a0i@72pWLIzNWcr1kpWqbyrHVmLt2WUrh3nywqyZ7mtaxW0prWZLtpArkbOOK4@Ql0qmbGGypQtnYjjzhq5hecdtMU/ehmODaKreOpYq081oW@qS5bzw7ETW8@SV6cZF1Y8Phc1BpJY7tmjr5l7yxs7ZCR6bsfOf43un1fEM6ZeOFaJjqtfreXLWVFKvmSnwFsc9ly23fpjhjrwUDA2xMt08Oa8EK1AKS01IpZMDt3l8KSag@nnyC5U5i2XNGPplC0IZoGLftfmmwgJw0WnHtCwrjzp4avBAvHmenCCZnHeOKVpFHqksmdsmG9NEYp1huUVmegS2EqphBV9vjozkUIYCieB0asoA9ko4XNizmvtqDDttUyUz5AWGNyFVW9Jd8UFKm25DSljIloTFhquFUZ4iOzyeCpRwSnhSGii1k3gkIJibAckqedkCn0VbOnAAwJCEHAK0plU5QtfsbcuXwjKTLkTmcRSRv1Q4O5g6lciMWyp8tsE/VB1pO@We2FgDVJ3T/kpAE@VsxKho6xRoeJDayGHgkd/IVWpNp6@xA/RtiFR86JF8iYsNwe2kWrKmX/AaHSfWWQUVodWJ9VS14hNDOLvg/QxPldQU61ls05AawWUUwRzgvJccjQ0wITxTJt1GHlkV0tnUKinH8nriRvdrVhoQqP9/6lFfkCn@lyvOToTWskDIa9OIAbQ5PfGQRyC1jrqqBOHos4rtnAjTILH@3s6MHSlkdG5FKpYTglNvJVbyGke@66E8oqbeyNP5Nu@pcXFSZgYTAk2D2jXjNK8GAb32rJRWYRFd4sB/7JRGcZkDwWwpPAaCAMDYjmWD5ZcWtfZbQdZoGVzpIdMMXELmRAiBsDAriaF@2Qqh58B52xXsXKxBYewqhLeQI7OiiVoAnEvQuhCdULaPgMfHtlyQqhBCj5Ta1GKbJVYwP3hjqEAI4kiF952XRqN9HV2c9lEWHaGMz2LdCItC0VZDbNHQ0sCU1ARuT1qNaOhIKCoAR8BoCaAE8mlqgdEPmOmgAxcAciAO0enW1A3NmXBfjvbz0KBgcmUsNNrSgHBbtDQN9kAMRpGst7VawRUVgyDuQ2QqeOtl0So0X0dloXAqQjukN0@S@@wnwe2DZjQZtvf4GzSB98K6aRJs5bqhhCYKrvLC0Bi82VX@x1S2E2slAMF4bBxsn3UVoz/rKk10FffFrlIily/xFdPau/jKHW0lTIFbXWUc7dFc5snxbXZiOvUZS6l4HWzlSx2FDOUIdBS3msqvDOV3@In@Yj9h6GsU/MlWRv0FO9l@eYnKoxEezSS/o5sMXI9u8ny0jjD3fmMrN5mJu81Nilu9ZGuW1J8WSn0QnWWbtV321wzjt3kHlyGPKW@3kt/rIzeYyNY@sI/xd7OJvCMx/XEbyTDn/J9iJLCPT2ZyFxfZ5IjP1yzkfGMIo33wX1sKmsbdbCqfTOQN7@/sIWfVHzIRo/9UE/nLg8d/3fgIhIC82Jujs@9BO/jDOQFzOYMQXIWJRIRnhCn6xDSt4pbZ0Amh1aKMeSaV9HEOEDnABl8fV1wqDn1Dp7hMYSlDX3nkTnIigARE8O7xj5iopWF7GvflWwBqqRRJA@2C55sWyQKkcoohazA7cYUDxbjUC8BKgBg6WyIxAV56Ty5CHbDUBkMbvxDaiNf@P/7@CO9jLmetH7VrikJmQAP10g8VEZs@I3IhkLyWWuKXJfdhaLYeDVBJRZAAUgCwaMEgGhhxIpaWcYe6Xwmes7YJKzigxt8p9NHTcEPKYEqN33fAbc2ldpv@4TqT1E4vrRDLeAA7Z31qpcek3PkBr2gauUpwh2bBmAMcjo8v1NCaiOymIkxzK7Lxa9MrYQdTYm6kLRybvt7vYFt6ZP8jMlhKwGKQgOvC7JJuK5QZ@7kvjXeYdGjoxpBkOExLZJEpnYnGP4lz2mhCluLWssZuDmKUCRqZ/xc "Perl 5 – Try It Online") (Perl 5) [Try it online!](https://tio.run/##rVhhc9NIEv2uXzEJVcTOOT4SdimOELZCMCTZBEJilmWBc42kkTz2SCNGkmWZ468f93pGchy4BNhdamuxZrpnut/r7icRZNlWHASfb4UikqlgZwfng53RwYsng9Gr50fD0eujJ8NDdt@7JdNAlaFgD7PAiJ3@@JEXjLlho@zte7bHztcfV9XUv1u@qevfh@N71bjz@d@dXx71N3/pvMtOup1f1vqb77a73Y879z597n5pvN5jm9neKPvH9u7KTXkRSk03rS4ZmcZX16TGquDJ13aPPJkWLMPPYiSM0aYT6DQvmI18MxF5zmPR/Yh7HjwIYMAePmTNKv206yIN1S4zoihNyrZ3P311JD0HOhRd9tFj@GMPb055u/Pzvfe7dllGrGOhG8WicR01Vh1y77GOw/7VweH@@f3NbrPZY7lcCB112nDZP9uVFftut2tvoT9X0lm3Rsze94CtX5uh9V5m6bk0Ey7TTptX9hagKpF2su7W9vu9O7ushM3dnVHBND2RQ4wf3jIGRwI2srLYZS55SpVtGtE@J7wIxqOQFxyELH@704zIS1X0XPC7TWleHP0xsCtRlAts6rJAUHExvmKwqWciKODV5IUSbe9PMqlEpwHv4mx43s16jesfg/MXo@Hg/PTo@f5w8KRdPti/GJwMLi7Yf5qFV8OnPXbbhtX83QRzp3tJ9poBVw2iq/Vi/9/YrWS/9xUgIzzzQowio5NRxotCmLRjUBDPX52cNAdE2jBbgQuiwKKO8lLo5I4rA5n2HAHdXdhst2S2QS66DHtUsp2Nd@lGc@oyBevZF0lW1KiD27fdUW/vvF/b27i1sXqYg5n4upqJDXgVbHdkMEJxdLpNbH0qaHq6Y/@7hOBKrquRNVc9BOJfBPGFxdpew9ng/PzF@ej5i9P94cEhnFYpcbZAyC5GnfVB0y7d3U9MqFwsN55yPNmNK5d@YTU0JYyuWH1a/ooqIwvRuRGH7R5xqYk179L7qwKJjBCdy@fuapO5TdTgcni5LNHbn2@xM57Ghie55@0Hg/hoeqpf5q@qN/6T6HBykp6Z4ez3hXdQJSyaaBMyn6dTFqs6G@dsJuYF@1DKRd97qucsrRNaxWk@rQZTNpEzEbKKqwImz5T02UQH09z6OHNWaDqGhRU3Ud97ad0WIhvXJme@0lWPtml2hDwq2LFM@t6hrppFVTcX2c2F8A3P2aRMsjXv1PTZMS7rseFv7r6zMdrY53HOIlExVafzvneRjWU6ZzrCXRznfCi5KRY9nBFiLCY1m@mq7w3HgkVIhfnahlLJBTehu8kFoOq@95rS7Lm0erYdWxBiCxV7XIZthhHgIu@cpTIeF8iD@5hTzcl97xjBhLzKmaJVxOHLmOXLYF2YCKzSLDSILG2AHQuVsYjPW5eGHIpQIBB4@zq2YM9EjgNr6rBxY3ZW@koGiAsMtybjMqaz3IUUNp2GkLAQTAmLlquJRovBssLlvkAKZ4QnhYFUK4lLLIKhXiBYJT@UwGdSxjk4AGAIQi4stLpUIUzn7GXJp8Iw7U8wvuEKy9dj@C504ktExg0l3mvxt1k72s54QWzMAWoa0v5MkPr0GoyiMvGBRgFSM7lYcMev48o3ukpX2AH6xloqvqgRfIyDNcGdSzVlWT3hCSpOzDE20xilTqz7qhSXDMF3wuseroqpKOY9V6Y2NIJLK4LZwrnm7TcFsEF4@kzmbXsEYxtOm6ukGOPVwHVaz1msQWD6/0N3/YU2xW854@xYpKmMYHKiM7EAbXm6UaA9LKmJ66uxIBwxU9j6sdAZAqvX8H62rxDR0AhfTDcIznTZYjFP4PK4RucRNUnbnnlRhjUVLjxloDEhUDTIPWWcJuVCoF9rFkujsIgqycG/q5RMcRkCwWAqCgwEAYCx7dIGy88Mcq2XDZmgZHBkgTYNwCXanAghECZ6JrmClxBpHzgvq4INxRwUuqqCeYl2xHzMXC8AzilonYhKKFM7wN1lSy6oq2BCl8SpxhtVGyVWMD94pilBNMS@svfnhcSbJ@M5HezXri0qQhnPYp4Jg0RRVgtXorakgSl1E7g9LvFmXqGPhKIE4AJGYwAlEE@WCOg/YCbHHFzY10NwSHqEtx2aM/a8EOVXoAcFkzNt0KMlDYh8iVZKg90Sg1Ekk2WueAtRlAyMeGEtfcHLQkalQvFVlBYSpyTSHOH1Pe8Wey642coakWGdnZ9RBPQCk3c9KyurgmKLyKrKU01j8HpV@UpUlhNrJgBB49YMtm@qik6/qSqZU5X8u1UlRizfoyu6ND@iKz8oK3YK3KgqzWh34tL3ntwkJ7pS35CUMU@srHyvopCg7IOO6EZRuSIof0JP0u/WE4a6RsKXstL0n5WT5cuL6zwa4U5Mwh9UkwVPGzUZNNJh594XsnKdmOQ3qUl0o5YsxZLq06BTt5yyLKM203pFML6M26oMaUx8s5T8WR25RkSW8oF9jL/rReQNNdNflxH3tfV3CAnk41JMfkRF2hjxvCIhw1YQGvngVyUFRZNfLyqXInLK6x/WkIvxXxIRnf6tInJ3a@enVkfQCIiLne5fHIB28Ac/AXG5QCPkY0wkIjwgTFEnOisVN8zYSrCl5tqYB1LJws0BIgfY4PVxxqXi6G/0KQ5TWApQVwVip3YigASa4M3Or5iosWadFOeFSwASqRS1BsqF/q2hRLAAKe5iyGrMThyRg2IcWtBnNQGiyRdf7UyAl7ogFaEKmKYaQxtfCKXDa/tf9@/gfszloCya3tVRJAOggXzpQ0W4og@IXDRImMhU4vuSF3ZolgUKYCwVQQJIAcCkBIMoYNgJl1rAc@R9KHjIysyuwEE13yn0WNBwQ8hgSjXvO@CW/qEob@uHp4GkcnqGD9Cpc8DORe3juxeTcv0It6Q0cpXgOYoFYw5w5Ly5IUGvCceuL@w0NyJoXpsOhVnoGHPDL6HY9Hq/zuzndM5@RQRTCVg0AsgrO7tkvmyUHvutjnWRY9KhoDNNLcMhWiJwTKWByIoHbk7rlJAlu7lMsBuCGKVtj/T/G0QKuv95S9lP7a37/wM "C++ (gcc) – Try It Online") (PCRE2 / C++) [Try it online!](https://tio.run/##rVfvc9s2Ev2uvwJWPLXUkZU4vbu5i87ncRvnh5ukju1rL3PuaUASIiGBAAOAoqhO/vbcW4CS3dzZidt@8IwFAou3b9/uI6ui@vj3o6qo2K5lh6z/sM/GrLIin1pRKZ6Kwd7D8ddH02nBlZ@mpqykEvZqcDWcXJ0/dHsjtoe/GRanuaAN2gvt3WA6ffby1cl0OhyxgyFC9h/Wsj/pzYwd7MrDR5NddTjDATe4uHz68s1wMvyFydlgV/3beauExn/D/YOfDw/7V7o/xGZXJ3iC5dGj0f7BcBJ2y6FIC0NbJgxRDyY9hnU2uI7x1VcI@ejnncO9B3u4Yrc8DLmV3KfFYNeOsGXCKEjMWXHnp8JaoBzuHJ6dnzyfvvlhenJ@/sP5Uf@E1p@w/pPBbnnUv7S1eMLwq/@MK4d/@4j0AQBCtP6u6k8@fMLaYDj5@J/B0T/A5@CqejUcHO2Mv746GA5/efyXDx8/PmBnXOeWl67XO05P8peL1@at@2fzLnk6ezF/pc/s5fJf6953Tclmc2MzlnC9YLlqq8KxpVh59r6W63HvmVkx3Za0imgJraYLNpdLkbEGeLDluZIJm5t04cKZuJ15Q2FY1nA7G/fehmNrURWtdSxRphnRY6lzlvGZZ6eyHPdemKZbVG13UXi4Fonljs3rstrpvbZjdorLRuzyx3jfWfF0BPi5YzPRMNXq1bh3URVSr5iZ4S6OOO9rbv16hBhZLljZsqVpxr3LQkBtS8ESE6A0cs1tFm@KAFQ77v1EaY5iWlCnsVsS8kAV@7bONhnOQBeddkzLvPDIgycGF8TI494pwGS8cUzRKnAkMmduCzbCBLDGsMwCme6ILYSq2IyvNke64hBCASA4nZg8kL0UDgFbBlUW3bazOlEyBS5UeLOlqHOKFS8k2BQNkLCQLoiLTa3mRnna2eDyRCCFM@KTYCDVRuKSwGBm1gCr5Psa/Mzr3KEGIAwg5DpQa2qVYeuKva35QlhmkrlIPY5i508Fzq5NmUgg45YSH234D1nHsp1xT9VYgVSd0fOlsIg96jia1WUCNjyKWsn1msf6xlol1jT6RnXAvg07FV@3AJ8jsCG6nVQLVrVzXkJxYpUW6CJInaqeqFpcVwhn57wd4aqcRLEaRZkGaESXUURzoHOnd9wJYI/4TJh0m/ZIiwBnk6skjPlN4Ea3K5YbFFD/f@ixv9Cm@F8uOTsVWssZtrwylVijbE7vebRHKGoZ@6oQxCOmFuufClMBWLvTH7FjBUSXViRisUd06m2L5bzEkW9bdB6Vpty0p/N11pJwcVKmBhMCokHumnHMQLkW6NeW5dIqLEIlDvWPSoEdyAwMpgvMbQgLBONxTBtVfm6Ra7ttyBKSQUiPNk1RS7Q5FYRImJul5AqnhNBj8LxVBbsUK5Qwqgrba7Qjgw3FXgCdC5R1LhqhbBsJj5dta0FdhS10Sa5NKbYosYL5wStDCaIhjlW433lpNOTrKHDSxrZoiGX8FqtKWCQKWa2jRIOkwSl1E2p7WmvsRh8JRQngCCqagygBPFUJGySa6aBDLUDkmmoIpVv4Ac2ZEC@D/Dx6UDC5NBY9WtOAcFu2NA32UBiMIlluc7WCK0oGm7gPOxPBay9ntYL4GkoLiVMS2gHeuNd7wN4IbverzmTY4PGfIQLvhXXDXrCVm4YSRBRc5ZmhMXi7q/yPqWwn1lKAgu5YN9g@6ypGf9ZVqugq7otdJQeWL/EVU9v7@Mo9bSVMgTtdpRvt0VzGvad32Ylp1GcspeBlsJUvdRQylONmFLvgVlP5laH8Bj/RX@wnDLpGwte20vVfsJPty0vsPBrh0Uyye7rJmuvOTU466whz7xNbuc1M3F1uMrvTS7ZmSfq06NT96Cxb1HbR3jCMT3EHlyGPye@2kt/qI7eYyNY@8Bzj73YTeUfN9PttJMWc83@IkcA@rs3kPi6ywYjfNyzkcmMInX3wX1sKRONuN5VrE3nN23t7yEXxu0zE6D/URL7Zf/ynjY@gEYCLvT6@@A5lR/1wTsBcLtAIrsBEooKnxCl0YqpacctsUEKQWmxjnkolfZwDVBxwg9fHJZeKo7/RpwimsJRCVx7YqZ2IIIEmePf4e0zU3LCBRrxsS0AplaLWgFzoa6wGWJCUDzFkDWYnQjiUGEG9AK1EiKGz@EJlAnVpPbkIKWChDYY2vhDqyNfB3/76CPdjLqe173rXzGYyBRvIlz5URBR9SsVFg2Sl1BJfqNyHoVl7CKDA5yEoAaUgYF6jghAw9omYWsod8n4heMbqKqzggOq@U@inp@EGyKiU6t53UNuSS@02@uE6lSSn51aIRTyAJxdtYqXHpOy/xC2aRq4S@AhmmAykLse7G0r0mojVTUSY5lak3WvTC2HXJsfcSGo4Nr3e9/FYeqD/HggWErQYAHBNmF3SbRtlxH5sc@MdJh0EXRlqGQ7TEmmslE5F5Z/EOW00MUv7VrLE0wyFUSb0yPi/ "PHP – Try It Online") (PCRE2 / PHP) [Try it online!](https://tio.run/##rVf9c9Q2Gv59/wolzDS73GaPwF3nLiEwoRRoCjehybVlgMvItmxrV5aMJK/XZvjXL31eybsJ3CVA2/yQWcvv5/N@PFZa17tFml7ckjpVTSbY/cQY5/9qRSFWs7KuH4zSklt2Xr9@yw7ZT9uP2naR3Gtedd2vZ@W3bTm@@M/44YPZ7YfjN/Xzyfjh1uz2m73J5P3dbz9cTD4V3p6y2/Xhef2XvYPRpUcJh1bw6sFIas9qi//nwlpjx6nRzrMQwO1KOMcLMXnvfLa/n0KA3b/PhlP6Gc6FztQBs8I3VrO9gw/BZMWlHk/Y@xHDX/0a3pTQ43qyu/f28M4BayBz7@65Z4aeSKHAjyAcbEJe6gIv6sYfsBhTQGl/P8AEd@N6@tHR/r5MuROTg/Wpq7hPS9aW3EfLubFsTL56chr8FMIrqcU4Jij1NLqEkf5wbx0@/cmcjfsJwzuCZrzzRu9MDj56GxRf33nLvvmGrX9vHe7c2plsxAIWhHU@vhr5uRPcpmW0MA0BT5HghD1k22e2EfuMbbN9tv2EK4eH7SuO89ZKL6LmLD0HbOPJkMPMyV7Q096UcjWUVdD7EP4P9QLoHy5usROuC8srNxodpd8XPyxemJfu3@2r5HH@bP5cn9iz5a/96Lu2Yvnc2IwlXC9Yobq6dGwpVp69a2Q/Gz0xK6a7ik5hLaHTdMHmciky1nLlIfJUyYTNTbpwQSeKM2/IDMtabvPZ6GVQ60VddtaxRJl2Sq@pITKee3Ysq9nomWmHQ9UNjsLLXiSWOzZvqnpr9MLO2DGcTdnZz9HfSfkYbcMLx3LRMtXp1Wx0WpdSr5jJ4YvDzruGW99PYSNDm1cdW5p2NjorBcuRCtorhNLKntsseooBqG42@oXSnMa0pqHj1iAUASr2qMnWGeaAi7Qd07IoPfLgiYGDaHk2OkYwGW8dU3SKOBJZMLcJNoaJwFrDMovI9ABsKVTNcr5aqwzFoQgFAoF2YooA9lI4GOwwrb4cxE6aRMkUcaHCa5GyKchWdEhhkzWEhIN0QVisazU3ypNkC@eJQAonhCeFgVRbCScBwcz0CFbJdw3wmTeFQw0AGIKQfYDWNCqD6Iq9bPhCWGaSuUg9VCH5Swnd3lSJRGTcUuLTNf4h61i2E@6pGiuAqjN6vxS0UqYDRnlTJUDDo6i17Hse6xtrlVjT6ivVAfo2SCredwi@gGFDcDupFqzu5rxCx4kVNoMu0OpU9UQ14rJC0J3zbgpXBTXFahrbNIRGcBlFMAc4t0ZHQwPsEJ4Jk249HmkZwlnnKinG4mrgRncrVhgUUP//0ON8YUzxWy45OxZayxwiz00tepTN6R0sWh6KWsW5KgXhSJt0@1iYGoF1WyCVI4WIzqxIxGKH4NSbESt4BZVHHSaPSlOtx9P5JuuocaEpU4MNgaZB7ppx2oq9wLx2rJBW4RBd4lD/2Cm14jIDgulCeCwEAYDxOqaNKj@1yLXbDGSFloFJjzFNUUuMORWEQJibpeQKWkLoGXDedAU7EyuUMHYVxBuMIzZkHWcBcC5Q1rlohbJdBDw629SCpgoi5KTQBgy5jhIn2B@8NpQgBuJIBf/OS3Aa444MJ10ci5ZQxrNY1cIiUbRVH1s0tDQwpWlCbY8bDWnMkVCUAFRQ0QJACcRTVwIUB5hJ0aEWjIgANUSnW1PVtGeCvQzt5zGDgsmlsZjRhhaE26ClabGHwmAVyWqTK74bFCUDIe6DZCJ442XeKDRfS2khcUpCO4Q3G41usX@B4XbrgWTY@O7f0QTeC@smo0ArVwklNFFglSeG1uD1rPI/pLLZWEsBCAa1YbF9llWM/iyr1JFV3BezSoFYvoRXTGO/hle@klbCFriRVYbVHsllNnp8E52YVn2GUkpeBVr5UkYhQjlCOfIbSeUjQvkdfKK/mE8Y@hoJX9LKMH@BTjYfL3HyaIVHMsm@kk16rgc2@X6gjrD3PqGV68jE3cQm@Y1csiFL6k@LSd2NzLKJ2i66K4TxadyBZYhjipup5PfyyDUksqEPvMf6u55EXtEw/XEaSbHn/J9CJKCPSzL5GhZZx4jnKxRytiaEgT74x5SCpnHXk8olibzg3VdzyGn5h0jE6D@VRO7t3v3bmkcwCIiLvTg6/Q5lR/2gJ0AupxgEV2IjUcFTwhR9YupG4X5rQyeEVotjzFOppI97gIoDbPD5uORSccw35hTGFI5S9JVH7DROBJDAELy6@yM2amHYWMNetgGgkkrRaKBd4B73MoxI0hQTLFmD3QkTDiWGUS8AKwFiSBcXUyZQl84Ti1AHLLTB0sYNoYl47f3zH3fgH3s5bfwwuybPJa7ptIHpoiJi06dUXAxIVkktcUXkPizNxqMBSqkIEkAKAOYNKogGhpyIqdGNGqwoeMaaOpxAQQ33FHr0tNwQMiqlhu8d1JZu/27dP1ynktrpqRViERXw5rRLcHXFptz@AV40rVwlOK752AzUXY4PHirMmojVTUTY5lakw2fTM2F7U2BvJA0Ymz7vt1m4ETv2IyJYSMBiEIBrw@6SbjMoU/ZzVxjvsOnQ0LWhkeEgLZHGSulU1H4/7mmjCVmSW8kKbzMURpkwI7P/prkC71/sqnCjPw8X@t8A "C++ (gcc) – Try It Online") (Boost / C++) ## Regex (.NET / Java / Ruby), 23🐌, 24🐌, 26, or 27 bytes These regex engines don't support `\pL` (they support `\p{L}`, but that isn't useful when we already need the case insensitivity flag anyway), thus `[A-Z]` is used: `(.*([A-Z])(?!.*\2)){26}` (23 bytes) 🐌 `(.*?([A-Z])(?!.*\2)){26}` (24 bytes) 🐌 `(?>.*?([A-Z])(?!.*\1)){26}` (26 bytes) `^(?>.*?([A-Z])(?!.*\1)){26}` (27 bytes) ``` ^ # 1. Anchor to the start of the string (without this, the regex would still # work but would be slower in its non-matches, due to trying to match at # every character position in the string, which we know will fail, but # the regex engine can't know) (?> # 2. Start an atomic group (every complete iteration of matching this group # is set in stone, and will not be backtracked); without only a normal # group, the regex would still work, but with most non-pangram inputs, # would take longer than the age of the universe to yield a non-match, # due to trying every way of matching ".*?" at every iteration of the loop .*? # 3. Skip zero or more characters, as few as possible in order to make the # following match ([A-Z]) # 4. Capture and consume an alphabetical character in \1 (?! # 5. Negative lookahead: Match outside (with zero-width) only if the inside # does not match .* # 6. Skip forward by zero characters or more in an attempt to make the # following expresison match \1 # 7. Match the character captured in \1 ) # 8. The effect of this negative lookahead is to assert that at no point # right of where \1 was captured does any character match \1 ){26} # 9. Only match if this group can be matched exactly 26 times in a row, # i.e. if we can find 26 characters in the range A-Z that don't match # any character right of themselves, i.e. that we can find the last # occurrence of 26 different alphabetical character in the string. ``` [Try it online!](https://tio.run/##rVdrc9w2EvzOXwGtq6Ld1Iol6x6VWCX7FPmpWIl80sXny@WqQBIksQsCNAAul1T8250egruWc5FsJdEnLTkAZrqnp4nU7aXGiveaV8LVPBXsonNeVPGlWPv4n6JoFLdP1rUVzkmj3VWquHOsunKee5mylZEZO@NSs@nsasUtc0f/mLz/3/TRw/jLR9Mfj/f@89Ns@mgn/vK/92ezq4O/v3s/OaQwe6RFy7C/WE9dfNEkzlupi@n9uYtfCl34cu9gNh/ef197Ojk@MVUtlch@/ujpi0Ij/xPuxOww7MHUYZQbO5Xas/xo/3Cqjk4QaZRAPTx7KbWYzmY7R7pR6jA/uj@7kvk0f7g/20S9ttKLEHYYMSZzNlVjUg/32RdfMPXj/k87R7v3dmfsozXTydX@u8ncxi/cGfdpOVWzR5NL24gHjE0eTJ5y5fDvZNj1txaq2eE7/L2/x865LiyvXBQdp0@KF8sz88r9q32TPM6fL17qc3u5@ncfnbQVyxfGZizheskK1dWlYysQx942so@jp2bNdFfRU@yW0NN0yRZyJTLWcuUR8kzJhC1MunTDmhDOvKFtWNZym8fRq2FZL@qys44lyrRzek1QZzz37FRWcfTctOND1Y0HDS97kVju2KKp6p3ozMbsFIfN2eUP4bzz8vEc6ReO5egH1el1HF3UpdRrZnKcxbHP24Zb38@xR1YIVnVoujaOLkvBcpTCEjOk0sqe2yycFBJQXRy9pjLnoaw5Q1tsQSgGqNg3TbapMAdctNoxLYvSow6eGBwQdo6jUyST8dYxRU@RRyIL5rbJhjSRWGtYZpGZHoEthapZztebJSM5lKFAIlidmGIAeyUcNuxYxX05hp03iYLOFg0Y3oSUTUF7hQMpbdoNKeFBuiQsNlwtjPIU2eLwRKCEc8KT0kCprcQhA4KZ6ZGskm8b4LNoCgcOABiSkP0ArWlUhtA1e9XwpbDMJAuReixF5OsSa3tTJRKZcUuFzzf4D1UH2s65JzbWAFVn9H4lSKzzEaO8qRKg4UFqLfueB34DV4k1rb7GDtC3Q6TifYfkC2xsCG4n1ZLV3YJX6DixTkuoCK1OrCeqER8YwtoF7@Y4qqCmWM9Dmw6pEVxGEcwDnDvR8dgAu4RnwqTbyCMth3Q2tUrKsbieuNHdmhUGBOrfTj3oCzLF/3LF2anQWuYIeWlq0YM2p3c95DGQWgVdlYJwxHRhk1NhaiTW7Uzm7Fgho0srErHcJTj1VmIFRnscfdNBeURNtZGn803WUeNipUwNJgSaBrVrxlltZS@g144V0io8RJc48B86pVYcU38BdITHQBAAGK9D2WD5mUWt3VaQFVoGW3rINAWXkDkRQiAszEpyhVVC6Bg4b7uCwX1AYegqhDeQI7OiDloAnEvQuhCtULYLgIfDtlyQqhBCh8AfYG2bLPEE84PXhgqEII7VcL4bzIRxRxsnXZBFSyjjt1jXwqJQtFUfWnRoaWBKagK3p41GNHQkFBWAJWC0AFAC@dSVgBEBZlrowAWA7IlDdLqFpdGcGfbL0H4eGhRMroyFRhsaEG6LlqbBPhCDUSSrba1WcEXFIIj7ITIRvPEybxSar6WyUDgVoR3Si6PoHvtOcLtXjybDpgd/QxN4L6ybRYOtXDeUoYkGV3lqaAze7Cr/ZyrbibUSgGBcNg62T7qK0Z90lTq4ivtsVymQy@f4imnsXXzljrYyTIFbXWUc7cFc4ujxbXZiWvUJSyl5NdjK5zoKGcox6MhvNZWPDOV3@In@bD9h6GsU/MFWRv0NdrL9eAnKoxEezCS7o5v0XI9u8mS0jmHu/cpWbjITd5ub5Ld6ydYsqT8tlLoXnGWbtV121wzj13kPLkMeU9xuJb/XR24wka194D3G380m8obE9MdtJMWc83@KkcA@PpjJXVxkkyN@X7OQy40hjPbBP7YUNI272VQ@mMgZ7@7sIRflHzIRo/9UE/nL3sFfNz4CISAvdnZ8cQLawR/WCZjLBYTgSkwkIjwlTNEnpqZbJrNDJwytFmTMU6mkD3OAyAE2@Hxccak49A2dYjOFRyn6yiN3khMBJCCCNwffYqIWhk3papttAaikUiQNtAuOrxskC5CKGYYsrmO0hQPF2BSX4Jo2hUCxtkBiArx0nlyEOmCpDYY2bghNwOv@11/t43zM5bTxo3ZNnssUaKBeuqiI0PQpkQuBZJXUEndW7oeh2Xg0QIkbLiABpABg0YBBNDDiRCgtxT0XrohrLGvq4QkWqPGeQj89DTekDKbU@L0Dbitc0N2mf7hOJbXTMyvEMizAm4suwU0Uk3LyAqdoGrlKcIdmwZgDHI6PJ1TQmgjsJmKY5lak42fTc2F7U2BuJA0cmz7vJ3iNC65j3yKDpQQsBgm4dphd0m2FMmc/dIXxDpMODV0bkgyHaYk0MKVTUfsHYU4bTchS3FpWeJuBGGUGjcS/AA "C# (.NET Core) – Try It Online") (.NET / C#) [Try it online!](https://tio.run/##rVjvc9s2Ev2uvwJWZmrKJ7NO7sfcxeNm3MRJ7MYZ5@RLL9f2bkASJCGBAAOAoqiM//bcW4JSnDR24rb@YgnALnbf291Has6XfH@eLd7LqjbWszm@x9LEe4fs@krjpfrsmhWFWNFO3SRKpixV3Dl2zqVm74Yl57nHv6WRGauwEc28lbpg3Bbup18mzJfWtI6drFJRe2lgOGLsqVSC5UdatP3HaBynJhMx9seTw@@bPBdWZP8UPBOWJf2xjxejjeXwNZ9MDod73dQftiX5jyJ3lCAFnr2QWkSTyc6RbpSayDxysXjbcOWi8bd7e3vjyeTdx0eDhyjyn3XwDh781gMcfAsPCc4tDt2fjnZ/1rv03x9ehbWrC@69sJrZo@ETsq1qusBNNyuPj2cn/zt9OTt5OTu9PH19MjkETLOUaw0IpK4bz44YZT2sRbPOeVHFUk/Am/ZMHh0csiHx/nxccvdSrDziZu8YQpY7RweTwcxgvwZeXumIHBzdp/twYwBR4bLgRMPDgAl8sEjFSujCl9HkuwP2zTdMxWnJ7bGPDoDO7r3dSc8v/Z1zn5YIvoIvG1fhW6Tg59MY8qiKc6mzaMIesfGlbcRDxsbsIRs/BcL4gqK4@pUVubq6uhoRg@//Gz36Lt57FP10vP@fXybRo5147@f7oPXB367eE0Hv77ELrgvLKzcaHacnxeni3Lxy/2rfJE/y5/MX@sJeLv@9Hj1uK5bPjc1YwvWCFaqrS8eWAIG9beQ6Hj01K6a7ilbhLaHVdMHmciky1nLlceSZkgmbm3TheptwnHlDbljWcpvHo1e92VrUZWcdS5Rpp7RN2Gc89@xMVvHouWmHRdUNF/Wba5FY7ti8qeqd0bmN2Rkum7LL1@G@i/LJFOEXjuWoF9XpVTya1aXUK2Zy3MXhB7Vr/XoKH1khWNWhf9t4dFmiK5EKS0wfSivX3GbhphCA6uLRj5TmNKQ1ZbmxWxCKHir0arbJMAdcZO2YlkXpkQdPDC4InuPRGYLJOOaDolXEkUi08DbYECYCaw3LLCLTA7ClUDXL@WpjMpBDEQoEAuvEFD3YS@HgsMNs8uVw7CJMrnkDhjdHyqYgX@FCCpu8ISQspAvCYsPV3ChPJ1tcngikcEF4UhhItZW4pEcwM2sEq@TbBvjMm8KBAwCGIOS6h9Y0KsPRFXvV8AXaxCRzkXqY4uSPJWzXpkokIuOWEp9u8O@zDrRhdhAbK4CqM9pfCure6YBR3lQJ0PAgtZbrNQ/8Bq4SDGV9jR2gb/uTiq87BF/AsSG4nVQLVndzXqHixArNrguUOrGeqEZ8YAi2c95NcVVBRbGahjLtQyO4jCKYezh3RsdDAewSngmTbtMeadmHs8lVUozF9cCN7lasMCBQfz700F9oU3yWS87OhNYS0sFemFqsQZvTux7t0ZNahb4qBeGIAcXGZ8LUCKzbGU/ZsUJEl1YkYrFLcOptixW8gsn3HTqPqKk27el8k3VUuLCUqcGEQNEgd804w9BaC/RrxwppFRZRJQ78h0qpFYeAzoGO8BgIAgBjO6QNlp9Z5NptG7JCycClR5um4BJtToQQCHOzlFzBSggdA@dtVbBLsQKFoapwvEE7MisGFQecC9A6F61QtguAh8u2XFBX4QhdUmhTiW2UWMH84Hh0QIJoiGPV3@9I7VG@jhwnXWiLtpeBDJVUC4tEUVbrUKJ9SQNT6iZwe9ZonEYfCUUJwASMFgAKsivrSkDxADMZOnABINfEISrdQlppzvT@MpSfRw8KJpfGokcbGhBuixapWyAGo0hW21yh24qSwSHu@5OJ4HgiyhuF4mspLSROSWiH8OLR6B57KbjdrweRYdGDv6IISNvdZNTLynVB6YuoV5WnhsbgzaryK1HZTqylAASD2TDYvqgqRn9RVeqgKu6rVaVALF@jK6axd9GVO8pKPwVuVZVhtAdxiUdPbpMT06ovSErJq15WvlZRSFCOQUd@q6h8JCi/QU/0V@sJQ10j4Q@yMvRfLyfbh5fQeTTCg5hkd1STNdeDmpwM0tHPvU9k5SYxcbepSX6rlmzFkurTolP3g7Jso7aL7ppgfBp3rzKkMcXtUvJbdeQGEdnKB/Yx/m4WkTfUTL9fRlLMOf@HCAnk44OY3EVFNjHi@zUJudwIwiAf/GNJQdG4m0Xlg4ic8@7OGjIrf5eIGP2Hisif9x/8ZaMjaATExc6PZ49BO/iDnYC4zNAIrsREIsJTwhR1YupGcctsXwl9qYU25qlU0oc5QOQAGzw@LrlUHP2NPqW3WiylqCuP2KmdCCCBJnjz4AdM1MKwSMNftgWgkkpRa6Bc6MW28fTW3hQTDFmD2QkXDhTDKd7fanKKBoVtgcAEeOk8qQhVwELTTwV4Q2gCXvf/8fcD3I@5nDZ@6F2T5zIFGsiXXlREKPqUyEWDZJXU0nnLfT80G98N78SchBUAzBswiALGORFSS7lD3s/xls@aul@BgRreU@irp@GGkMGUGp53wC391uE29cN1KqmcnlkhFsEAO7MusdJjUo5PcYumkasEdygWjDnA4fhwQ4VeE4HdRPTT3Ip0eGx6LuzaFJgbSQPFpsf7MbalR/Q/IIKFBCwGAbi2n13SbRtlyl53hfEOkw4FXRtqGQ7REmlgStMvMg/DnDaakKVzK1lhNwMxyvQ9Ev8f "Java (JDK) – Try It Online") (Java) [Try it online!](https://tio.run/##rVf9c9s2Ev1df8VamantjsxJfB9zZ4/Po8bOh9ukTu1rL5fmMiAJUpBAgAFAUVTn7l/PvSUoxe2dnbjtbxK4AHbf27ePdE3afXB0Qt/JUq7qxMiWzqbX08RJkU/i4tHR86cvv/3u/PH06vyY1MnDY2pnSkvSJ6UMfkSkClI7vF43wR@TNDnHPTrmB/rNwaO3JyfjH834GDv0m4dJcnD4to@KW3d0Iqs6dKf0xRcIf/h252T3wS6eEdVOmUCaTv5Djk5pfO0aeUQ0piMaPxHa4894c9IQG/@@e3f@8uzduw//2jv9W/Ll6d6b6cE/3@7vne4kX/74aH//p8M///vDhwd0KUzpROVHo2l2Xj5fvLCv/N/b1@lZ8Wz@jbl018t/rEeP24qKuXU5pcIsqNRdPfO0lKtA7xu1TkZP7IpMV/EqTkt5NVvQXC1lTq3QASFPtUppbrOF7/fEcAqWj6G8Fa5IRq/6bWtZzzrnKdW2nfBjZUrKRRHoQlXJ6Jlth0XdDRf1D9cydcLTvKnqndELl9AFLpvQ9ffxvsvZ2QTpl54KMKw7s0pGV/VMmRXZAncJnPO@ES6sJzgjLyVVHS1tm4yuZ5IKlEKp7VNp1Vq4PN4UE9BdMvqBy5zEsiZUWLcFoeyhoq@afFNhAbh4tyejyllAHSK1uCCenIwukEwuWk@aV5FHqkry22RjmkistZQ7ZGYGYGdS11SI1WbLQA5nKJEIdqe27MFeSo8DO6pEmA1hl02qVYa8wPAmZNaUfFa8kNPm05ASFrIFY7Hham514MgWl6cSJVwynpwGSm0VLukRzO0ayWr1vgE@86b04ACAIQm17qG1jc4RuqJXjVhIRzadyyxgKyJ/mGHv2lapQmbCceGTDf591ZG2SxGYjRVANTk/X0roopwMGBVNlQKNAFJrtV6LyG/kKnW2NTfYAfquj9Ri3SH5EgdbhtsrvaC6m4sKHSdX2QwqQqsz66lu5EeGsHcuugmuKrkpVpPYpn1qDJfVDHMP585oOjTALuOZkvIbeWSzPp1NrYpzLG8mbk23otKCQPP/U4/6gkzxWy0FXUhjVIGQb2wt16DNm90AefSkVlFXM8k4hmxG4wtpayTW7YwnNNXI6NrJVC52GU6zlVgpKmz5qoPymJpqI08fmrzjxsVOlVlMCDQNajckeGatJfTaUamcxiK6xIP/2Cm1FioHgtkCYxaNBYDxOJYNlp861NptBVmhZXBkgEwzcAmZMyEMwtwuldDYJaVJgPO2K@harkBh7CqEN5AjOVlHLQDOBWidy1Zq10XA42VbLlhVCOFLSmMruc0SK5gforZcIAQx1f39Pihr0L6eD067KIuWUcZ/WI10KBRttY4t2rc0MGU1gduLxiAaOpKaC8AWMFoCKIl86kpi/ANm3ujBBYBcM4fodGfhL5wun5ej/QI0KEktrYNGGx4QfouW4cHeE4NRpKptrXBEzcUgSIQ@MpWiCapoNJqv5bJQOBdhPNJLRqMH9FIKd1APJkN7h39CE4Qgnd8f9bZy01D6Jupd5YnlMXi7q/yPqWwn1lICgmHbMNg@6SrWfNJV6ugq/rNdpUQun@MrtnH38ZV72ko/Be50lWG0R3NJRmd32Ylt9ScsZSaq3lY@11HYUKago7jTVH5mKL/CT8xn@wmhr1HwR1sZ9NfbyfblJSqPR3g0k/yebrIWZnCT88E6@rn3C1u5zUz8XW5S3OklW7Pk/nRQ6kF0lm3WbtHdMIxf5t27DHtMebeV/FofucVEtvaB5xh/t5vIaxbTb7eRDHMu/C5GAvv4aCb3cZFNjvh/w0KuN4Yw2If4uaWgafztpvLRRF6I7t4ecjX7TSZize9qIn84OPzjxkcgBORFL6ZXj0E7@MM@CXO5ghD8DBOJCc8YU/SJrRstHLm@E/pWizIWmdIqxDnA5AAbvD4uhdIC@oZOcZjGUoa@Csid5cQASYjg9eHXmKilpT2D8/ItAJXSmqWBdsH1@C6ERNKm3MeQtZidOMKDYhwa@NuPAbG8Fx@UJMFLF9hFuAMWxmJo4wuhiXg9@utfHuJ@zOWsCYN2bVGoDGigXv5QkbHpMyYXAskrZZQPToR@aDahG75fBRsrAJg3YBANjDgZS8uER93P8A1MTd2vYIMevlP4b@DhhpTBlB7ed8BtJZTxm/4RJlPcTk@dlIu4AU@uutSpgEk5fo5bDI9cLYVHs2DMAQ4vhhsqaE1GdlPZT3Mns@G16Zl0a1tibqQNHJtf78d4rAKy/xoZLBRgsUjAt/3sUn4rlAl935U2eEw6NHRtWTICpiWzyJTJZB2O4py2hpHluJWq8DQHMdr2Gkn@Cw "Ruby – Try It Online") (Ruby) ## Regex (ECMAScript / Python), 23🐌, 24🐌, 32, or 33 bytes The same progression of speed applies: `(.*([A-Z])(?!.*\2)){26}` (23 bytes) 🐌 - [Try it online! (ECMAScript)](https://tio.run/##fU1fS8MwHHzvp/iNwZKUttMhe1ipY@BEQWXqBHXuIW3TLlua1CRd3cY@e@3EN0E4jju4P2u6pSbRvLS@KXnKdKHkhu0aHUlWwxPLp18lxvvosu82OHDxYuK/LwkedwL3Y0DIYTA8Nm5/TwKrnq3mMsckMIInDA89/4J4gDgiYaY05tFZiEWkGU0FlwwT0olkJUTIo3NycAB4hjkp2w2LSdh6Ab0eiMXZshOhLjqZsrLGaqwDy4zFgozRXFdsBIBG6JoK00r0U/0NChIemy7MqMw1LQz4oKTYtcSg4JIXVJy0BzFLaGUY2BU30MIoMELVjjNJpvnt5l49mpf6Lb7KbtZ3cqbn29e943ThQUm//LvtAY1jzbacWpZ6kFDz3wWNk5Rl@YqvN6KQqvzUxlbb@hs "JavaScript (SpiderMonkey) – Try It Online") / [(Python)](https://tio.run/##fY5RS8MwEMff@ylu2UOb0Y5ugg@VIEOnDnROnaB2e0jbdM2WJjXpNqb42WuKiA@KcNzd/@7P76461IWSRw0vK6Vr0MzRQEAjhBqv3/PiUfCyxN5pp99bDDF@Hx5/NHYXD6JgsDwBTkInVxoEcAmqYtILceQA8Bx4BJXmsvZwq8ngayqsRWCgMgMRWwQh7kK6EQgi4rBl/mELlx3idt1vHpMZQXO9ZREAas2a9Q2jOi087YPwWz25nN7ej89GD2MMTBgG6ILaEgFqv/nhCNx0YUblStPSQABKioNNDEoueUlF2/uQsJRuLaQuuAEbRoERau84o3S8mmxu1J153D8n5/nV@lrO9Hz39OY4XZgqGVS/2T7QJNFsx2nNMh9Sav47QZM0Y/mq4OuNKKWqXrWpt7v9Jw "Python 3 – Try It Online") `(.*?([A-Z])(?!.*\2)){26}` (24 bytes) 🐌 - [Try it online! (ECMAScript)](https://tio.run/##bVVdb9s2FH3Xr7hugFoKFLUrhj408IJ0/VrQDsnqrdu6PlASJVGmSIWkrI@ivz07lGyvDwP8YFH349xzzqVqtmc2M6J1F7YVOTeNVjs@PpiN4j39xsvXQxuG0@anJ@cPYXJ@FX6@vvj7SxRerZLzf55F0ddnz789nD@ZosTpj84IVYZRYqXIePg8vvgximkt1tFloU0oNk8vQ7kxnOVSKB5G0WqjOikvxeaH6GtAJIpQRC1quDC6xLOkx49Jfn76ZbVZn639Q9s560xoEsetC2V0td6ajr8gWr9Yv2HS4u96Tj0Eyujy28MZ3TJVGtbYILjOXpe/7D7oO/t7/1f6qnhXv1e3Zrv/cwp@7hsqam1ySpnaUSnHtrK054Oj@05MSfBGD6TGxp@iWupPsx3VYs9z6pl0CHkrRUq1znZ2zlnCyWlfhvKemSIJ7ua0ibfVaCylUvexfw3mKGeFoxvRJME73R8O5XhoNL@ceGqYpbpr2lXwwSR0g2Yxbf9Y@t1Wr2LALy0VUE@OakiCj20l1EC6QC@GOvcdM26KUSMvOTUj7XWfBNuKU4FRKNUzlF5MzORLpwWAHJPgkx8zXsaKCaKeSChnquhllx8nLECXz7akRFk5zMFSjQZL5SS4AZic9ZakPwWOVJRkT2AXmADWa8oNkKkDsRWXLRVsOKYcxPEIOYAgO9XlTPaeWxQcqWGuOoTddim8CVxQ@BhSdaWvtTT0sH01QMJBtvNcHLWqtXQ@skfzlGOEW8@nh4FRe4EmM4O5ngBWivsO/NRdaaEBCAMIMc3U6k7mCB3ormM7bkinNc8cUhH5qULupJtUABkzfvD4yP889SLbLXNejQGkqty/33O/e/GBo6JrUrDhIGorpokt@i5apUb36jt1wL6ZIyWbRoAvUVh7uq2QO2rHmjVwHB@yClsEq3vVU9nx/xRCbs3GGK1Kb4ohXmw6Q/N0aelpnulcBdcHA6w9nykJe1yPrJrhHGcVHmP5PXCtxoFKDQHV/0Nf9gtriv9iz@iGKyUKhLzXLZ8gm1Vrh/WYRW2Wvaq459FlFT264boFsHH1KKZrCURbw1O@W3s61WnFStYg5eWIzfPSNMf1tK7LR29cZIpM44aAaTC7Ika40yaOfR2pFEbiEC6x0H9xSiuZyMFgtuMOFwIHwXi9jA2V3xrMOp4WsoFlUNJhTTNoiTX3gngSar0XTCKLc5WA55MraMsHSLi4CuEd1pEMb5ddAJ07yFrznkszLoQvzU5a@K1CiG9SKt3wE0qc4P5grfYDYiGu5dzfOqEV7Gt94XRc1qL3LOOZDy03GBS2mhaLzpYGp36boO1NpxCNPeLSD4AUKFqCKA48bcOV8zT7RAstQOTkNYTTjW5af8/M9XLYz2EHOYm9NtjRzl8Q9sSW8hf7LAyuItGcZsXnSfphEMTcHJly1jlRdBLm6/1YGNwPoSzgJUFwRr9qddEevjF0AaOijlZwB0uhEFRxPI8pYxZHKc9YZ/3gsD5@VpPFNyAIWJrlvCgrUe9ko3Rr4Kh9P4xT@y8 "JavaScript (SpiderMonkey) – Try It Online") / [(Python)](https://tio.run/##bVVNb9w2FLzrVzyvD@sNZMFJgB5cLAIncZwYSWo3btPW8YGSKIlaipRJafVR9Le786TdTQ4BDKxFvY95M/OoemgKa14@qaq2riEnA0drcovF4ukkevbq5P7i9J@H1cmro@jZtxer1b8vfvnvCS/vn5@fPn/4ldT6LMisI03KkK2lOTlbnQdEKiN1TrVTpjlZ8fP6@XyqEaJXJExK@h4l1uvlN7M8J73W92dc8ydhZw9H6@Xxcl9PmnS9uHOtPCdacLCTkZfCJcWJC0mH/Pzh6vNvv1@@ufhyuSKpvaTFO4Gfc1owmu919OrpmG6EyZ2ofBBcJJf5h80ne@v/6P6O32bvy4/mxt1t/xqDN11FWWldSrEwG8r1UBeetrJv6LFVYxS8sz2ZoeJTVIv5NNlQqbYypU7oBiFXWsVU2mTjp5w5nBrLZSjthMui4HZKG2VdDM5TrG0X8mtlckpF1tC1qqLgve12h3rYNZpejjJ2wlPZVvVR8MlFdI1mId39Ofe7Kd6GgJ97ymRHejB9FHypC2V6shl6CdR5bIVrxhA10lxSNdDWdlFwV0jKMArFdoLSqVG4dO40A9BDFHzlMcN5rJDYF3sS8okqet2m@wkz0MXZnozKiwZziNiiwVw5Cq4BJhWdJ82nwBGrnPwB7AwTwDpLqQMysyO2kLqmTPT7lJ04jFACCLJjm09kb6VHwYEq0RS7sJs21ioBLii8DynanGvNDRk2VwMkHCQb5mKvVWl1w5EdmscSI9wwnwwDo3YKTSYGUzsCrFaPLfgp29xDAxAGEGqcqLWtThHa020rNtKRjUuZNEhF5NcCuaOtYgVkwvHg4Z7/aepZthvRsBr9MG0Q3m8lLJ@HO46ytorBRgNRazWOYtZ31ip2tjM/qAP23RSpxTgAfI7Clun2Sm@oHkpRwXGyTwpsEazOqse6ld8VQm4phhCtcjZFH842naAxXVYzzROdR8HFzgBL5jMm5ffrkRQTnP2sijHmPwK3ZugptxDQ/Bz6vF9YU/yvtoKupTEqQ8hHXFwjZPNm2WA9JlGrea8KyTw2SUGLa2lrABuOFiFdaCC6czKWmyXTaQ4rlosKKa8HbB5LU@3X0zdtOrBxkakSixsCpsHshgRfR6PEvg6UK6dxCJd46D87pdZCpWAw2cgGF4IEwXg9jw2VrxxmHQ4LWcEyKNlgTRNoiTVnQZiE0m6V0MiS0kTg@eAKupM9JJxdhfAW64g7tJ53AXRuIGspO6ndMBM@NztowVuFEG6SG1vJA0qc4P4Q@LJgQCzEhZ76@0ZZA/t6LhwP81p0zDKeZV9Lh0Fhq3G26GRpcMrbBG2vW4No7JHUPABSoGgOoiTw1JU0DdPMiR5agMiRNYTTna1qvmemeins12AHJamtddjRli8If2DL8MU@CYOrSFWHWZ0UmodBkGimyFiKtlFZq2G@jsfC4DyE8YAXBcExfbbmtN59Y@gURkUda@AOEUMhqNLINKREeBzFMhGt58Fhffx5Sx7fgCAQcZLKLC9UudGVsbWDo7ZdP4z1/w "Python 3 – Try It Online") ECMAScript and Python lack atomic groups, so they must be emulated using lookahead+capture+backref: `((?=(.*?([A-Z])(?!.*\3)))\2){26}` (32 bytes) - [Try it online! (ECMAScript)](https://tio.run/##rVddc9s2Fn3Xr4CTmYrMyGripp02Hm/Gbb7qNB1n7W032/YBJEESEggwACiK7PS3Z88FKMXtrp247ZsE4gL3nnPPPeSKb7jLrWz9oWtlIWxj9FoM7@yJFj37p6iebtskGU/@8em9d0ny@CRZ3nuc/HR6@J9f0uTxwfLez5@lafrzUfrr0Re/vbv36ZguvbnwVuoqSZdOyVwkXywOH6YLNpfz9Lg0NpEn948TdWIFL5TUIknTgxPdKXUsTx6kv84Yk2Ui0xZn@CQ9xn/FPvmEqZ/u/3JwMr87pz9t5523iV164Xyi0sfzS9uJR4zNH82fceXwcx5Cp40qPf7t3V12znVleeNms9P8afXt@pV57f7Vv8melC9W3@lze7n59zj7pm9YuTK2YBnXa1apoa0d24itZ287OS5nz8yW6aGhVZyW0Wq@Ziu5EQXrufLY8lzJjK1MvnYhJm5n3tAxrOi5LZez1yFsFG09WMcyZfoFPQZyrOClZ2eyWc5emH5aVMN0UXg4isxyx1Zd0x7MXtklO8NlC3b5Q7zvvH6yQPqVYyVYVIPeLmcXbS31lpkSd3Gc87bj1o8LnFFUgjUD25h@ObusBStRCstMSKWXI7dFvCkmoIbl7EcqcxHLWjCQugehClCxr7tiV2EJuCjaMS2r2qMOnhlcEE9ezs6QTMF7xxStIo9MVsztk41pIrHesMIiMz0BWwvVspJvdyETOZShQCKIzkwVwN4IhwMH1nBfT9vOuwy9ibzA8G5L3VV0VryQ0qbTkBIW8jVhseNqZZSnnT0uzwRKOCc8KQ2U2ktcEhAszIhklXzbAZ9VVzlwAMCQhBwDtKZTBbZu2euOr4VlJluJ3CMUO3@sETuaJpPIjFsqfLHDP1QdaTvnntjYAlRd0PONIO0tJozKrsmAhgeprRxHHvmNXGXW9PoKO0Dfhp2KjwOSr3CwIbidVGvWDiveoOPENq@hIrQ6sZ6pTrxnCLErPixwVUVNsV3ENg2pEVxGEcwBzoPZ6dQAc8IzY9Lt5JHXIZ1drZJyrK4mbvSwZZUBgfr/px71BZnit9xwdia0liW2fGdaMYI2p@ce8gikNlFXtSAcfV6zO2fCtEhsOLizYKcKGV1akYn1nODUe4lVvEHI1wOUR9Q0O3k63xUDNS4iZW4wIdA0qF0zzjDTRgG9DqySVmERXeLAf@yUVnFZAMF8LTwGggDAeBzLBsvPLWod9oJs0DI40kOmObiEzIkQAmFlNpIrRAmhl8B53xXsUmxBYewqbO8gR2ZFG7UAONegdSV6oewQAY@X7bkgVWELXVJp04h9lljB/OCtoQIhiFMV7ndeGo32dXRwNkRZ9IQy/ottKywKRVuNsUVDSwNTUhO4Pes0dkNHQlEBCAGjFYASyKdthPYEMwU6cAEgR@IQnW5N09KcCecVaD8PDQomN8ZCox0NCLdHS9NgD8RgFMlmXyvsSVEx2MR92JkJ3nlZdgrN11NZKJyK0A7pLWezu@x7we1hO5kMS44@RxN4L6xLZ8FWrhpKaKLgKs8MjcHrXeV/TGU/sTYCEExh02D7oKsY/UFXaaOruI92lQq5fIyvmM7exlduaSthCtzoKtNoj@aynD25yU5Mrz5gKTVvgq18rKOQoZyCjvJGU/mdofwJP9Ef7ScMfY2C39vKpL9gJ/uXl6g8GuHRTIpbusnI9eQmTyfrCHPvD7ZynZm4m9ykvNFL9mZJ/Wmh1MPoLPus7Xq4Yhh/zDu4DHlMdbOV/FkfucZE9vaB5xh/15vIGxLTX7eRHHPO/y1GAvt4bya3cZFdjvh/xUIud4Yw2Qf/vaWgadz1pvLeRF7x4dYeclH/JRMx@m81kc8Ojx7ufARCQF7s1enFN6Ad/CFOwFwuIARXYyIR4Tlhij4xbae4ZTZ0Qmi1KGOeSyV9nANEDrDB6@OGS8Whb@gUhyks5egrj9xJTgSQgAjeHL3ERK0MSzTOK/YANFIpkgbaBdfjqwsSyboqxZA1mJ04woFiHOoFYCVADMVWSEyAl8GTi1AHrLXB0MYXQhfxevDVl/dxP@Zy3vlJu6Ys8V1paQLTh4qITZ8TuRBI0Ugt8dHHfRianUcD1FIRJIAUAKw6MIgGxj4RS8u5Q90v8EHKujasIEBN3yn019NwQ8pgSk3vO@C24VK7Xf9wnUtqp@dWiHUMwJOLIbPSY1Le@Ra3aBq5SnCHZsGYAxyOTzc00JqI7GYiTHMr8um16YWwo6kwN7IOjk2v93fwWOLbl71EBmsJWAwScH2YXdLthbJgPwyV8Q6TDg3dGpIMh2mJPDKlc9H6R3FOG03I0r6tbPC0ADHKBI0s/ws "JavaScript (SpiderMonkey) – Try It Online") / [(Python)](https://tio.run/##rVddc9s2Fn3nr7hWHix1ZI3jdHd2vaPJuPl2m9ZZe9vNJnkASYiEBAIMAIqiOvvbs@cSlOx2aydu@2QTBC7OPefee6i6C6U1jz6pqrYukJOJozm50Wj0aTx@PB/Pvno8fnd29J8Pk/Hjg9lX7x9NJpP3J5OfT/7630/Y9O7h6dHDD/8gNT9OFtaRJmXI1tKMjyenCZFakDql2ikTxhN@nj@Mqxpb9ISEyUm/Q4j5/PC9OTwlPdfvjjnmb2w7/nAwP3xwuIsnTT4fXblGnhKNeLOTMy@Fy8qxm5Ke8vOrF9//8M9nT84un01Iai9p9FzgzymNGM11HD359IAuhCmcqHySnGXPiler1/aN/1f7Nn26eLn8zly4q/W/t8mTtqLF0rqcUmFWVOiuLj2t5SbQx0ZtZ8lzuyHTVbyKaCmvZitaqrXMqRU6YMsLrVJa2mzl@zNxOwXLYShvhVvMkjf9sa2sy855SrVtp/xamYJysQh0rqpZ8tK2w6Luhov6l1uZOuFp2VT1QfLazegcl03p6sd430X5dAr4haeFbEl3ZjNLLutSmQ3ZBe4SiPOxES5sp4iRF5Kqjta2nSVXpaQFUqHU9lBatRUujzdFALqbJT9xmtOY1pS4LnYkFD1V9E2T7zJcgC4@7cmoogzIQ6QWF8TIs@QcYHLRetK8ChypKsjvwUaYANZayh2QmYHYUuqaFmKzOzKIwwglgOB0aoue7LX0CNhRJUI5bLtoUq0y4ILCuy1lU3CseCHD5miAhIVsxVzstFpaHXhni8tTiRQumE@GgVRbhUt6BnO7BVitPjbgZ9kUHhqAMIBQ255a2@gcWzf0phEr6cimS5kFHMXOn0qc3doqVUAmHCc@3fHfZx1luxCB1dh0fQfh/Vqi5IvpwNGiqVKwESBqrbZbEfWNWqXOtuaGOmDf9Tu12HYAXyCwZbq90iuqu6WoUHFyk5XoIpQ6q57qRl4rhLNL0U1xVcFFsZnGMu2hMV1WM809nQfJ2VAAh8xnSsrv2iMrezi7XBVjLG4Ct6bbUGEhoPlt6LG/0Kb4X60FnUtj1AJbvsPg2kI2bw4D2qMXtYp9VUrmMWQljc6lrQGsOxhN6UwD0ZWTqVwdMp1m32KFqHDkmw6dx9JUu/b0ock7LlycVJnFhEDRIHdDgsfRVqJfOyqU01hElXjoHyul1kLlYDBbyYCBIEEwXse0ofILh1y7fUNWKBmEDGjTDFqizVkQJmFp10ponJLSzMDzviroSm4gYawqbG/QjpihdewF0LmCrEvZSu26SHi8bK8FdxW28CWFsZXco8QK5oeAwyBBNMSZ7u/3QVmD8vUcOO1iW7TMMp7lppYOiaKstrFE@5IGp9xN0Pa8MdiNPpKaE8ARKFqAKAk8dSVNYJr5oIcWIHLLGqLSna1qnjN9vBzlF9CDktTaOvRowwPC79kyPNh7YTCKVLXP1UmhORlsEqHfmUrRBLVoNIqv5bSQOCdhPODNkuQBfQ9zOqoHk6HxyV9QBCFI5ydJbys3DaUvot5Vnlseg7e7yv@Zyn5irSUoGI4Ng@2zrmLNZ12ljq7iv9hVCmD5El@xjbuPr9zTVvopcKerDKM9mssseXqXndhWf8ZSSlH1tvKljsKGcgY5Fneayi8M5Xf4ifliPyHUNRK@tpWh/3o72X@8xM7jER7NJL@nm2yFGdzk2WAd/dz7la3cZib@LjdZ3Okle7Pk@nTo1KPoLHvUbtXdMIxf4@5dhj2muNtKfq@P3GIie/vAe4y/203kLTfTH7eRDHMu/ClGAvu4NpP7uMgOI55vWMjVzhAG@xC/tBQUjb/dVK5N5LXo7u0hl@UfMhFr/lQTeXR08vXOR9AIwEWvzy6fQHboh3MS5nKJRvAlJhILnjGnqBNbN1o4cn0l9KUW21hkSqsQ5wCLA27w@bgWSgv0N/oUwTSWMtRVAHZuJyZIognennyLiVpYGhvEy/cEVEprbg2UC66vG4AFScUEQ9ZidiKEh8QIGiRoZUIsny0ATEIX/EblskKglbEY2viF0ES@Hv79b8e4H3M5a8LQu3axUBnYQL78Q0XGos9YXDRIXimjfHAi9EOzCSiAUmmmBJSCgGUDBVHA2CdjapnwyPulFDk1db@CA3r4ncKPgYcbIEMpPXzvQNtKKON39SNMpricXjgpV/EA3lx2qVMBk3L0CrcYHrlaCo9iwZgDHV4MN1ToNRnVTWU/zZ3Mhs@ml9JtbYG5kTZwbP68H@G1CkD/LRCsFGixAODbfnYpv2@UKf3YFTZ4TDoUdG25ZQRMS2ZRKZPJOpzGOW0NM8v7NqrC2xzCaNv3yOx/ "Python 3 – Try It Online") `^((?=(.*?([A-Z])(?!.*\3)))\2){26}` (33 bytes) - [Try it online! (ECMAScript)](https://tio.run/##rVdrc9s2Fv2uXwEnMxWZkdXUTTu78XgzbvOqm@w4a2/b9LEzIAmSkECAAUBRZKe/PXsuQCnuw07c9psE4gL3nnPPPeSKb7jLrWz9oWtlIWxj9FoMb@2JFj37j6iebNskGU/@9fG9t/9LkkcnyfLeo@SH08Pvf0qTRwfLez9@mqbpj0fpz0ef//L23sdjuvTmwlupqyRdOiVzkXy@OHyQLthcztPj0thEntw/TtSJFbxQUoskTQ9OdKfUsTz5JP15xpgsE5m2OMMn6TH@K/bRR0z9cP@ng5P53Tn9aTvvvE3s0gvnE5U@ml/aTjxkbP5w/pQrh5/zEDptVOnxL2/vsnOuK8sbN5ud5k@qr9YvzSv33/519rh8vnqhz@3l5rtx9mXfsHJlbMEyrtesUkNbO7YRW8/edHJczp6aLdNDQ6s4LaPVfM1WciMK1nPlseWZkhlbmXztQkzczryhY1jRc1suZ69C2CjaerCOZcr0C3oM5FjBS8/OZLOcPTf9tKiG6aLwcBSZ5Y6tuqY9mL20S3aGyxbs8pt433n9eIH0K8dK0KgGvV3OLtpa6i0zJe7iOOdNx60fFzijqARrBrYx/XJ2WQtWohSWmZBKL0dui3hTTEANy9m3VOYilrVgIHUPQhWgYl90xa7CEnBRtGNaVrVHHTwzuCCevJydIZmC944pWkUemayY2ycb00RivWGFRWZ6ArYWqmUl3@5CJnIoQ4FEEJ2ZKoC9EQ4HDqzhvp62nXcZehN5geHdlrqr6Kx4IaVNpyElLORrwmLH1cooTzt7XJ4JlHBOeFIaKLWXuCQgWJgRySr5pgM@q65y4ACAIQk5BmhNpwps3bJXHV8Ly0y2ErlHKHZ@WyN2NE0mkRm3VPhih3@oOtJ2zj2xsQWouqDnG0HaW0wYlV2TAQ0PUls5jjzyG7nKrOn1FXaAvg07FR8HJF/hYENwO6nWrB1WvEHHiW1eQ0VodWI9U514xxBiV3xY4KqKmmK7iG0aUiO4jCKYA5wHs9OpAeaEZ8ak28kjr0M6u1ol5VhdTdzoYcsqAwL1H6ce9QWZ4rfccHYmtJYltrwwrRhBm9NzD3kEUpuoq1oQjj6v2Z0zYVokNhzcWbBThYwurcjEek5w6r3EKt4g5IsByiNqmp08ne@KgRoXkTI3mBBoGtSuGWeYaaOAXgdWSauwiC5x4D92Squ4LIBgvhYeA0EAYDyOZYPlZxa1DntBNmgZHOkh0xxcQuZECIGwMhvJFaKE0EvgvO8Kdim2oDB2FbZ3kCOzoo1aAJxr0LoSvVB2iIDHy/ZckKqwhS6ptGnEPkusYH7w1lCBEMSpCvc7L41G@zo6OBuiLHpCGf/FthUWhaKtxtiioaWBKakJ3J51GruhI6GoAISA0QpACeTTNkJ7gpkCHbgAkCNxiE63pmlpzoTzCrSfhwYFkxtjodGOBoTbo6VpsAdiMIpks68V9qSoGGziPuzMBO@8LDuF5uupLBRORWiH9Jaz2V32b8HtYTuZDEuOPkMTeC@sS2fBVq4aSmii4CpPDY3B613ld6ayn1gbAQimsGmwvddVjH6vq7TRVdwHu0qFXD7EV0xnb@Mrt7SVMAVudJVptEdzWc4e32QnplfvsZSaN8FWPtRRyFBOQUd5o6n8ylD@hJ/oD/YThr5Gwe9sZdJfsJP9y0tUHo3waCbFLd1k5HpykyeTdYS59xtbuc5M3E1uUt7oJXuzpP60UOphdJZ91nY9XDGM3@YdXIY8prrZSv6sj1xjInv7wHOMv@tN5DWJ6a/bSI455/8WI4F9vDOT27jILkf8v2IhlztDmOyD/9pS0DTuelN5ZyIv@XBrD7mo/5KJGP23msinh0cPdj4CISAv9vL04kvQDv4QJ2AuFxCCqzGRiPCcMEWfmLZT3DIbOiG0WpQxz6WSPs4BIgfY4PVxw6Xi0Dd0isMUlnL0lUfuJCcCSEAEr4@@xkStDEs0ziv2ADRSKZIG2gXX46sLEsm6KsWQNZidOMKBYhzqBWAlQAzFVkhMgJfBk4tQB6y1wdDGF0IX8frkn/@4j/sxl/POT9o1ZYnvSksTmD5URGz6nMiFQIpGaomPPu7D0Ow8GqCWiiABpABg1YFBNDD2iVhazh3qfo4PUta1YQUBavpOob@ehhtSBlNqet8Btw2X2u36h@tcUjs9s0KsYwCeXAyZlR6T8s5XuEXTyFWCOzQLxhzgcHy6oYHWRGQ3E2GaW5FPr03PhR1NhbmRdXBser2/g8cS377sa2SwloDFIAHXh9kl3V4oC/bNUBnvMOnQ0K0hyXCYlsgjUzoXrX8Y57TRhCzt28oGTwsQo0zQyPL/ "JavaScript (SpiderMonkey) – Try It Online") / [(Python)](https://tio.run/##rVfvc9s2Ev3Ov2KtfLDUkTWOc3dz5xtNxs1vt@k5Z197uSQ3A5IQCQkEGAAURXX6t@feEpTs9monbvvJJggs3r63u4@qu1Ba8@iTqmrrAjmZOJqTG41Gn/47Hj@ej2dfPR6/Ozv6z4fJ@PHB7Kv3jyaTyfuTyY8nf/npE3a9e3h69PDD30nNj5OFdaRJGbK1NOPjyWlCpBakTql2yoTxhJ/nD@OqxhY9IWFy0u8QYj4/fG8OT0nP9btjjvkr244/HMwPHxzu4kmTz0dXrpGnRCPe7OTMS@GycuympKf8/OrFd//457MnZ5fPJiS1lzR6LvDnlEaM5jqOnnx6QBfCFE5UPknOsmfFq9Vr@8b/q32bPl28XH5rLtzV@t/b5Elb0WJpXU6pMCsqdFeXntZyE@hjo7az5LndkOkqXkW0lFezFS3VWubUCh2w5YVWKS1ttvL9mbidguUwlLfCLWbJm/7YVtZl5zyl2rZTfq1MQblYBDpX1Sx5adthUXfDRf3LrUyd8LRsqvogee1mdI7LpnT1fbzvonw6BfzC00K2pDuzmSWXdanMhuwCdwnE@dgIF7ZTxMgLSVVHa9vOkqtS0gKpUGp7KK3aCpfHmyIA3c2SHzjNaUxrSlwXOxKKnir6usl3GS5AF5/2ZFRRBuQhUosLYuRZcg4wuWg9aV4FjlQV5PdgI0wAay3lDsjMQGwpdU0LsdkdGcRhhBJAcDq1RU/2WnoE7KgSoRy2XTSpVhlwQeHdlrIpOFa8kGFzNEDCQrZiLnZaLa0OvLPF5alEChfMJ8NAqq3CJT2Dud0CrFYfG/CzbAoPDUAYQKhtT61tdI6tG3rTiJV0ZNOlzAKOYucPJc5ubZUqIBOOE5/u@O@zjrJdiMBqbLq@g/B@LVHyxXTgaNFUKdgIELVW262I@katUmdbc0MdsO/6nVpsO4AvENgy3V7pFdXdUlSoOLnJSnQRSp1VT3UjrxXC2aXopriq4KLYTGOZ9tCYLquZ5p7Og@RsKIBD5jMl5XftkZU9nF2uijEWN4Fb022osBDQ/Dr02F9oU/yv1oLOpTFqgS3fYnBtIZs3hwHt0Ytaxb4qJfMYspJG59LWANYdjKZ0poHoyslUrg6ZTrNvsUJUOPJ1h85jaapde/rQ5B0XLk6qzGJCoGiQuyHB42gr0a8dFcppLKJKPPSPlVJroXIwmK1kwECQIBivY9pQ@YVDrt2@ISuUDEIGtGkGLdHmLAiTsLRrJTROSWlm4HlfFXQlN5AwVhW2N2hHzNA69gLoXEHWpWyldl0kPF6214K7Clv4ksLYSu5RYgXzQ8BikCAa4kz39/ugrEH5eg6cdrEtWmYZz3JTS4dEUVbbWKJ9SYNT7iZoe94Y7EYfSc0J4AgULUCUBJ66kiYwzXzQQwsQuWUNUenOVjXPmT5ejvIL6EFJam0derThAeH3bBke7L0wGEWq2ufqpNCcDDaJ0O9MpWiCWjQaxddyWkickzAe8GZJ8oC@gzkd1YPJ0PjkzyiCEKTzk6S3lZuG0hdR7yrPLY/B213l/0xlP7HWEhQMx4bB9llXseazrlJHV/Ff7CoFsHyJr9jG3cdX7mkr/RS401WG0R7NZZY8vctObKs/YymlqHpb@VJHYUM5gxyLO03lZ4byG/zEfLGfEOoaCV/bytB/vZ3sP15i5/EIj2aS39NNtsIMbvJssI5@7v3CVm4zE3@Xmyzu9JK9WXJ9OnTqUXSWPWq36m4Yxi9x9y7DHlPcbSW/1UduMZG9feA9xt/tJvKWm@n320iGORf@ECOBfVybyX1cZIcRzzcs5GpnCIN9iJ9bCorG324q1ybyWnT39pDL8neZiDV/qIk8Ojr5085H0AjARa/PLp9AduiHcxLmcolG8CUmEgueMaeoE1s3WjhyfSX0pRbbWGRKqxDnAIsDbvD5uBZKC/Q3@hTBNJYy1FUAdm4nJkiiCd6efIOJWlgaG8TL9wRUSmtuDZQLrq8bgAVJxQRD1mJ2IoSHxAgaJGhlQiyfLQBMQhf8SOWyQqCVsRja@IXQRL4e/u2vx7gfczlrwtC7drFQGdhAvvxDRcaiz1hcNEheKaN8cCL0Q7MJKIBSaaYElIKAZQMFUcDYJ2NqmfDI@6UUOTV1v4IDevidwo@BhxsgQyk9fO9A20oo43f1I0ymuJxeOClX8QDeXHapUwGTcvQKtxgeuVoKj2LBmAMdXgw3VOg1GdVNZT/NncyGz6aX0m1tgbmRNnBs/rwf4bUKQP8NEKwUaLEA4Nt@dim/b5Qpfd8VNnhMOhR0bbllBExLZlEpk8k6nMY5bQ0zy/s2qsLbHMJo2/fI7H8 "Python 3 – Try It Online") --- *Edit: Silly me, I assumed that this problem required variable-length lookbehind or other tricks that substitute for it, without even trying to do it without that. Thanks to @Neil for pointing this out.* [Answer] # Julia, 38 bytes ``` s->endof(∩('a':'z',lowercase(s)))>25 ``` This is simple - `lowercase` deals with the uppercase/lowercase issue, `'a':'z'` holds all of the lowercase letters, `∩` is intersection, removes any character that isn't a letter and, because `'a':'z'` comes first, will only have one of each letter that appears in `s`. `endof` is the shortest way to get the length of the resulting array, and if it's 26, then it's a pangram (it can't be more than 26, and `>25` saves a byte relative to `==26`). [Answer] # Ruby, ~~41~~ 33 ``` ->s{(?a..?z).all?{|c|s[/#{c}/i]}} ``` ## Usage ``` p=->s{(?a..?z).all?{|c|s[/#{c}/i]}} p["AbCdEfGhIjKlMnOpQrStUvWxYz"] #=> true p["ACEGIKMOQSUWY BDFHJLNPRTVXZ"] #=> true p["public static void main(String[] args)"] #=> false p["The quick brown fox jumped over the lazy dogs. BOING BOING BOING"] #=> true ``` Thanks to Vasu Adari for saving me 8 bytes [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 4 bytes ``` lêAå ``` [Try it online!](http://05ab1e.tryitonline.net/#code=bMOqQcOl&input=VGhlIHF1aWNrIGJyb3duIGZveCBvdmVyIHRoZSBsYXp5IGRvZ3MuIEJPSU5HIEJPSU5HIEJPSU5H) ``` l # Push lowercase input. ê # Push sorted, uniquified lowercase input. A # Push lowercase alphabet. å # Is lowercase alphabet in sorted, uniquified, lowercase input? # True if panagram, false if not. ``` [Answer] ## [Retina](https://github.com/mbuettner/retina), 22 bytes ``` Msi`([a-z])(?!.*\1) 26 ``` [Try it online.](http://retina.tryitonline.net/#code=TXNpYChbYS16XSkoPyEuKlwxKQoyNg&input=MTIzYWJjZGVmZ2hpamtsbQp5Tk9QUVJTVFVWV1h6WnozMjE) The first line matches any letter which does not appear again later in the string. That ensures that we don't match each letter at most once, no matter how often it occurs. Match mode will by default replace the string with the number of matches found. So in the second stage, we match `26` against the result of the first input, which will give either `0` or `1`, depending on whether we found the maximum of 26 matches or not. [Answer] # Python 3.5, 47 bytes ``` lambda s:{*map(chr,range(65,91))}<={*s.upper()} ``` Same principle as [Mitch Schwartz's answer](https://codegolf.stackexchange.com/a/66224/13959), but using the [PEP 0448](https://www.python.org/dev/peps/pep-0448/) enhancements to `*` unpacking, first introduced in Python 3.5. This version differs slightly from what I wrote in my comment to Mitch's post, in that I turn the numbers into letters rather than vice versa. That's because that's how I wrote my original attempts at a solution, before discovering that I couldn't out-golf Mitch without outright copying his approach. So consider that tweak my one remaining shred of originality! [Answer] # [Haskell](https://www.haskell.org/), ~~59~~ ~~56~~ ~~53~~ 51 bytes ``` p s=and[any(`elem`map toEnum[a,a+32])s|a<-[65..90]] ``` [Try it online!](https://tio.run/##TY3BTsJAAAXvfMVLT23Exmg0MZEDYK0VoWJBxNqELV3awnZ37W4rEP@91nDx8ubwJpmMqB1lrGkkVI/wJCT8YK4oo8WqIBJaOLwqQtIlZ1eXkaV@yN15eHNt27cXUdQUJOfooRXHMGWZcw0b0kIHodGPh4mzcTNvO2Jj7stpGeh5vdgvj0a3Axj9oeN6o7E/DeaL5Scf3D88Pj1PXl5nb@8fJ0NWMcvXUJroFrXIE/wFzUC3pTSMQMpUWSd3llF8Vfl6h7gU3xwbsce2KiRNIGpaQrc/I8cDEpEqGwPfm7j/14iaXw "Haskell – Try It Online") **Explanation:** Give an input string `s`, for each `a` in range 65 to 90 (the ASCII codes for `A` to `Z`) it is checked whether any character in `s` is equal to either `a` (the upper case character) or `a+32` (the lower case character), converted to a character by `toEnum`. This generates a list of booleans. `and` checks if they're all `True`. **Old version:** ``` import Data.Char p s=and[any((==)a.toUpper)s|a<-['A'..'Z']] ``` For every upper case alphabet letter, check whether some letter from `s` in upper case is equal to it. `any(==a)s` is the same as `elem a s` but allows to modify the elements of `s` before the comparison - in this case, covert them to upper case. [Answer] # [Haskell](https://www.haskell.org/), 43 bytes ``` f s=until(all(`notElem`s))(succ<$>)"Aa">"[" ``` [Try it online!](https://tio.run/##TY3LTsJAAEX3fMXNhEWbGL5ASArWWhEqFkSsJEzfA9OZOjOtyM/XGjZs7lnck5yS6lPGedfl0ONGGMYtyrl1ENK4PKsO2rYt3STJ/XBiE4eSCYlIV1EmMEatmDAYoqI18p4DRMSJZ6mbe6V/nPOFCOqVCs2m3Z53F3I3AIgzcz1/vghW4Wa7@xLTh8en55fl69v6/ePzatRNzFkCbajp0UqW4r9nhabPFdEeVBXavrrrMsN3w5ITYiV/BHJ5xrGp6iyFbDMF0/@cXn6RykKPMA38pXe7ZN/9AQ "Haskell – Try It Online") Iterates through the lowercase/uppercase pairs until it finds one where both are not elements of the input, and checks that this failure is past the alphabet. [Answer] # [Vim](https://www.vim.org/), ~~30~~ 26 bytes ``` :%s/\A*/\r/g :sor ui 26Dr1 ``` [Try it online!](https://tio.run/##K/v/30q1WD/GUUs/pkg/ncuqOL9IoTSTy8jMpcjw//@QjFSFwtLM5GyFpKL88jyFtPwKhazS3ILUFIX8stQihRKgfE5iVaVCSn56sZ6Ck7@nnzsyCQ) Let's get this [language of the month](https://codegolf.meta.stackexchange.com/q/21955/62393) started! I am still a beginner in Vim, so golfing suggestions are much appreciated :) ### Explanation The first line of the program uses a regex to substitute any (possibly empty) sequence of non-alphabetic characters (`\A*`) with a newline; since the empty string also gets matched, this will result in a series of lines each containing at most one character, which will be a letter. The first line will always be empty (the initial empty string became a newline). `:sor ui` `sor`ts the lines `i`gnoring case, and removes duplicates (also ignoring case). If the input was a pangram we will now have an empty line followed by 26 lines each with a character from `a` to `z`; if the input was not a pangram, some of those lines will be missing. `26D` deletes the first 26 lines, which will leave us with either `z` (for a pangram) or an empty string (for a non-pangram). The only truthy values in Vim are non-zero numbers (or strings starting with a non-zero number), so our last step will be `r1` (replace the first character with `1`) which will result in `1` for a pangram, and an empty string otherwise. [Answer] These have the same regex as in my [regex answer](https://codegolf.stackexchange.com/a/197535/17216). I felt it was worth posting a standalone answer showing its use in languages that don't require an import to access regex functions (resulting in very effective golf). In order of how favorably it compares against the current best non-regex answer. This answer previously showed programs/functions that couldn't handle multiline input (as the challenge demonstrates is required by its second test case), but they all do so properly now unless otherwise noted. # Java, 46 bytes `a->a.matches("(?si:.*([A-Z])(?!.*\\1)){26}.*")` (46 bytes, always slow) - [Try it online!](https://tio.run/##fY/BbtswDIbvfgrGAVopiIWshx3iOUGGrdiAtuiQFtjW9kA7sq1EpjxLjpcVefZUdbrLAgwQJFI/@f3kGrcYrVebg6pq0zhY@1y0TmmRt5Q5ZUiMYjgRR3GQabQWrlERPAcAdZtqlYF16PyzNWoFldfY0jWKiocnwKawvC8FuHxjfziq44/GaIk0gxySA0YzFBW6rJSWhWxu1VSM2MMi@vnE2XwgRo@PF5w/X7zfi1HID7EnLjMkkg0oqlsHCZDs/v6x5c46WQlF3O9BDlQyiaErlZbA@npRor2Rvx3jfjxQOVODZMLf2ozXaz@j08ReAcm7uN/gODhob3aEkCdcKZJ9VQ5MCy2pcCXjswmcnYEWWYnNwrEJHyTnw3PeYzzoHx@WC6xrvWOawxzCu6aVU4AQphBeorY@Cb3DSZfmcbDf7w9DuEUqGqwsRGBI7/wloVKkKtSv8RhSmWFrJbhSWfDHGrDadEGwyD4XXzfX5pu9736kn/Iv6yu6be623/8EwRBuDEX1KXsMmKaN3Cp0cjWGDO3/LDDNVjIvSrXe6IpM/auxrt12Lw "Java (JDK) – Try It Online") `a->a.matches("(?si:.*?([A-Z])(?!.*\\1)){26}.*")` (47 bytes, slow for non-matches) - [Try it online!](https://tio.run/##bVVdT9w4FH3Pr7hMpZKgIaL7sA9lAdHt0i6Cigr2s@2DkziJM44dbGcyScVvZ4/jmdlquxIS4NyPc8@5x27Ymh03xepZtJ02jhr8n/ZOyLTsVe6EVunRKX338eg0yiWzlm6ZUPQ1Iur6TIqcrGMOv9ZaFNTiW3zvjFDVpy/ETGWTOZToalv7p/B1@UZryZk6p5LOntnxOUtb5vKa23gRX1jxOj26iD9dHv/9JYkvDtKjz59fJcnXH358So8WyfMpSt7nTCluSKiud3RGig@7s/h@tI63qVAJBlGOxNnJKQ21kJziOT6tmf3ANy5OgI9EGYuDs5Nkm6bxvQNIJ1XsC5y9Op1HCMhJolkoolDhRig@R5UUy1RyVbk6Ts5P6OVLkmleM3Pp4pPk4OzwxWEyl0Gh//SJy5R1nRxjmdAFLR5Mz18TLeg1La6YtPhngQ7fZcnkNHp6enp@QXdMVYa1Noou81@qX1e3@qP9bfgre1u@b27UnXlY/zlFPw8tlY02BWVMraiSY1dbWmMGeuzFlEZXekNqbP0pqmX@NF9RI9a8oIFJh5B3UmTU6Hxl55wQTk77MlQMzJRp9HFOm3hXj8ZSJvWw9J89dQUrHV2LNo3e62F7KMdto/njxDPDLDV92x1EtyalazRb0sPvod9d/XYJ@JWlEnLLUW3S6L6rhdqQLtGLoc5jz4yblqhRVJzaEZs5pNFDzanEKJTpGcogJmaK0CkAkGMa/eHHXIaxllRqsyehmqmiN32xm7AEXT7bkhJV7TAHyzQahMppdA0wBRssSX8KHJmoyO7BBpgANmgqDJCpLbE1lx2VbLNL2YrjEXIAQXamq5nsNbcoOMJ1rt6G3QVPNj0U3oXUfeVrhYYetq8GSDjIV56LnVaNls5HDmiecYxw5/n0MDDqINBkZrDQE8BK8diDn6avLDQAYQAhppla3csCoRv62LMVLKqzhsP8wAKGa@ROus0EkDHjB1/u@J@nDrLdMefV2IBUVfjvaz5fG1uOyr7NwIaDqJ2YJhb0DVplRg/qG3XAvpkjJZtGgK9QWHu6rZAr6saGtdg4voFXVYVV96pnsuf/KoTcho1LtKr8UmyWYU1naJ4uLT3NM50H0eV2AQ49nxkJu7NHXs9wdrMKj7H6FrhW44YqDQHV/0MP/oJN8bdYM7rmSokSITe64xNks@rQwR6zqG3wVc09j7hZaXHNdQdg48FiSZcSiB4Mz/jq0NOp9harWIuUNyOc56Vpd/a0ri9Gv7jIFLnGDYGlweyKGOE@mjj8OlIljMQhtsRC/7ApnWR4Ghqwwx0uBA6C8TmMDZXfGcw67g3ZYmVQ0sGmObSEzb0gnoRGrwWTyOJcpeB5vxX0wDeQMGwVwnvYkQzfvk@gcwVZGz5wacZAeGi218K7CiG@SaV0y/cocYL7g@EpxIAwxKWc@1v/kmF9rS@cjcEWw/x@FdikjhsMirWaworOKw1OvZug7XWvEA0fcekHQAoUrUAUB56u5XiwQLNPtNACRE5eQ2y60W3n75m5XoH1c/AgJ7HWBh7t/QVh92z5xykIg6tItPtZDWfSD4Mg5ubIjDO88GUvsXyDHwuD@yGUBbw0il7QB62Ou@0bQ8dYVNTRCtvBMigEVRwvlpQzi6OM56y3fnCsPn6sJos3IIpYlhe8rGrRrGSrdGewUethM07dPw "Java (JDK) – Try It Online") `a->a.matches("(?si)(?>.*?([A-Z])(?!.*\\1)){26}.*")` (50 bytes, reasonable speed) - [Try it online!](https://tio.run/##rVdhc9s2Ev3OX7FWZmrJI3OctL1p43MyTtMkdeOOM/b1Ltf2A0iCJCQQYABQFNXJb889AJTiJmcnbvvJFgEs3r7dt49csBU7XBTLd6JptXG0wO@0c0KmZadyJ7RKD47po8WD4ySXzFo6Z0LR7wlR22VS5GQdc/iz0qKgBmvTS2eEqn75jZip7CxsJXo2xv5nXJ0/0Vpyph5RSSfv2OEjljbM5TW308n0sRWz6eNH6cHj6S@nh//9DT/20oNff70/m/3@4B9v04PJ7N0xol7mTCluSKi2c3RCivfbZ9PLwTrepELNkItyJE6OjqmvheQ0DfvTmtmf@NpNZ4BIopyKvZOj2XhMY70FTifV1Ac4uX8csojgSeKyGEQhwkuheNhV0lSmkqvK1dPZoyP64guSaV4zc@qmR7O9k/17@7MQBoE@uGdapqxt5TCVM3pMkyvT8YdEE3pIk2dMWvyY4IaPTsnZcfL27dt39@iCqcqwxibJaf599cPyXL@y/@pfZ0/LF4uX6sJcrf6zSb7rGyoX2hSUMbWkSg5tbWmFHOhNJzZp8kyvSQ2Nf4pomX@aL2khVrygnkmHLc@lyGih86UNZ@J2ctqHoaJnpkyTV@HYhrf1YCxlUvdzv@ypK1jp6Ew0afJC9@NDOYwXhcUNzwyztOiadi85Nymd4bI5Xf0c77uon84Bv7JUotxyUOs0uWxrodakS9zFEOdNx4zbzBGjqDg1A5qzT5OrmlOJVCjTAUovNswU8aYIQA5p8m@f5jymNadSmx0JVaCKnnTFNsMSdPnTlpSoaoc8WKZxQYycJmcAU7DekvRPgSMTFdkd2AgTwHpNhQEyNRJbc9lSydbbI2NxPEIOIDid6SqQveIWAQcIz9Xjtosoy0WHCm@31F3lY8ULPWwfDZDwIF96Lra1Wmjp/M4el2ccKVx4Pj0MpNoLXBIYLPQGYKV404GfRVdZ1ACEAYTYBGp1JwtsXdOrji0hUZ0tOPQPLGC4xtmNbjIBZMz4xOdb/kPWsWwXzPlqrEGqKvz6iofJMXJUdk0GNhyK2orNhsX6xlplRvfqWnXAvgk7JdsMAF8hsPZ0WyGX1A4L1qDj@BpaVRVa3Vc9kx1/XyGcXbBhjqsq3xTreWzTAM3TpaWnOdC5l5yODbDv@cxI2K088jrA2eYqPMbqOnCthjVVGgVU/x961Bdkiv/FitEZV0qU2PJSt3yDslm17yCPUNQm6qrmnkcMV5qccd0C2LA3mdOpBKIrwzO@3Pd0qp3EKtbgyJMByvOlabbytK4rBt@4OClyjQmBpkHuihhhHm049DpQJYzEQ3SJRf1jp7SSwR0WYIc7DAQOgrEc00aVnxvkOuwE2aBlENJBpjlqCZn7gngSFnolmMQpzlUKnnddQVd8jRLGrsL2DnIkw0eLAp1LlHXBey7NEAmPl@1q4VWFLf6SSumG71DiCeYHgxsiQQjiVIb7rTcztK/1gbMhyqIPFlagk1pukCjaahNbNLQ0OPVqQm3POoXd0BGXPgEcQUUrEMWBp204DAs0@4MWtQCRG19DdLrRTevnTIhXoP0cNMhJrLSBRjs/IOyOLW9OsTAYRaLZ5Wo4kz4ZbGIu7Mw4g8mXnUTz9T4tJO6TUBbw0iS5Rz9xZg7b0WRo@uBrNIFz3NhZEmzluqGEJgqu8kz7MXizq3xkKruJteKgYDw2DrZPugreXD7lKm10FfvZrlIBy@f4iu7MXXzljrYSpsCtrjKO9mguafL0NjvRvfyEpdSsCbbyuY7iDeUU5ShvNZU/GMqf8BP12X5C6Gsk/N5WRv0FO9m9vETl@REezaS4o5tsmBrd5PvROsLc@8BWbjITe5ublLd6yc4sfX8aKPUwOssOtVkO1wzjQ9zBZbzHVLdbyZ/1kRtMZGcfWMf4u9lEXnsx/XUbyTHn3N9iJLCP92ZyFxfZYsTvaxZytTWE0T7YHy0FTWNvNpX3JnLOhjt7yGX9l0xEq7/VRL48fPDV1kcgBOCi89PL71B21A/nOMzlEkKwNSaSL3juOUWf6LaTzJAJnRBaLcqY5UIKF@eALw64wevjignJoG/oFMEkHuXoKwfsXk6eIA4RvH7wIyZqpWmqEK/YEdAIKb000C64Hh99kEjWVTMMWXzC@hAWJUZQfJq1PigEirMVgHHUZXDeRXwHLJXG0MYXQhf5uv/tN0e4H3M579yoXV2WIgcbyNd/qPDY9LkvLgRSNEIJ6wxzYWh2bhg/aZk3VhCw6FBBNDD28ZhazizyfsFZQV0bnuCAHL9T/E/nhxsgo1JyfN9Bbf2HvN32D1O58O303HC@jAewcjlkRjhMyskPuEX5kYsveotmwZgDHZaNNzTQGo/VzXiY5obn42vTC242usLcyDo4tn@9n2BZOKD/EQiWArRoALB9mF3C7oQyp5@HSjuLSYeGbrWXDINp8TxWSuW8dQ/jnNbKM@v3rUWD1QKFkTpoJP0f "Java (JDK) – Try It Online") # PHP, 53 or 55 bytes PHP imposes a strict backtracking limit (or time limit?) on its regexes, so the version that would be 52 bytes doesn't work at all; it always returns an empty result (except for very short non-pangram strings, for which it prints `0`). `<?=preg_match('/(.*?(\pL)(?!.*\2)){26}/si',$argv[1]);` (53 bytes) - [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdX0NPy14jpsBHU8NeUU8rxkhTs9rIrFa/OFNdRyWxKL0s2jBW0/r///8hGakKhaWZydkKSUX55XkKafkVClmluQWpKQr5ZalFXCVA@ZzEqkqFlPz0Yj0FJ39PP3dkEgA "PHP – Try It Online") The 53 byte version, however, actually runs fast; it prints an empty result or `0` for false, and prints `1` for true. However, with sufficiently long pangram strings having a long separation between occurrences of new letters, it returns a false negative, due to taking too long to process the string. `<?=preg_match('/(?>.*?(\pL)(?!.*\1)){26}/si',$argv[1]);` (55 bytes) - [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdX8PeTk/LXiOmwEdTw15RTyvGUFOz2sisVr84U11HJbEovSzaMFbT@v///yEZqQqFpZnJ2QpJRfnleQpp@RUKWaW5BakpCvllqUVcJUD5nMSqSoWU/PRiPQUnf08/d2QSAA "PHP – Try It Online") `<?=preg_match('/^(?>.*?(\pL)(?!.*\1)){26}/si',$argv[1]);` (56 bytes) - [Try it online!](https://tio.run/##K8go@P/fxt62oCg1PT43sSQ5Q0NdP07D3k5Py14jpsBHU8NeUU8rxlBTs9rIrFa/OFNdRyWxKL0s2jBW0/r///8hGakKhaWZydkKSUX55XkKafkVClmluQWpKQr5ZalFXCVA@ZzEqkqFlPz0Yj0FJ39PP3dkEgA "PHP – Try It Online") These versions print `0` for false and `1` for true. This beats [640KB's answer](https://codegolf.stackexchange.com/a/181403/17216) when it is ported to handle multiline input: `<?=!array_diff(range(a,z),str_split(strtolower($argv[1])));` (59 bytes) - [Try it online!](https://tio.run/##Tck9D4IwEIDh3V9xJg5tQozOfpCwGBdd3IwhVY62itx5FBD@fGV0efMmDzuO25QdA4qQ5IJMEnxt1Uqn@4l2cyNihrzwZanE1BaVSUadNEHyhisf1HSBKupR1MKI7a7rm9Z6E2O8OIRP6x8vuAv1NZT0hWf7ZiyAOpRZmLwy4wAF2WYJ2fl4Ovz3Bw "PHP – Try It Online") # JavaScript ES9, 38 bytes `a=>/(.*([A-Z])(?!.*\2)){26}/si.test(a)` (38 bytes, always slow) - [Try it online!](https://tio.run/##fZBNa8JAEIbv@RXTCCYrSbQeejBEEdpSoS0WLLRVD5tko6ub3bizSWjF357Gngr9gGF4D8/zDsyOVhQTzQvjS5WyJosaGo37btBzl1P/bU3cyUXQWw0JOQ6vTn3kgWFoXEqaEKNBqNmh5Jq5jmY0FVwyhwRJmw2bScN0RhPmHrksSjMqtEoYYoAm5fJEAiVd58vwRDQ@WgAI3S58o1Rpglpz07avpENCwOgybDlx5sRysL6InI7zp5S5gkzshS7ZCMAe2bdUYBttcu741RAkPJGmA3MqN5rmCD4oKd7bxSDnkudUnLMHMUtoiQzMliO0gwpQqNqypsnNZrZ/UE/4XL/G19nd7l7O9aJ6@bCsDjwq6Rc/uz2gcaxZxduvpR4kFP87QeMkZdlmy3d7kUtVHDSasqo/AQ "JavaScript (Node.js) – Try It Online") `a=>/(.*?([A-Z])(?!.*\2)){26}/si.test(a)` (39 bytes, slow for non-matches) - [Try it online!](https://tio.run/##dVXLbtw2FN3rK64dIDMTyEqaRRcxHMNpmoeRFA7qNm2TLCjpSqKGIhWSGj2CfLt7KM1MvUiBWWio@zj3nHuoWuyEy6xs/Zk2Od8VF3fi4vnjdfLocv3p6uyfL5v15Uny6PPTzebb05@/P3Yy8ez8Wmzuzt3Fk3PLXztpeb2yLHIlNa82SYZnz2@1Z1uIjNffpG47/6y1JmPnEudzqb9vEqPXqzkjVhfPv0VEjh4@pHtRpvNJb6VH9c96tTknd/HTOeJUiFOfnnw5uVg9WP1vUrFWm8vTW9vxM6LTZ6evhHJ4PN2EGj/MUJvz75u7B3QjdGlF46LoKvu1fLt9bz64P/q/05fFm/qdvrG3u7@m6Je@oaI2NqdU6C2VamwrRzsePIGSKYlemYH02IRTVEvDabalWu44p14oj5DXSqZUm2zr5pwlnLwJZSjvhS2S6MOcNnFbjdZRqkwfh9dSl5SLwtO1bJLojen3h2rcN5pfTpxa4ajumvYkem8TukazmG7/XPrdVC9jwC8dFdyTGvWQRL@3ldQDmQK9BOp87YT1U4waecnUjLQzfRLdVkwFRqHUzFB6OQmbL50WAGpMoo9hzHgZK6bC2CMJ5UwVvejyw4QF6ArZjrQsK485RGrQYKmcRNcAk4vekQqnwJHKktwR7AITwHpDuQUyvSe2YtVSIYZDyl6cgJABBNmpKWeyd@xQcKRG@GofdtOlSmbABYUPIVVXhlpLwwA7VAMkHGTbwMVBq9ooHyJ7NE8ZI9wEPgMMjNpLNJkZzM0EsEp@7cBP3ZUOGoAwgJDTTK3pVI7QgT50YsuWTFpz5pGKyI8VcifTpBLIhA2Dxwf@56kX2W6ED2oMIFXn4f2OLWrHe46KrknBhoeorZwmsei7aJVa0@t76oB9O0cqMY0AX6KwCXQ7qbbUjrVosHE8ZBVchFUPqqeq4/8UQm4txhityrAUQ7ys6Qwt0GVUoHmm8yS62i/AKvCZknQHe2TVDOcwqwwYy/vAjR4HKg0E1D@GvvgLNsWz3Am6Zq1lgZB3puUJsjm98rDHLGqz@KriwKPPKjq9ZtMC2HhyGtOVAqJbyylvV4FOfbRYKRqkvBjhvCBNc7Cn810@hsVFpswMbggsDWbXJHA5yYnh15FKaRUOsSUO@i@b0iohczCYbdnjQmAQjNfL2FD5tcWs49GQDVYGJT1smkFL2DwIEkiozU4KhSxmnYDn41bQLQ@QcNkqhHewI1luFy@Azi1krblnZceF8KXZUYvgKoSEJqU2DR9R4gT3h2hNGBCGuFJzf@el0VhfFwqn42KLPrCM/zy0bDEo1mpaVnReaXAa3ARtrzuNaPiIVRgAKVC0BFHh09Q2rH2gOSQ6aAEip6Ahh09A04Z7Zq6XY/08PMgkd8bCo124INyRLR0u9lkYXEWyOc6Kb50KwyBI@DkyZdF5WXQKy9eHsTB4GEI7wEui6AH9ZvRZu//G0BkWFXWMxnaIFApBFc95TJlwOEo5E50Lg2P18XOGHL4BUSTSLOeirGS9VY02rcVG7fphnNp/AQ "JavaScript (Node.js) – Try It Online") `a=>/((?=(.*?([A-Z])(?!.*\3)))\2){26}/si.test(a)` (47 bytes, fairly reasonable speed) - [Try it online!](https://tio.run/##rVddc9s2Fn3nr4CdmUrqyGzqdne68bgZt2k@3GbHGbvtZps@gCRIQgIBBgBFkZn89uy5AKW43dqJ275JIC5w7zn33EOu@Ia73MrWH2lTiHfl6Tt@@vVn8/nD03n66cP5L2dH//11MX94kH766ovFYvHqePHm@J9vP3My9cL5OV@8O3Gn90@seN1JK@YzK3ihpBazRZrjtxfPtBe25LmYv5G67fyD1ppcOJc6X0j9dpEaPZ@FiKU6/fpNwphjn3zCru0ynU97Kz1Of6VnixPmTj8/wT5F@9Qv9389OJ3dm90YVM7V4uHhle3EA8YOHxw@5srh5@GCzvjDCLU4ebt4d49dcF1Z3rgkOcu/q56tn5sX7sf@ZfaofLr6QV/Yq81/xuTbvmHlytiCZVyvWaWGtnZsI7aeAZIxTR6bLdNDQ6s4LaPVfM1WciMK1nPlseWJkhlbmXztQkzczryhY1jRc1umyYsQNoq2HqxjmTL9kh5LXbGCl56dyyZNnpp@WlTDdFF4OIrMcsdWXdMeJM9tys5x2ZJd/RTvu6gfLZF@5VgpeqYGvU2Ty7aWestMibs4znndcevHJc4oKsGagW1MnyZXtWAlSmGZCan0cuS2iDfFBNSQJj9TmctY1pKVxu5BqAJU7Juu2FVYAi6KdkzLqvaog2cGF8ST0@QcyRS8d0zRKvLIZMXcPtmYJhLrDSssMtMTsLVQLSv5dhcykUMZCiSC6MxUAeyNcDhwYA339bTtosuUzJEXGN5tqbuKzooXUtp0GlLCQr4mLHZcrYzytLPH5ZlACReEJ6WBUnuJSwKChRmRrJKvO@Cz6ioHDgAYkpBjgNZ0qsDWLXvR8bWwzGQrkXuEYufPNWJH02QSmXFLhS93@IeqI20X3BMbW4CqC3q@ERZnLyeMyq7JgIYHqa0cRx75jVxl1vT6GjtA34adio8Dkq9wsCG4nVRr1g4r3qDjxDavoSK0OrGeqU68ZwixKz4scVVFTbFdxjYNqRFcRhHMAc6D5GxqgBnhmTHpdvLI65DOrlZJOVbXEzd62LLKgED9x6lHfUGm@C03nJ0LrWWJLT@YVoygzemZhzwCqU3UVS0IR5/X7PBcmBaJDQeHS3amkNGVFZlYzwhOvZdYxRuEfDNAeURNs5On810xUOMiUuYGEwJNg9o14xhOchTQ68AqaRUW0SUO/MdOaRWXBRDM18JjIAgAjMexbLD8xKLWYS/IBi2DIz1kmoNLyJwIIRBWZiO5QpQQOgXO@65gV2ILCmNXYXsHOTIr2qgFwLkGrSvRC2WHCHi8bM8FqQpb6JJKm0bss8QK5gdvDRUIQZypcL/z0mi0r6ODsyHKoieU8V9sW2FRKNpqjC0aWhqYkprA7XmnsRs6EooKQAgYrQAUWVPbCO0JZgp04AJAjsShIAtoWpoz4bwC7eehQcHkxlhotKMB4fZoaRrsgRiMItnsa4XXKSoGm7gPOzPBOy/LTqH5eioLhVMR2iG9NEnusX8Lbo/ayWTY/PgfaAIPt3SLJNjKdUMJTRRc5bGhMXizq/yfqewn1kYAgilsGmwfdBWjP@gqbXQV99GuUiGXj/EV09m7@ModbSVMgVtdZRrt0VzS5NFtdmJ69QFLqXkTbOVjHYUM5Qx0lLeaym8M5U/4if5oP2HoaxT83lYm/QU72b@8ROXRCI9mUtzRTUauJzf5brKOMPd@Zys3mYm7zU3KW71kb5bUnxZKPYrOss/arodrhvH7vIPLkMdUt1vJn/WRG0xkbx94jvF3s4m8JDH9dRuJ7/R/h5HAPt6byV1cZJcj/l@zkKudIUz2wX9rKWgad7OpvDeR53y4s4dc1n/JRIz@W03ki6PjL3c@AiEgL/b87PJb0A7@ECdgLpcQgqsxkYjwnDBFn5i2U9wyGzohtFqUMc@lkj7OASIH2OD1ccOl4tA3dIrDFJZy9JVH7iQnAkhABC@Pv8dErQyba5xX7AFopFIkDbQLrsdXISSSddUCQ9ZgduIIB4pxqBeAlQAxFFshMQFeBk8uQh2w1gZDG18IXcTr8399dR/3Yy7nnZ@0a8pS5kAD9dKHiohNnxO5EEjRSC2dt9yHodl5NEAtFUECSAHAqgODaGDsE7G0nDvU/RRfuqxrwwoC1PSdQn89DTekDKbU9L4Dbhsutdv1D9e5pHZ6YoVYxwA8uRwyfIFiUh4@wy2aRq4S3KFZMOYAh@PTDQ20JiK7mQjT3Ip8em16KuxoKsyNrINj0@v9IQsfto59jwzWErAYJOD6MLuk2wtlyX4aKuMdJh0aujUkGQ7TEnlkSuei9Q/inDaakKV9W9ngaQFilAkaSf8H "JavaScript (Node.js) – Try It Online") `a=>/^((?=(.*?([A-Z])(?!.*\3)))\2){26}/si.test(a)` (48 bytes, very reasonable speed) - [Try it online!](https://tio.run/##rVfvc9s2Ev3OvwJ2ZiqpI7Ope3dzF4@bcZvmh9t0nLGvvVzTmwFJkIQEAgwAiiIz@dvTtwCluL3aidt@k0AssPvevn3kim@4y61s/ZE2hXhXnr7jp19@9r/5/OHpPP304fyns6P//ryYPzxIP331xWKxeHW8eHP8j7efOZl64fycL96duNP7J1a87qQV85kVvFBSi9kizfHbi2faC1vyXMzfSN12/kFrTS6cS50vpH67SI2ez0LEUp1@@SZhzLFPPmHXdpnOp72VHqe/0rPFCXOnn59gn6J96qf7Px@czu7Nbgwq52rx8PDKduIBY4cPDh9z5fDzcEFn/G6EWpy8Xby7xy64rixvXJKc5d9Uz9bPzQv37/5l9qh8uvpOX9irzX/G5Ou@YeXK2IJlXK9ZpYa2dmwjtp4BkjFNHpst00NDqzgto9V8zVZyIwrWc@Wx5YmSGVuZfO1CTNzOvKFjWNFzW6bJixA2irYerGOZMv2SHktdsYKXnp3LJk2emn5aVMN0UXg4isxyx1Zd0x4kz23KznHZkl39EO@7qB8tkX7lWCl6pga9TZPLtpZ6y0yJuzjOed1x68clzigqwZqBbUyfJle1YCVKYZkJqfRy5LaIN8UE1JAmP1KZy1jWkpXG7kGoAlTsq67YVVgCLop2TMuq9qiDZwYXxJPT5BzJFLx3TNEq8shkxdw@2ZgmEusNKywy0xOwtVAtK/l2FzKRQxkKJILozFQB7I1wOHBgDff1tO2iy5TMkRcY3m2pu4rOihdS2nQaUsJCviYsdlytjPK0s8flmUAJF4QnpYFSe4lLAoKFGZGskq874LPqKgcOABiSkGOA1nSqwNYte9HxtbDMZCuRe4Ri5481YkfTZBKZcUuFL3f4h6ojbRfcExtbgKoLer4RFmcvJ4zKrsmAhgeprRxHHvmNXGXW9PoaO0Dfhp2KjwOSr3CwIbidVGvWDiveoOPENq@hIrQ6sZ6pTrxnCLErPixxVUVNsV3GNg2pEVxGEcwBzoPkbGqAGeGZMel28sjrkM6uVkk5VtcTN3rYssqAQP37qUd9Qab4LTecnQutZYkt35lWjKDN6ZmHPAKpTdRVLQhHn9fs8FyYFokNB4dLdqaQ0ZUVmVjPCE69l1jFG4R8NUB5RE2zk6fzXTFQ4yJS5gYTAk2D2jXjGE5yFNDrwCppFRbRJQ78x05pFZcFEMzXwmMgCACMx7FssPzEotZhL8gGLYMjPWSag0vInAghEFZmI7lClBA6Bc77rmBXYgsKY1dhewc5MivaqAXAuQatK9ELZYcIeLxszwWpClvokkqbRuyzxArmB28NFQhBnKlwv/PSaLSvo4OzIcqiJ5TxX2xbYVEo2mqMLRpaGpiSmsDteaexGzoSigpACBitABRZU9sI7QlmCnTgAkCOxKEgC2hamjPhvALt56FBweTGWGi0owHh9mhpGuyBGIwi2exrhdcpKgabuA87M8E7L8tOofl6KguFUxHaIb00Se6x7wW3R@1kMmx@/Hc0gYdbukUSbOW6oYQmCq7y2NAYvNlV/s9U9hNrIwDBFDYNtg@6itEfdJU2uor7aFepkMvH@Irp7F185Y62EqbAra4yjfZoLmny6DY7Mb36gKXUvAm28rGOQoZyBjrKW03lV4byB/xEf7SfMPQ1Cn5vK5P@gp3sX16i8miERzMp7ugmI9eTm3wzWUeYe7@xlZvMxN3mJuWtXrI3S@pPC6UeRWfZZ23XwzXD@G3ewWXIY6rbreSP@sgNJrK3DzzH@LvZRF6SmP68jcR3@r/CSGAf783kLi6yyxH/r1nI1c4QJvvgv7YUNI272VTem8hzPtzZQy7rP2UiRv@lJvLF0fHfdj4CISAv9vzs8mvQDv4QJ2AulxCCqzGRiPCcMEWfmLZT3DIbOiG0WpQxz6WSPs4BIgfY4PVxw6Xi0Dd0isMUlnL0lUfuJCcCSEAEL4@/xUStDJtrnFfsAWikUiQNtAuux1chJJJ11QJD1mB24ggHinGoF4CVADEUWyExAV4GTy5CHbDWBkMbXwhdxOvzf/3zPu7HXM47P2nXlKXMgQbqpQ8VEZs@J3IhkKKRWjpvuQ9Ds/NogFoqggSQAoBVBwbRwNgnYmk5d6j7Kb50WdeGFQSo6TuF/noabkgZTKnpfQfcNlxqt@sfrnNJ7fTECrGOAXhyOWT4AsWkPHyGWzSNXCW4Q7NgzAEOx6cbGmhNRHYzEaa5Ffn02vRU2NFUmBtZB8em1/tDFj5sHfsWGawlYDFIwPVhdkm3F8qS/TBUxjtMOjR0a0gyHKYl8siUzkXrH8Q5bTQhS/u2ssHTAsQoEzSS/gI "JavaScript (Node.js) – Try It Online") When looping this set of test cases, it can be seen that the 48 byte version is about 12 times as fast as the 47 byte version (in SpiderMonkey's regex engine). This now [ties in length with l4m2's answer](https://codegolf.stackexchange.com/a/222767/17216), which counts individual regex matches. Given the speed difference, that answer obviously wins. # Ruby, 35 bytes `->s{s=~/(.*([A-Z])(?!.*\2)){26}/mi}` (35 bytes, always slow) - [Try it online!](https://tio.run/##fU1dS8JQGL7fr3g2wy/c1F104TiJUFFQYWBQzRFn8ziPnp2tczaHif31Na2uguDl5X0@X1WEuyojlX2h95p89ttOt@1P7Neg0x6bTnfudjp79/zQT/ih4mTgoVxxwSBIzHJtAHwJbh75rMi1ByYXHjgZekdB@PYwIMSaS8urE8IfOI7tBj@uszciufiuMIXDkizfjdFs1rFBYJJWo1VrQKa4zJH5IsAY1kwVbARYGMG6pkLXwDr1Gb9OcYJVA1MqY0UTDRupFLt6MSRc8oSK491DyCJaaIZ8xTXq0Sm0SEvDmERX8e3mPn3UT@VLeLm8Wd/JqZptnz8Mo4GHVNrZ3@4eaBgqtuU0Z4seIqr/e0HDaMGW8YqvNyKRafaudF5syy8 "Ruby – Try It Online") `->s{s=~/(.*?([A-Z])(?!.*\2)){26}/mi}` (36 bytes, slow for non-matches) - [Try it online!](https://tio.run/##bVVdb9s2FH3Xr7h2h6YtHDXNwx4aeEG6ru2MdkixbN2WBgMpURJlilRIyfoour@enSvZXh8G5CEm78e555xL@VYOD/X64fSH8CWs/3n@JH52@eT26vSvu6dPLhfxs8/nT59@Of/@6/NKf33Q67ML6gptFJl1rpoQEemM9ILP67YJF6RsekF6/eKCL8zt6Yu79Xr52S4vkGFuz@L49PxuH/Xd32urzVxiYWJV1c1wSY8fI@3sbrE@eXSCO6Laa9tQfWvu6JKWN75VL4mW9JKWb4QJ@LGc6kWHSDP9fHhE18LmXlQhiq6Sn/Kftx/cx/Bb96d8nb0r39trf7P7Y4x@7CrKSudTksJuKTdDXQTaqb6h@1aPcfTG9WSHik9RTfJpsqVS71RKnTANQt4aLal0yTZMOXM4NY7LUNoJn8XRxyltVHUx@EDSuG7F19rmlIqsoY2u4uid6/aHZtg3mi5HJb0IVLZVvYg@@Jg2aLaim9/nftfF6xXg54Ey1ZEZbB9Hv9aFtj25DL0E6ty3wjfjCjXSXFE10M51cXRTKMowCkk3Qen0KHw6d5oBmCGOPvGYq3msFWXOH0nIJ6roVZseJsxAF2cHsjovGswhpEODuXIcbQAmFV0gw6fAIXVO4Qh2hglgnaPUA5ndE1soU1Mm@kPKXhxGqAAE2dLlE9k7FVBwoEo0xT7supVGJ8AFhQ8hRZtzrbkhw@ZqgISDZMtcHLQqnWk4skNzqTDCNfPJMDBqp9FkYjB1I8Aafd@Cn7LNAzQAYQChx4la15oUoT19bMVWeXKyVEmDVER@KpA7ukpqIBOeB18d@J@mnmW7Fg2r0YNUm/L9TsHy@WrPUdZWEmw0ELXW4yhmfWetpHed/UYdsO@nSCPGAeBzFHZMd9BmS/VQigqOU31SYItgdVZdmlb9pxBySzGs0CpnU/Sr2aYTNKbLGaZ5onMRXe0NcMJ8StLhsB5JMcE5zKoZY/4tcGeHnnIHAe3/Q5/3C2uK//VO0EZZqzOEvHe1GiFbsCcN1mMStZr3qlDMY5MUtNwoVwPYsFiu6MoA0Y1XUm1PmE57XLFcVEh5NWDzWJrqsJ6hadOBjYtMnTi8EDANZrck@DkaFfZ1oFx7g0O4JED/2Sm1EToFg8kW7yiMBYJxPY8Nld96zDocF7KCZVCywZom0BJrzoIwCaXbaWGQpZSNwfPRFXSjekg4uwrhLdaRvKrnXQCdW8haqk4ZP8yEz82OWvBWIYSb5NZV6ogSJ3g/RO14QCzElZn6h0Y7C/sGLiyHeS06Zhm/VV8rj0Fhq3G26GRpcMrbBG03rUU09kgZHgApUDQHUQp46krhZQfNnBigBYgcWUM43Tt8OBgu10thvwY7qEjvnMeOtvxAhCNblh/2SRg8Rbo6zuqVMDwMgkQzRUol2kZnrYH5Oh4Lg/MQNgBeHEWP6BdnT@v9N4ZOYVTUcRbuEBIKQZVGpStKRMCRVIloAw8O6@MvOAr4BkSRkEmqsrzQ5dZU1tUejtp1/TDW/wI "Ruby – Try It Online") `->s{s=~/(?>.*?([A-Z])(?!.*\1)){26}/mi}` (38 bytes, fairly reasonable speed) - [Try it online!](https://tio.run/##rVdhc9s2Ev3OX7FWbmq7I6uJ73pzjUf1uE2T1G1unLHbXi713IAkREICAQYARZGd3l9P3xKU4vbOTtz2m0Rggd339u0jXZN2b@v526PP/U9@/t9PDk4/n318evD67Ojf14cHp3uzj398dHj40/Hff/6kUj@/VfOHJ9SWSkvS80IGnxCpBak9fl43wZ@QNPkJqfmjE17Qr48eXc/nkx/N5AQR@vXD2ezo@Hrc9Zf/zI3S8Yg9PZNVHbpT@ugjhD283pvvP9jHGlHtlAlUv9bXdEqTK9fIx0QTekyTp0J7/JkM5yXbnXr4@/YBXQhTOFH5JDnLviq@Xr2wL/137av0yeL58ltz4a7W/@qTL9uKFkvrckqFWVGhu7r0tJabQG8a1c@Sp3ZDpqv4KU5L@Wm2oqVay5xaoQO2PNMqpaXNVn6IidspWD6G8la4xSx5OYT1si475ynVtp3ysjIF5WIR6FxVs@S5bceHuhsvGhZ7mTrhadlU9V7yws3oHJdN6er7eN9F@WSK9AtPC9mS7sxmllzWpTIbsgvcJXDOm0a40E9xRl5Iqjpa23aWXJWSFiiFUjuk0qpeuDzeFBPQ3Sz5gcucxrKmtLBuB0IxQEVfNPm2wgXg4mhPRhVlQB0itbggnjxLzpFMLlpPmp8ij1QV5HfJxjSRWGspd8jMjMCWUte0EJttyEgOZyiRCKJTWwxgr6XHgR1VIpTjtosm1SpDXmB4u6VsCj4rXshp82lICQ@yFWOx5WppdeCdLS5PJUq4YDw5DZTaKlwyIJjbHslq9aYBPsum8OAAgCEJ1Q/Q2kbn2Lqhl41YSUc2XcosIBQ7fygR29sqVchMOC58usV/qDrSdiECs7EBqCbn9bVEyxfTEaNFU6VAI4DUWvW9iPxGrlJnW3ODHaDvhp1a9B2SL3CwZbi90iuqu6Wo0HFyk5VQEVqdWU91I98xhNil6Ka4quCm2Exjmw6pMVxWM8wDnHvJ2dgA@4xnSspv5ZGVQzrbWhXnWNxM3JpuQ4UFgeb/px71BZnit1oLOpfGqAW2fGtr2YM2b/YD5DGQWkVdlZJxDFlJk3NpayTW7U2mdKaR0ZWTqVztM5xmJ7FCVAj5ooPymJpqK08fmrzjxkWkyiwmBJoGtRsSPI56Cb12VCin8RBd4sF/7JRaC5UDwWyFOYrGAsBYjmWD5WcOtXY7QVZoGRwZINMMXELmTAiDsLRrJTSipDQz4LzrCrqSG1AYuwrbG8iRnKyjFgDnCrQuZSu16yLg8bIdF6wqbOFLCmMrucsSTzA/RG25QAjiTA/3@6CsQft6PjjtoixaRhn/5aaWDoWirfrYokNLA1NWE7g9bwx2Q0dScwEIAaMFgJLIp64kJjtg5kAPLgBkzxyi052FcXC6fF6O9gvQoCS1tg4abXhA@B1ahgf7QAxGkap2tTopNBeDTSIMO1MpmqAWjUbztVwWCucijEd6syR5QP@Uwh3Vo8nQwfGnaIIQpPOHyWArNw1laKLBVZ5aHoO3u8r/mMpuYq0lIBjDxsH2Xlex5r2uUkdX8R/sKgVy@RBfsY27j6/c01aGKXCnq4yjPZrLLHlyl53YVr/HUkpRDbbyoY7ChnIGOhZ3msqvDOV3@In5YD8h9DUKfmcro/4GO9m9vETl8QiPZpLf0016YUY3@Wq0jmHu/cZWbjMTf5ebLO70kp1Zcn86KPUoOssua7fqbhjGb/MeXIY9prjbSn6vj9xiIjv7wDrG3@0m8orF9MdtJMOcC3@KkcA@3pnJfVxkmyP@37CQq60hjPYhfm0paBp/u6m8M5EXoru3h1yWf8hErPlTTeSvR8d/2/oIhIC86MXZ5ZegHfwhTsJcLiEEX2IiMeEZY4o@sXWjhSM3dMLQalHGIlNahTgHmBxgg9fHtVBaQN/QKQ7TeJShrwJyZzkxQBIieHX8DSZqYenA4Lx8B0CltGZpoF1wPT78IJG0KQ4xZC1mJ47woBiHBv6oY0Asx@KLkSR46QK7CHfAylgMbXwhNBGvR5/94yHux1zOmjBq1y4WKgMaqJc/VGRs@ozJhUDyShnlgxNhGJpN6MYPVMHGCgCWDRhEA2OfjKVlwqPu51Lk1NTDEwTo8TuF/wYebkgZTOnxfQfcVkIZv@0fYTLF7fTMSbmKAVi57FKnAibl5GvcYnjkaik8mgVjDnB4Md5QQWsyspvKYZo7mY2vTc@l622BuZE2cGx@vZ9gWQVk/w0yWCnAYpGAb4fZpfxOKFP6vits8Jh0aOjasmQETEtmkSmTyTo8jnPaGkaW921UhdUcxGg7aGT2Cw "Ruby – Try It Online") `->s{s=~/^(?>.*?([A-Z])(?!.*\1)){26}/mi}` (39 bytes, very reasonable speed) - [Try it online!](https://tio.run/##rVdhc9y2Ef1@v2J17kRS5nSxlTbTWnPRKHFsR4k78khN6jpqByRBEncgQAPg8chM@tedtwTvrKSVbCX5dkdggd339u0jXZN0b@vF26PP/Y9@8d9P/n1w@vn849OD12dH/7o@PDjdm3/8w6PDwx@PP/vpk0r99FYtHp5QWyotSS8KGfyESOWk9vh53QR/QtJkJ6QWj054Qb8@enS9WEx/MNMTROjXD@fzo@Prcdef/rMwSscj9vRcVnXoTumjjxD28Hpvsf9gH2tEtVMmUP1aX9MpTa9cIx8TTekxTZ8K7fFnOpw32e7Uw9@3D@hCmMKJyk8mZ@lXxderF/al/0f7KnmSP19@ay7c1fqf/eTLtqJ8aV1GiTArKnRXl57WchPoTaP6@eSp3ZDpKn6K0xJ@mq5oqdYyo1bogC3PtEpoadOVH2LidgqWj6GsFS6fT14OYb2sy855SrRtZ7ysTEGZyAOdq2o@eW7b8aHuxouGxV4mTnhaNlW9N3nh5nSOy2Z09V2876J8MkP6hadctqQ7s5lPLutSmQ3ZHHcJnPOmES70M5yRFZKqjta2nU@uSkk5SqHEDqm0qhcuizfFBHQ3n3zPZc5iWTPKrduBUAxQ0RdNtq0wB1wc7cmoogyoQyQWF8ST55NzJJOJ1pPmp8gjUQX5XbIxTSTWWsocMjMjsKXUNeVisw0ZyeEMJRJBdGKLAey19Diwo0qEctx20SRapcgLDG@3lE3BZ8ULOW0@DSnhQbpiLLZcLa0OvLPF5YlECReMJ6eBUluFSwYEM9sjWa3eNMBn2RQeHAAwJKH6AVrb6AxbN/SyESvpyCZLmQaEYuf3JWJ7WyUKmQnHhc@2@A9VR9ouRGA2NgDVZLy@lmj5YjZilDdVAjQCSK1V34vIb@QqcbY1N9gB@m7YqUXfIfkCB1uG2yu9orpbigodJzdpCRWh1Zn1RDfyHUOIXYpuhqsKborNLLbpkBrDZTXDPMC5NzkbG2Cf8UxI@a080nJIZ1ur4hyLm4lb022osCDQ/P/Uo74gU/xWa0Hn0hiVY8u3tpY9aPNmP0AeA6lV1FUpGceQljQ9l7ZGYt3edEZnGhldOZnI1T7DaXYSK0SFkC86KI@pqbby9KHJOm5cRKrUYkKgaVC7IcHjqJfQa0eFchoP0SUe/MdOqbVQGRBMV5ijaCwAjOVYNlh@5lBrtxNkhZbBkQEyTcElZM6EMAhLu1ZCI0pKMwfOu66gK7kBhbGrsL2BHMnJOmoBcK5A61K2UrsuAh4v23HBqsIWvqQwtpK7LPEE80PUlguEIM70cL8Pyhq0r@eDky7KomWU8V9uaulQKNqqjy06tDQwZTWB2/PGYDd0JDUXgBAwWgAoiXzqSmKyA2YO9OACQPbMITrdWRgHp8vnZWi/AA1KUmvroNGGB4TfoWV4sA/EYBSpalerk0JzMdgkwrAzkaIJKm80mq/lslA4F2E80ptPJg/o71K4o3o0GTo4/guaIATp/OFksJWbhjI00eAqTy2Pwdtd5X9MZTex1hIQjGHjYHuvq1jzXlepo6v4D3aVArl8iK/Yxt3HV@5pK8MUuNNVxtEezWU@eXKXndhWv8dSSlENtvKhjsKGcgY68jtN5ReG8hv8xHywnxD6GgW/s5VRf4Od7F5eovJ4hEczye7pJr0wo5t8NVrHMPd@ZSu3mYm/y03yO71kZ5bcnw5KPYrOssvarbobhvHrvAeXYY8p7raS3@ojt5jIzj6wjvF3u4m8YjH9fhtJMefCH2IksI93ZnIfF9nmiP83LORqawijfYhfWgqaxt9uKu9M5IXo7u0hl@XvMhFr/lAT@fTo@M9bH4EQkBe9OLv8ErSDP8RJmMslhOBLTCQmPGVM0Se2brRw5IZOGFotylikSqsQ5wCTA2zw@rgWSgvoGzrFYRqPUvRVQO4sJwZIQgSvjr/BRC0sHRicl@0AqJTWLA20C67Hhx8kkjTFIYasxezEER4U49DAH3UMiOVYfDGSBC9dYBfhDlgZi6GNL4Qm4vXob399iPsxl9MmjNq1ea5SoIF6@UNFxqZPmVwIJKuUUT44EYah2YRu/EAVbKwAYNmAQTQw9slYWio86n4uRUZNPTxBgB6/U/hv4OGGlMGUHt93wG0llPHb/hEmVdxOz5yUqxiAlcsucSpgUk6/xi2GR66WwqNZMOYAhxfjDRW0JiO7iRymuZPp@Nr0XLreFpgbSQPH5tf7KZZVQPbfIIOVAiwWCfh2mF3K74Qyo@@6wgaPSYeGri1LRsC0ZBqZMqmsw@M4p61hZHnfRlVYzUCMtoNG5j8D "Ruby – Try It Online") When looping this set of test cases, the same result is seen: the 39 byte version is 12 times as fast as the 38 byte version. This is 2 bytes longer than [Alexis Andersen's mixed code/regex answer](https://codegolf.stackexchange.com/a/66301/17216). # Ruby `-n0`, 30 bytes Prints `nil` for false and `0` for true, which are respectively falsey and truthy in Ruby. If printing `0` or `1` is desired, replace `~` with `!!` (+1 byte). `p ~/(.*([A-Z])(?!.*\2)){26}/mi` (30 bytes, always slow) - [Try it online!](https://tio.run/##KypNqvz/v0ChTl9DT0sj2lE3KlZTw15RTyvGSFOz2sisVj838/9/x2TXdM9s3/zA4tDySK4klzSPLJ@8gKKQsoiqf/kFJZn5ecX/dfMMAA "Ruby – Try It Online") `p ~/(.*?([A-Z])(?!.*\2)){26}/mi` (31 bytes, slow for non-matches) - [Try it online!](https://tio.run/##KypNqvz/v0ChTl9DT8teI9pRNypWU8NeUU8rxkhTs9rIrFY/N/P/f8dk13TPbN/8wOLQ8kiuJJc0jyyfvICikLKIqn/5BSWZ@XnF/3XzDAA "Ruby – Try It Online") `p ~/(?>.*?([A-Z])(?!.*\1)){26}/mi` (33 bytes, fairly reasonable speed) - [Try it online!](https://tio.run/##KypNqvz/v0ChTl/D3k5Py14j2lE3KlZTw15RTyvGUFOz2sisVj838///kIxUhcLSzORshaSi/PI8hbT8CoWs0tyC1BSF/LLUIq4SoHxOYlWlQkp@erGegpO/p587Mvkvv6AkMz@v@L9ungEA "Ruby – Try It Online") `p ~/^(?>.*?([A-Z])(?!.*\1)){26}/mi` (34 bytes, very reasonable speed) - [Try it online!](https://tio.run/##KypNqvz/v0ChTj9Ow95OT8teI9pRNypWU8NeUU8rxlBTs9rIrFY/N/P//5CMVIXC0szkbIWkovzyPIW0/AqFrNLcgtQUhfyy1CKuEqB8TmJVpUJKfnqxnoKTv6efOzL5L7@gJDM/r/i/bp4BAA "Ruby – Try It Online") This is 2 bytes longer than [Alexis Andersen's answer](https://codegolf.stackexchange.com/a/66301/17216) when it is ported to be a full program using `-n0` instead of a lambda (and it prints `false` or `true`): `p (?a..?z).all?{|c|~/#{c}/i}` (28 bytes) - [Try it online!](https://tio.run/##KypNqvz/v0BBwz5RT8@@SlMvMSfHvromuaZOX7k6uVY/s/b//5CMVIXC0szkbIWkovzyPIW0/AqFrNLcgtQUhfyy1CKuEqB8TmJVpUJKfnqxnoKTv6efOzL5L7@gJDM/r/i/bp4BAA "Ruby – Try It Online") # Perl 5 `-p0`, 28 bytes `$_=/(.*(\pL)(?!.*\2)){26}/si` (28 bytes, always slow) - [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfQ09LI6bAR1PDXlFPK8ZIU7PayKxWvzjz/3/HZNd0z2zf/MDi0PJIriSXNI8sn7yAopCyiKp/@QUlmfl5xf91CwwA "Perl 5 – Try It Online") `$_=/(.*?(\pL)(?!.*\2)){26}/si` (29 bytes, slow for non-matches) - [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfQ0/LXiOmwEdTw15RTyvGSFOz2sisVr848/9/x2TXdM9s3/zA4tDySK4klzSPLJ@8gKKQsoiqf/kFJZn5ecX/dQsMAA "Perl 5 – Try It Online") `$_=/(?>.*?(\pL)(?!.*\1)){26}/si` (31 bytes, fairly reasonable speed) - [Try it online!](https://tio.run/##K0gtyjH9/18l3lZfw95OT8teI6bAR1PDXlFPK8ZQU7PayKxWvzjz/3/HZNd0z2zf/MDi0PJIriSXNI8sn7yAopCyiKp/@QUlmfl5xf91CwwA "Perl 5 – Try It Online") `$_=/^(?>.*?(\pL)(?!.*\1)){26}/si` (32 bytes, very reasonable speed) - [Try it online!](https://tio.run/##K0gtyjH9/18l3lY/TsPeTk/LXiOmwEdTw15RTyvGUFOz2sisVr848/9/x2TXdM9s3/zA4tDySK4klzSPLJ@8gKKQsoiqf/kFJZn5ecX/dQsMAA "Perl 5 – Try It Online") This is 2 bytes longer than [Xcali's regex + hash answer](https://codegolf.stackexchange.com/a/181393/17216) when its `[a-z]` is replaced with `\pL`. Also, for some reason that answer only requires the `-p` command-line parameter yet still works with multiline input, while this one requires `-p0` to do so. # Perl 5, 40 bytes `say@ARGV[0]=~/(.*(\pL)(?!.*\2)){26}/si+0` (40 bytes, always slow) - [Try it online!](https://tio.run/##K0gtyjH9/784sdLBMcg9LNog1rZOX0NPSyOmwEdTw15RTyvGSFOz2sisVr84U9vg////jsmu6Z7ZvvmBxaHlkVxJLmkeWT55AUUhZRFV//ILSjLz84r/6/qa6hka6BkAAA "Perl 5 – Try It Online") `say@ARGV[0]=~/(.*?(\pL)(?!.*\2)){26}/si+0` (41 bytes, slow for non-matches) - [Try it online!](https://tio.run/##K0gtyjH9/784sdLBMcg9LNog1rZOX0NPy14jpsBHU8NeUU8rxkhTs9rIrFa/OFPb4P///47Jrume2b75gcWh5ZFcSS5pHlk@eQFFIWURVf/yC0oy8/OK/@v6muoZGugZAAA "Perl 5 – Try It Online") `say@ARGV[0]=~/(?>.*?(\pL)(?!.*\1)){26}/si+0` (43 bytes, fairly reasonable speed) - [Try it online!](https://tio.run/##K0gtyjH9/784sdLBMcg9LNog1rZOX8PeTk/LXiOmwEdTw15RTyvGUFOz2sisVr84U9vg////jsmu6Z7ZvvmBxaHlkVxJLmkeWT55AUUhZRFV//ILSjLz84r/6/qa6hka6BkAAA "Perl 5 – Try It Online") `say@ARGV[0]=~/^(?>.*?(\pL)(?!.*\1)){26}/si+0` (44 bytes, very reasonable speed) - [Try it online!](https://tio.run/##K0gtyjH9/784sdLBMcg9LNog1rZOP07D3k5Py14jpsBHU8NeUU8rxlBTs9rIrFa/OFPb4P///47Jrume2b75gcWh5ZFcSS5pHlk@eQFFIWURVf/yC0oy8/OK/@v6muoZGugZAAA "Perl 5 – Try It Online") This is 4 bytes longer than a port of [Xcali's regex + hash answer](https://codegolf.stackexchange.com/a/181393/17216) with `[a-z]` replaced with `\pL`: `++@a{(uc@ARGV[0])=~/\pL/g};say%a==26` (36 bytes) - [Try it online!](https://tio.run/##K0gtyjH9/19b2yGxWqM02cExyD0s2iBW07ZOP6bARz@91ro4sVI10dbWyOz///@Oya7pntm@@YHFoeWRXEkuaR5ZPnkBRSFlEVX/8gtKMvPziv/r@prqGRroGQAA "Perl 5 – Try It Online") Reading multiline input from stdin instead of a command-line argument would be 4 bytes longer, replacing `@ARGV[0]` with `join('',<>)`. [Answer] # CJam, 11 bytes ``` '[,65>qeu-! ``` This is a complete program. [Try it online](http://cjam.aditsu.net/#code='%5B%2C65%3Eqeu-!&input=123abcdefghijklm%20NOPQRSTUVWXYZ321). Explanation: ``` '[,65> Build upper case alphabet (see CJam tips thread). q Get input. eu Convert to all upper case. - Set difference between alphabet and upper cased input. ! Negate. ``` [Answer] ## [Minkolang 0.14](https://github.com/elendiastarman/Minkolang), 18 bytes ``` $o7$ZsrlZ'26'$ZN. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=%24o7%24ZsrlZ%2726%270%24ZN%2E&input=123abcdefghijklm%20NOPQRSTUVWXYZ321) ### Explanation ``` $o Read in whole input as characters 7$Z Uppercase every letter s Sort r Reverse lZ Alphabet - uppercase and lowercase '26' Pushes 26 on the stack 0$Z Count how often the top 26 numbers of the stack appear in the stack N. Output as number and stop. ``` [Answer] ## PowerShell v3+, ~~65~~ ~~56~~ 52 Bytes ``` ($args.ToLower()-split''|sls [a-z]|group).Count-eq26 ``` Thanks to [TessellatingHeckler](https://codegolf.stackexchange.com/users/571/tessellatingheckler) for the 9-byte golf. * Takes the input string, converts it `.ToLower()`case, then `-split`s on every character * Those are fed into an alias `sls` for `Select-String` which matches based on a regex `[a-z]` to pull out only the letters * Those are then fed into `Group-Object`, so we're only selecting one individual instance of each letter * That is then `.Count`ed to see if it's `-eq`ual to 26, and prints `True` or `False` accordingly * Requires PowerShell v3 or newer for the `sls` alias [Answer] # R, ~~53~~ 45 bytes ``` all(97:122%in%utf8ToInt(tolower(readline()))) ``` **Old version at 53 bytes:** ``` all(letters%in%strsplit(tolower(readline()),"")[[1]]) ``` Usage: ``` > all(97:122%in%utf8ToInt(tolower(readline()))) The quick brown fox jumps over the lazy dog [1] TRUE > all(97:122%in%utf8ToInt(tolower(readline()))) Write a function or program that takes as its input a string and prints a truthy value if the string is a pangram and a falsey value otherwise. [1] FALSE > all(97:122%in%utf8ToInt(tolower(readline()))) 123abcdefghijklm NOPQRSTUVWXYZ321 [1] TRUE > all(97:122%in%utf8ToInt(tolower(readline()))) Portez ce vieux whisky au juge blond qui fume [1] TRUE ``` [Answer] # [2sable](http://github.com/Adriandmen/2sable), ~~6~~ 5 bytes 6 byte version: ``` AIl-g_ ``` [Try it online!](http://2sable.tryitonline.net/#code=QUlsLWdf&input=VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw) Explanation: ``` A Push alphabet Il Push lowercase input - Remove all chars of input from alphabet g Get length of the remainder _ Print negative bool, where length < 1 = 1 (true), length > 0 = 0 (false) ``` --- 5 byte version, inspired by carusocomputing's [05AB1E answer](https://codegolf.stackexchange.com/a/98202/59970): ``` lÙ{Aå ``` [Try it online!](http://2sable.tryitonline.net/#code=bMOZe0HDpQ&input=VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw) Explanation: ``` l Push lowercase input Ù{ Push sorted uniquified input A Push alphabet å Is alphabet in sorted, uniquified input? ``` [Answer] # [J](http://jsoftware.com/), 23 bytes ``` (u:65+i.26)*/@e.toupper ``` [Try it online!](https://tio.run/##y/r/P81WT0Gj1MrMVDtTz8hMU0vfIVWvJL@0oCC16H9qcka@QpqCekFpUk5mskJxSWIJkCrLz0xRyE3MzNMILinKzEuPjlVILEov1lTngql3THJOcU1zz/DM8s7xzfMvCCwKLgktC6@IrEKoMTQyTkxKTklNS8/IzMrOyVXw8w8IDAoOCQ0Lj4iMMjYyRChV/w8A "J – Try It Online") [Answer] # MATLAB / [Octave](https://www.gnu.org/software/octave/), ~~35~~ 33 bytes ``` @(x)~nnz(setdiff(65:90,upper(x))) ``` [Try it online!](https://tio.run/##TY5BT8IwHMXvfor/xbRLzIIHTTQxERDmRJi4ISLh0K3tKI62du2cO/jVxzAxennv8Hvv5anMkoq1/Mb3/fYW1963lA0umaWCc3x5cX3VO3NaM9Mhz2s5Rv10SEc82Ia7STGVkZ6b2C6qZb1qkAeniXHshOM16g9HQTiZRvN4sVwhOO8BGtyN7x8eZ0/PycvrG9r8pZF2aSEyKC2xnVVKUNgTIXFsjZD5egPE5KV33B@TovypJFsGH05k75Aa9SmBqxp2bq8ZBVUxA7bjBWm@gKq89GEQhbPgv/6ebQ8 "Octave – Try It Online") --- The anonymous function returns a logical 1 if the input `x` is a pangram, or a logical 0 if it isn't. Essentially it uses the same approach as @ThomasKwa's Pyth solution. The set difference between all characters in the upper case alphabet range (`65:91`) and the input string (converted to upper case). Any characters that are in the alphabet but not in the input string are returned by `setdiff`. Only if the array returned by the set difference is empty is the string a pangram. Using upper case instead of lower case saves a couple of bytes compared with `'a':'z'` because the ASCII value can be used instead to make the range. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes ``` ḷo⊇Ạ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P/hju35j7raH@5a8P9/tJJjknOKa5p7hmeWd45vnn9BYFFwSWhZeEVklZKOkqOzq7unt69/YHBoeCSXk4ubh5ePX0BQSFhEFFC2oDQpJzNZobgksQRIleVnpijkJmbmaQSXFGXmpUfHKiQWpRdrAhWGZKQqFJZmJmcrJBXll@cppOVXKGSV5hakpijkl6UWKZQA5XMSqyoVUvLTi/UUnPw9/dyRSaVYAA "Brachylog – Try It Online") ``` The input ḷ lowercased o sorted ⊇ is a superlist of Ạ the lowercase alphabet. ``` [Answer] # [Julia](https://julialang.org), ~~26~~ 25 bytes ``` !s='a':'z'⊆lowercase(s) ``` * remove `.` by @MarcMush [Attempt This Online!](https://ato.pxeger.com/run?1=bVRLctw2EF1lw1O0ZkO7ajTrVFKqRFYUaeLIsiM7kuPSAiRBEhIIMPgMTR0gi1whG218iBwlWfokfg2MPnZ5FjNTQPfr1-91458PV1Ercfv_N01wMfTz3rtisV8dNIftUb--eq5PzOn4yp2FN5vz929vFstisVjsHxwerZ-fnL46e3P-tnj208_Hv_z64uVvr3-_-AO3CHndS_ozqvqaKmcnQ619T1dxGGVDdiMdBdxrcTNTYzu_omen6xdHj7-BcVkUrdA-8RljpVVNPoiAn41VDQ1CmSdnwSnTvbsk4Tr_NHFL_A5RYybRBumMtWZJwnPJmSbpJNV2QBa1zg7k695avUyE6l7pxklD0YNnsNRZEqahUYuZlEkxR0qYUHrqhGukWRUF8WcdaEIJgZ5ch87Qo563MUuaVOjJ2zZQ5yTgOyc8mj5mLowPXPy71yVdo1drG6qkiEG1UVOrLch70upashDOLx8lp77CJPVG0ihF3e8GlOKmRbij7kcWazeoQbIrgLGRL9FoIyGvCDjX1ns7eLItjcpc5_6lcDpX20KBVBwMVRZVnap7aBlVWBHbXinXgD7q2hycmXC2F5DdW_KTlAECJXZfVR7dj3yjHFQckI7CFmo6vtTKB8TiHyKGFZXHdqJejCP7i1GQxJrslNny2qmMybKQZb3ubDs1khoxPxhLtWBxRH3N9gCTHcilNsqrQL3y6FXJLDwdWGeUByqMzQJxCtyZUTLZ3qsBw-_Iyw1wZigJ5_d5MLMnD8fZwzQFfS7tBeZcaJ112h6yOGJeJlBmU1uDFMitIDcPoVaDCrLZ0kGDEsUw8FkEJ0N0qSFO5tWshQ9arui8BxP21jm1kSnVi-lze3gTeHW2Y_D5EpTnTJPln23EYnMgG_FDyVjZBiQKSsvZudi2vMq1vB_kh0JOIHAS8z32yZzI5ooE6sPjg2WZxbo38nsqhUEEDK4BFQ1GB7akMiLkgms4BHEhMMbH2Mo2M-tyt-1wu8J-DLOXul2VdGa5jSoqjSahXtdD7pxPzkZeji3wiLQ4IshYPFdyt7IguSK8S8Xlhxja3W__3fF7pSi_K2_Kj3__lTYbNsgn_mm-_--Y7b3Yyy8yJPgRT4J0gXYu9vhQFphAvI8pKL2SX8TwWQrKeLe3-fcT) [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), ~~36~~ ~~19~~ 17 bytes ``` {~#(97+!26)^0+_x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6quU9awNNdWNDLTjDPQjq+o5eJKi1ZyTHJOcU1zz/DM8s7xzfMvCCwKLgktC6+IrFKKBcs7u7p7evv6BwaHhkc6ubh5ePn4BQSFhEVEQeRDMlIVCkszk7MVkoryy/MU0vIrFLJKcwtSUxTyy1KLFEqA8jmJVZUKKfnpxXoKTv6efu7IJMSUgtKknMxkheKSxBIgVZafmaKQm5iZpxFcUpSZlx4dq5BYlF6sqRQLAB8tP98=) *-2 bytes thanks to ngn!* Return `1` for true, `0` for false. Explanation: ``` {~#(97+!26)^0+_x} / Main program. x is input _ / Lowercase 0+ / Convert each character to ASCII value ^ / Without (set function) (97+!26) / Lowercase alphabet (ASCII value) # / Length ~ / Not ``` [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 57 bytes ``` \O:- \+ (between(97,122,Z),\+sub_atom_icasechk(O,_,[Z])). ``` [Try it online!](https://tio.run/##TYvNcoIwGEX3fYpvWMEYmambTrurP6XUaqporYjDJBAhCglNAlhf3jKu3NyzOOdWShYy6@uWX68RfulD1AObMtMyJuznJ/Q4GKDQQVFP1zQmRpYxT4hmSX6yMYrRLtw7jttdrVc6SicHL/eP02ImcLVQgVk3m/P2YrkPnR5NPH86w4tgvdlGYjh@e//4nH8tV98/4S2oalrwBLQhpkMjeQol4cIOjOIi2@2BqEw7t3SVM/iteXICqmQr4CDPcKzLiqUgG6bAdL4glz9IZaZdGGJ/7t2v5f4D "Prolog (SWI) – Try It Online") Buried deep within the Prolog library is the very convenient predicate `sub_atom_icasechk`, which is a "half case-insensitive" check for a substring (half as in lowercase characters can match uppercase but not vice-versa). We just need to surround this in a check that all lowercase letters succeed this check. [Answer] # [Japt](https://github.com/ETHproductions/Japt), 14 bytes ``` #ao#{ e@Uv fXd ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=I2FvI3sgZUBVdiBmWGQ=&input=IkEgcXVpY2sgYnJvd24gZm94IGp1bXBzIG92ZXIgdGhlIGxhenkgZG9nLiI=) ### How it works ``` // Implicit: U = input string #ao#{ // Generate a range of integers from charCode("a") to charCode("{"). e@ // Check if every item X in this range returns truthily to: Uv fXd // convert U to lowercase, and put all instances of X.toCharCode() in an array. // This returns false if U does not contain one of the characters. // Implicit: output last expression ``` [Answer] # Bash, 45 42 bytes 41 byte program, plus 1 because it must be invoked with `bash -e`: ``` for i in {a..z} { [ ${1//[^$i${i^}]} ] } ``` Amazingly, I managed a Bash answer with no quote characters! (yes, I checked with inputs beginning with `-f` and the like). This assumes a locale where the lower-case English letters are contiguous from `a` to `z`. Input is via the first argument to the program. The way this works is, for each alphabetic letter `$i`, we test whether the string contains `$i` or its upper-case equivalent `${i^}` by removing all other characters. If this results in the empty string, then the input did not contain that letter, and we exit with `1` (false). If we have a non-empty result, then we passed the test and move on to the next letter. If the input string contains every English letter, we will reach the end of the program, thus exiting with `0` (true). ]
[Question] [ ## Definitions * An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of `2` is algebraic, because it is a zero of `x^2 - 2`. * A transcendental number is a real number which is not algebraic. ## Task You are to choose a transcendental number. Then, write a program/function that takes a positive integer `n` and output the `n`-th **decimal** digit after the decimal point of your chosen transcendental number. You must state clearly in your submission, which transcendental number is used. You can use 0-indexing or 1-indexing. ## Example `e^2=7.389056098...` is a transcendental number. For this number: ``` n output 1 3 2 8 3 9 4 0 5 5 6 6 7 0 8 9 9 8 ... ``` Note that the initial `7` is ignored. As I mentioned above, you can choose other transcendental numbers. ## Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Lowest score in bytes wins. [Answer] # [Python](https://docs.python.org/2/), 3 bytes ``` min ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@bmfe/oCgzr0RBXV0vKz8zTyM6TaO4pEijQlMzLb9IoUIhM0@hKDEvPVXD0MBAM1bzPwA "Python 2 – TIO Nexus") Takes a number string, outputs its smallest digit as a smallest character. For example, `254` gives `2`. The decimal with these digits starts ``` 0.0123456789011111111101222222220123333333012344444401234555550123456666012345678801234567 ``` This is [OEIS A054054](https://oeis.org/A054054). **Claim:** This number `c` is transcendental **Proof:** Note that `c` is very sparse: almost all of its digits are zero. That's because large `n`, there's high probability `n` has a zero digit, giving a digit min of zero. Moreover, `c` has long runs of consecutive zeroes. We use an existing result that states this means `c` is transcendental. Following this [math.SE question](https://math.stackexchange.com/q/6321/24654), let `Z(k)` represent the position of the `k`'th nonzero digit of `c`, and let `c_k` be that nonzero digit, a whole number between `1` and `9`. Then, we express the decimal expansion of `c`, but only taking the nonzero digits, as as the sum over `k=1,2,3,...` of `c_k/10^Z(k)`. We use the result of [point 4 of this answer](https://math.stackexchange.com/a/6565/24654) by George Lowther: that `c` is transcendental if there are infinitely many runs of zeroes that are at least a constant fraction of the number of digits so far. Formally, there must be an `ε>0` so that `Z(k+1)/Z(k) > 1+ε` for infinitely many `k`. We'll use `ε=1/9` For any number of digits `d`, take `k` with `Z(k) = 99...99` with `d` nines. Such a `k` exists because this digit in `c` is a `9`, and so nonzero. Counting up from `99...99`, these numbers all contain a zero digit, so it marks the start of a long run of zeroes in `c`. The next nonzero digit isn't until `Z(k+1) = 1111...11` with `d+1` ones. The ratio `Z(k+1)/Z(k)` slightly exceeds `1+1/9`. This satisfies the condition for every `d`, implying the result. [Answer] # Pyth, 1 byte ``` h ``` Input and output are strings. The function takes the first digit of the index. The resulting transcendental number looks like: `0.0123456789111111111122222222223 ...` This is transcendental because it is `1/9` plus a number which has stretches of zeroes of length at least a constant fraction of the number. Based on [this math.stackexchange answer](https://math.stackexchange.com/questions/6321/have-all-numbers-with-sufficiently-many-zeros-been-proven-transcendental/6565#6565), that means that the number is transcendental. There are stretches of zeroes are from digit `100 ... 000` to `199 ... 999`, so ratio of `Z(k+1)` to `Z(k)` is 2 infinitely often. Thus, the above number minus `1/9` is transcendental, and so the above number is transcendental. [Answer] # [Python 2](https://docs.python.org/2/), 19 bytes ``` lambda n:1>>(n&~-n) ``` The **n**th digit is **1** if **n** is a power of **2** and **0** otherwise. [Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqJBnZWhnp5GnVqebp/m/oCgzr0QhN7FAI01HoSgxLz1Vw1BHwchQU/M/AA "Python 2 – TIO Nexus") [Answer] # brainfuck, 2 bytes ``` ,. ``` Similarly to some other answers, returns the first decimal digit and ignores the rest. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` e!€ ``` Uses Liouville's constant. [Try it online!](https://tio.run/nexus/jelly#@5@q@Khpzf///w0B "Jelly – TIO Nexus") [Answer] ## Retina, 4 bytes ``` 1!`. ``` Returns the first digit of the input number. Because that port was so boring, here are some more ports: ``` O`. 1!`. ``` (8 bytes) Returns the minimum digit of the input number. ``` .+ $* +`^(11)+$ $#1$* ^1$ ``` (25 bytes) Returns 1 if the input number is a power of 2. ``` .+ $*_ $.` +1`.(\d*)_ $1 1!`. ``` (30 bytes) Champernowne's constant. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog) 2, 7 bytes ``` ⟦₁c;?∋₎ ``` [Try it online!](https://tio.run/nexus/brachylog2#@/9o/rJHTY3J1vaPOrofNfX9/29k8D8KAA "Brachylog – TIO Nexus") Calculates digits of the Champernowne constant (possibly times a power of ten due to indexing issues, which clearly don't matter here). Basically, this just concatenates together integers, and then takes the *nth* digit. [Answer] # Python 2, 13 bytes Input and output are strings. ``` lambda n:n[0] ``` The number's nth digit is the most significant digit of n when it is written in decimal. [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` 4YA50<A ``` This uses the first of the two numbers given [here](https://en.wikipedia.org/wiki/Moser%E2%80%93de_Bruijn_sequence#Decimal_reciprocals) divided by 3 (which [maintains transcendence](https://en.wikipedia.org/wiki/Transcendental_number#Properties)): > > 1.100110000000000110011... > > > Input is 1-based. [Try it online!](https://tio.run/nexus/matl#@28S6WhqYOP4/78hAA "MATL – TIO Nexus") Or [see the first 20 decimals](https://tio.run/nexus/matl#s1Jy@G8S6WhqYOP4P1Yt47@RAQA). ### Explanation ``` 4YA % Convert to base 4 using chars '0', '1', '2', '3' as digits 50<A % Are all digits less than '2'? Gives 0 (false) or 1 (true) ``` [Answer] # JavaScript, 51 bytes This function computes `n`th digit of Champernowne's Constant. Add `f=` at the beginning and invoke like `f(arg)`. Note that `n` is 1-indexed. ``` n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1] ``` ## Explanation This function takes in a single argument `n`. It, then, creates an `n`-characters long String of repetitive 1s. Then, it splits that String into an Array of 1s . After that, it iterates over every element of the Array and multiplies them with their index in the Array incremented by 1. Then, it joins the Array together over `""` (empty String) to form a String. At last, it returns the `n`th element of the obtained String. **Note:** *The type of the returned value is always String*. ## Test Snippet ``` let f = n=>[..."1".repeat(n)].map((c,i)=>c*++i).join``[n-1] i.oninput = e => o.innerHTML = f(parseInt(e.target.value,10)); ``` ``` <input id=i><pre id=o></pre> ``` [Answer] # Python 2, 43 bytes Champernowne's constant. ``` lambda n:"".join(`i`for i in range(n+1))[n] ``` [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 3 bytes ``` 2|⍴ ``` [Try it online!](https://tio.run/nexus/apl-dyalog#@@/4qG2CUc2j3i3//zs@6pjxqHfqoRWPejcbGgABAA "APL (Dyalog Unicode) – TIO Nexus") (the test suite generates a range of numbers from `1` to `10000`, converts them to a string, and then applies the train `2|⍴` on them). Takes the input number as a string and returns its length mod 2. So `123` => `3 mod 2` => `1`. The sequence starts off like so: ``` 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 ... ``` so this can be generalised like so: `9 1s 90 0s 900 1s ...` Multiplying this number by 9 gives us a [Liouville number](https://en.wikipedia.org/wiki/Liouville_number), which is proven to be transcendental. [Answer] # Haskell, ~~25 bytes~~ 17 bytes ``` (!!)$concat$map show[1..] ``` [Champernowne's Constant](https://en.wikipedia.org/wiki/Champernowne_constant) can be 0 or 1 indexed as C10\*.01 is still transcendental. Edit: as per nimis comment you can use the list monad to reduce this to ``` (!!)$show=<<[1..] ``` [Answer] # JavaScript, 73 bytes This is a program which computes the `n`th digit of the Liouville Constant, where `n` is the input number given by invoking the function `g` as `g(arg)` (and `n` is 1-indexed). Note that the newline in the code is necessary. ``` f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1 return r} ``` ## Explanation The program consists of two functions, `f` and `g`. `f` is a recursive factorial-computing function, and `g` is the main function of the program. `g` *assumes* to have a single argument `n`. It defines a default argument `r` with a value of 0. It, then, iterates over all the Integers from 0 to `n`, and, in each iteration, checks whether the function `f` applied over `i` (the current index) equals `n`, i.e. whether `n` is a factorial of `i`. If that happens to be the case, `r`'s value is set to 1. At the end of the function, `r` is returned. ## Snippet for Testing ``` f=n=>n<1?1:n*f(n-1);g=(n,r=0)=>{for(i=0;i<=n;i++)if(f(i)==n)r=1 return r} i.oninput = e => o.innerHTML = g(parseInt(e.target.value,10)) ``` ``` <input id=i><pre id=o></pre> ``` **Warning:** *Don't put a very large value in the Snippet's input box! Otherwise, your device may freeze!* [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 1 byte ``` Ḣ ``` [Try it online!](https://tio.run/nexus/jelly#@/9wx6L///@rGxoYqAMA "Jelly – TIO Nexus") 1st digit of quoted 0-indexed input.1 1See isaacg's answer for proof of validity. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~3~~ ~~1+1= 2~~ 1 byte Another port of [feersum's solution](https://codegolf.stackexchange.com/a/120631/58974). Takes input as a string. ``` g ``` [Try it online](http://ethproductions.github.io/japt/?v=1.4.4&code=Zw==&input=IjgwIg==) --- ## Explanation ``` :Implicit input of string U g :The first character of the string ``` [Answer] # Pyth, ~~7~~ ~~5~~ 4 bytes ``` @jkS ``` [Try it online!](http://pyth.herokuapp.com/?code=%40jkUh&input=10&debug=0) Uses Champernowne's constant. Saved ~~2~~ 3 bytes thanks to Leaky Nun. [Answer] # Java 8, 18 bytes Same as [Dennis' answer for Python 2](https://codegolf.stackexchange.com/a/120630/58251), the [Fredholm number](https://en.wikipedia.org/wiki/Transcendental_number#Numbers_proven_to_be_transcendental) ``` n->(n&(n-1))>0?0:1 ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes (noncompeting) ``` NαAIUVN⟦UGPi⁺α¹⟧β§β⁺α›α⁰ ``` [Try it online!](https://tio.run/nexus/charcoal#@/9@z7pzG9/vWfh@z8r3e7a@37PN79H8ZWDW8oDMR427zm08tPPR/OXnNh0CYjD/UQOIaNzw/78JAA "Charcoal – TIO Nexus") **Note:** As of post time, does not work for `n` where `n` is a positive multiple of 14. # Explanation ``` Nα Input number to a A β Assign to b I Cast UVN Evaluate variable N ⟦UGPi⁺α¹⟧ With arguments GetVariable(Pi) and a+1 §β⁺α›α⁰ Print b[a+(a>0)] ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~3~~ 1 byte **EDIT**: Using the proof from the other answers, returns the first digit of input ``` ¬ ``` 1-indexed for π (only up to 100000 digits) ``` žs¤ ``` How it works ``` žs # Implicit input. Gets n digits of pi (including 3 before decimal) ¤ # Get last digit ``` Or, if you prefer e (still 1-indexed) (only up to 10000 digits) ``` žt¤ ``` [Try it online!](https://tio.run/nexus/05ab1e#@390X/GhJf//GxoYGAAA "05AB1E – TIO Nexus") [Answer] # TI-BASIC, 16 bytes Basically tests if the input `N` (1-indexed) is a triangular number. This is the same as returning the `N`th digit of 0.1010010001…, which is [proven](https://math.stackexchange.com/a/781687/101777) to be transcendental. The sequence of digits is [OEIS A010054](https://oeis.org/A010054). ``` Input N int(√(2N 2N=Ans(Ans+1 ``` [Answer] # [Duocentehexaquinquagesimal](https://esolangs.org/wiki/Duocentehexaquinquagesimal), 1 byte *Ties [isaacg's Pyth answer](https://codegolf.stackexchange.com/a/120639/94066), [Erik the Outgolfer's Jelly answer](https://codegolf.stackexchange.com/a/120683/94066), [Neil A.'s 05AB1E answer](https://codegolf.stackexchange.com/a/120983/94066), and [Shaggy's Japt answer](https://codegolf.stackexchange.com/a/121403/94066) for #1.* ``` . ``` [Try it online!](https://tio.run/##S0oszvifnFhiYxPzqGGRXbx1cWqKgm6mgrphsXWcNVDIWl0hXsHILq80x7qkqDQPqDRVQbdY11Ah3jo1OSNfQTdPQR2oLOnQMuPDW5yP7stQsrPR1tXTiY5VetSw0Evdzg6isEY/v6BEP784MSkzFUopxNslWYOFk4oSM/PSSpOzESyFpP96/4EG/zc0MgYA) [Answer] # [Pyt](https://github.com/mudkip201/pyt), 5 bytes ``` Đř!∈Ɩ ``` [Try it online!](https://tio.run/##K6gs@f//yISjMxUfdXQcm/b/v5EJAA "Pyt – Try It Online") Liouville Constant ``` Đ implicit input (n); duplicate ř! get [1!,2!,...,n!] ∈ is n in that list? Ɩ coerce to integer; implicit print ``` [Answer] # Regex (ECMAScript), 13 bytes ``` ((xx|)x*)\1+$ ``` [Try it online!](https://tio.run/##TY/NTsJAFEZfpTaG3kttocQYwziwcsGGhS6RxQQu7dXpdDIzQOVn6wP4iL5IxQWJybc7i@@cd7VTfuXYhsxbXpOrG/NBn52ThvbRC5XPrQU4yMmg30E7vQzbPr4V6W3XHxwwD81rcGxKwNxrXhE83GX3iMLLodhXrAlAS0dqrdkQIN5Is9Uaj6XUubeaAyRZgoI3AEaWuSZThgono9OJ/VzNgaVVztPMBCgXwyXiFdB/YCbFtBj/YQyVa/bxzOyU5nXklClpHMWpFpvGgeAnSYLTFC@HtYzbOHdkSQVgzGsVVhU4xKPv9ewlKsBfRyHsNvjggNMk@vn6jpK0XoyWV1VxPndFVowefwE "JavaScript (SpiderMonkey) – Try It Online") Takes its input in unary, as a string of `x` characters whose length represents the number. The output is returned as the length of capture group `\2`. Returns the \$n\$th digit of \$0.00020202220202220202220222220202222202220202220222220...\$, where the \$n\$th digit is \$2\$ if \$n\$ is a composite number, and \$0\$ otherwise. ``` # tail = N = input number ((xx|)x*) # \1 = the largest proper divisor of N; # \2 = 2 if \1 >= 2, or 0 otherwise; # tail -= \1 \1+$ # Assert that \1 divides tail ``` If the return value of `\2` is defined to be \$0\$ when it is unset, then this can be reduced to **12 bytes**, with \$0.00010101110101110101110111110101111101110101110111110...\$ as the transcendental number: ``` (x?(x)*)\1+$ ``` [Try it online!](https://tio.run/##TY/NTsJAFEZfpTaG3kttocQYQx1YuWDDQpfoYgKX6dXpdDIzQOVn6wP4iL5IhUQTN9/mLL5z3uRW@qVjGzJveUWubsw7fXROGNpFT6QeWwuwF5NBv4N2Ci328aVIr7v@YI95aJ6DY6MAc695SXB3k90ill4My13FmgC0cCRXmg0B4pUwG63xoITOvdUcIMkSLHkNYITKNRkVKpyMjkf2czkHFlY6TzMTQC2Gr4h/gP4DMymmxfiCMVSu2cUzs5WaV5GTRtE4ilNdrhsHJT8IKjlN8XxYi7iNc0eWZADGvJZhWYFDPPhez56jAlw6itJugg8OOE2i78@vKEmhXoxep5f5FR4Pz8mnU1dkxej@Bw "JavaScript (SpiderMonkey) – Try It Online") ### Regex (ECMAScript), 14 bytes ``` ((x*)(?=\2)x)* ``` [Try it online!](https://tio.run/##Tc@9bsIwFIbhW0kzkHOSJpCoqipcw9SBhaEdKYMFB8et41i2gZSftRfQS@yNpDAgdX6G73s/xE74lVM25N6qNbmmNZ/01TtuaB@9knzpLMCBT4ZpD9ClCFP@XmGHaZ8OD1iE9i04ZSRg4bVaETze5w@IzPMR29dKE4DmjsRaK0OAeMfNVms8Sq4Lb7UKkOQJMrUBMFwWmowMNU6q00n5uZiD4lY4TzMTQC5GS8Qb0H8wk3Jajq@MoXbtPp6ZndBqHTlhJI2jONNs0zpg6pkTU1mGl8GGx11cOLIkAigsGhFWNTjEox8M7CUqwLWjZHYbfHCgsiT6/f6JkqxZVMvbVXY@92VeVk9/ "JavaScript (SpiderMonkey) – Try It Online") The output of this one is also returned as the length of capture group `\2`. Returns the \$n\$th digit of \$0.01001100001111000000001111111100000000000000001...\$ (with 1-indexing). The \$n\$th digit of this transcendental number is the 2nd digit of the binary expansion of \$n+1\$, [OEIS A079944](https://oeis.org/A079944). ``` # tail = N = input number ( (x*)(?=\2) # \2 = floor(tail / 2); tail -= \2 x # tail -= 1 )* # Iterate the above as many times as possible ``` [Answer] # Fourier, 16 bytes ``` I~NL~S10PS~XN/Xo ``` [**Try it online!**](https://tio.run/nexus/fourier#@@9Z5@dTF2xoEBBcF@GnH5H//7@xuQUA) As other answers have done, outputs the first digit of the input. An explanation of the code: ``` N = User Input S = log(N) X = 10 ^ S Print (N/X) ``` [Answer] # JavaScript (ES6) Just a few ports of some other solutions --- ## [feersum's Python solution](https://codegolf.stackexchange.com/a/120631/58974), 12 bytes ``` n=>(""+n)[0] ``` ``` f= n=>(""+n)[0] o.innerText=f(i.value=1) i.oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` --- ## [Dennis' Python solution](https://codegolf.stackexchange.com/a/120630/58974), 13 bytes ``` n=>1>>(n&--n) ``` ``` f= n=>1>>(n&--n) o.innerText=f(i.value=1) i.oninput=_=>o.innerText=f(+i.value) ``` ``` <input id=i type=number><pre id=o> ``` --- ## [xnor's Python solution](https://codegolf.stackexchange.com/a/120635/58974), 20 bytes ``` n=>Math.min(...""+n) ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 6 + 3 ( `-c`) = 9 bytes ``` ({}<>) ``` [Try it online!](https://tio.run/nexus/brain-flak#@69RXWtjp/n/v6GBwX/dZAA "Brain-Flak – TIO Nexus") 1st digit of 0-index string input (hence the `-c` flag). [Answer] # C#, 13 bytes ``` n=>(n+"")[0]; ``` From feersum's solution. Almost same solution than the js port. [Try it online](https://dotnetfiddle.net/zwjTyy) [Answer] # J, 2 Bytes The same solution everyone else is using: ``` {. ``` Returns the first digit of n. IO is on strings ## Liouville's Constant, 9 Bytes ``` (=<.)!inv ``` Returns `1` if input is the factorial of an integer. ## Pi, 13 Bytes ``` {:":<[[email protected]](/cdn-cgi/l/email-protection)^ ``` The last non-decimal digit of pi times 10^n. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` LḂ ``` [Try it online!](https://tio.run/##y0rNyan8/9/n4Y6m////KxkbmhiaWhqZmRorAQA "Jelly – Try It Online") Take the length of the input number modulo 2. Equivalent to [this APL answer](https://codegolf.stackexchange.com/a/120674/61384). ]
[Question] [ ## Multiplicative Persistence 1. Multiply all the digits in a number 2. Repeat until you have a single digit left As explained by *Numberphile*: * [*Numberphile* "What's special about 277777788888899?"](https://www.youtube.com/watch?v=Wim9WJeDTHQ) * [*Numberphile* "Multiplicative Persistence (extra footage)"](https://www.youtube.com/watch?v=E4mrC39sEOQ) ### Example 1. 277777788888899 → 2x7x7x7x7x7x7x8x8x8x8x8x8x9x9 = 4996238671872 2. 4996238671872 → 4x9x9x6x2x3x8x6x7x1x8x7x2 = 438939648 3. 438939648 → 4x3x8x9x3x9x6x4x8 = 4478976 4. 4478976 → 4x4x7x8x9x7x6 = 338688 5. 338688 → 3x3x8x6x8x8 = 27648 6. 27648 → 2x7x6x4x8 = 2688 7. 2688 → 2x6x8x8 = 768 8. 768 → 7x6x8 = 336 9. 336 → 3x3x6 = 54 10. 54 → 5x4 = 20 11. 20 → 2x0 = 0 This is the current record, by the way: the smallest number with the largest number of steps. ## Golf A program that takes any whole number as input and then outputs the result of each step, starting with the input itself, until we hit a single digit. For 277777788888899 the output should be ``` 277777788888899 4996238671872 438939648 4478976 338688 27648 2688 768 336 54 20 0 ``` (Counting the number of steps is left as an exercise to the user). ### More Examples From [A003001](https://oeis.org/A003001): ``` 25 10 0 ``` From A003001 as well: ``` 68889 27648 2688 768 336 54 20 0 ``` From the *Numberphile* video, showing that the single digit doesn't have to be 0: ``` 327 42 8 ``` --- *So there has been [a question about Additive Persistence](https://codegolf.stackexchange.com/q/1775/14150), but this is Multiplicative Persistence. Also, that question asks for the number of steps as output, while I'm interested in seeing the intermediate results.* [Answer] # TI-BASIC (TI-84), ~~30~~ ~~32~~ 31 bytes *-1 byte thanks to @SolomonUcko!* ``` While Ans>9:Disp Ans:prod(int(10fPart(Ans10^(seq(-X-1,X,0,log(Ans:End:Ans ``` Input is in `Ans`. Output is displayed as the challenge requests. The trailing `Ans` is needed to print the last step. I will admit, I did not think of this formula myself, rather I found it [here](http://tibasicdev.wikidot.com/sum-of-digits) and modified it to better fit the challenge. **EDIT:** Upon rereading the challenge, I realized that the program must terminate if the product is one digit. Hence, **2 bytes** were to be added to account for this. **Example:** ``` 24456756 24456756 prgmCDGF8 24456756 201600 0 11112 11112 prgmCDGF8 11112 2 ``` **Explanation:** ``` While Ans>9 ;loop until the product is one digit Disp Ans ;display the current product prod( ;get the product of... int( ; the integer part of... 10fPart( ; ten times the fractional part of... Ans ; each element in the following list times the ; current product 10^( ; multiplied by the list generated by using each ; element of the following list as an exponent ; for 10^n seq(-X-1),X,0,log(Ans ; generate a list of exponents from -1 to -L where ; L = the length of the current product End Ans ;leave the final product in "Ans" and implicitly ; print it ``` **Visual Model:** `Ans` starts off as `125673`. This model only covers the logic behind multiplying the digits; everything else is easier to understand. ``` seq(-X-1,X,0,log(Ans => seq(-X-1,X,0,5.0992 {-1 -2 -3 -4 -5 -6} 10^(... {.1 .01 .001 1E-4 1E-5 1E-6} Ans... {12567.3 1256.73 125.673 12.5673 1.25673 .125673} fPart(... {.3 .73 .673 .5673 .25673 .125673} 10... {3 7.3 6.73 5.673 2.5673 1.25673} int(... {3 7 6 5 2 1} (the digits of the number, reversed) prod(... 1260 (process is repeated again) seq(-X-1,X,0,log(Ans => seq(-X-1,X,0,3.1004 {-1 -2 -3 -4} 10^(... {.1 .01 .001 1E-4} Ans... {126 12.6 1.26 .126} fPart(... {0 .6 .26 .126} 10... {0 6 2.6 1.26} int(... {0 6 2 1} prod(... 0 (product is less than 10. loop ends) ``` --- **Notes:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. `10^(` is [this one-byte token](http://tibasicdev.wikidot.com/ten-exponent). This program will not provide the correct sequence of products with integers greater than 14 digits long due to the limitations of decimal precision on the TI calculators. [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), 9 bytes ``` {*/.'$x}\ ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlpLX09dpaI25n@agpE5GFiAgaXlfwA "K (ngn/k) – Try It Online") `{` `}\` keep applying the function in curly braces until the sequence converges `$x` format the argument as a string (list of characters) `.'` evaluate each (other dialects of k require a colon, `.:'`) `*/` times over, i.e. product [Answer] # [R](https://www.r-project.org/), ~~59~~ 57 bytes ``` n=scan();while(print(n)>9)n=prod(n%/%10^(0:log10(n))%%10) ``` [Try it online!](https://tio.run/##DcnBCoAgDADQrxG2U2p0qLBPCcKkBrKJCn3@8vpeVSmdhBu0SCVx8DMqhxYvBty/l3KCUok7MB4rcihVbmAzGWdPsFuWx9lxaAag@kV/ "R – Try It Online") Since `print` `invisibly` returns its input, we can use `print(n)` inside the `while` loop to simulate a `do-while` loop. This is inspired by one of my [tips for golfing in R](https://codegolf.stackexchange.com/a/157131/67312). The header helps prevent large numbers from being printed in scientific notation. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` DP$Ƭ ``` [Try it online!](https://tio.run/##y0rNyan8/98lQOXYmv///xuZg4EFGFhaAgA "Jelly – Try It Online") ### Explanation ``` D | convert to decimal digits P | take the product $ | previous two links as a monad Ƭ | loop until no change, collecting all intermediate results ``` As a bonus, here's a [TIO](https://tio.run/##AT8AwP9qZWxsef//RFAkxqxM4oCZ/3LFk8SLQDIsMyw0LDYsNyw4LDnhuIxGw4c7JOKCrDHhu4skw5DhuYD//zH/MTU) which will find the numbers with the largest number of steps for a given range of numbers of digits. It scales well even on TIO. [Answer] # [dzaima/APL](https://github.com/dzaima/APL), ~~14~~ 11 bytes ``` ∪{×/⍎¨⍕⍵}⍡≡ ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfyf9qhtgsb/Rx2rqg9P13/U23doxaPeqY96t9Y@6l34qHPhf02uR31TgWrSFEzhLHNzczjbyBwMLMDA0vI/AA "APL (dzaima/APL) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~7~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Δ=SP ``` [Try it online](https://tio.run/##yy9OTMpM/f//3BTb4ID//43MwcACDCwtAQ) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W@f/cFNvggP@1h7bZ/482MgcDCzCwtNQxMtUxA7F0jI3MYwE). **Explanation:** ``` Δ # Loop until the number no longer changes: = # Print the number with trailing newline (without popping the number itself) # (which will be the implicit input in the first iteration) SP # Convert the number to a list of digits, and calculate its product ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes ``` Most@FixedPointList[Times@@IntegerDigits@#&,#]& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773ze/uMTBLbMiNSUgPzOvxCezuCQ6JDM3tdjBwTOvJDU9tcglMz2zpNhBWU1HOVbtf0ARUJWCvoNCerSRORhYgIGlZez//wA "Wolfram Language (Mathematica) – Try It Online") [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 23 bytes ``` {$_,{[*] .comb}…10>*} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJZm@79aJV6nOlorVkEvOT83qfZRwzJDAzut2v/WCsWJlQppGkbmYGABBpaWmv8B "Perl 6 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~46~~ 43 bytes -3 thanks to xnor (chained comparison) ``` def f(n):print n;n>9>f(eval('*'.join(`n`))) ``` **[Try it online!](https://tio.run/##XY3BCsIwEETP7VcsvWQjQWwq6Ebot1QwwYhsQk0Fvz6mET048HZgBnbiK10D65wv1oFDlibOnhPwiUcaHdrn@Y5iI7a34BknnqSU2YUZkn0k8AyoD1XHKiIF/a7QF3RhWL0cPewVEJE0bfNZ6DzHJZlO1Ve/NCypxtA2DtdGfish8t/WGw "Python 2 – Try It Online")** [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes ``` 0Print@#+#>9&&#0@@Times@@@RealDigits@#& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yCgKDOvxEFZW9nOUk1N2cDBISQzN7XYwcEhKDUxxyUzPbOk2EFZ7X96tJE5GFiAgaVl7P//AA "Wolfram Language (Mathematica) – Try It Online") -6 bytes from @att [Answer] # [Julia 0.7](http://julialang.org/), ~~36~~ 33 bytes ``` f(n)=n>9?[n;f(prod(digits(n)))]:n ``` [Try it online!](https://tio.run/##yyrNyUw0//8/TSNP0zbPztI@Os86TaOgKD9FIyUzPbOkGCiuqRlrlfc/N7FAI1PXrqAoM68kJ08jU1MnTcPIHAwswMDSUlPzPwA "Julia 0.7 – Try It Online") Thanks to H.PWiz for -3 bytes. [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), 29 bytes ``` qqlYp:s/./&*/g C<C-r>=<C-r>"<BS> <esc>|@qq@q ``` [Try it online!](https://tio.run/##K/v/v7AwJ7LAqlhfT19NSz@dy1nIVkiJg0u6xqGw0KHw/38jczCwAANLSwA "V (vim) – Try It Online") [Answer] # JavaScript (ES6), 45 bytes Returns an array of integers. ``` f=n=>[n,...n>9?f(eval([...n+''].join`*`)):[]] ``` [Try it online!](https://tio.run/##VchNCoAgEEDhfRfJ6WcWbcwgO4gISWkUMhMVXd@oXd/uvc3d7pyOdb9q4tmnFHrqtaEKEUmrIQh/uyjMm2WeW9x4pbEYATpjbZqYTo4eIy8iCCklQPZ/jfy0H6UA0gM "JavaScript (Node.js) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 54 bytes ``` for($a=$args;$a-gt9){$a;$a=("$a"|% t*y)-join"*"|iex}$a ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl0VYlsSi92FolUTe9xFKzWiURyLTVUFJJVKpRVSjRqtTUzcrPzFPSUqrJTK2oVUn8//@/kTkYWICBpSUA "PowerShell – Try It Online") --- Iterative method that first writes the input argument, then converts it into a string and pipes it into a character array. This array is joined by a single asterisks, and executed as a command with the invoke expression alias. Since this writes Starting number down to the last number greater than 0, (20, in the given test scenario), I add a final `$a` to the end to output. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 51 bytes ``` filter f{$_ if($_-gt9){("$_"|% t*y)-join'*'|iex|f}} ``` [Try it online!](https://tio.run/##XZDdasMwDIXv8xTGuDQuCtQ/seXBYG@Si83ZUkLapRnrSPLsmZwtZUwXx9KnI2R0OX/G/voW23ZZ6qYdYs/qUVRZU@eiKl6HIMeci4pPOzYcvmRxOjfd/rCfmnib6nlenvKMUUCu/Rq4RgjA/gMbgtMGnVfoNViDwQRnEaz1GLwDQz1E0D5BnVLvkKiD0oI@wlH@blJAj9oqbagkcfd2Iuov0cbSd0i0BdxgmeZIVAnlxrwnRmID0FqFyS3ZxHZsXB2iAybi7RKfh/jCHhndacV9vH60QwLdVK@IC7raD@ZFfOf3KS4fNj/P5uUb "PowerShell – Try It Online") [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~79~~ ~~74~~ 68 bytes ``` void f(int a){Print(a);if(a>9)f((a+"").Aggregate(1,(j,k)=>k%48*j));} ``` I try to stay away from recursion in C# due to how long the method declaration is, but in this case it saves compared to a loop. [Try it online!](https://tio.run/##Sy7WTS7O/P@/LD8zRSFNIzOvRCFRszqgCMjQSNS0zkzTSLSz1EzT0EjUVlLS1HNMTy9KTU8sSdUw1NHI0snWtLXLVjWx0MrS1LSu/Q/WrxeQWFScqhGUmpjik5mXqqEJlPpvYmEEAA "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # [PHP](https://php.net/), 63 bytes ``` <?=$n=$argn;while($n>9)echo" ",$n=array_product(str_split($n)); ``` Iterative version, call with `php -nF` input from `STDIN`. [Try it online!](https://tio.run/##K8go@G9jX5BRoKCSWJSep2CrkJaeWlKsERzi4umnaa1gbweUtlXJswVLW5dnZOakaqjk2VlqpiZn5CtxKekA5RKLihIr4wuK8lNKk0s0ikuK4osLcjJLgOo0Na3//zcyBwMLMLC0BAA "PHP – Try It Online") # [PHP](https://php.net/), ~~72~~ 71 bytes ``` function h($n){echo"$n ",($n=array_product(str_split($n)))>9?h($n):$n;} ``` [Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUMjRU8jSrU5Mz8pVU8riUdIBc28SiosTK@IKi/JTS5BKN4pKi@OKCnMwSkEpNTTtLe7AeK5U869r/II1AMxTS0lNLijWCQ1w8/TQVNHUUAjwC4l39faz/G5mDgQUYWFoCAA "PHP – Try It Online") Recursive version, as function. Input: [277777788888899](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUMjRU8jSrU5Mz8pVU8riUdIBc28SiosTK@IKi/JTS5BKN4pKi@OKCnMwSkEpNTTtLe7AeK5U869r/II1AMxTS0lNLijWCQ1w8/TQVNHUUAjwC4l39faz/G5mDgQUYWFoCAA "PHP – Try It Online") ``` 277777788888899 4996238671872 438939648 4478976 338688 27648 2688 768 336 54 20 0 ``` Input: [23](https://tio.run/##K8go@G9jXwAk00rzkksy8/MUMjRU8jSrU5Mz8lXydJS4lHSAfNvEoqLEyviCovyU0uQSjeKSovjigpzMEpBSTU07S3uwJiuVPOva/yCdQEMU0tJTS4o1gkNcPP00FTR1FAI8AuJd/X2s/xsZAwA) ``` 23 6 ``` [Answer] # [J](http://jsoftware.com/), 16 bytes ``` ([:*/,.&.":)^:a: ``` [Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F8j2kpLX0dPTU/JSjPOKtHqvyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagpE5GFiAgaUl138A "J – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~61~~ ~~62~~ 59 bytes ``` def f(n):print n;n>9and f(reduce(int.__mul__,map(int,`n`))) ``` [Try it online!](https://tio.run/##K6gsycjPM/r/PyU1TSFNI0/TqqAoM69EIc86z84yMS8FKFaUmlKanKoBFNWLj88tzYmP18lNLADxdRLyEjQ1Nf@naRiZg4EFGFhaanKBTeECShhr/gcA "Python 2 – Try It Online") -3 bytes, thanks to Jonathan Allan [Answer] # [Ruby](https://www.ruby-lang.org/), ~~38~~ ~~35~~ 34 bytes ``` f=->n{p(n)>9&&f[eval n.digits*?*]} ``` [Try it online!](https://tio.run/##KypNqvz/P81W1y6vukAjT9POUk0tLTq1LDFHIU8vJTM9s6RYy14rtvZ/WrSRORhYgIGlZex/AA "Ruby – Try It Online") 1 byte saved by by G B. [Answer] # perl 5 (`-n` `-M5.01`), ~~32~~ ~~30~~ 25 bytes ``` say$_=eval;s/\B/*/g&&redo ``` [25 bytes](https://tio.run/##K0gtyjH9/784sVIl3ja1LDHHulg/xklfSz9dTa0oNSX//38jczCwAANLy3/5BSWZ@XnF/3Xz/uv6muoZGAIA) [30 bytes](https://tio.run/##K0gtyjH9/784sVIl3ja1LDHHulhfw14xrkZFU19LP11NrSg1Jf//fyNzMLAAA0vLf/kFJZn5ecX/dfP@6/qa6hkYAgA) [32 bytes](https://tio.run/##K0gtyjH9/784sdJaRclWXUvdWkMl3ja1LDFHycFNSdPOUk2tKDUl//9/I3MwsAADS8t/@QUlmfl5xf91cwrc9PX/6/qa6hkYAgA) [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), ~~9~~ 10 bytes ``` h(ôo▒ε*h(→ ``` [Try it online!](https://tio.run/##y00syUjPz0n7/z9D4/CW/EfTJp3bqpWh8aht0v//hlymXJZchsZchkbGJqZcRuZgYAEGlpb/AQ "MathGolf – Try It Online") Now it correctly handles inputs that are single digits. Not perfect, but at least it is correct. ## Explanation ``` h( check length of input number and decrease by 1 ö → while true with pop using the next 6 operators p print with newline ▒ split to list of chars/digits ε* reduce list by multiplication h( length of TOS without popping, subtracted by 1 (exits when len(TOS) == 1) ``` [Answer] # APL(NARS), 19 chars, 38 bytes ``` {⍵≤9:⍵⋄∇×/⍎¨⍕⍵⊣⎕←⍵} ``` test: ``` f←{⍵≤9:⍵⋄∇×/⍎¨⍕⍵⊣⎕←⍵} f 23 23 6 f 27648 27648 2688 768 336 54 20 0 ``` [Answer] ## Haskell, 45 bytes ``` f n=n:[x|n>9,x<-f$product$read.pure<$>show n] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzbPKrqiJs/OUqfCRjdNpaAoP6U0uUSlKDUxRa@gtCjVRsWuOCO/XCEv9n9uYmaegq1CQVFmXomCikKagpE5GFiAgaXlfwA "Haskell – Try It Online") [Answer] # [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 9 bytes Horribly inefficient - don't even *try* to run the first test case! ``` _ì ×}hN â ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI=&code=X%2bwg131oTiDi&input=Nzc3) ``` _ì ×}hN â :Implicit input of integer U N :Starting with the array of inputs (i.e., [U]) h :Do the following U times, pushing the result to N each time _ :Take the last element in N and pass it through the following function ì : Convert to digit array × : Reduce by multiplication } :End function â :Deduplicate N :Implicitly join with newlines and output ``` [Answer] # Chevron, 100 bytes ``` >^__>>^n ->+11?^n<10 >^n ^d<<1 ^i<<1 ^m<^i>^n ->+4??^m=^__ ^d<<^d*^m ^i<<^i+1 ->-4 ^n<<^d ->-10 ><^n ``` This is a fairly new language of my own creation - prototype interpreter, documentation, and example programs can be found at <https://github.com/superloach/chevron>. ## Explanation: * `>^__>>^n` - take the input as a NUM, with empty prompt * `->+11?^n<10` - if the number is under 10 (1 digit), skip to the end * `>^n` - output the current number * `^d<<1` - initialise the product to 1 * `^i<<1` - initialise the character index to 1 * `^m<^i>^n` - get i'th character of the number * `->+4??^m=^__` - jump out of loop if no character is found * `^d<<^d*^m` - multiply character into product * `^i<<^i+1` - increment character index * `->-4` - hop back to continue getting characters * `^n<<^d` - once loop is done, assign product as new number * `->-10` - hop all the way to the beginning for the next iteration * `><^n` - exit, printing the final number [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes ``` ẉ?Ḋ|ẹ×↰ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GuTvuHO7pqHu7aeXj6o7YN//8bmYOBBRhYWv4HAA "Brachylog – Try It Online") ### Explanation ``` ẉ Write the input followed by a linebreak ?Ḋ If the input is a single digit, then it's over | Otherwise ẹ Split the input into a list of digits × Multiply them together ↰ Recursive call with the result of the multiplication as input ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), 46 bytes ``` f=a=>a>9?[a,...f(eval([...a+''].join`*`))]:[a] ``` [Try it online!](https://tio.run/##JcpLDkAwFAXQ5Wh93sBAkGAh1aQXrZCmTxDbL4nZGZwdD6753I67mDBZXwRebIyuQ9ejbwaFnIicsA@8UB@RJYmmnbdgUiOlbhV0nDlc7C15XoUTZVXX8i9jMDK@ "JavaScript (Babel Node) – Try It Online") --- # [JavaScript (Babel Node)](https://babeljs.io/), 44 bytes *If the input can be taken as String* ``` f=a=>a>9?[a,...f(''+eval([...a].join`*`))]:a ``` [Try it online!](https://tio.run/##JcrdCkAwGAbgy9nm5yvKAYULQe3FaGvtE3L7oxw@9Tg8uJbTHnc@YzY@D7yaGLcWbYeu7gdkRLRJIVLzwMvhEyZybINOtFJTg7hwuNgb8rzLb1ZFKdQ/xqBVfAE "JavaScript (Babel Node) – Try It Online") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~64~~ 59 bytes ``` for($a="$args";9-lt$a){$a;$a="$(($a|% t*y)-join'*'|iex)"}$a ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SEMl0VZJJbEovVjJ2lI3p0QlUbNaJdEaLKoBlKxRVSjRqtTUzcrPzFPXUq/JTK3QVKpVSfz//7@RORhYgIGlJQA "PowerShell – Try It Online") Iterative method. Takes input and stores it into `$a`, then enters a `for` loop so long as the length of `$a` is two or more (i.e., it's bigger than `9`). Inside the loop we output `$a` and then recalculate it by converting it `t`oCharArra`y`, `join`ing it together with `*`, and then `iex` (short for `Invoke-Expression` and similar to `eval`). Once we're out of the loop, we have a single digit left to print, so we place `$a` onto the pipeline again. *-5 bytes thanks to KGlasier.* [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes ``` θW⊖Lθ«≔IΠθθ⸿θ ``` [Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRKNQ05qrPCMzJ1VBwyU1uSg1NzWvJDVFwyc1L70kAyirqalQzcXpWFycmZ6n4ZxYXKIRUJSfUpoM0qmpowDSzgkxSSmmSAnBA0nU/v9vZA4GFmBgaflftywHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` θ ``` Print the input for the first time. ``` W⊖Lθ« ``` Repeat while the length of the input is not 1. ``` ≔IΠθθ ``` Replace the input with its digital product cast to string. ``` ⸿θ ``` Print the input on a new line. ]
[Question] [ The challenge is simple: Write a function or program that takes an input `x`, and outputs the lower case alphabet if `x` is part of the lower case alphabet, outputs the upper case alphabet if `x` is part of the upper case alphabet and outputs just `x` if it's not part of either. Rules: * The input can be function argument or from STDIN * The input will be any of the printable ASCII characters from 32 to 126 (space to tilde). * The input may be inside quotation marks,`'x'` or `"x"`, but remember that `'` and `"` are valid input and should be supported. * The input can be any of the letters in the alphabet, i.e. you can't assume it will be `a` or `A`. * The output should be only one of the alphabets or the single symbol, but trailing newlines are OK. * The letters in the alphabet should not be separated by spaces, commas or anything else. Some examples: ``` F ABCDEFGHIJKLMNOPQRSTUVWXYZ z abcdefghijklmnopqrstuvwxyz " " <- Input: Space <- Output: Space ``` Shortest code in bytes win. --- Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others. --- ## Leaderboard The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Pyth, 10 bytes ``` h/#z[GrG1z ``` [Test suite](https://pyth.herokuapp.com/?code=h%2F%23z%5BGrG1z&test_suite=1&test_suite_input=F%0Az%0A%22%0A+&debug=0) We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. (`[GrG1z`) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (`/#z`) Finally, we take the first element of the filtered list. [Answer] # [TeaScript](https://github.com/vihanb/TeaScript), 5 bytes ``` xN(0) ``` TeaScript has a (almost) built-in for this :D [Try it online](https://vihan.org/p/TeaScript/#?code=%22xN(0)%22&inputs=%5B%22a%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) (note: the online interpreter has been updated to TeaScript v3 so in which this is `N0`) [Try all the test cases](https://vihan.org/p/TeaScript/#?code=%22_m(%23(x%3Dl,%20%20xN(0)%20%20))j%60%5Cn%60%22&inputs=%5B%22A%22,%22b%22,%221%22,%22%20%22,%22%5C%22%22%5D&opts=%7B%22int%22:false,%22ar%22:false,%22debug%22:false,%22chars%22:false,%22html%22:false%7D) --- ### [TeaScript 3](https://github.com/vihanb/TeaScript/tree/master/beta), 2 bytes [non-competing] Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge ``` N0 ``` --- ### 1 byte alternative If we could output `0123456789` for digits, then this could be: ``` ° ``` [Answer] # LabVIEW, 23 [LabVIEW Primitives](http://meta.codegolf.stackexchange.com/a/7589/39490) The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case. The for loop goes 26 times to create an alphabet or once to pass the symbol through. [![](https://i.stack.imgur.com/JJUTz.gif)](https://i.stack.imgur.com/JJUTz.gif) [Answer] ## Haskell, 48 bytes ``` f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0 ``` Usage example: ``` *Main> f 'g' "abcdefghijklmnopqrstuvwxyz" *Main> f 'H' "ABCDEFGHIJKLMNOPQRSTUVWXYZ" *Main> f '\'' "'" ``` Take all lists of ['a'..'z'], ['A'..'Z'] and the singleton list with the input char `c` where `c` is element of. For letters we have always two matches, so we pick the first one. [Answer] # JavaScript (ES6), 79 bytes ``` x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x) ``` ## Explanation JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters. ``` x=>( a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet x>"`"&x<"{"?a: // if x is a lower-case letter, output alphabet x>"@"&x<"["?a.toUpperCase(): // if x is an upper-case letter, output upper-case x // else just output x ) ``` ## Test ``` var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x) ``` ``` X = <input type="text" oninput="result.textContent=solution(this.value)" /> <pre id="result"></pre> ``` [Answer] ## R, ~~90~~ 75 bytes ``` a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="") ``` Thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe). Old version (90 bytes): ``` a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a ``` Looks ugly, but those `cat`s cannot be outsourced to functions, IMHO. [Answer] # Python 3, ~~92~~ ~~84~~ ~~82~~ 74 bytes Current version: 74, thanks to isaacg and wnnmaw! ``` lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()] ``` Ungolfed: (for some definition of ungolfed) ``` lambda c: ( c, ''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)]) ) [c.isalpha()] ``` --- First version: 92 ``` def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c) ``` Second version: 82, thanks to isaacg! :) ``` lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c ``` [Answer] # Python 3, ~~118~~ ~~105~~ ~~98~~ ~~97~~ 83 bytes Simple solution. **EDIT:** Golfed with thanks to Erik the Golfer's suggestion. ``` lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()] ``` Ungolfed: ``` def f(s): a='ABCDEFGHIJKLMNOPQRSTUVWXYZ' if s.isalpha(): if s.islower():return a.lower() else:return a return s ``` [Answer] # PHP, 62 ~~76~~ ~~82~~ bytes PHP is doing OK now: ``` <?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x; ``` Takes an input from command line, like: ``` $ php alphabet.php A $ php alphabet.php "a" $ php alphabet.php " " $ php alphabet.php _ ``` **Edits** * *Saved* **6 bytes** by replacing `91>ord($x)` with `Z<$x`. Thought way to complicated. Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork). * *Saved* **14 bytes** by removing `strtoupper` and building the demanded range directly. [Answer] # Perl, ~~46~~ ~~34~~ 33 bytes *includes +2 for `-nE`* ``` say/[a-z]/?a..z:/[A-Z]/?A..Z:$_ ``` Run as ``` perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_' ``` --- * *update 34* save 12 bytes by omitting `for` and using barewords, thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings). * *update 33* save 1 byte using `-E` and `say` instead of `print`. [Answer] # Ruby, 41 + 1 = 42 With switch `-p`, run ``` ([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&} ``` This generates the string ``` ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz ``` and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work. **Edited to add explanation, by request:** The `-p` flag does essentially ``` while( $_ = STDIN.gets ) #execute code print $_ end ``` `[*?A..?z]` is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. `*''` joins the array into a string, so we can call `.scan` on it. `scan` will find each match of the regular expression `/\w+/`, populate the magic variable `$&` with it, and call the block. Each time the block is iterated, it checks whether the matched string contains `$_` and sets the output to that string if so. So if $\_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged. The ungolfed version would look something like ``` while ($_ = STDIN.gets ) %w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet| $_ = alphabet if alphabet.include?($_) end print $_ end ``` [Answer] # CJam, 18 bytes ``` '[,65>_elr:R]{R&}= ``` `'[,65>` pushes the uppercase alphabet, `_el` the lowercase alphabet, and `r:R` a single-char string that is read from STDIN and assigned to variable `R`. These are wrapped in an array (`]`) and the first one that has any chars in common with `R` is selected using `{R&}=`. [Answer] # Retina, 62 bytes ``` [a-z] abcdefghijklmnopqrstuvwxyz [A-Z] ABCDEFGHIJKLMNOPQRSTUVWXYZ ``` The two short lines are the regex to match. If the input is lowercase (in the range `[a-z]`), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched. [Try it online.](http://retina.tryitonline.net/#code=W2Etel0KYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXoKW0EtWl0KQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVo&input=QQpmCj8) [Answer] ## Python 2.7.10, ~~95~~ ~~93~~ 79 bytes This is my first time even attempting to golf, so please, any help or advice is extremely appreciated! ``` from string import* lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()] ``` Thanks to Morgan Thrapp for the help! [Answer] # Ruby, ~~46~~ 43 characters (42 characters code + 1 character command line option) ``` [?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""} ``` Thanks to: * [Jordan](https://codegolf.stackexchange.com/users/11261/jordan) for the `===` magic (-3 characters) Sample run: ``` bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}' abcdefghijklmnopqrstuvwxyz bash-4.3$ echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}' ABCDEFGHIJKLMNOPQRSTUVWXYZ bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}' @ ``` [Answer] #[MATL](https://esolangs.org/wiki/MATL), 22 bytes ``` jtt1Y2XIm~Iw?km?Ik]]1$ ``` This uses the [current version (3.1.0)](https://github.com/lmendo/MATL/releases/tag/3.1.0) of the language. *EDIT (Sep 15, 2017): Try it at [MATL Online!](https://matl.io/?code=jtt1Y2XIm%7EIw%3Fkm%3FIk%5D%5D1%24&inputs=e&version=20.4.1) (with a newer version of the language).* ###Examples ``` >> matl jtt1Y2XIm~Iw?km?Ik]]1$ > e abcdefghijklmnopqrstuvwxyz >> matl jtt1Y2XIm~Iw?km?Ik]]1$ > T ABCDEFGHIJKLMNOPQRSTUVWXYZ >> matl jtt1Y2XIm~Iw?km?Ik]]1$ > " " ``` ###Explanation ``` j % input string (assumed to be a single character) tt % duplicate twice 1Y2 % predefined literal: uppercase letters XI % copy to clipboard I m~ % check if not member I % paste from clipboard I w % swap elements in stack ? % if k % convert string to lowercase m % check if member ? % if I % paste from clipboard I k % convert string to lowercase ] % end ] % end 1$ % input specification for implicit printing ``` [Answer] ## Perl, 23 bytes Includes +2 for `-nE` (instead of the normal +1) to be fair to the other perl solution Run with the input on STDIN without trailing newline: ``` echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_' ``` Just the code: ``` say/\pL/?a&$_|A..Z:$_ ``` [Answer] # Lua, ~~98~~ 97 bytes Sadly, I didn't find a solution shorter than 26 bytes to set `a` with the alphabet. In fact, I didn't find shorter than 32. **Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p** ``` c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a) ``` You can test it online on the [official site](http://www.lua.org/cgi-bin/demo) or on [ideone](http://ideone.com/). If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function. ``` function f(c) a="abcdefghijklmnopqrstuvwyz" print(not c:find"%a"and c or c:find"%u"and a:upper()or a) end print(f("\"")) print(f("a")) print(f("Q")) ``` [Answer] # Japt, 9 bytes ``` ;[CBU]æøU ``` [Run it online](https://ethproductions.github.io/japt/?v=1.4.6&code=O1tDQlVd5vhV&input=Imgi) [Answer] # C (gcc), 91 bytes A function that accepts a `char` and prints the result via stdout (91 bytes): ``` f(x){puts(isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9No0KzuqC0pFgjszgxpyAjEci3r7CzNLBXSkxKTklNS8/IzMrOyc3LLygsKi4pLSuvqKxSslJydHJ2cXVz9/D08vbx9fMPCAwKDgkNC4@IjFKyUqvQtK79n5uYmaehWZ2ckVikUKFgq5CeWgJia2haK4AsBapIBAA) Bonus (a shorter version of `MD XF`'s answer, since I don't have enough reputation to comment (90 bytes):) ``` #define f(x)isalpha(x)?x>90?"abcdefghijklmnopqrstuvwxyz":"ABCDEFGHIJKLMNOPQRSTUVWXYZ":&x ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU2jQjOzODGnICMRyLKvsLM0sFdKTEoGSqdnZGZl5@Tm5RcUFhWXlJaVV1RWKVkpOTo5u7i6uXt4enn7@Pr5BwQGBYeEhoVHREYpWalV/M9NzMzT0KxOzkgsUqhQsFVITy0BsTU0rRUKSkuKNUAWalrX/k8EAA) [Answer] ## Mathematica, 75 bytes ``` #/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]& ``` Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of `ToCharacterCode` and `FromCharacterCode`. [Answer] # C (function), 71 bytes ``` f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);} ``` [Answer] # Python, 81 bytes ``` f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0] ``` This is basically a translation of the Pyth answer. It defines a function `f` that takes as argument the character and returns the result. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf/), 17 bytes [Try it here.](http://conorobrien-foxx.github.io/Jolf/#code=PyBocExpcGw_IGhwVWlwdWk&input=RgoKegoKIgoKIA) ``` ? hpLipl? hpUipui ? if hpL the lowercase alphabet (array) contains i the input pl return the lowercase alphabet (string) ? else if hpU the uppercase alphabet (array) contains i the input pu return the uppercase alphabet (string) i otherwise, return the input implicit: print the result ``` [Answer] ## Java, 165 characters ``` class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}} ``` Generates the required output to stdout (rather than returning it). Input is via the runtime arguments. How it works. 1) Setup some integer variables c = the ASCII value of the first character of the first parameter of the runtime arguments. d = c converted to lowercase ASCII value (by ORing it with 32) b = calculation to see if d is a letter. Will be <0 if a letter. e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c. f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26 2) Loop from e to e+f outputing each character to stdout. [Answer] ## MATLAB: ~~71~~ 68 bytes ``` i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),''] ``` (thanks to OP for saving 3 bytes) Test: ``` i='a' ans= abcdefghijklmnopqrstuvwxyz i='A' ans= ABCDEFGHIJKLMNOPQRSTUVWXYZ i='~' ans= ~ ``` Explanation: Uppercase alphabet occupies `65:90` ASCII characters. Lowercase alphabet is at `97:122` ASCII. So, `b=i<65|i>122|(i>90&i<97)` checks whether the input character `i` is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if `b==1` and `i<97` (uppercase character). If `b==1` and `i>96`, 32 is added to `65:90` that corresponds to `97:122` - the lowercase alphabet. [Answer] # SpecBAS, 111 bytes I've been through several versions of this, 111 seems to be the best I can manage. ``` 1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz" 2 ?IIF$(l$ IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l$) ``` Line 2 uses the `?` shortcut for `PRINT` and nested inline `IF` statements Pseudo code explanation ``` IF character IN "a".."z","A".."Z" THEN IF character = UPPERCASE character THEN print UPPERCASE alphabet ELSE print alphabet ENDIF ELSE print the character ENDIF ``` [Answer] # Swift 2, 142 Bytes ``` func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s} ``` ### Ungolfed ``` func d(s: String) -> String{ let a="abcdefghijklmnopqrstuvwxyz" for v in s.utf8{ return ( v > 64 && v < 91 ? a.uppercaseString : ( v > 96 && v < 123 ? a : s ) ) } return s } ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~19~~ 16 bytes -3 bytes thanks to `else` ``` DAsåiAëDAusåiAuë ``` How it works ``` # implicit input D # duplicate A # push lowercase alphabet s # swap last two elements å # push a in b i # if A # lowercase alphabet ë # else D # duplicate Au # uppercase alphabet s # swap last two elements å # push a in b I # if Au # uppercase alphabet ë # else leave input # implicit print ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fxbH48NJMx8OrXRxLwazSw6v//08EAA "05AB1E – Try It Online") [Answer] ## Java SE 8, ~~71~~ 69 bytes Golfed: ``` (a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a<b)s+=a++;return s;} ``` Ungolfed: ``` (a,s)->{ // String as a parameter. If declaration is necessary it adds 8 bytes char b = 97; // Uppercase A char, this is important if (a < 91) // If it is not past 'z', where a is a char param b -= 32; // Then go back to the lowercase alphabet a = b; // Done to prevent a cast b += 26; // End of alphabet while (a < b) // Go to end of alphabet s += a++; // Append character return s;} // Then return ``` I had originally implemented the following ``` String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s; ``` It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post. edit: 2 bytes saved by Stewie Griffin by changing ``` a - 91 < 0 to a < 91 ``` ]
[Question] [ This is my first golf contest. **What you need to do** Build me, in the shortest amount of bytes possible, my AC remote control system. My room is too cold right now, and I'm missing my remote. Now, I don't want you literally building it or anything, just golf this: A slow increment of temperature, starting at 40 degrees, and ending at exactly 72. The increment time must always be 500 millis per increment. It can wait another 500ms at the end. I would prefer it to stop however. The increment itself must go up by two each time, like my remote. You should not clear the screen. You should have newlines. **What should happen** Example output (everything in parentheses shouldn't be outputted). ``` 40 (wait 500 millis) 42 (wait 500 millis) 44 (..repeat until 72..) 72 (stop or wait 500ms) ``` **Keep in mind** This is my first golf, so I apologize if this is too hard to golf. :( Best of luck, golfers! [Answer] # Minecraft 1.9.0+, ~~204~~ 162 bytes + ~~58~~ ~~36~~ ~~28~~ ~~24~~ 20 blocks = ~~262~~ ~~240~~ ~~232~~ ~~186~~ 182 blytes This solution is golfed down, and it can't be seen whole in one, or even two screenshots. Uses two glitches and abuses another two features of the game [![RUN! MINECRAFT WILL KILL YOU!](https://i.stack.imgur.com/kPgVk.jpg)](https://i.stack.imgur.com/kPgVk.jpg) This solution uses the same principles as the one below, just a 4 blocks more compact design. * Abuses the fact that Chain command blocks (green blocks) can't be powered by redstone, only by a singal from a impulse command block (orange). * Abuses the fact pistons take 0.30 seconds to extend completely, and redstone needs only 0.10s to register a signal. * Also abuses a twofold glitch to set the timer (TNT) off: the redstone next to the timer (TNT) gets not only powered, but also thinks the TNT is another redstone and powers it. * On top of all these abuses, the signal shortener (thing under the TNT) is one-use, after it gets powered it changes shape, allowing to pass signal *through* it to the "incrementer" (topmost orange block) A bit of explanation on the functionality of it's different parts can be seen in older solutions (but best in the one just below). You can also **Try it Offline!** (simplified solution incrementing by 4, works only in 1.11+) **by running [this command](http://pastebin.com/L8R5j3TL) in a command block**. --- ### Old solution, Minecraft 1.9.0+, 186 blytes: [![MINECRAFT ABUSE](https://i.stack.imgur.com/XCwBQ.png)](https://i.stack.imgur.com/XCwBQ.png) Since TNT normally explode after 3.0s in Minecraft, this one has to be placed by a command (`/setblock`) with a specified fuse. Also uses a more compact design to remove redundant command block (containing 42 bytes) and redstone against the older versions. I'm sure this can't get any lower... ### Older solution, Minecraft 1.9.0+, 232 blytes: Oops, I found out these older solutions increment by 4... [![golfcraft](https://i.stack.imgur.com/DcLTx.png)](https://i.stack.imgur.com/DcLTx.png) Uses the 1.9 command block chain feature (green block thing) to save blocks. Also uses a more compact signal shortener then in the older solutions ### Even older solution, Minecraft 1.7.0+, 240 blytes: [![the soulless monster](https://i.stack.imgur.com/rU2DN.jpg)](https://i.stack.imgur.com/rU2DN.jpg) Uses a more compact timer (TNT) then the first solution (below). ### Oldest solution, Minecraft 1.7.0+, 262 blytes: [![the old monster](https://i.stack.imgur.com/CQRMd.png)](https://i.stack.imgur.com/CQRMd.png) --- This is so long because of the way Minecraft handles variables: * To define a variable (int): `scoreboard objectives add <variable> dummy` * To set a value to a variable (each entity including players has it's own variable value): `scoreboard players set <entity> <variable> <value>` + `*` can be used as `<entity>` to select all entities and save bytes. + only defined variables may be used + the value of the variable must be set to a number, not a variable * To increment var1 by var2: `scoreboard players operation <entity> var1 += <entity> var2` + `<entity>` must be a single entity, eg. `@p`, not `*` --- Screenshots are of my own, dual licenced under [WTFPL](http://www.wtfpl.net/) and what licence SE decides to use today (currently `cc by-sa 3.0 with attribution required`) :-) [Answer] # Bash + linux utilities, 19 ``` seq 40 2 72|pv -qlL2 ``` `seq` generates the numerical output. `pv` ratelimits it to 2 lines/sec. [Answer] # Vim, ~~24~~, 23 bytes/keystrokes ``` i40<esc>qq:sl500m Yp2<C-a>q15@q ``` *One byte saved thanks to @Kritixi Lithos!* Written from my phone, tested in mobile vim (which is apparently a real thing). Here's a gif of it running: [![enter image description here](https://i.stack.imgur.com/yJJYh.gif)](https://i.stack.imgur.com/yJJYh.gif) And here is a command-by-command explanation: ``` i40<esc> " Insert '40' into the buffer qq " Start recording into register 'q' :sl500m " Sleep form 500 ms Y " Yank this line p " and paste it on a newline 2<C-a> " Increment this line twice q " Stop recording 15@q " Callback register 'q' 15 times ``` [Answer] # JavaScript (ES6), 52 bytes ``` f=(i=40)=>console.log(i)|i-72&&setTimeout(f,500,i+2) f() ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ 12 bytes ``` 40µṄœS.+2µ⁴¡ ``` [Try it online!](https://tio.run/nexus/bash#088vKNHPSs3JqYSQCqmleQrq/00MDm19uLPl6ORgPW2jQ1sfNW45tPC/ukKNQnlGZk6qQlFqYoq1Qko@F2dBUWZeSZqCumqxFQgZmOgZpsWUqBbH5KkrqGikJJakKqhrq3ooqPoqqAbrqfqpayqoBLkG@ERypeTnpf4HAA "Bash – TIO Nexus") The Jelly program is wrapped in a Bash script to prefix each line of output by a timestamp. ### How it works ``` 40µṄœS.+2µ⁴¡ Main link. No arguments. 40 Set the return value to 40. µ µ⁴¡ Execute the chain between the two µ 16 times. Ṅ Print the return value, followed by a linefeed. . Yield 0.5. œS Sleep for 0.5 seconds. Yield the previous result. +2 Add 2. ``` After the last iteration, the final value of **72** is printed implicitly and the program exits. [Answer] # [Perl 6](http://perl6.org/), 30 bytes ``` for 20..36 {sleep .5;say 2*$_} ``` Sorry that it looks like un-golfed code, I don't see a way to make it shorter... The version that stops right after the last number, would be 37 bytes: ``` for 20..36 {sleep .5 if $++;say 2*$_} ``` [Answer] # Pyth - 12 bytes Very simple, uses a for loop from 0-17. ``` V17+40yN.d.5 ``` [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 20 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` {⎕DL.5⊣⎕←⍵}¨38+2×⍳17 ``` `{` the anonymous function  `⎕DL` delay...  `.5⊣` half (a second) rather than the value of  `⎕←` print (with newline)  `⍵` the argument `}¨` applied to each of `38+` thirty eight plus `2×` twice `⍳17` the integers from 1 to 17 [Answer] # TI-Basic (CE or CSE only), 16 bytes ``` :For(A,40,72 :Pause A,.5 :End ``` Note that many commands are single byte tokens. [Answer] # C compiled with Clang 3.8.1 on Linux, ~~62~~ ~~59~~ 58 bytes *2 bytes saved thanks to @ranisalt* ``` s=38;main(){for(;s<74;printf("%d\n",s+=2))usleep(500000);} ``` **59 bytes** ``` s=38;main(){for(;s<73;printf("%d\n",s+=2+usleep(500000)));} ``` **62 Bytes** ``` s=38;main(){for(;s!=72;){printf("%d\n",s+=2);usleep(500000);}} s=38 # Initializes a global (int) variable, this is only possible in C, in other languages from the C family variables must have an explicit type. main() # Is the main entry point, again as before, in case a type isn't specified C defaults to int printf("%d\n",s+=2) # printf outputs to stdout based on the pattern defined in the first parameter # %d is a placeholder for an int variable # \n appends a newline to stdout # The second parameter increments the s variable and afterwards it goes in the placeholder's spot. usleep(500000) # This function is Linux specific, it takes an int as parameter, it represents how much time the app needs to sleep in microseconds ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 14 bytes ``` 17:E38+".5Y.@D ``` Try it in [MATL Online!](https://matl.io/?code=17%3AE38%2B%22.5Y.%40D&inputs=&version=19.7.0) You may need to reload the page if it doesn't initially work. ### Explanation ``` 17: % Push array [1 2 ... 17] E % Multiply by 2, element-wise 38+ % Add 38, element-wise. This gives [40 42 ... 72] " % For each k in that array .5Y. % Pause 0.5 seconds @D % Push k and display % End (implicit) ``` --- ## Old version (before spec change), clearing the screen ``` 17:E38+"5&Xx@D ``` Try it in [MATL Online!](https://matl.io/?code=17%3AE38%2B%225%26Xx%40D&inputs=&version=19.7.0) [Answer] # Mathematica, 34 bytes ``` Pause[Print@#;.5]&/@Range[40,72,2] ``` Full program. Takes no input and outputs to STDOUT. [Answer] ## R, 49 bytes ``` x=38;while(x<72){Sys.sleep(.5);x=x+2;cat(x,"\n")} ``` Very trivial solution but it does the trick. [Answer] # [Perl 6](http://perl6.org), 27 bytes ``` sleep .say/2 for 40,42...72 ``` `say` returns `True`, which is coerced to a numeric `1` when divided by `2`. Unicode shenanigans can get it down to 23 characters: ``` sleep .say/2 for ㊵,㊷…72 ``` But that's 29 UTF-8-encoded bytes. [Answer] # Python 2, ~~57 56~~ 55 Bytes ``` import time a=40 while a<73:print a;time.sleep(.5);a+=2 ``` EDIT: -1 Byte thanks to Mega Man -1 Byte thanks to Flp.Tkc [Answer] ## Ruby, 33 bytes ``` (40).step(72,2){|n|p n;sleep 0.5} ``` [Answer] # C#, 95 bytes ``` ()=>{for(int i=40;i<73;i+=2){System.Console.WriteLine(i);System.Threading.Thread.Sleep(500);}}; ``` It is a simple for loop, it waits an extra 500ms at the end. [Answer] ## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), 21 bytes ``` [44,72,4|?a┘'sleep 1. ``` QBIC starts a FOR-loop, running from 44 to 72 and incrementing the counter by 4 on every loop. It then sleeps for 1 second. QBasic doesn't have a more finegrained control foor `sleep`, so I've added a `.` to simulate giving `.5` as an argument. [Answer] # Kotlin, 47 bytes I guess it was not said in the problem statement that solutions should actually contain increment by two, so the `40+2*i` is legal here. If written as a regular Kotlin source with `main`: ``` fun main(args:Array<String>){(0..16).map{println(40+2*it);Thread.sleep(500)}} ``` (77 bytes) **UPD**: In Kotlin 1.3, `args:Array<String>` can be removed, so it's 18 bytes less. And in Kotlin Script, the whole program would be ``` (0..16).map{println(40+2*it);Thread.sleep(500)} ``` (47 bytes) [Answer] # Ruby 31 bytes ``` 20.upto(36){|n|p n*2 sleep 0.5} ``` [Try it online!](https://tio.run/##FczBCsIgAAbgcz7Ff5i4FYlt1aHOQYeKqFOwi0PHBsOJOiKyZ7eC7/w10nfJTc0LSw2WSsEnG8a82hbvaKKFmZfED1pbCL75JIaIZ9cPGk5LtYcaycy63oQWjPrdn1jzVVsH6mvDkOVKhl@8oEfQM@id0wsrkN0O19ODqNHo9AU "Bash – TIO Nexus") [Answer] ## Haskell, 67 bytes ``` import System.Posix.Unistd mapM((>>usleep 500000).print)[40,42..70] ``` If you want to go with ghc only, you can save a few bytes by importing `GHC.Conc` and using `threadDelay` instead of `usleep`. [Answer] # php, 38 bytes ``` for(;35>$t+=2;usleep(5e5))echo$t+38,_; ``` uses underscore as delimiter. Run with `-nr`. [Answer] ## Clojure, 54 bytes ``` (doseq[t(range 32 73 2)](println t)(Thread/sleep 500)) ``` Third lisp ftw. Just iterates over the range, printing and sleeping each iteration. Sleeps at the end. Ungolfed: ``` (doseq [t (range 32 73 2)] (println t) (Thread/sleep 500))) ``` ## A version that doesn't sleep at the end, 66 bytes ``` (doseq[t(range 32 73 2)](println t)(if(< t 72)(Thread/sleep 500))) ``` Note, these are full programs since the instructions don't specify. Add a byte to each if a function is required. [Answer] ## Racket 46 bytes ``` (for((i(range 40 73 2)))(println i)(sleep .5)) ``` Ungolfed: ``` (define (f) (for ((i (range 40 73 2))) (println i) (sleep .5))) ``` Command to run: `(f)` [Answer] # Octave, ~~38~~ 35 bytes *Saved 3 bytes thanks to @LuisMendo by changing `endfor` to `end`* ``` for i=20:36;disp(2*i);sleep(.5);end ``` [Try it online!](https://octave-online.net/#cmd=for%20i%3D20%3A36%3Bdisp(2*i)%3Bsleep(.5)%3Bend) I am new to Octave, so this solution still might be golfed further. Any tips are welcome! ### Ungolfed ``` for i=20:36 disp(2*i) sleep(.5) end ``` [Answer] # Python 2, ~~57~~ 58 Bytes **Edit** Counted as 57 bytes on my handy but TIO says 58 now that I'm back on my own machine so that's my final offer. Interestingly enough TIO doesn't seem to respect the timeout and just waits and then prints out the whole list in one go. Works on QPython for Android and Python 2 on my Ubuntu box so that's good enough for me. ``` import time for x in range(40,74,2):print x;time.sleep(.5) ``` [Try it online!](https://tio.run/nexus/python2#@5@ZW5BfVKJQkpmbypWWX6RQoZCZp1CUmJeeqmFioGNuomOkaVVQlJlXolBhDVKkV5yTmlqgoWeq@f8/AA "Python 2 – TIO Nexus") Would be ~~58~~ 59 in Python 3 so doesn't beat @sonrad10 anyway. [Answer] # R, ~~44~~ 42 bytes Straightforward for-loop, there's likely a golfier way. (Also, crossed-out 44 is still regular 44...) ``` for(i in 20:36*2)cat(i,"\n",Sys.sleep(.5)) ``` [Answer] # F#, 60 bytes `async{for i in 40..2..72 do printfn"%d"i;do!Async.Sleep 500}` This is an async expression, in order to run it pass it into `Async.Start` or `Async.RunSynchronously`. [Answer] # [Noodel](https://tkellehe.github.io/noodel/), noncompeting 10 bytes Cannot compete because *Noodel* was born after the challenge was created:( ``` 40Ḷ16ñ++ḍh ``` [Try it:)](https://tkellehe.github.io/noodel/editor.html?code=40%E1%B8%B616%C3%B1%2B%2B%E1%B8%8Dh&input=&run=true) ### How it works ``` 40 # Creates the literal number 40 and places it into the pipe. Ḷ16 # Loop the following code 16 times. ñ # Print what is in the front of the pipe with a new line. ++ # Increment what is in the pipe by two. ḍh # Delay for a half a second (500ms). ``` --- There is not a version of *Noodel* that supports the syntax used in this answer. Here is a version that is correct: ``` kȥḶ16ñ⁺2ḍh ``` ``` <div id="noodel" code="kȥḶ16ñ⁺2ḍh" input="" cols="10" rows="17"></div> <script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script> <script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script> ``` [Answer] # Windows Batch - ~~65 62~~ 61 bytes *btw this is my first PPCG answer* ``` @for /l %%p in (40,2,72)do @echo %%p&@ping 1.1 -n 1 -w 10>nul ``` This exits when the degree reaches 72. --- # ~~76~~ 75 bytes - Does not sleep at end ``` @for /l %%p in (40,2,72)do @echo %%p&if %%p lss 72 @ping 1.1 -n 1 -w 10>nul ``` --- ]
[Question] [ Given an input string S, return `truthy` if all the letters in S are Lexically Ordered: their ASCII values need to be in either ascending or descending order. Return `falsy` in other cases. ## Input * Input will be in the same case (all upper- or all lowercase). Your submission should be able to handle both. * Input will consist of ASCII in the range `[A-Za-z]` only * Input length will be at least 1, up to whatever maximum your language supports. * Input is a string - not a list of characters, not an array of ASCII-codepoints. ## Output * Output should be `true` or `false`, or `0/1`, or any other distinct `true / false` style output your language can provide. * All true cases need to have the same output, as well as all the false cases. No "False is 0, true is 1, 2, or 3". ## Additional rules * [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden * Answer must be a full program or a function, not a snippet or a REPL-entry. * [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins. ## Test cases **Truthy** ``` "ABCDEF" "ZYX" "no" "tree" --> the multiple 'e's don't break the order "q" ``` **Falsy** ``` "ABCDC" "yes" "deed" ``` **Invalid** ``` "Hello" --> invalid input - mixed case-, does not have to be handled "" --> invalid input - length 0-, does not have to be handled "\n " --> invalid input - newline is not in range [A-Za-z]-, does not have to be handled ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~53~~ ~~44~~ ~~40~~ 39 bytes ``` lambda a:`sorted(a)`[2::5]in(a,a[::-1]) ``` [Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQaJVQnF9UkpqikaiZEG1kZWUam5mnkaiTGG1lpWsYq/k/Lb9IIVMhMw@ICkpLNDStuBQKijLzShQyddQVdO0U1HXSNDI1/0crOTo5u7i6KekoRUVGAMm8fCBRUpSaCqQKgRgk7QykK1OLlWK5AA "Python 2 – TIO Nexus\"/ZgIyGm9eSaOZk25@MkQogyyNDjXbkesIWVg4CiZP8Wga2DOHAuw1dDuQdtgGOugDsfu1J@VVbfrRRiToGTvRYv0f3fir1/V2PwA \"Python 2 – TIO Nexus") [Answer] # [Haskell](https://www.haskell.org/), 33 bytes ``` (%)=scanl1 f s=s==max%s||s==min%s ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/X0NV07Y4OTEvx5ArTaHYttjWNjexQrW4pgbEysxTLf6fYxut5Ojk7OLqpqSjFBUZASTz8oFESVFqKpAqBGKQtDOQrkwtBpIpqakpSrFcuYmZeQq2CrmJBb4KBUWZeSUKKiCOQppCzn8A "Haskell – Try It Online") *Thanks to Ørjan Johansen for 1 byte with aliasing `scanl1` infix.* Haskell is an interesting language to golf sorting-based challenges because it does not have a built-in sort, barring a lengthy `import Data.List`. This encourages finding a way to do the task by hand without explicitly sorting. The code uses `scanl1`, which folds an operation over the list from left to right, keeping track of the intermediate results. So, `scanl1 max` has the effect of listing the cumulative maxima of the list, i.e. the maxima of progressively longer prefixes. For example, `scanl1 max [3,1,2,5,4] == [3,3,3,5,5]`. The same with `min` checks whether the list is decreasing. The code checks the two cases and combines them with `||`. Compare to other expressions: ``` (%)=scanl1;f s=s==max%s||s==min%s f s=or[s==scanl1 q s|q<-[min,max]] f s=s==scanl1 max s||s==scanl1 min s f s=any(\q->scanl1 q s==s)[min,max] f s=any((==s).(`scanl1`s))[min,max] f s=elem s$(`scanl1`s)<$>[min,max] ``` [Answer] # [Perl 6](http://perl6.org/), 25 bytes ``` {[le] .comb or[ge] .comb} ``` ### How it works: * `.comb` splits the input into a sequence of characters. * `le` and `ge` are the *"less or equal"* and *"greater or equal"* string comparison operators. * `[ ]` around an infix operator, reduces ("folds") the argument list with that operator. (It's smart enough to return True if the input has only zero or one characters.) * `or` returns True if the expressions on either side of it is true. [Answer] # JavaScript (ES6), 43 bytes ``` ([...s],q=s+"")=>q==s.sort()|q==s.reverse() ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes ``` Â)¤{å ``` [Try it online!](https://tio.run/nexus/05ab1e#@3@4SfPQkurDS///ryxOBQA "05AB1E – TIO Nexus") **Explanation** ``` Â) # pair the input with it's reverse in a list ¤{ # get a copy of the reverse and sort it å # check if the sorted copy is in the list of [input,reverse_input] ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 7 bytes ``` dZSuz2< ``` [Try it online!](https://tio.run/nexus/matl#@58SFVxaZWTz/7@6o5Ozi6ubOgA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#S/ifEhVcWmVk898l5L@6o5Ozi6ubOpd6VGQEkMzLBxIlRampQKoQiEHSzkC6MrUYSKakpqaoAwA). ``` d % Implicitly input string. Push array of consecutive differences of code points ZS % Sign. Transforms each entry into 1, 0 or -1 u % Unique z % Number of nonzeros 2< % Is it less than 2? Implicit display ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 5 bytes ``` Ṣm0ẇ@ ``` [Try it online!](https://tio.run/nexus/jelly#@/9w56Jcg4e72h3@H91zuP1R0xpvII78/1/d0cnZxdVNXUdBPSoyAkTl5YPIkqLUVBBdCCJAapxBjMrUYhDl4urqog4A) Originally was `Ṣm0w` at four bytes. ## Explanation ``` Ṣm0ẇ@ Input: string S Ṣ Sort S m0 Concatenate sort(S) with reverse(sort(S)) ẇ@ Sublist exists? Check if S is contained in the previous result ``` [Answer] ## Clojure, 47 bytes ``` #(let[c(map int %)a apply](or(a <= c)(a >= c))) ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 70 bytes ``` o(s,a)char*s;{for(a=0;s[1];s++)a|=s[1]-*s&64|*s-s[1]&32;return a!=96;} ``` I was hoping to find a shorter solution based on a recursive function, but it didn't work out due to the output requirement. So here's an imperative approach. At least, C's operator precedence works nicely for the inner loop statement. [Try it online!](https://tio.run/nexus/c-gcc#VY7LCsIwEEX3/YoxoiS1ii8EjRV8foPPRWwiFjTVTFyI@u21UURyV3PPzJ2ZPKMYCZYchQmRPw6ZoSJucty0dhxrNSaesavrIVZ73WeIdeeqnTY3yt6MBlGK@z3@ysupTk43qWCIVqZZ4zgKglRbsAotULceQmTwCKDQxRStAyUVHEBFbjWJACMoPmGMB69v8CxSTX8Bt4WS8WQ6my9IMfNn69XSBzrzvTVK@USIfeKTq2/dnamP7gp9IJWTJJ@H8zc "C (gcc) – TIO Nexus") [Answer] # R, 48 ~~50~~ ~~61~~ bytes As an unnamed function ``` function(s)sd(range(sign(diff(utf8ToInt(s)))))<1 ``` Thanks to @guiseppe for a few extra bytes. `charToRaw` takes `s` and splits into a raw vector. This is converted to integers and a `diff` applied. `sign` makes the diffs a single unit. `range` reduces the vector to it's minimum and maximum. Then if the standard deviation `sd` is less than 1 it is TRUE [Try it online!](https://tio.run/##Pck9DoAgDIbh3YtQRjcHPYC7F@CnJSwloeX8FUPiNz353m50GQ1OWhuDeMnQAxcEqYUhVyIYSsfTbtaZv527EThFUee3qRDTQophISP2pY6Y/2/KXg "R – Try It Online") [Answer] # MATL, 8 bytes ``` tPvGSXma ``` [**Try it Online!**](https://tio.run/nexus/matl#@18SUOYeHJGb@P@/uqOTi7OLOgA) **Explanation** ``` % Implicitly grab the input as a string tP % Create a copy that is reversed v % Vertically concatenate these GS % Grab the input again and sort it Xm % Check if each row of the normal and reversed matrix is equal to the sorted one a % Check if either row matched % Implicitly display the result ``` [Answer] ## Mathematica, 33 bytes ``` 0<=##||##>=0&@@ToCharacterCode@#& ``` Based on [this tip](https://codegolf.stackexchange.com/a/47929/8478). Unfortunately, I have to use `ToCharacterCode` instead of `Characters`, because `<=` and `>=` don't compare strings. [Answer] # [PowerShell](https://github.com/PowerShell/PowerShell), 61 bytes ``` param($a)$a-in-join(($b=[char[]]$a)|sort),-join($b|sort -des) ``` [Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSqKmSqJuZp5uVn5mnoaGSZBudnJFYFB0bC5SpKc4vKtHUgcipJIG5CropqcWa////r0wtBgA "PowerShell – TIO Nexus") Takes input `$a`, then checks whether it's `-in` a two-element array. The array is formed by taking `$a`, casting it as a `char`-array, storing that in `$b` for later, piping it to `sort-object` which sorts lexically. The other element is `$b` sorted in `-des`cending order. [Answer] # Bash + coreutils, 59 bytes ``` f()(sed 's/\(.\)/\1\ /g'<<<$s|grep .|sort -c$1) s=$1 f||f r ``` The input string is passed as an argument. The output is returned in the exit code (0 for truthy, 1 for falsy, as usual), as allowed by [PPCG I/O methods](http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5330#5330). [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes I've tried to find a 4 bytes solution without success, so for now here's the most interesting 5 bytes solution I've found: ``` :No₎? ``` [Try it online!](https://tio.run/nexus/brachylog2#@2/ll/@oqc/@/3@l1JTkpEQlAA "Brachylog – TIO Nexus") `o`, the ordering function, can take a parameter: `0` means ascending order, `1` means descending order. We set that parameter to an unbound variable `N`. Brachylog will try different values for `N` (only `0` or `1` are possible), try to unify the result with the input, and return whether any of those tries succeeded. [Answer] # [Perl](https://www.perl.org/), 35 bytes *Saved 4 bytes thanks to [@Xcali](https://codegolf.stackexchange.com/users/72767/xcali) directly, and 4 more indirectly.* 31 bytes of code + `-pF` flag. ``` @b=reverse@a=sort@F;$_=/@a|@b/x ``` [Try it online!](https://tio.run/##K0gtyjH9/98hybYotSy1qDjVIdG2OL@oxMHNWiXeVt8hscYhSb/iv7WCSryCtq2CwX9HJ2cXVzeuqMgIrrx8rpKi1FSuQi6QoDNXZWoxV0pqasq//IKSzPy84v@6vqZ6BoYG/3VzCtwA "Perl – TIO Nexus") The code sorts the input, and checks if the inputs matches itself sorted (or in reverse order). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,Ue@Ṣ ``` **[Try it online!](https://tio.run/nexus/jelly#@68TmurwcOei////lxSlpgIA "Jelly – TIO Nexus")** # How? ``` ,Ue@Ṣ - Main link: string , - pair string with U - reverse(string) Ṣ - sorted(string) e@ - exists in with reversed arguments ``` [Answer] ## Haskell, ~~54~~ 50 bytes ``` t a=or[and(zipWith(<=)`f`tail$a)|f<-[(=<<),(<*>)]] ``` Usage example: `t "defggh"` -> `True`. [Try it online!](https://tio.run/nexus/haskell#BcFBCoAgEADAryziQaN@sPaNDiK4YOpCmcieor/bzBQg9wxPLZmX@8FSDTobcxTiS5P9Mm7eOES7Glx2G8K8iRs46IObgAYBlc5cSlUwfw "Haskell – TIO Nexus"). Maybe using `sort` like may other answers is shorter although it requires `import Data.List`. Here's a different approach: For every function `f` from `[(=<<),(<*>)]`, calculate `and(zipWith(<=)`f`tail$a)` and require any of the results to be `True`. The functions are ``` ((=<<) (zipWith(<=)) tail) a ((<*>) (zipWith(<=)) tail) a ``` which both perform comparisons of neighbor elements of the input list `a` with `<=`, but one with the arguments flipped resulting in a `>=`. `and` checks if all comparisons are `True`. [Answer] # PHP, 66 bytes ``` $a=$s=$r=str_split($argv[1]);sort($s);rsort($r);echo$s==$a|$r==$a; ``` takes input from command line argument. Run with `-r`. [Answer] # [Ruby](https://www.ruby-lang.org/), 44 bytes ``` ->s{[s,s.reverse].include?s.chars.sort.join} ``` [Try it online!](https://tio.run/nexus/ruby#lYxBCsIwFET3nuKTdf03UNGqZ1BLFiUZ2ookmp8K0nr2yF@4FjfzGHgzZbmWqZFKOOGJJLA8BHcbPTbCrm@TsMSU@RqH8C7d6h990Zjtrt4fjqYiczmfFCFq5gQoH8YyWtfTRHOG5JnuYxbqGi2Wvg@1ui@IwgP@x6qUDw "Ruby – TIO Nexus") [Answer] # [Racket](https://racket-lang.org/), 93 bytes ``` (define(f s)(let([t(string->list s)])(or(equal?(sort t char<=?)t)(equal?(sort t char>=?)t)))) ``` [Try it online!](https://tio.run/nexus/racket#bYxNDoJADEb3nKIZN@3CGyhEUc/gT1xMoIPEcZCZsvD02JAYg7GL16Rfv7fwNjQQbXVnGbFm1wZGB4nQs@BFMElsQ7PMfZtEz1fCLiL3g/UFpi4KCFQ3G1frgoT@BPkU6HzsIJxkKXFgwElqNttytz8YMOfTURk6hURmXb0hyvBhn@C@PcqymctZn2ayUpsvTsqauf5VTO80vgE "Racket – TIO Nexus") Ungolfed: ``` (define (lex-sorted? string) (let ([char-list (string->list string)]) (or (equal? (sort char-list char<=?) char-list) (equal? (sort char-list char>=?) char-list)))) ``` Using the sort then compare to original approach [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes ``` {t:!#x;(t~<x)|t~>x} ``` [Try it online!](https://ngn.codeberg.page/k#eJxLs6ousVJUrrDWKKmzqdCsKamzq6jl4tJXCCkqLcmo5EqLVnJ0cnZxdVOKBbEjIqMgjKjICAgjLx9ClxSlpgJZQJ1uiTnFqXCdzhDpytRiCCMlNTVFKRYAT8Yi2w==) A little bit lengthy. I have considered using inline assignment, but it seems to be on the same length as this one. Returns `0` for false and `1` for true. Explanations: ``` {t:!#x;(t~<x)|t~>x} Main function. Takes x as input t: Assign variable t to ! Range between 0 to #x; Length of x (exclusive) ( <x) Ascended version of x ~ Matches (deep equal) t Variable t | Or >x Descended version of x ~ Matches t Variable t ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` r,sṠƇ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWK4p0ih_uXHCsfUlxUnIxVHDBkpKi1FQIGwA) #### Explanation ``` r,sṠƇ # Implicit input r, # Pair the input with its reverse sṠ # Sort the input Ƈ # Is this in the list? # Implicit output ``` [Answer] # [J-uby](https://github.com/cyoce/J-uby), 28 bytes ``` (:>>+(A|:==%:sort)&:any?)%:~ ``` This is equivalent to the below Ruby code, with `A` equivalent to `chars` and `:~` equivalent to `reverse`: ``` ->s{[s,s.reverse].any?{_1.chars==_1.chars.sort} ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700K740qXLBIjfbpaUlaboWezSs7Oy0NRxrrGxtVa2K84tKNNWsEvMq7TVVreogSm6qFSi4RSs5Ojm7uCrFcoE5rs4uTo4wTkVlVVWlUixE9YIFEBoA) [Answer] # [Arturo](https://arturo-lang.io), 39 bytes ``` $->s[some?@[reverse<=split s]=>sorted?] ``` [Try it!](http://arturo-lang.io/playground?MUX9rS) ``` $->s[ ; a function taking an argument s some?@[...]=>sorted? ; is at least one item in the list [...] sorted? split s ; convert s from string to block of length-1 strings <= ; duplicate reverse ; reverse; both stack items get trapped in the list ] ; end function ``` [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata) + `-e`, 4 bytes ``` oᶜ↔= ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFNtJJurpKOgpJuqlLsgqWlJWm6FivyH26b86htiu2S4qTkYqjggpvGSo5Ozi6ubkpcSlGREUAyLx9IlBSlpgKpQiAGSTsD6crUYiCZkpqaogTRCwA) ``` o Sort ᶜ↔ Optionally reverse = Check equality ``` [Answer] # MATLAB / Octave, 38 bytes ``` @(x)any(all([x;flip(x)]'==sort(x)',1)) ``` [Online demo](http://ideone.com/613pjC) [Answer] # JavaScript (ES6) ~~74~~ ~~62~~ ~~50~~ ~~47~~ 43 bytes ``` ([...a],b=a+'')=>b==a.sort()|b==a.reverse() ``` After some golfing and bugfixing, this answer ended up being pretty much the same as ETHProduction's, so please check his answer out and give it a `+1`. [Answer] # [Pushy](https://github.com/FTcode/Pushy), 7 bytes ``` ogoGo|# ``` [**Try it online!**](https://tio.run/nexus/pushy#@5@fnu@eX6P8//9/pZKi1FQlAA) Explanation: ``` \ Implicit: Input on stack as charcodes og \ Check if the stack is sorted ascendingly (Push 0/1) oG \ Check if the stack is sorted descendingly (Push 0/1) \ - Note that this will work regardless of the first check, as input \ is guaranteed to be /[A-Za-z]+/ o| \ Bitwise OR # \ Print the result ``` [Answer] # Pyth, 5 bytes ``` }Q_BS ``` A program that takes input of a `"quoted string"` and prints `True` or `False` as appropriate. [Test suite](http://pyth.herokuapp.com/?code=%7DQ_BS&test_suite=1&test_suite_input=%22ABCDEF%22%0A%22ZYX%22%0A%22no%22%0A%22tree%22%0A%22q%22%0A%22ABCDC%22%0A%22yes%22%0A%22deed%22&debug=0) **How it works** ``` }Q_BS Program. Input: Q }Q_BSQ Implicit variable fill Q Is Q } in SQ Q sorted B or _ Q sorted reversed? Implicitly print ``` ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win. Closed 7 years ago. [Improve this question](/posts/26388/edit) You are developing some code to generate ID numbers. Policy requires that no ID numbers include the digit sequence *666*. Create a function (or your language's equivalent) which takes a positive integer parameter and returns the next integer that does not include *666* when that integer is expressed in decimal. (60606 is fine, 66600 is not.) Your code must not use a loop that adds one until it finds a result that fits the rules. ``` f(1) returns 2. f(665) returns 667. f(665999999) returns 667000000 without having looped a million times. (Following examples added since the question was first posed.) f(666666666) also returns 667000000. f(66600) returns 66700. f(456667) returns 456670. ``` UPDATE: Replacing 666 with 667 won't work if there's more than one 666 in the input. [Answer] # Python, no string manipulation ``` def f(n): n += 1 p = 1 m = n while m: if m % 1000 == 666: n += p - n % p p *= 10 m /= 10 return n ``` Works by finding powers of 10, `p`, where 666 appears, and adding `p - n % p` to `n` which replaces `666xxxxx` with `66700000`. [Answer] # JavaScript (updated to work with all test cases) The little-known truth is that there are actually four `6`s, but one of the betrayed the others and polymorphed into code form to eradicate them from the ~~world~~ digits of the numbers. Here is that traitorous six: ``` x=prompt(''+ 'Enter number'); alert( ( (~x[ 'ind'+ 'exOf']('666')))?(x .replace(/666(.*)$/, function (mat,g){ return '667'+g ['re'+ 'place' ](/./g,0)})):((+x+ 1+'').replace( 666,667))); ``` Here is an explanation. First, beautify the code and remove useless stuff like `''+'string'` and `((code))`: ``` x = prompt('Enter number'); alert( ~x['indexOf']('666') ? x.replace(/666(.*)$/, function(mat,g) { return '667' + g['replace'](/./g,0) }) : (+x+1+'').replace(666, 667) ); ``` Convert weird notations (like `~indexOf` and `['replace']`) into more common ones: ``` x = prompt('Enter number'); alert( x.indexOf('666') > -1 ? x.replace(/666(.*)$/, function(mat, g) { return '667' + g.replace(/./g, 0) }) : ((parseInt(x) + 1) + '').replace(666, 667) ); ``` And now simply understand that the algorithm goes like this: * If there is already a 666 in the input, + replace it with a 667. + replace every digit after that with a 0. * else, + add one to the number. + NOTE: we are now guaranteed to have either no 666, a 666 at the end of the string, or a 666 somewhere else that already has zeroes going to the end (think "carrying" when doing "manual" addition). + if there's a 666, replace it with a 667. --- **Old version (doesn't work for `666666666`)**: ``` s='Enter number';x =prompt( ''+ s);x=+x+ (-~![]); x=(''+x).replace('666', 666+([][ +[]]+[]) [+[]]['l ength'[ 'repla'+ 'ce']( / /g,'')]);alert(x) ``` To understand this, let's first beautify it: ``` s = 'Enter number'; x = prompt('' + s); x = +x + (-~![]); x = ('' + x).replace('666',666+([][+[]]+[])[+[]]['l ength'['repla'+'ce'](/ /g,'')]); alert(x); ``` Now let's remove useless things like `'' + string` and `'str' + 'ing'`, remove the unnecessary `s` variable, and change weirdness like `-~![]` into `1`: ``` x = prompt('Enter number'); x = +x + 1; x = ('' + x).replace('666', 666+"undefined"[0]['l ength'['replace'](/ /g,'')]); alert(x); ``` `'l ength'['replace'](/ /g,'')` is simply `"length"`: ``` x = prompt('Enter number'); x = +x + 1; x = ('' + x).replace('666', 666+"undefined"[0].length); alert(x); ``` And `"undefined"[0]` is `"u"`, and `"u".length` is `1`: ``` x = prompt('Enter number'); x = +x + 1; x = ('' + x).replace('666', 666 + 1); alert(x); ``` Now we're done! It should be pretty easy to understand now. [Answer] # Applescript This site doesn't have enough Applescript answers. Lets banish some demons! ``` property demon : "666" property trinity : 1 on exorcise above possessed set possessed to possessed as text set relic to AppleScript's text item delimiters set AppleScript's text item delimiters to demon set deliverance to possessed's first text item if possessed is deliverance then set deliverance to possessed + trinity else set AppleScript's text item delimiters to trinity set compellingPower to ¬ (count of possessed's characters) - ¬ (count of deliverance's characters) - ¬ (count of demon's characters) set deliverance to ¬ deliverance & ¬ demon + trinity & ¬ last text item of (((10 ^ compellingPower) as integer) as text) end if set AppleScript's text item delimiters to relic return deliverance end exorcise log (exorcise above 666) log (exorcise above 66666666) log (exorcise above 1266612) log (exorcise above 1212) ``` Log output: ``` (*667*) (*66700000*) (*1266700*) (*1213*) ``` --- I'd wanted to get some of the more powerful [quotes from The Exorcist](http://www.imdb.com/title/tt0070047/quotes) into this, but that would have made this posted decidedly NSFW. You can read the IMDB page instead. [Answer] ## Perl You said we must not increment in a loop. I'm not using any mathematical operators at all! Here is a pure regex-substitution approach (no guarantees it's safe for your sanity). ``` #!/usr/bin/perl $_ = <>; s/$/ ~0123456789/; s/(?=\d)(?:([0-8])(?=.*\1(\d)\d*$)|(?=.*(1)))(?:(9+)(?=.*(~))|)(?!\d)/$2$3$4$5/g; s/9(?=9*~)(?=.*(0))|~| ~0123456789$/$1/g; s/(?!^)\G\d|(666)\d/${1}0/g; s/666/667/g; print($_) ``` The first three substitutions increment the number by one. I did solve that problem myself once, but it included a substitution that had to be looped until no more substitutions were made, so I used [Andrew Cheong's approach](https://stackoverflow.com/a/12946132/1633117) instead. The fourth substitution turns all digits following a `666` into zeros. The final substitution turns the remaining `666` into a `667`. As a bonus this will work with multiple integers in the input as long as they are separated by non-digit characters. [Answer] # LiveScript This is bending the rules. You see, you said I must not use a loop that **adds one** until it finds a correct result. So I **subtract minus one** instead! ``` nextId = (id) -> while (id + 1).toString!indexOf('666') != -1 id -= -1 id + 1 ``` A golfed version in **~~53~~ ~~48~~ 45 bytes** for fun: ``` n=(i)->(while~(i+1+'')indexOf(\666)=>i-=-1);i+1 ``` Thanks to [user1737909](https://codegolf.stackexchange.com/users/8328/user1737909) for helping golf it further. ## Tests Requires [Node.js](http://nodejs.org/) with the `LiveScript` npm module or a compatible assert library. ``` assert = require \assert assert.equal nextId(1), 2 assert.equal nextId(665), 667 assert.equal nextId(665999999), 667000000 assert.equal nextId(66600), 66700 assert.equal nextId(456667), 456670 ``` [Answer] # Ruby This is (I think) the first answer that works for 666666666. (Except the cheaty subtracting -1 answer. ;) ) ``` x = gets.chomp.to_i + 1 p (x..x.to_s.gsub('666', '667').to_i).select{|i| !(i.to_s.index '666') }.min ``` I'm in a hurry now; explanation will be added later. **Update**: much more efficient version (almost constant runtime I believe): ``` x = gets.chomp if x.index '666' # replace ex. 6661234 with 6670000 puts x.sub(/666(.*)/){ "667#{"0" * $1.length}" } else # old algorithm (guaranteed to result in # 0 or 1 666s now) puts (x.to_i+1).to_s.sub(/666/, "667") end ``` [Answer] **PowerShell** ``` ($args[0]+1 -replace '(?<=666.*).','0') -replace '666', '667' ``` [Answer] # J Finally, a good use for `E.`! ``` (({.~ , '667' {.!.'0'~ #@[ - ]) '666'&E. i. 1:) @ ": @ >: ``` In essence, we find the first position in which the argument has a full `666`, and we replace that substring and everything after with `66700000...` until the end. Explained in detail: * `":@>:` - Increment by one and convert to string. * `'666'&E.` - Make a vector of booleans, true in each place that '666' begins in the string. * `i.1:` - Find the index of the first true in the vector, else return the length of the vector. * `#@[-]` - Length of the string (which is also the length of the vector) minus the result of `i.`. * `'667'{.!.'0'~` - Take a substring of '667' with a length of that result, padding on the right with '0' if necessary. * `{.~` - Take a substring with the length of the original result from `i.`. * `,` - Append the two together. In use: ``` f =: (({.~,'667'{.!.'0'~#@[-])'666'&E.i.1:)@":@>: f 1 NB. this leaves okay numbers untouched 2 f 665999999 NB. properly handles multiple increments 667000000 f 16266366646666 NB. only takes effect at sets of 3 sixes 16266366700000 ``` And since this isn't a code golf, this doesn't have to get golfed to hell with crazy optimizations. Everybody wins! [Answer] # C# ## 148 137 chars Was able to shave off a few chars thanks to @recursive ``` public static int f(int b){b++;var z=new Regex("666\\d*");var q=z.Replace(b+"","667",1);return int.Parse(q.PadRight((b+"").Length,'0'));} ``` Ungolfed: ``` public static int f(int b) { b++; var z = new Regex("666[\\d]*"); var q = z.Replace(b+"", "667", 1); return Int32.Parse(q.PadRight((b+"").Length, '0')); } ``` Fiddle: <http://dotnetfiddle.net/XB83bf> [Answer] # Python ``` def next_id(id_num): id_num_p1=str(id_num+1) pieces=id_num_p1.split('666') if len(pieces)==1: return id_num+1 next_id_str=pieces[0]+'667'+'0'*(len(id_num_p1)-len(pieces[0])-3) return int(next_id_str) ``` [Answer] # Perl ``` $_++;$_.=$/;s:666(.*):667 .'0'x($+[1]-$-[1]):e ``` Inline code which changes the content inside `$_`, a pretty standard ideology in perl. Can be used in conjunction with `-p` flag like this: ``` $ perl -p % <<< 66666 66700 ``` [Answer] # J No strings, loops or conditionals: ``` next =: 3 :'<.(y+1)(+-|~)10^<:666 i:~666,1000|<.(y+1)%10^i.<.10^.>:y' next 1 2 next 665 667 next 665999999 667000000 next 666666666 667000000 next 66600 66700 ``` Similarly to cardboard\_box's solution, this separates the number into groups of three digits by dividing by powers of ten. It uses the index of the first occurrence of 666 to round the number up appropriately. [Answer] # Haskell (70 characters) Here is a simple implementation in Haskell. ``` import Data.List import Data.Char nextid :: Integer -> Integer nextid = foldl' ((+).(*10)) 0 . purge . map digitToInt . show . (+1) where purge (6:6:6:xs) = 6 : 6 : 7 : map (const 0) xs purge (x:xs) = fromIntegral x : purge xs purge [] = [] ``` * Firstly, it uses `map digitToInt . show` to convert a possibly evil ID to a list of digits. * Next, `purge` matches the evil pattern and replaces it with its good equivalent. * Finally, `foldl' ((+).(*10)) 0` reduces the list of digits to one `Integer`. Let's see if it works! ``` ghci> nextid 1 2 ghci> nextid 665 667 ghci> nextid 665999999 667000000 ghci> nextid 666666666 667000000 ghci> nextid 66600 66700 ghci> nextid 456667 456670 ghci> nextid 6660239486660239466 6670000000000000000 ``` Looks good. And just for fun a golfed version. ``` f=read.w.show.(+1);w('6':'6':'6':t)="667"++(t>>"0");w(h:t)=h:w t;w t=t ``` [Answer] # Java Isn't it enough to do this? ``` private static int nextId(int currentId) { String currentIdStr = String.valueOf(currentId); return currentIdStr.contains("666") ? Integer.parseInt(currentIdStr.replace("666", "667")) : ++currentId; } ``` [Answer] ## R Replacing 666 with 667 works. ``` f <- function(x) { x <- as.integer(x + 1) if (grepl(666, x)) { k <- regexpr(666, x) cat(substring(x, 1, k + 1), 7, rep(0, nchar(x) - k - 2), sep = "") } else cat(x) } ``` Results ``` > f(1) 2 > f(665) 667 > f(665999999) 667000000 > f(666666666) 667000000 > f(66600) 66700 > f(126660) 126670 > f(126661) 126670 > f(666666666) 667000000 ``` [Answer] 3 Different JavaScript answers: # 1. JavaScript (ECMAScript 6) ``` f=x=>(a=b=c=0,[c?'0':a+(a=b)+(b=i)==666?(c='7'):i for(i of ""+(x+1))].join('')*1) ``` Converts the number to a string then iterates over each character until it finds `666` then it changes that last `6` to a `7` and outputs `0` for all following characters. # 2. JavaScript (ECMAScript 6 Draft) Recursive function without string manipulation: ``` g=(x,y=x+1,p=1)=>y?g(y%1e3==666?y*p+p:y>x?y:x,y/10|0,p*10):x ``` Or more verbosely: ``` function g(x,y=x+1,p=1) { if ( y == 0 ) return x; else if ( y % 1000 == 666 ) return g( y*p+p, Math.floor(y/10), p*10 ); else return g( Math.max(y, x), Math.floor(y/10), p*10 ); } ``` Tests: ``` g(5) // 6 g(65) // 66 g(665) // 667 g(66599) // 66700 g(66666) // 66700 g(6656665665) // 6656670000 ``` # 3. JavaScript Using regular expressions: ``` function h(x)(""+(x+1)).replace( /^(.*?)(666)(.*)$/, function(a,b,c,d)(b+667+d.replace(/./g,0)) )*1 ``` Or (the same but using ECMAScript 6) ``` h=x=>(""+(x+1)).replace(/^(.*?)(666)(.*)$/,(a,b,c,d)=>b+667+d.replace(/./g,0))*1 ``` [Answer] ***AWK*** ``` awk '{i=index(++$0,"666")} i{a=substr($0,1,i-1) b=substr($0,i+3) gsub(/./,0,b) $0=a"667"b} 1 ' <<_INPUT_ 1 665 665999999 666666666 66600 _INPUT_ ``` gives ``` 2 667 667000000 667000000 66700 ``` ***edit: 2nd solution*** ``` awk -F666 -vOFS=667 '{++$0;$1=$1} NF-1{for(gsub(/./,0,$2);NF>2;--NF){$2=$2 0 0 0 for(i=length($NF);i;--i)$2=$2 0}}1 ' <<_INPUT_ 1 665 665999999 666666666 66600 1236661 _INPUT_ ``` yields ``` 2 667 667000000 667000000 66700 1236670 ``` [Answer] # Python: ``` def f(b): b = `b+1` while '666' in b: b = b.replace('666','667',1) return int(b) ``` Or: ``` f=lambda b:int(`b+1`.replace('666','667')) ``` [Answer] ## Java ``` public static int f(int i) { i++; i += findAdjustment(i); return i; } private static int findAdjustment(int i) { if (i < 666) { return 0; } int adjustment = findAdjustment(i / 10); if (adjustment != 0) { // Leftmost 666 found, fix adjustment by current last digit return adjustment * 10 - i % 10; } else if (i % 1000 == 666) { return 1; // This is leftmost 666, need to be corrected by 1 } else { return 0; // no adjustment needed } } ``` Using recursive function to find leftmost 666 and calculation how much to adjust the number when popping the call stack again. [Answer] ## Batch Simple iterated string manipulation. ``` @echo off setLocal enableDelayedExpansion set /a inp=%1+1 for /f usebackq %%a in (`powershell "&{'%inp%'.length-1}"`) do ( set a len=%%a-2 set chars=%%a ) for /l %%b in (0, 1, %len%) do ( if "!inp:~%%b,3!"=="666" ( set inp=!inp:~0,%%b!667 set /a a=%%b+3 for /l %%c in (!a!, 1, %chars%) do set inp=!inp!0 goto :break ) ) :break echo %inp% ``` It starts at the first three characters of the number (as a string), and works its way to the end until it finds 666, it then replaces that 666 with 667, and loops to the length of the string adding zeros. The test cases all produce the correct results. [Answer] # perl, 45 bytes A single regex with the /e flag does all the work here: ``` $_=<>+1;s/666(.*)$/"667".0 x length$1/e;print ``` [Answer] ## SQL To be precise, SQL Server 2012 Transact-SQL. ``` create function dbo.GoodIntegers( @i bigint ) returns bigint as begin declare @s varchar(20) = cast( @i+1 as varchar(20) ) ; declare @badindex int = charindex( '666', @s ) ; declare @rv bigint = cast ( iif( @badindex = 0 , @s , concat( left( @s, @badindex - 1 ), '667', replicate( '0', len( @s ) - @badindex - 2 ) ) ) as bigint ) ; return @rv ; end ; -- function dbo.GoodIntegers ``` [Answer] # Python ``` import re def exorcise(number): number = str(number+1) i = re.compile("^(\d*?)(666)(\d*)$") if re.match(i,number): n = re.match(i,number).groups() return int(n[0]+"667"+"".join(["0"*len(n[2])])) return int(number) ``` [Answer] # Julia ``` function f(x::Int) y = string(x+1) n = length(y) z = string(^("0",n)) ~ismatch(r"6{3}", y) ? int(y) : while ismatch(r"6{3}",y) m = match(r"6{3}", y) y = string(y[1:m.offset+1], '7', z[m.offset+3:n]) end int(y) end ``` REPL results ``` julia> f(1) 2 julia> f(665) 667 julia> f(665999999) 667000000 julia> f(666666666) 667000000 julia> f(66600) 66700 julia> f(456667) 456670 ``` [Answer] # C# Am I doing it right ``` static int F(int n) { n++; int a = 666; int b = 1; while (n >= b) { if (((n - a) / b) % 1000 == 0) { n += b; } a *= 10; b *= 10; } return n; } ``` [Answer] ## vba ``` Function f(num As Long) As Long Dim SixPos As Long Dim s As String s = CStr(num) SixPos = InStr(s, "666") If SixPos = 0 Then s = CStr(num + 1) SixPos = InStr(s, "666") End If If SixPos Then Mid(s, SixPos + 2, 1) = "7" If Len(s) > SixPos + 2 Then Mid(s, SixPos + 3, Len(s) - SixPos + 3) = String$(Len(s) - SixPos + 3, "0") End If End If f = CLng(s) End Function ``` In action: ``` Sub demo() Debug.Print f(1) 'returns 2. Debug.Print f(665) 'returns 667. Debug.Print f(665999999) 'returns 667000000 without having looped a million times. '(Following examples added since the question was first posed.) Debug.Print f(666666666) 'also returns 667000000. Debug.Print f(66600) 'returns 66700. Debug.Print f(456667) 'returns 456670. End Sub ``` result: ``` 2 667 667000000 667000000 66700 456670 ``` [Answer] ## C++ I know this isn't code-golf, but (a) some people have suggested that it is a good golf challenge, and (b) this is my first challenge/golf answer, I thought it would be fun, and if I do this here I don't get shown up in an actual golf challenge for being a terrible golfer. X) Basically, replaced '666' with '667' works if you do it for the first instance in the number and then write out trailing 0s. Golfed (175 155 chars): ``` #include<sstream> int f(int x){std::stringstream s,o;s<<++x;x=0;for(char c=s.get();!s.eof();c=s.get())o<<((x+=c=='6')++==3?'7':--x>3?'0':c);o>>x;return x;} ``` Ungolfed: ``` #include<sstream> int f(int x){ std::stringstream s,o; s<<++x; // Increment to next int. x=0; // Reusing this to count 6s for(char c=s.get();!s.eof();c=s.get()){ // For each digit if (c=='6'){ ++x; // Count sixes... } if(x==3) { // Devil's number! c='7'; // Output 7 here. ++x; // Increment once more. } else if (x > 3) { c='0'; // Already replaced 666 with 667, so write out 0s } o<<c; // Append digit } o>>x; // Get int return x; } ``` [Answer] # Ruby ``` n=(gets.chomp.to_i+1).to_s i=n.index("666") if i!=nil n=n[0..i+1]+"7"+"0"*(n.length-i-3) end puts n ``` [Answer] # perl, 36 just a sub, no bytes A shorter version than my last solution, using a mix of arithmetic and regex ops. ``` sub{($_[0]+1)=~s/666(.*)/667$1/r-$1} ``` [Answer] **C** ``` #include <stdlib.h> #include <stdio.h> int next(int a) { for(int b=a+1,c=0,d=0; b>665 ;b/=10, c++) if(b%1000==666) {d=c; a=b;} a++; while(d --> 0) a*=10; return a; } void main(int a, char *v[]) { int c = a>1?atoi(v[1]):0; printf("%d\n",next(c)); } ``` OK - no bounds checking and far too much whitespace but it's not golf. Also a fun bit of formatting in "while (d --> 0)". ]
[Question] [ ### Introduction If you're not familiar with [Hexagony](https://github.com/mbuettner/hexagony), it's an esoteric language created by Martin Büttner. The thing is that this language accepts multiple forms for the program. The following programs are all equivalent: ``` abcdefg ``` and ``` a b c d e f g ``` So basically, the code has been rolled up into a regular hexagon. But note that adding a new command to the code, which would be `abcdefgh` would result into the following program: ``` a b c d e f g h . . . . . . . . . . . ``` As you can see, the first step is rolling up the code into a hexagon, and after that the hexagon is filled in with no-ops (`.`) to the next [centered hexagonal number](https://en.wikipedia.org/wiki/Centered_hexagonal_number). Your task is simple, when given a string (the source code), output the full hexagon source code. ### The rules * You may provide a program or a function. * Leading whitespace is allowed, but only when the hexagon doesn't get out of shape * Trailing whitespace is allowed. * Note that whitespace in the program **are ignored**. So `a b c` is equal to `abc` * Only the printable ASCII characters (`32 - 126`) are used, so only the regular `Space` character is ignored. * Assume that the length of the string is greater than 0. * 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: ?({{&2'2':{):!/)'*/ Output: ? ( { { & 2 ' 2 ' : { ) : ! / ) ' * / Input: H;e;l;d;*;r;o;Wl;;o;*433;@.>;23<\4;*/ Output: H ; e ; l ; d ; * ; r ; o ; W l ; ; o ; * 4 3 3 ; @ . > ; 2 3 < \ 4 ; * / Input: .?'.) .@@/'/ .!.> +=(<.!)} ( $>( <% Output: . ? ' . ) . @ @ / ' / . ! . > + = ( < . ! ) } ( $ > ( < % . . . . . . . . ``` [Answer] ## [Hexagony](https://github.com/mbuettner/hexagony), 271 bytes I present to you, the first 3% of a Hexagony self-interpreter... ``` |./...\..._..>}{<$}=<;>'<..../;<_'\{*46\..8._~;/;{{;<..|M..'{.>{{=.<.).|.."~....._.>(=</.\=\'$/}{<}.\../>../..._>../_....@/{$|....>...</..~\.>,<$/'";{}({/>-'(<\=&\><${~-"~<$)<....'.>=&'*){=&')&}\'\'2"'23}}_}&<_3.>.'*)'-<>{=/{\*={(&)'){\$<....={\>}}}\&32'-<=._.)}=)+'_+'&< ``` [Try it online!](http://hexagony.tryitonline.net/#code=fC4vLi4uXC4uLl8uLj59ezwkfT08Oz4nPC4uLi4vOzxfJ1x7KjQ2XC4uOC5ffjsvO3t7OzwuLnxNLi4ney4-e3s9LjwuKS58Li4ifi4uLi4uXy4-KD08Ly5cPVwnJC99ezx9LlwuLi8-Li4vLi4uXz4uLi9fLi4uLkAveyR8Li4uLj4uLi48Ly4uflwuPiw8JC8nIjt7fSh7Lz4tJyg8XD0mXD48JHt-LSJ-PCQpPC4uLi4nLj49JicqKXs9JicpJn1cJ1wnMiInMjN9fV99JjxfMy4-LicqKSctPD57PS97XCo9eygmKScpe1wkPC4uLi49e1w-fX19XCYzMictPD0uXy4pfT0pKydfKycmPA&input=Lj8nLikgLkBALycvIC4hLj4gICArPSg8LiEpfSAgICAoICAkPiggPCU) You can also run it on itself, but it will take about 5-10 seconds. In principle this might fit into side-length 9 (for a score of 217 or less), because this uses only 201 commands, and the ungolfed version I wrote first (on side-length 30) needed only 178 commands. However, I'm pretty sure it would take forever to actually make everything fit, so I'm not sure whether I'll actually attempt it. It should also be possible to golf this a bit in size 10 by avoiding the use of the last one or two rows, such that the trailing no-ops can be omitted, but that would require a substantial rewrite, as one of the first path joins makes use of the bottom left corner. ### Explanation Let's start by unfolding the code and annotating the control flow paths: [![enter image description here](https://i.stack.imgur.com/hZvGn.png)](https://i.stack.imgur.com/hZvGn.png) That's still quite messy, so here is the same diagram for the "ungolfed" code which I wrote first (in fact, this is side-length 20 and originally I wrote the code on side-length 30 but that was so sparse that it wouldn't improve the readability at all, so I compacted it just a little bit to make the size a bit more reasonable): [![enter image description here](https://i.stack.imgur.com/Nk8wE.png)](https://i.stack.imgur.com/Nk8wE.png) Click for larger version. The colours are exactly the same apart from a few very minor details, the non-control-flow commands are also exactly the same. So I'll be explaining how this works based on the ungolfed version, and if you really want to know how the golfed one works, you can check which parts there correspond to which in the larger hexagon. (The only catch is that the golfed code starts with a mirror so that the actual code begins in the right corner going left.) The basic algorithm is almost identical to [my CJam answer](https://codegolf.stackexchange.com/a/66712/8478). There are two differences: * Instead of solving the centred hexagonal number equation, I just compute consecutive centred hexagonal numbers until one is equal to or larger than the length of the input. This is because Hexagony does not have a simple way to compute a square root. * Instead of padding the input with no-ops right away, I check later if I've already exhausted the commands in the input and print a `.` instead if I have. That means the basic idea boils down to: * Read and store input string while computing its length. * Find the smallest side-length `N` (and corresponding centred hexagonal number `hex(N)`) which can hold the entire input. * Compute the diameter `2N-1`. * For each line, compute the indent and the number of cells (which sum to `2N-1`). Print the indent, print the cells (using `.` if the input is already exhausted), print a linefeed. Note that there are only no-ops so the actual code starts in the left corner (the `$`, which jumps over the `>`, so the we *really* start on the `,` in the dark grey path). Here is the initial memory grid: [![enter image description here](https://i.stack.imgur.com/sQMPA.png)](https://i.stack.imgur.com/sQMPA.png) So the memory pointer starts out on edge labelled *input*, pointing North. `,` reads a byte from STDIN or a `-1` if we've hit EOF into that edge. Hence, the `<` right after is a conditional for whether we've read all the input. Let's remain in the input loop for now. The next code we execute is ``` {&32'- ``` This writes a 32 into the edge labelled *space*, and then subtracts it from the input value in the edge labelled *diff*. Note that this can never be negative because we're guaranteed that the input contains only printable ASCII. It will be zero when the input was a space. (As Timwi points out, this would still work if the input could contain linefeeds or tabs, but it would also strip out all other unprintable characters with character codes less than 32.) In that case, the `<` deflects the instruction pointer (IP) left and the light grey path is taken. That path simply resets the position of the MP with `{=` and then reads the next character - thus, spaces are skipped. Otherwise, if the character was not a space, we execute ``` =}}})&'+'+)=} ``` This first moves around the hexagon through the *length* edge until its opposite the *diff* edge, with `=}}}`. Then it copies the value from opposite the *length* edge into the *length* edge, and increments it with `)&'+'+)`. We'll see in a second why this makes sense. Finally, we move the a new edge with `=}`: [![enter image description here](https://i.stack.imgur.com/3gNg9.png)](https://i.stack.imgur.com/3gNg9.png) (The particular edge values are from the last test case given in the challenge.) At this point, the loop repeats, but with everything shifted one hexagon northeast. So after reading another character, we get this: [![enter image description here](https://i.stack.imgur.com/gkJLf.png)](https://i.stack.imgur.com/gkJLf.png) Now you can see that we're gradually writing the input (minus spaces) along the northeast diagonal, with the characters on every other edge, and the length up to that character being stored parallel to the edge labelled *length*. When we're done with the input loop, memory will look like this (where I've already labelled a few new edges for the next part): [![enter image description here](https://i.stack.imgur.com/safv0.png)](https://i.stack.imgur.com/safv0.png) The `%` is the last character we read, the `29` is the number of non-space characters we read. Now we want to find the side-length of the hexagon. First, there is some linear initialisation code in the dark green/grey path: ``` =&''3{ ``` Here, `=&` copies the length (29 in our example) into the edge labelled *length*. Then `''3` moves to the edge labelled *3* and sets its value to `3` (which we just need as a constant in the computation). Finally `{` moves to the edge labelled *N(N-1)*. Now we enter the blue loop. This loop increments `N` (stored in the cell labelled *N*) then computes its centered hexagonal number and subtracts it from the input length. The linear code which does that is: ``` {)')&({=*'*)'- ``` Here, `{)` moves to and increments *N*. `')&(` moves to edge labelled *N-1*, copies `N` there and decrements it. `{=*` computes their product in *N(N-1)*. `'*)` multiplies that by the constant `3` and increments the result in the edge labelled *hex(N)*. As expected, this is the Nth centered hexagonal number. Finally `'-` computes the difference between that and the input length. If the result is positive, the side-length is not large enough yet, and the loop repeats (where `}}` move the MP back to the edge labelled *N(N-1)*). Once the side-length is large enough, the difference will be zero or negative and we get this: [![enter image description here](https://i.stack.imgur.com/VvwAA.png)](https://i.stack.imgur.com/VvwAA.png) First off, there is now the really long linear green path which does some necessary initialisation for the output loop: ``` {=&}}}32'"2'=&'*){=&')&}} ``` The `{=&` starts by copying the result in the *diff* edge into the *length* edge, because we later need something non-positive there. `}}}32` writes a 32 into the edge labelled *space*. `'"2` writes a constant 2 into the unlabelled edge above *diff*. `'=&` copies `N-1` into the second edge with the same label. `'*)` multiplies it by 2 and increments it so that we get the correct value in the edge labelled *2N-1* at the top. This is the diameter of the hexagon. `{=&')&` copies the diameter into the other edge labelled *2N-1*. Finally `}}` moves back to the edge labelled *2N-1* at the top. Let's relabel the edges: [![enter image description here](https://i.stack.imgur.com/unKjM.png)](https://i.stack.imgur.com/unKjM.png) The edge we're currently on (which still holds the diameter of the hexagon) will be used to iterate over the lines of the output. The edge labelled *indent* will compute how many spaces are needed on the current line. The edge labelled *cells* will be used to iterate over the number of cells in the current line. We're now on the pink path which computes *indent*. `('-` decrements the *lines* iterator and subtracts it from *N-1* (into the *indent* edge). The short blue/grey branch in the code simply computes the modulus of the result (`~` negates the value if it's negative or zero, and nothing happens if it's positive). The rest of the pink path is `"-~{` which subtracts the *indent* from the diameter into the *cells* edge and then moves back to the *indent* edge. The dirty yellow path now prints the indentation. The loop contents are really just ``` '";{}( ``` Where `'"` moves to the *space* edge, `;` prints it, `{}` moves back to *indent* and `(` decrements it. When we're done with that the (second) dark grey path searches for next character to print. The `=}` moves in position (which means, onto the *cells* edge, pointing South). Then we have a very tight loop of `{}` which simply moves down two edges in the South-West direction, until we hit the end of the stored string: [![enter image description here](https://i.stack.imgur.com/Wm3z7.png)](https://i.stack.imgur.com/Wm3z7.png) Notice that I've relabelled one edge there *EOF?*. Once we've processed this character, we'll make that edge negative, so that the `{}` loop will terminate here instead of the next iteration: [![enter image description here](https://i.stack.imgur.com/ZzkZd.png)](https://i.stack.imgur.com/ZzkZd.png) In the code, we're at the end of the dark grey path, where `'` moves back one step onto the input character. If the situation is one of the last two diagrams (i.e. there's still a character from the input we haven't printed yet), then we're taking the green path (the bottom one, for people who aren't good with green and blue). That one is fairly simple: `;` prints the character itself. `'` moves to the corresponding *space* edge which still holds a 32 from earlier and `;` prints that space. Then `{~` makes our *EOF?* negative for the next iteration, `'` moves a back a step so that we can return to the North-West end of the string with another tight `}{` loop. Which ends on the *length* cell (the non-positive one below *hex(N)*. Finally `}` moves back to the *cells* edge. If we've already exhausted the input though, then the loop which searches for EOF? will actually terminate here: [![enter image description here](https://i.stack.imgur.com/oz5hi.png)](https://i.stack.imgur.com/oz5hi.png) In that case `'` moves onto the *length* cell, and we're taking the light blue (top) path instead, which prints a no-op. The code in this branch is linear: ``` {*46;{{;{{= ``` The `{*46;` writes a 46 into the edge labelled *no-op* and prints it (i.e. a period). Then `{{;` moves to the *space* edge and prints that. The `{{=` moves back to the *cells* edge for the next iteration. At this point the paths join back together and `(` decrements the *cells* edge. If the iterator is not zero yet, we will take the light grey path, which simply reverses the MP's direction with `=` and then goes looking for the next character to print. Otherwise, we've reached the end of the current line, and the IP will take the purple path instead. This is what the memory grid looks like at that point: [![enter image description here](https://i.stack.imgur.com/rf95h.png)](https://i.stack.imgur.com/rf95h.png) The purple path contains this: ``` =M8;~'"= ``` The `=` reverses the direction of the MP again. `M8` sets the sets its value to `778` (because the character code of `M` is `77` and digits will append themselves to the current value). This happens to be `10 (mod 256)`, so when we print it with `;`, we get a linefeed. Then `~` makes the edge negative again, `'"` moves back to the *lines* edge and `=` reverses the MP once more. Now if the *lines* edge is zero, we're done. The IP will take the (very short) red path, where `@` terminates the program. Otherwise, we continue on the purple path which loops back into the pink one, to print another line. --- *Control flow diagrams created with Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer). Memory diagrams created with the visual debugger in his [Esoteric IDE](https://github.com/Timwi/EsotericIDE).* [Answer] ## CJam, ~~56~~ ~~52~~ ~~50~~ 48 bytes My first thought was, "hey I already have code for this!" But then I couldn't be bothered to pull the necessary pieces together from the Ruby code, especially because they didn't seem very suitable to being golfed. So I tried something else in CJam instead... ``` lS-{_,4*(3/mq:D1%}{'.+}wD{D(2/-z_S*D@-@/(S*N@s}/ ``` [Test it here.](http://cjam.aditsu.net/#code=lS-%7B_%2C4*(3%2Fmq%3AD1%25%7D%7B'.%2B%7DwD%7BD(2%2F-z_S*D%40-%40%2F(S*N%40s%7D%2F&input=.%3F'.)%20.%40%40%2F'%2F%20.!.%3E%20%20%20%2B%3D(%3C.!)%7D%20%20%20%20(%20%20%24%3E(%20%3C%25) ### Explanation A bit of maths about centred hexagonal numbers first. If the regular hexagon has side length `N`, then it will contain `3N(N-1)+1` cells, which has to equal the source code length `k`. We can solve that `N` because it's a simple quadratic equation: ``` N = 1/2 ± √(1/4 + (k-1)/3) ``` We can ignore the negative root, because that gives a negative N. For this to have a solution, we need the square root be a half-integer. Or in other words, `√(1 + 4(k-1)/3) = √((4k-1)/3)` needs to be an integer (luckily, this integer happens to be the diameter `D = 2N-1` of the hexagon, which we'll need anyway). So we can repeatedly add a single `.` until that condition is met. The rest is a simple loop which lays out the hexagon. A useful observation for this part is that the spaces in the indentation plus the non-spaces in the code in each line add up to the diameter. ``` lS- e# Read input and remove spaces. { e# While the first block yields something truthy, evaluate the second... _, e# Duplicate the code and get its length k. 4*( e# Compute 4k-1. 3/ e# Divide by 3. mq e# Take the square root. :D e# Store this in D, just in case we're done, because when we are, this happens e# to be the diameter of the hexagon. 1% e# Take modulo 1. This is 0 for integers, and non-zero for non-integers. }{ e# ... '.+ e# Append a no-op to the source code. }w D{ e# For every i from 0 to D-1... D(2/ e# Compute (D-1)/2 = N, the side length. -z e# Subtract that from the current i and get its modulus. That's the size of the e# indentation on this line. _S* e# Duplicate and get a string with that many spaces. D@- e# Subtract the other copy from D to get the number of characters of code e# in the current line. @/ e# Pull up the source code and split into chunks of this size. (S* e# Pull off the first chunk and riffle it with spaces. N e# Push a linefeed character. @s e# Pull up the remaining chunks and join them back into a single string. }/ ``` It turns out that we don't need to use double arithmetic at all (except for the square root). Due to the multiplication by 4, there are no collisions when dividing by 3, and the desired `k` will be the first to yield an integer square root. [Answer] # Pyth, ~~57~~ ~~54~~ ~~50~~ ~~49~~ ~~48~~ 46 ``` V+UJfgh*6sUTlK-zd1_UtJ+*d-JNjd:.[K\.^TJZ=+Z+JN ``` [Test Suite](https://pyth.herokuapp.com/?code=V%2BUJfgh%2a6sUTlK-zd1_UtJ%2B%2ad-JNjd%3A.%5BK%5C.%5ETJZ%3D%2BZ%2BJN&input=%3F%28%7B%7B%262%272%27%3A%7B%29%3A%21%2F%29%27%2a%2F&test_suite=1&test_suite_input=%0Aa%0Aab%0Aabcdefgh%0A%3F%28%7B%7B%262%272%27%3A%7B%29%3A%21%2F%29%27%2a%2F%0AH%3Be%3Bl%3Bd%3B%2a%3Br%3Bo%3BWl%3B%3Bo%3B%2a433%3B%40.%3E%3B23%3C%5C4%3B%2a%2F%0A.%3F%27.%29+.%40%40%2F%27%2F+.%21.%3E+++%2B%3D%28%3C.%21%29%7D++++%28++%24%3E%28+%3C%25&debug=0) Prints a leading space on each line. This version requires a proof that **10^n >= 3n(n - 1) + 1** for all **n >= 1**. Thanks to [ANerdI](https://codegolf.stackexchange.com/users/43444/a-nerd-i) and [ErickWong](https://math.stackexchange.com/users/30402/erick-wong) for providing proofs. Following these inequalities: **10^n > (1+3)^n = 1 + 3n + 9n(n - 1) + ... > 3n(n - 1) + 1** one can easily see that this is correct for **n >= 2**. Examining the **n = 1** case is rather trivial, giving **10 > 1**. Alternatively, taking the derivatives of these equations twice shows that **10^n** has a greater second derivative for all **n >= 1**, which can then be cascaded down to the first derivatives, and finally to the original equations. ### Explanation ``` ## Implicit: z=input(); Z=0 Jf...1 ## Save to J the side length of the hexagon the code fills up ## by finding the first number such that: gh*6sUT ## the the T'th hexagonal number is greater than... ## Computes 6 * T'th triangular number (by using sum 1..T-1) + 1 lK-zd ## ...the length of the code without spaces (also save the string value to K) V+UJ_UtJ ## For loop over N = [0, 1, ..., J-1, ..., 0]: +*d-JN ## append J - N spaces to the front of the line jd ## riffle the result of the next operation with spaces :.[K\.yJ ## slice the string given by K padded to be the length of the Jth hexagon ## number with noops Z=+Z+JN ## from Z to Z + J + N, then set Z to be Z + J + N ``` [Answer] ## Perl, ~~203~~ ~~200~~ 198 *includes + 1 for `-p`* ``` s/\s//g;{($l=y///c)>($h=1+3*++$n*($n-1))&&redo}$s=$_.'.'x($h-$l);for($a=$n;$a<($d=2*$n-1);$a++){$s=~s/.{$a}/$&\n/,$s=reverse($s)for 0..1}$_=join$/,map{(' 'x abs($n-$i++-1)).$_}$s=~/\S+/g;s/\S/ $&/g ``` *run as: `echo abc | perl -p file.pl`* A very naive approach: ``` #!/usr/bin/perl -p s/\s//g; # ignore spaces and EOL etc. { # find the smallest hex number: ($l=y///c) # calc string length > ($h=1+3*++$n*($n-1)) # && redo # (should use 'and', but..) } $s = $_ # save $_ as it is used in the nested for . '.' x ($h-$l); # append dots to fill hexagon for ( $a = $n; $a < ($d=2*$n-1); $a++ ) { $s=~s/.{$a}/$&\n/, # split lines $s=reverse($s) # mirror for 0..1 # twice } $_ = join$/, # join using newline map { # iterate the lines (' 'x abs($n-$i++-1)) .$_ # prepend padding } $s=~/\S+/g; # match lines s/\S/ $&/g # prepend spaces to characters # -p takes care of printing $_ ``` --- * *update 200* save a byte moving variable assignment, and another 2 by omitting final `;`; code itself under 200 bytes now! * *update 198* save 2 bytes by using `$s=~/\S+/g` instead of `split/\n/,$s` [Answer] # JavaScript (ES6), 162 ~~172~~ Anonymous function The hexagon size is found resolving the equation from [wikipedia](https://en.wikipedia.org/wiki/Centered_hexagonal_number) ``` 3*n*(n-1)-1 = l ``` The solving formula is basically ``` n = ceil(3+sqrt(12*l-3))/6) ``` With some algebra and some approximation (thx to @user18655 too) it becomes ``` n = trunc(sqrt(l/3-1/12)+1.4999....) ``` ``` s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`") ``` More readable ``` s=>{ s=s.match(/\S/g); m=n=Math.sqrt(s.length/3-1/12)+1.49999; p=o=''; for(i=n+n; --i; i>n?++m:--m) for(o += '\n'+' '.repeat(n+n-m), j=m; j--; o += ' ') o+=s[p++]||'.'; return o } ``` **Test snippet (better full page - running time ~ 1 minute)** ``` f=s=>eval("s=s.match(/\\S/g);m=n=Math.sqrt(s.length/3-1/12)+1.49999|0;p=o=``;for(i=n+n;--i;i>n?++m:--m)for(o+=`\n`+` `.repeat(n+n-m),j=m;j--;o+=` `)o+=s[p++]||`.`") t=0; r='0'; (T=_=>t++<816?(O.innerHTML=f(r=t%10+r),setTimeout(T,20)):0)() ``` ``` pre { font-size: 66% } ``` ``` <pre id=O></pre> ``` [Answer] # Pyth, ~~52~~ 51 bytes ``` Jfgh**3TtTl=H-zd1=+H*\.*lHTV+UJt_UJAcH]+JN+*-JNdjdG ``` [Try it online.](https://pyth.herokuapp.com/?code=Jfgh**3TtTl%3DH-zd1%3D%2BH*%5C.*lHTV%2BUJt_UJAcH%5D%2BJN%2B*-JNdjdG&input=H%3Be%3Bl%3Bd%3B*%3Br%3Bo%3BWl%3B%3Bo%3B*433%3B%40.%3E%3B23%3C%5C4%3B*%2F&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=Jfgh**3TtTl%3DH-zd1%3D%2BH*%5C.*lHTV%2BUJt_UJAcH%5D%2BJN%2B*-JNdjdG&test_suite=1&test_suite_input=%3F%28%7B%7B%262%272%27%3A%7B%29%3A!%2F%29%27*%2F%0AH%3Be%3Bl%3Bd%3B*%3Br%3Bo%3BWl%3B%3Bo%3B*433%3B%40.%3E%3B23%3C%5C4%3B*%2F%0A.%3F%27.%29+.%40%40%2F%27%2F+.!.%3E+++%2B%3D%28%3C.!%29%7D++++%28++%24%3E%28+%3C%25&debug=0) Each line has one extra leading space, as permitted by the OP. ### Explanation ``` f 1 | find first number n for which -zd | remove spaces from input =H | put result in H l | length of input without spaces g | is less than or equal to h**3TtT | nth centered hexagonal number J | put result (hexagon side length) in J | *lHT | ten times length of input without spaces *\. | that amount of dots =+H | append to H | UJ | numbers 0 up to side length - 1 + t_UJ | add numbers side length - 2 down to 0 V | loop over result +JN | current loop number + side length cH] | split to two parts at that position A | put parts to G and H -JN | side length - current loop number - 1 * d | that many spaces jdG | join code on the line (G) by spaces + | concatenate parts and print ``` [Answer] ## [Retina](https://github.com/m-ender/retina), 161 bytes *Thanks to FryAmTheEggman for saving 2 bytes.* This answer is non-competing. Retina has seen a few updates since this challenge, and I'm pretty sure I'm using some of the newer features (although I haven't checked). Byte count assumes ISO 8859-1 encoding. The first line contains a single space. Note that most of the `·` are actually centre dots (0xB7). ``` ^ $._$*·¶ ^·¶ ¶ ((^·|\2·)*)·\1{5}·+ $2· ^·* $.&$* ·$&$&$.&$* M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$ +m`^( *·+)· *¶(?=\1) $& · · O$`(·)|\S $1 · . G-2` ``` [Try it online!](http://retina.tryitonline.net/#code=IAoKXgokLl8kKsK3wrYKXsK3wrYKwrYKKChewrd8XDLCtykqKcK3XDF7NX3CtysKJDLCtwpewrcqCiQuJiQqIMK3JCYkJiQuJiQqIApNISZtYCg_PD0oPz0gKijCtykrKV4uKikoPzwtMT4uKSsoPygxKSEpfF4uKyQKK21gXiggKsK3KynCtyAqwrYoPz1cMSkKJCYgCsK3CiDCtwpPJGAowrcpfFxTCiQxCsK3Ci4KRy0yYA&input=MTIzNDU2IDc4) Well... ### Explanation It seems easiest to build the layout first using just a single character (`·` in this case) and then fill the resulting layout with the input characters. The main reasons for this are that using a single character lets me make use of backreferences and character repetition, where laying out the input directly would require expensive balancing groups. ``` ``` Although it doesn't look like much, this first stages removes spaces from the input. ``` ^ $._$*·¶ ``` We start by prepending an additional line which contains `M` centre dots, where `M` is the length of the input (after removing spaces). ``` ^·¶ ¶ ``` If the input was a single character, we remove that centre dot again. This is an unfortunate special case that isn't covered by the next stage. ``` ((^·|\2·)*)·\1{5}·+ $2· ``` This computes the required side length `N` minus 1. Here is how that works: centred hexagonal numbers are of the form `3*N*(N-1) + 1`. Since triangular numbers are `N*(N-1)/2`, that means hexagonal numbers are six times a triangular number plus 1. That's convenient because matching triangular numbers (which are really just `1 + 2 + 3 + ... + N`) in a regex is fairly easy with forward references. The `(^·|\2·)*` matches the largest triangular number it can. As a nice bonus, `$2` will then hold the index of this triangular number. To multiply it by 6, we capture it into group `1` and match it another 5 times. We make sure there are at least two more `·` with the `·` and the `·+`. This way the index of the found triangular number doesn't increase until there's one character more than a centred hexagonal number. In the end, this match gives us two less than the side-length of the required hexagon in group `$2`, so we write that back together with one more centre dot to get `N-1`. ``` ^·* $.&$* ·$&$&$.&$* ``` This turns our string of `N-1` centre dots into `N-1` spaces, `2N-1` centre dots and another `N-1` spaces. Note that this is the maximum indentation, followed by the diameter of the hexagon, followed by the indentation again. ``` M!&m`(?<=(?= *(·)+)^.*)(?<-1>.)+(?(1)!)|^.+$ ``` This is unpleasantly long, but it basically just gives us all *overlapping* matches, which are either a) `2N-1` characters long and on the first line or b) the second line. This expands the result from the previous stage into the full, but weirdly indented hexagon. E.g. for input `12345678` we'd get: ``` ··· ···· ····· ···· ··· 12345678 ``` This is why we needed to append spaces in the previous stage as well. ``` +m`^( *·+)· *¶(?=\1) $& ``` This fixes the indentation of the lines after the centre, by repeatedly indenting any line that is shorter than the previous (ignoring trailing spaces), so we get this: ``` ··· ···· ····· ···· ··· 12345678 ``` Now we just insert some spaces with ``` · · ``` Which gives us: ``` · · · · · · · · · · · · · · · · · · · 12345678 ``` Phew, that's done. ``` O$`(·)|\S $1 ``` Time to fill the input string into the centre dots. This is done with the help of a sort stage. We match all centre dots and each character on the last line, and we sort them by the result of the given substitution. That substitution is empty for the characters on the last line and `·` for the centre dots, so what happens is that the centre dots are simply sorted to the end (since sorting is stable). This moves the input characters into place: ``` 1 2 3 4 5 6 7 8 · · · · · · · · · · · ········ ``` Just two things left now: ``` · . ``` This turns centre dots into regular periods. ``` G-2` ``` And this discards the last line. [Answer] ## JavaScript (ES6), 144 bytes ``` (s,n=1,l=0,p=0,m=s.match(/\S/g))=>m[n]?f(s,n+6*++l,l):[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n` ``` Where `\n` represents the literal newline character. Uses a technique for creating a hexagon that I've previously used on several other [hexagonal-grid](/questions/tagged/hexagonal-grid "show questions tagged 'hexagonal-grid'") answers. For ES7 taking square roots works out slightly shorter than the recursive approach: ``` (s,p=0,m=s.match(/\S/g),l=(~-m.length/3)**.5+.5|0)=>[...Array(l+l+1)].map((_,i,a)=>a.map((_,j)=>j<l-i|j<i-l?``:m[p++]||`.`).join` `).join`\n` ``` [Answer] # [Python 3](https://docs.python.org/3/), 144 bytes ``` c=input().replace(' ','') n=x=1 while x<len(c):x+=n*6;n+=1 c=c.ljust(x,'.') while c:print(' '*(x-n)+' '.join(c[:n]));c=c[n:];n-=(len(c)<x/2)*2-1 ``` [Try it online!](https://tio.run/##LY49b4MwGIR3/wqHIf4gmGJoBr@4ZeyYThmSKKqMpRBZBlGiuuLHU0d0upPu7tENv9Ot9@Vi@tbqJEkWozs/PCbKxGgH92UsJZjsCGHI66AL9HPrnMWhdtZTw1RIted78GmMjDbC3R/fEw07IuJi7Ro1jJ2fnhxOQ@ZZGp24910EnJS/MAZxefLqAj7TdAXXIZeMy6xY4in0TyoUtsEa@jzLYKWyRaACyxJjXL026J3O81YSSdTM1CZnhOfoA64WRpBOwEF8HsHlhwIaeGnh3ENMMbbgoI3KY62Ho8MQhVe4LKERbyDL@lwBzzd/ "Python 3 – Try It Online") This uses a rather varying amount of leading whitespace for different sized hexagons, but the general shape survives. [Answer] # [Nibbles](http://golfscript.com/nibbles), 27 bytes ``` +!/|.,~+.,;+-$~$::"\n"`<!=$_^-@~" "`'$~-,;+%_~,@$:@^~".": ``` That's 54 nibbles, each half a byte in the binary form (the " " and "\n" are only 2 nibbles each). Run it like this (Nibbles isn't on TIO yet...): ``` > echo abcdef | nibbles hex.nbl a b c d e f . ``` ## How? Rather than compute the smallest centered hexagonal number, calculate the spaces that would be added before each input character for all possible sized hexagons. Find the first one that has as many entries as there are input characters and then just zip them together. This is a good example of the power of laziness, although mainstream languages could have accomplished the same feat with streams/enumerators. ### Translation ``` + concat ! zip with / foldr | filter . ,~ map [1..] (call it n) + . , concat map 1 to (call it i) ; + -$~ $ n-1+n (saved, call it k) : append :"\n" newline prepended with `< != $ _ splitAt abs n-i (returns take part) ^ -@~ " " replicate " " k-1 times `' $ transpose of the drop part from splitAt below is the fn for filter ~ - not of difference (aka <=) , ; +%_~ length of input with spaces removed via concat words of input (saved) , @ length of space table $ fold's element variable (essentially / ... $ is a way to take head of a list) :@^~"." our space removed input with infinite "." added : append (arg to zip with), combines space table with input ``` One trick is that newline was prepended to the first space table element on each line, so that the final zip also adds newlines correctly. Another trick is the realization that each line has 2n-2 spaces. So a take/drop (splitAt) is used to take the number needed before the first of the line and the remainder is all the things needed before each character (transpose is used to convert that to a list of strings instead of just a string). It seems a little silly to precompute the fact that we need to add a single space to most characters, but doing so is what ultimately enables us to count the size of the hexagon and combine that hexagon with the input trivially. [Answer] # [Knight](https://github.com/knight-lang/knight-lang), ~~158~~ 152 bytes ``` ;=n~1;=pP;=s'';Wp;=s+sI?32Ap''A Ap=pGp 1Lp;W<+1+**3=n+nTn*3nLsN;=i+1*2nW+1=i-iT;O+*' '=xI>=x-n iFx~x'\';=j~2;W<=j+1j-*2n xIs;O+A As' \'=sGs 1LsO'. \'O'' ``` idek anymore lol [Try It Online!](https://tio.run/##lVhrV9s4Gv4@v0J4W2zFjknonNlTjMhQlvZwtg3dwgxnN0mLbCuJqSOnvkA6ifvX2Ve@yrlA5wvY1qP3pue9KHf0nkZO6M3jNg9c9uj4NIrQv7k3mcbnYRiEiC1ixt0IZW/LNAd8pGHEmuvSnhL1KeGxN3sedxWHjM6WTsCjOEycOAg1ipfx1IvMKEhChxGawoo3v5l6MYvm1GFasT6jsTPVDj5rg@FoOBhG8D09Gumrfww@D/mopQ356gXGrQOczhn7Cqshi5OQI0n4oDNarXji@2kuzDYc0sFLn8WIEttkC@ZoEhxbhQixhRBCe@LhSIYQ6dmMEhts1yioMX3GJ/EUG3TgjHAaB@C4xydbrUrTLBzo@r8fz6/IYGTlofqT@glbRjGNPQfNxSloNl7a5kZ4rDFE8Z6G4EPHoseZmEK/RXU9988h2fcBHZmlLMsbaw4u7HFSydc0THgW9jB4QJw95IxIXWYnky3fd3iXCTHrRcD1k5nNwh24chFwb4LAZ5TvAFaracGq9xCMkPoV8fLQrZEsSuZCupGJ@uLSmALXckclJVucKd7rfds8Kd6boA03yg8yjH3zhXkFgiIPrKbcYcE491pyY39fMh74mD@VURDCqxAUIdngT8n1Opuu347w4LT9v1HrwOhWlKf7@@KAhUxNuVaENpy6yWxeOXNbOvMiy88U36Z@PK1d2att3d@njWObyDgk4/aawDQn8zyJppr4iq08Vc77f158uux/OO9fk2VaJMyFy3i8xoHn3B/Q9l9fRuJvp/36C4RgPQCZUDA2fYpNngABm5rxybZ6Yw9weYhynAgUmOtNuJAjeTKoMaOKmrnBO1Aig@8Dz0WdPXE@peVWnaByXdZu/@BfefDAkVdZhtSGaeptM@aZC7iMrxTdn6XX0NU3QwoBLdKF4nVSFQs1p6jrSlwp99ec0alUOnAKNfhJeLsJnyX@k/BWE@5697KX9ZI4icYhlKI@0HhqAm@4I0k9AL93HZJyRjkPYgSq4EyQ/R39xcJAAVMD92/qrhW@pM/qA/GJH0j65sHD0/pq8avVnkaPO/innG@1fsJ7tpgHXJCUxiwzCMUB1EbOJsC3e4bAOBaCkf6OSnIsn9vOenPSQDWIX9O@Dw3xad5L1bsifr8oqTjnvBDSKCFlBRHtdi0HFAHWsPJUZ8jkFc4/E0onmIGZLNtiKlUw/uYuOTjiWxkdaI7PBkdQyCZU6jmKOsIwx0XDq1Grh4fdA@Mwo5WIBjDLlokEGsSwkg8x1MyHOwFWVNGWnNVKVVTxgGuX6qFVFD2wauZxYJKLviUBEIpxJ0jEZ@YeoRdLmt5ua@mZ/c08MrodvFp11mpWMSA8VbOEE7cFoFC4WXoEqNZlhmzOKPQeuQI9w/hq1HqS8RVKPlT4WHRX2EXdq@/cOaIpCdm3xAuZpowjBRtLMSJnS7a05Ew93/0yDwOHRQL19o/@2fXFZf@q7s1voQY81ZolluQHDJN5JWZgS50uO2lpVrUkXvWOsqzTVyY@yBnDxDwt5mPx4sJ87B475WzslrPxmGQWmaUpQtneeAedPnjQu/kE0XCSzMTA8WLp6t0UgRI0Fl5CR7VFI7VYHtgxTqUzFoHQHMM22NpIAZ@ctbFCiCM0f@Z0xoidP4PqiDibs2u2QTNNs0JVlSWv4orQHnsB1xS9klqFx0blyJltpTpRDKTotpnLqLq4rmzUpkv7jjmx6UUZfw0Yl9JxoQqFbOJFMctcxEsIbVf0qvKCtHaX0JQ@mIRmCQx5NiTqgjqx/x1BL0DOlIbwBjOLH/AJ1CSrJggdEVvSCIGpOpd8tEWSwQ1Us6U8wHLtqceo/L5hbaWB0g/QvZAMhTLxXWFrpsLdg1opZZUIODaqECgfFUPD5KS4kimKYZM3yXjMQpP6fuBoMIC7gQgS1TrAiA5M5AZQ3oYrJbbB8K@Wo4OrD5BxTOtCF85WspucKXLrxoPEV4Zcwdghjhn5HtwQOwZq15N9WWkcnMqWfcota7TusR@Ar78evv719W//PHz9Wyv7GlLuBjMRNnn/uWJQciJCRhuhrSHqqSogVaLn4S2ssuXuBgb0SjNzSeY4DGZnwICzwIVBs7g74aPSXPk4TafAncZiZpONfJMZSeVPZ/mn4nKZ/ZWXb7Plqg81ndvhqPKfbFNREE228NaruITdqxRkd63mBaiBfF8hhceyIWUyyeh/CW6dVONbI9ilZVHsBklsPoTQuEFgnufYoI2YXTYF1VoLacpwmF0PC7IB03o75JdsBAg@2oq5Fb3xl1tsVDOTbIkOFBVFpD4u0WgL3xrOtzeQ4l6wDdnaQIq@vA15sIHMbgNbkC83ZQbb7fy8gcym7i3I4wpZUaXcIiaCaou852T3nsmuPb3de0TJ37pnv9qj0TKvG7/T9IptR43MWz27jR7ZmxlpSdvyVWNbwIgEa9QWcaVdrUCldL1vJjI1i/u5TSr9dkP4TSV8Kbqn1UhaC6@l21YyX@QioOmTE7o1WM6m7@@kTVnQarsNu3FJM0T5l17LCkbLXymFkNVKUZpRuyoUuJmKctMzqlzibmquwGWrF2N9j@owVZYmQIfDuqPXJumu6MV1w/ihyhWveXUHHESnrCIwsdwPDqETPj4@mj3VxMj8/fcD9QCZe@YJQkgn2rG5h1N4RBpCL040dPzyl0eL8B9di8w/WiRSVetmDv/16KL36vB0rqqn6HRO5u/mqPt@bt0c61291XpFuM6veesVfx/1LeLp3dYhv9G7xGt719al3lKRShYXJ2TR5sh7u/ixUIeqRe5@HIIEcqd379qwAS0uIgCDgkhFQ5VE7yJQEl2qJrxdqur/AQ) [Test Suite](https://tio.run/##lVhrV9u4Fv08/Arh22IrNk4CXb2rMSKlDO2whgam0GHdm6RFtpXErWOnfgBt4v515shPOQ/ofAm2tXVe2uchvtBbGlqBM4t2Pd9mD5ZLwxD96TnjSXQSBH6A2H3EPDtE6ds8yQAXNAhZfV3YU6A@xF7kTJ/GXUYBo9O55XthFMRW5AcKxfNo4oR66MeBxQhNYMWZXU@ciIUzajElX5/SyJoozU9KfzAc9AchfE86Q3Xxn/6ngTdsKANv8QzjRhMnM8a@wmrAojjwkCC83xouFl7sukkmzNQs0sJzl0WIElNn98xSBDg2chF8CyGEdvlDR4QQ4VkPYxNsVyio0V3mjaMJ1mjfGuIk8sFxxxuvtSpJ0nCgq/9dnFyS/tDIQvU3dWM2DyMaORaa8VNQTDw39ZXwGCOI4i0NwIeWQQ9SMbl@g6pq5p9F0u99OtQLWYYzUiyc22Mlgq9JEHtp2AP/DnnsLmNEYjMzHq/5vsG7VIheLQKuF09NFmzAFYuAe@P7LqPeBmC5muSsOoNgBNQtiZeFbolkYTzj0rVU1GebRhS4ljkqKFnjTP5e7VvnSf5eB624UXwQYeyby83LERQ5YDX1LOaPMq8FN3Z2BOOBj9lTEQUuvAxBHpIV/hRcr7Lp6u0Q9492/z9sNLV2SXm6s8MPmMtUpCuJa8OJHU9npTM3hTPP0vxM8E3iRpPKle3K1p0dWju2sYhDIm67DkwyMs/icKLwr9jIUuWk9/fph/Pe@5PeFZknecKc2syLljjwlPt9uvvj85D/tnZffYYQLAcgFQrGJo@xyeEgYFM9PulWZ@QALgtRhuOBAnOdscflCJ70K8ywpGZm8AYUz@Bb37FRa5ufT2G5USWoWJeVm4/eV8@/85BTWobkmmnyTT3mqQu4iK8Q3V@l18BWV0MKAc3TheJlUuULFaeobQtcKfZXnFGpUDpwAjX4UfhuHT6N3UfhjTrcdm5FL6slfhK1QyhEvafRRAfeeJYgtQl@bzok6Zh6nh8hUAVngszv6AcLfAlM9e1/qbtS@Jw@qQ/Ex64v6Jv5d4/rq8QvFtsKPWjhX3K@0fgF79n9zPc4SWnEUoNQ5ENt9NgY@HbLEBjHAjDS3VBJDsRz21hvDmuoGvEr2vegIT7Oe6F6l8Tv5SUVZ5znQmolpKggvN0u5YDEwQqWHusMqbzc@SdCaflTMJOlW3SpDMa/3CUGh38rogPN8cngcAqZhAo9R5KHGOa4cHA5bHTxoN3U9lJa8WgAs0yRSKCBDyvZEEP1bLjjYEnmbclaLGRJ5g@4cqkaWnnRA6umjgdMstG32AdCMc/yY/6Z2R30bE6Tm3UtPbW/nkdau4UXi9ZSzcoHhMdqFnfiJgfkCldLDwdVuvSAzRiF3iNWoCcYX45ajzK@RImHCh/z7gq7qH353bM6NCEB@xY7AVOkUShhbc5H5HTJFJasiePan2eBb7GQo95@7B1fnZ73Lqve/BZqwGOtWWBJdsAwmZdi@qbQ6dKTFmZVQ@BVt5NmnbrQcTNjDOPzNJ@P@YsN87F9YBWzsV3MxiOSWqQXpnBl26MNdHrvQO/2xogG43jKB45nc1ttJwiUoBH3EjqqyRupwbLAjnAinDEPhGJppsaWRgr4ZC2NFVwcodmzR6eMmNkzqA6JtTq7phsUXddLVFlZsiouce2R43uKpJZSy/CYqBg5061UJZKGJNXUMxllF1elldp0bn5hVqQ7YcpfDcalZJSrQgEbO2HEUhfxHELb5r2quCAt3SUUqQcmoWkMQ54JiXpPrcj9jqAXIGtCA3iDmcX1vTHUJKMiCB0SU9AIgSk7l3i0eZLBDVQxhTzAYu2pxqjsvmGspYHU89EtlwyFMnZtbmuqwt6GWilkFQ841soQSBeSpmBymF/JJEkzyZt4NGKBTl3XtxQYwG2fB4kqLWBECyZyDShvwpUSm2D4V8NSwdU7yDimtKELpyvpTU7nuXXtQOJLA0/C2CKWHroO3BBbGtqtJvui0lg4ES37kFlWa90j1wdfX@y9evHq5X/3Xr1spF8D6tn@lIdN3H8iaZQc8pDRWmgriHwkc0iZ6Fl4c6tMsbuBAd3CzEySPgr86TEw4Ni3YdDM7064U5grHqdu5bijiM9sopFvUiOp@Ok4@5RfLtNfcfkmXS77UN25DY5Kf6Wb8oKos3tnuYoL2O1SQXrXql@AasizEsk9Fg0pkklE/865dViOb7VgF5aFke3HkX4XQOMGgVmeY43WYnZeF1RpzaVJg0F6PczJBkzrbpBfsBEguLMWc8N749YN1sqZSbREBYryIlIdF2@0uW8153dXkPxesA7ZWEHyvrwO2VxBpreBNcjnqzL99XZ@WkGmU/ca5EGJLKlSbOETQblF3HO4ec94057u5j285K/ds1PuUWiR17X/03TzbZ1a5i2e3EY75mpGGsK2bFVbFzAiwGq1hV9pFwtQKVzv64lM9fx@bpJSv1kTfl0Kn/PuadSS1sBL6baWzKeZCGj65JCuDZa16vs7YVMatMpuzaxd0jRe/oXXooLR4r@UXMhiIUn1qF3mCuxURbHpCVU2sVc1l@Ci1fOxvktVmCoLE6DDYdVSK5NUm/fiqmH8lMWKV7@6Aw6iU1QRmFhu@3vQCR8eHqhp2Ww03sr/Tra6yny@syfvyZ057mw3sdxobv1hMMM1bKNhBIZvXLsG/DZe7O8br/VDY2//YPDCAJTelXWM9Nevm3IT6dv6IUJIJcqBvo0TeEQKQs8OFXTwfOvBICP05uz8@M@t3wzi/WwbZHZhkFCWjesZ/FXD0@7@3tFMlo/Q0YzM3s1Q@2xmXB@obbXR2Cee6l15jX3vLOwZxFHbjT3vWm0TZ9e5Ms7Vhoxkcn96SO53PeS8vf95Lw9kg3z5uQcSyBe1/WUXNqD70xDAoCCU0UAm4bsQlITnsg5v57K8tWWQH6i1df3H6dkJOkAKQT@QoqI2@oExegmGHx@dnaHR1m/nH68uPl4hWf4H) ]
[Question] [ [Portable Spec](https://gist.github.com/Maltysen/70f56bdbaa82f308cb03). *Iɴꜱᴘɪʀᴇᴅ ʙʏ @ConorO'Brien's ᴜꜱᴇʀɴᴀᴍᴇ.* *Aʟꜱᴏ ᴛʜᴀɴᴋꜱ ᴛᴏ @Dᴏᴏʀᴋɴᴏʙ ꜰᴏʀ ꜱʜᴏᴡɪɴɢ ᴍᴇ ᴛʜᴇ ᴇxɪꜱᴛᴇɴᴄᴇ ᴏꜰ `ǫ` ᴀɴᴅ `x`.* Sᴍᴀʟʟ Cᴀᴘꜱ ᴀʀᴇ ᴘʀᴇᴛᴛʏ ᴄᴏᴏʟ. Tʜᴇʏ ᴀʀᴇ ᴜɴɪᴄᴏᴅᴇ ᴄʜᴀʀᴀᴄᴛᴇʀꜱ ᴛʜᴀᴛ ʀᴇᴘʟᴀᴄᴇ ꜱᴍᴀʟʟ ʟᴇᴛᴛᴇʀꜱ. Tʜᴇʏ ʟᴏᴏᴋ ᴊᴜꜱᴛ ʟɪᴋᴇ ᴛʜᴇ ᴄᴀᴘɪᴛᴀʟ ᴏɴᴇꜱ, ʙᴜᴛ ꜱᴍᴀʟʟᴇʀ, ᴀɴᴅ ʟᴏᴏᴋ ʀᴇᴀʟʟʏ ᴏꜰꜰɪᴄɪᴀʟ. Yᴏᴜʀ ᴛᴀꜱᴋ ɪꜱ ᴛᴏ ᴡʀɪᴛᴇ ᴀ ᴘʀᴏɢʀᴀᴍ ᴛʜᴀᴛ ᴄᴏɴᴠᴇʀᴛꜱ ʀᴇɢᴜʟᴀʀ ᴛᴇxᴛ ɪɴᴛᴏ ꜱᴍᴀʟʟ ᴄᴀᴘꜱ. Hᴇʀᴇ ɪꜱ ᴀ ʟɪꜱᴛ ᴏꜰ ᴛʜᴇ ᴜɴɪᴄᴏᴅᴇ ᴄʜᴀʀᴀᴄᴛᴇʀꜱ ꜰᴏʀ ꜱᴍᴀʟʟ ᴄᴀᴘꜱ: ``` ᴀ ʙ ᴄ ᴅ ᴇ ꜰ ɢ ʜ ɪ ᴊ ᴋ ʟ ᴍ ɴ ᴏ ᴘ ǫ ʀ ꜱ ᴛ ᴜ ᴠ ᴡ x ʏ ᴢ ``` ## Cʟᴀʀɪꜰɪᴄᴀᴛɪᴏɴꜱ * Rᴇɢᴜʟᴀʀ ᴄᴀᴘꜱ ʀᴇᴍᴀɪɴ ʀᴇɢᴜʟᴀʀ ᴄᴀᴘꜱ ᴀɴᴅ ꜱᴏ ᴅᴏ ᴘᴜɴᴄᴛᴜᴀᴛɪᴏɴꜱ, ꜱᴘᴀᴄᴇꜱ, ᴇᴛᴄ. * Iɴᴘᴜᴛ ᴄᴀɴ ʙᴇ ᴍᴜʟᴛɪᴘʟᴇ ʟɪɴᴇꜱ. * Tʜɪꜱ ɪꜱ [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), ꜱᴏ ꜱʜᴏʀᴛᴇꜱᴛ ᴄᴏᴅᴇ ɪɴ **ʙʏᴛᴇꜱ** ᴡɪɴꜱ! ## Tᴇꜱᴛ Cᴀꜱᴇꜱ ``` Hello World -> Hᴇʟʟᴏ Wᴏʀʟᴅ abcdefghijklmnopqrstuvwxyz -> ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ Welcome to Programming Puzzles and Code Golf Stackexchange! It is a website -> Wᴇʟᴄᴏᴍᴇ ᴛᴏ Pʀᴏɢʀᴀᴍᴍɪɴɢ Pᴜᴢᴢʟᴇꜱ ᴀɴᴅ Cᴏᴅᴇ Gᴏʟꜰ Sᴛᴀᴄᴋᴇxᴄʜᴀɴɢᴇ! Iᴛ ɪꜱ ᴀ ᴡᴇʙꜱɪᴛᴇ. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 73 bytes ``` T`a-z`ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ ``` This is exactly what Retina's transliterate mode was made for. It replaces all lowercase letters (`a-z`) with their corresponding small caps version. Annoyingly, the character codes of the small caps characters are all over the place, so it can't take advantage of ranges for the second part: ideally it would be `T`a-z`ᴀ-ᴢ`. [Try it online.](http://retina.tryitonline.net/#code=VGBhLXpg4bSAypnhtIThtIXhtIfqnLDJosqcyarhtIrhtIvKn-G0jcm04bSP4bSYx6vKgOqcseG0m-G0nOG0oOG0oXjKj-G0og&input=SGVsbG8gV29ybGQKCmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6CgpXZWxjb21lIHRvIFByb2dyYW1taW5nIFB1enpsZXMgYW5kIENvZGUgR29sZiBTdGFja2V4Y2hhbmdlIQpJdCBpcyBhIHdlYnNpdGU) [Answer] # Pyth, ~~61~~ ~~59~~ 58 bytes ``` LXbGsmC+*7389<dGCd"#ʙ'(*ꜰɢʜɪ-.ʟ0ɴ2;ǫʀꜱ>?CDxʏE ``` This defines a named function `y`. Try it online in the [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=LXbGsmC%2B%2a7389<dGCd"%23%CA%99%27%28%2a%EA%9C%B0%C9%A2%CA%9C%C9%AA-.%CA%9F0%C9%B42%3B%C7%AB%CA%80%EA%9C%B1>%3FCDx%CA%8FE"%0Ayj.z&input=Hello+World%0Aabcdefghijklmnopqrstuvwxyz). The code contains no unprintable characters. ### Idea Among the small caps, there are 14 characters in the range **7424 – 7458**, and all of them require three bytes to be stored verbatim. By subtracting **7389** from their code points, we map them in the printable ASCII range **35 – 69**, so each of them will occupy only one byte. To decode the string, we simply add **7389** to the code points of all characters that come before **a**. ### Code ``` L Define y(b): Xb Transliterate b... G by replacing the lowercase ASCII letters... with the characters of result of the following: m "… Map; for each d in that string: *7389<dG Calculate (7389 * (d < 'abc...xyz')). + Cd Add the product to int(d). C Cast to character. s Turn the resulting char array into a string. ``` [Answer] ## Javascript (ES6), 114 bytes ``` a=>a.replace(/[a-z]/g,b=>'ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ'[b.charCodeAt()-97]) // snippet var o = document.getElementById("o"); var t = document.getElementById("t"); t.onkeyup = _=>o.textContent = (a=>a.replace(/[a-z]/g,b=>'ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ'[b.charCodeAt()-97]))(t.value); ``` ``` <!-- snippet --> <input id="t" placeholder='Sample Text' /> <pre id="o"></pre> ``` [Answer] # CJam, ~~78~~ ~~74~~ ~~67~~ ~~66~~ 63 bytes ``` q'{,97>"#ʙ'(*ꜰɢʜɪ-.ʟ0ɴ2;ǫʀꜱ>?CDxʏE"{_'a<7389*+}%er ``` This uses the same idea as [my other answer](https://codegolf.stackexchange.com/a/60458). The code contains no unprintable characters. Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q'%7B%2C97%3E%22%23%CA%99'(*%EA%9C%B0%C9%A2%CA%9C%C9%AA-.%CA%9F0%C9%B42%3B%C7%AB%CA%80%EA%9C%B1%3E%3FCDx%CA%8FE%22%7B_'a%3C7389*%2B%7D%25er&input=Hello%20World%0Aabcdefghijklmnopqrstuvwxyz). ### How it works ``` q e# Read all input and push it on the stack. '{, e# Push the range of all characters up to 'z'. 97> e# Remove the first 97 characters. This leaves lowercase letters. "#ʙ'(*ꜰɢʜɪ-.ʟ0ɴ2;ǫʀꜱ>?CDxʏE" { e# Map; for each character in that string: _'a< e# Check if a copy of the character is lower than 'F'. Pushes 1 or 0. 7389* e# Multiply the resulting Boolean by 7389. + e# Add the product to the character's code point. }% e# er e# Perform transliteration; replace each letter in the input by the e# corresponding character of the modified string. ``` [Answer] # [Python 3](https://docs.python.org/3/), 140 bytes ``` import sys;print(sys.stdin.read().translate(dict(zip(range(97,123),'ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ')))) ``` [Try it online!](https://tio.run/nexus/python3#DYlBCoJAFECv0s4RRKgWEZ3G0mxKx2lmKnXlogiKaFskVC5rU/DvEM4t/tZL2LzV472WxjwRqiMzOeKCMkWMuVL5lLki8Hxiu0p4TEaeCohPJ4rklBNTwoAMB06317cdC6HQV4Qtwg5h35SfutJl/UI4IBz1HeFUA8IZ4fJ766Ipvwg3hBLhgfBMtRmVZRva1htP/GAazuh8EcUs4Ush1Wq9SbP8Dw "Python 3 – TIO Nexus") Hooray for built-in Unicode support! Now works with multi-line input. *-10 bytes thanks to @Bakuriu* [Answer] ## [><>](http://esolangs.org/wiki/Fish), ~~118~~ 116 Bytes -2 bytes thanks to @torcado. I'll try to think of a way to remove that entire alphabet from my code later. I haven't been able to test it with newlines, but I see no reason for it not working with them. ``` !oi:0(?;::"{"($"`")*0$. v"a"%&"ᴢʏxᴡᴠᴜᴛꜱʀǫᴘᴏɴᴍʟᴋᴊɪʜɢꜰᴇᴅᴄʙᴀ"& >:?!v1-$~ ~00.> ``` Try it [online](http://fishlanguage.com/playground). Emoticons found in the code: `0:(`, `:0`, `:"{`, `>:`, `0=`, and the debatable ones: `i:`, `>:?`, `:?`, `?;` [Answer] # Julia, 126 bytes ``` t->join([(i=Int(c);96<i<123?split("ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ","")[i-96]:c)for c=t]) ``` Ungolfed: ``` function f(t::AbstractString) # Split the small caps into an array (this particular Unicode # string does not like to be indexed for whatever reason) s = split("ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ", "") # Create an array with replaced letters r = [(i = Int(c); 96 < i < 123 ? s[i-96] : c) for c in t] # Join the array back into a string join(r) end ``` [Answer] ## Perl 5, 84 bytes **(83 bytes script and `-p`)** ``` use utf8;y/a-z/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/ ``` Nothing particularly different, but it's worth noting the necessity of the `use utf8;` statement to get legible text. A warning is displayed as well, but I believe the consensus is that they are acceptable: ``` $perl -p smallcaps.pl <<< 'Programming Puzzles and Code Golf' Wide character in print, <> line 1. Pʀᴏɢʀᴀᴍᴍɪɴɢ Pᴜᴢᴢʟᴇꜱ ᴀɴᴅ Cᴏᴅᴇ Gᴏʟꜰ $perl -p smallcaps.pl <<< 'Programming Puzzles and Code Golf' 2> /dev/null Pʀᴏɢʀᴀᴍᴍɪɴɢ Pᴜᴢᴢʟᴇꜱ ᴀɴᴅ Cᴏᴅᴇ Gᴏʟꜰ ``` --- ## Perl, 80 bytes **(74 bytes script and `-pMutf8`)** Thanks [@hobbs](https://codegolf.stackexchange.com/users/1683/hobbs)! ``` y/a-z/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/ ``` ``` $perl -pMutf8 -e'y/a-z/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/' <<< 'Programming Puzzles and Code Golf' 2> /dev/null Pʀᴏɢʀᴀᴍᴍɪɴɢ Pᴜᴢᴢʟᴇꜱ ᴀɴᴅ Cᴏᴅᴇ Gᴏʟꜰ ``` [Answer] ## 05AB1E, 73 bytes (non-competing) Yet again, I wish Adnan had published this language earlier. ``` A"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"‡ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=QSLhtIDKmeG0hOG0heG0h-qcsMmiypzJquG0iuG0i8qf4bSNybThtI_htJjHq8qA6pyx4bSb4bSc4bSg4bSheMqP4bSiIuKAoQ&input=SGVsbG8gV29ybGQ) Explanation: ``` A - Push a-z "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ" - Push "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ" ‡ - Pop a, b, c Push a.transliterate(b -> c) ``` [Answer] # Ruby, 89 bytes ``` p ARGV[0].tr "a-z","ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ" ``` To use: ``` ruby <file-name> "<string>" ``` [Answer] # Julia, 105 bytes ``` t->map(c->96<c<123?["ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"...][c-'`']:c,t) ``` This is simple - for each character in `t`, it checks to see if the character, `c`, is lowercase (`96<c<123`) - if it is, it subtracts the character with value 96 (`'`'`) from the character, and looks up the corresponding character in the array `[ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"...]`. If it's not lowercase, then just use `c` itself. The `map` function applies this procedure for each character in the string. Alternative, if we can restrict input to ASCII less than 127: ### Julia, 104 bytes ``` t->join(['\1':'`';"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ{|}~"...][t.data]) ``` In this case, the array is longer, including all characters between ASCII 1 (`'\1'`) and 126 (`'~'`), with the lowercase letters replaced as appropriate - it then uses the characters in `t`, expressed as unsigned integers (`t.data`), to lookup the values in the array, and `join`s the new characters back into a string at the end. [Answer] # Sed, 97 bytes ``` y/abcdefghijklmnopqrstuvwxyz/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/ ``` [Answer] # Java, ~~306~~ ~~275~~ ~~217~~ ~~215~~ 189 bytes Well, Java is definetely not the best language to accomplish this task in... but, here it is anyway: ``` void p(String s){for(int i=1;i<27;s=s.replace("abcdefghijklmnopqrstuvwxyz".charAt(++i),"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ".charAt(i)));System.out.print(s); ``` Thanks to @ThomasKwa and @DHall for help in shaving off 91 characters! [Answer] # [Scala](http://scala-lang.org/), 125 bytes ``` (s:String)=>s.map(c=>('a'to'z'zip "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"toMap).getOrElse(c,c)) ``` An anonymous function that has string as an input and output. Iterate through its chars and get the unicode version of them by matching them from dict/map. Return original char if the unicode one doesn't exist. ### Usage 1. Open Scala REPL and paste the code above 2. It will create a function (`resX`) that can be called by passing a string (e.g. `resX("my String")`) [Answer] ## Perl 6, 78 bytes The simplest command line version: ``` $ perl6 -pe'tr/a..z/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/' # 76 + 2 = 78 ``` It gets a bit larger if you put it into a file. ``` $_=$*IN.slurp-rest;tr/a..z/ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ/;.print # 102 ``` [Answer] # [Sacred JavaScript ES6](http://esolangs.org/wiki/Sacred), 600 Bytes Hey look, [I answered!](https://codegolf.stackexchange.com/questions/60443/s%E1%B4%8D%E1%B4%80%CA%9F%CA%9F-c%E1%B4%80%E1%B4%98%EA%9C%B1-c%E1%B4%8F%C9%B4%E1%B4%A0%E1%B4%87%CA%80%E1%B4%9B%E1%B4%87%CA%80#comment145438_60443) ``` ( ))) ) )( ) ))( ))) () ((( (( ()((( ))( ) ( )() (((( () ) () ( () )( )(( ((() () ((( (( ()((( (( (((((((() ) )( ) ))(( )( ) )((( ) ( () )( )(( ) (( ) ( ()(((((( (((( ()() ) ((() ( () () (( )( ( )) (( (( (((( ()( ((() () ((( (( ()((( (( (((( (((((( () (())( ) ) ((() ) )( ) )) ( )((()))) ())() ( () ((() ) ( ()((()() ) )(()) ()( ()( () )()()(( () )(()(()())() ()()) ( ( ) ())))) ) (() ()(((( ) )() ) ( )(( ( (( ) )( (( ((()( ( ((((() () (( ) ( )()( ()((( ) )((((( ( ( ) (( ) ) )( )(( )) (((( ((() () ) ( ) (( (( ((()(((()((((() ((() () (( ))((( ( ( )) (( )( () ( () ``` Here's a cool image: ![](https://i.stack.imgur.com/6rJwl.png) # JavaScript ES6, 120 Bytes This is the code. ``` k=>k.match(/./g).map(z=>new Array(26) .fill(0).map((q,e)=>"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"[e])[z.charCodeAt()-97]||z).join``) ``` This is the snippet. ``` while(1)alert(prompt().match(/./g).map(z=>new Array(26) .fill(0).map((q,e)=>"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"[e])[z.charCodeAt()-97]||z).join`` ``` [Answer] # Python, 99 bytes ``` def s(t):return"".join([(a,"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"[(ord(a)+7)%26])[96<ord(a)<123] for a in t]) ``` I tried to find some pattern in the Unicode codes for small capitals, but I'm not sure there is one. [Answer] # [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~81~~ ~~80~~ ~~78~~ 75 [bytes](https://en.wikipedia.org/wiki/UTF-8) ``` r\aÈcg"ʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢᴀʙᴄᴅᴇꜰɢ ``` * Saved 2 bytes thank to [ETHproductions](https://codegolf.stackexchange.com/users/42545/ethproductions) [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=clxhyGNnIlx1MDI5Y1x1MDI2YVx1MWQwYVx1MWQwYlx1MDI5Zlx1MWQwZFx1MDI3NFx1MWQwZlx1MWQxOFx1MDFlYlx1MDI4MFx1YTczMVx1MWQxYlx1MWQxY1x1MWQyMFx1MWQyMXhcdTAyOGZcdTFkMjJcdTFkMDBcdTAyOTlcdTFkMDRcdTFkMDVcdTFkMDdcdWE3MzBcdTAyNjI&input=IldlbGNvbWUgdG8gUHJvZ3JhbW1pbmcgUHV6emxlcyBhbmQgQ29kZSBHb2xmIFN0YWNrZXhjaGFuZ2UhCkl0IGlzIGEgd2Vic2l0ZSI) [Answer] # [Raku](https://raku.org/), 69 bytes ``` {S:g[(q)|<[a..wyz]>]=$0??'ǫ'!!'ᴀ'.uniname.subst(/.$/,$/).uniparse} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqPVqjULPGJjpRT6@8sirWLtZWxcDeXv34anVFRfWHWxrU9UrzMvMSc1P1ikuTiks09PVU9HVU9DVBwgWJRcWptf@LEysV0jTUE5OSU1LT0jMys7JzcvPyCwqLiktKy8orKqvUNf8DAA "Perl 6 – Try It Online") Special handling for `q`; for other lowercase letters other than `x`, generate the Unicode name for the small caps (eg, `LATIN LETTER SMALL CAPITAL S`) and parse it. I saved a few bytes by using the Unicode name of the character `ᴀ` (`LATIN LETTER SMALL CAPITAL A`) as a template, and replacing the final character with the letter I want to convert. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `U`, 56 bytes ``` ka`#Ẏṗ'(*¥ṫ§Ẋ⟨ẎṫẊ₅-.Ẏẏ0Ẋ¦2;Ṫ₆Ẏ↓¥ṫε>?CDxẎḋE`C:70<7389*+CĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJVIiwiIiwia2FgI+G6juG5lycoKsKl4bmrwqfhuorin6jhuo7huavhuorigoUtLuG6juG6jzDhuorCpjI74bmq4oKG4bqO4oaTwqXhuavOtT4/Q0R44bqO4biLRWBDOjcwPDczODkqK0PEvyIsIiIsIkhlbGxvIFdvcmxkIl0=) Port of CJam. ## How? ``` ka`#Ẏṗ'(*¥ṫ§Ẋ⟨ẎṫẊ₅-.Ẏẏ0Ẋ¦2;Ṫ₆Ẏ↓¥ṫε>?CDxẎḋE`C:70<7389*+CĿ ka # Push the lowercase alphabet `#Ẏṗ'(*¥ṫ§Ẋ⟨ẎṫẊ₅-.Ẏẏ0Ẋ¦2;Ṫ₆Ẏ↓¥ṫε>?CDxẎḋE` # Push string "#ʙ'(*ꜰɢʜɪ-.ʟ0ɴ2;ǫʀꜱ>?CDxʏE" C # Convert to character codes: [35, 665, 39, 40, 42, 42800, 610, 668, 618, 45, 46, 671, 48, 628, 50, 59, 491, 640, 42801, 62, 63, 67, 68, 120, 655, 69] : # Duplicate 70< # For each, is it less than 70? 7389* # Multiply by 7389 + # Add C # Convert from character codes Ŀ # Transliterate the implicit input from the lowercase alphabet to this ``` Previous answer: ## [Vyxal](https://github.com/Vyxal/Vyxal), 61 bytes ``` ka»7ȧ∵ẋǍ}Żq(ṗ⌐>⁋8≤M?↵:‡⌊&fǍ≈⁋D5£ɾ|øP₂@ġĿ≤ǔxτ¶_ṙɾ|ȧ.,=»»₃↲»τCĿ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrYcK7N8in4oi14bqLx419xbtxKOG5l+KMkD7igYs44omkTT/ihrU64oCh4oyKJmbHjeKJiOKBi0Q1wqPJvnzDuFDigoJAxKHEv+KJpMeUeM+EwrZf4bmZyb58yKcuLD3Cu8K74oKD4oaywrvPhEPEvyIsIiIsIkhlbGxvIFdvcmxkIl0=) ## How? ``` ka»7ȧ∵ẋǍ}Żq(ṗ⌐>⁋8≤M?↵:‡⌊&fǍ≈⁋D5£ɾ|øP₂@ġĿ≤ǔxτ¶_ṙɾ|ȧ.,=»»₃↲»τCĿ ka # Push the lowercase alphabet »7ȧ∵ẋǍ}Żq(ṗ⌐>⁋8≤M?↵:‡⌊&fǍ≈⁋D5£ɾ|øP₂@ġĿ≤ǔxτ¶_ṙɾ|ȧ.,=» # Push compressed integer 454193002670633612531343815167055208136573147142298478503419521655224802790872780438775790455172058745698867697958481400 »₃↲» # Push compressed integer 42802 τ # Convert the big integer to that custom base as a list: [7424, 665, 7428, 7429, 7431, 42800, 610, 668, 618, 7434, 7435, 671, 7437, 628, 7439, 7448, 491, 640, 42801, 7451, 7452, 7456, 7457, 120, 655, 7458] C # Convert it from character codes to characters Ŀ # Transliterate the implicit input from the lowercase alphabet to that ``` [Answer] # Lua, 160 bytes ``` function c(a) return a:lower():gsub("%w",function(d)b=a.byte(d)-96;return("ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"):sub(b,b)end)end ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jellylanguage), 65 bytes ``` “⁾ḋḷ?D8=ƙʂȤ£²^ĖẸI)¡e[µ°⁾ṢJ*MĠɓ¤Ḃġ⁽vEEɲạ®G{(ŀ³⁻¹ƭTẸⱮ’ṃ“ȥ3’Ọ Øaż¢Fy ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FjfrHzXMedS47-GO7oc7ttu7WNgem3mq6cSSQ4sPbYo7Mu3hrh2emocWpkYf2npoA0jZzkVeWr5HFpycfGjJwx1NRxY-atxb5up6ctPDXQsPrXOv1jjacGjzo8bdh3YeWxsC1Pxo47pHDTMf7mwG2nJiqTGIvbuH6_CMxKN7Di1yqwRKLylOSi6GOmZ9tJIH0HH5CuH5RTkpSrFQYQA) ``` “⁾ḋḷ?D8=ƙʂȤ£²^ĖẸI)¡e[µ°⁾ṢJ*MĠɓ¤Ḃġ⁽vEEɲạ®G{(ŀ³⁻¹ƭTẸⱮ’ṃ“ȥ3’Ọ : Link 1 “⁾ḋḷ?D8=ƙʂȤ£²^ĖẸI)¡e[µ°⁾ṢJ*MĠɓ¤Ḃġ⁽vEEɲạ®G{(ŀ³⁻¹ƭTẸⱮ’ : Compressed integer for 454193002670633612531343815167055208136573147142298478503419521655224802790872780438775790455172058745698867697958481400 “ȥ3’ : Compressed integer for 42802 ṃ : Base decompression; convert x to base length(y) then index into y; results in character codes Ọ : Cast to characters Øaż¢Fy : Main Link Øa : Lowercase alphabet ¢ : Last link as a nilad ż : Zip; interleave x and y F : Flatten list y : Translate the elements of y according to the mapping in x; change the characters ``` Integers used to get the character codes borrowed from [Steffan's](https://codegolf.stackexchange.com/users/92689/steffan) [Vyxal Answer](https://codegolf.stackexchange.com/a/248389/106844) ]
[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/3105/edit). Closed 6 years ago. [Improve this question](/posts/3105/edit) Your task is to draw the mandelbrot set in ascii. It should look something like ![enter image description here](https://i.stack.imgur.com/GPzpD.png) The complex number `c` lies in the mandelbrot set, when the sequence `z(n+1) = z(n)^2 + c`, `z(0) = 0` remains bounded. For the purpose of this challenge you can consider the sequence bounded for `c` if `|z(32)| < 2`. Plot the mandelbrot set on the complex plane from (-2 - i) to (1 + i), and a minimum resolution of 40x30, using ascii characters in your favourite language, using as few characters as possible. [Answer] ## C, 988 chars Here's mine, which does an ASCII mandelbrot, written as an ASCII mandelbrot, in C. Oh.. and it also has interactive zoom functionality. (press the keypad numbers 1-9 to zoom in on the respective area) ``` int main(int argc, char* argv[]){ unsigned char c='r';double x1,y,y1,t=0,q=78,r=22,x, x2,y2,a,b,v;do{(c=='r')?(y2=-(y1=-1.6),x1= -2.0f,x2=0.8):(c=='?')? c=0, printf("%f\ ,%f:%f,%f",x1,y1,x2,y2):(c <':'&&c>48) ?x=x1,y=y1,*(c>'3'&&c<':' ?&y1: &t) +=(y2-y1)/3,*(c>'6'&&c< ':'?&y1 :&t)+=(y2-y1)/3, *((c == '8' ||c+3=='8'||c+3 +3== '8'?&x1 :&t))+=(x2-x1 )/ 3,*((c =='9'||c+3== '9'||c +6=='9' ?&x1: &t) )+=2*(x2-x1) /3,x2= x1+(x2-x)/3, y2 =y1+( y2-y)/3:(c=0);for(y= y2;y>= y1&&c;c=1,y-=(y2-y1)/r, putchar ('\n')) for(x=x1;x<=x2; x+=(x2- x1)/q){a=b=c=0; while ( ++c&&(a=(t =a)*a)<4&&(v=b*b)<4)a-=v-x ,b=y+b*2*t; putchar("#@XMW*N&KPBQYKG$R" "STEEVxHOUV" "CT()[]%JL={}eou?/\\|Ili+~<>_-^\"!;:`,. "[ c?c>>2:63]);}} while((c=getchar ())!='x'); return 0;/* Mandelbrot - S.Goodwin.2001*/} ``` Originally posted here <http://marquisdegeek.com/rnd_obs.php> [Answer] **Common lisp -- 195 chars** ``` (loop for y from -1 to 1 by 1/15 do (loop for x from -2 to 1 by .04 do (let*((c 126) (z (complex x y)) (a z)) (loop while (< (abs (setq z (+ (* z z) a))) 2) while (> (decf c) 32)) (princ (code-char c)))) (terpri)) ``` Tested with sbcl and clisp. Result: ``` ~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}||||||||{{{zyvrwum{|||||}}}}}}~~~~~~~~~~~~~ ~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}|||||||||{{{zyxvptwyz{{|||||}}}}}}~~~~~~~~~~~ ~~~~~~~~~}}}}}}}}}}}}}}}}}}}}|||||||||{{{{zwLtb huwx{{{{||||}}}}}}}~~~~~~~~~ ~~~~~~~~}}}}}}}}}}}}}}}}}}}|||||||||{{zzzyxvn Knwyz{{{{||||}}}}}}~~~~~~~~ ~~~~~~~}}}}}}}}}}}}}}}}}}||||||||{{zzzzyyywuk qwxyzzzz{{|||}}}}}}~~~~~~~ ~~~~~}}}}}}}}}}}}}}}}}}|||||||{{{zxjnpwwtjsqpi lqrujnxyyxrz{|}}}}}}}}~~~~~ ~~~~}}}}}}}}}}}}}}}}}|||||{{{{{zzzxt> qf pttfqeqz{|}}}}}}}}~~~~ ~~~~}}}}}}}}}}}}}}}|||{{{{{{{{zzzxwup sxz{||}}}}}}}~~~~ ~~~}}}}}}}}}}}}|||{z{{{{{{{zzzzywkmo rwyz{{||}}}}}}}~~~ ~~}}}}}}}}}||||{{zwvyyyyyyyyyyyxvsP swvz{||}}}}}}}}~~ ~~}}}}|||||||{{{zzwrtsww^uwwxxwvr iz{|||}}}}}}}~~ ~}}}|||||||{{{{{zyxws mj Ubhuutl sxz{|||}}}}}}}}~ ~}||||||||{{{{{zyytun qq avz{|||}}}}}}}}~ ~|||||||{{zzzyxsvvum j Sz{{|||}}}}}}}}~ ~{{{{{yyzzzyyxwtbUP qyz{{||||}}}}}}}~ ~ pvxyz{{||||}}}}}}}} ~{{{{{yyzzzyyxwtbUP qyz{{||||}}}}}}}~ ~|||||||{{zzzyxsvvum j Sz{{|||}}}}}}}}~ ~}||||||||{{{{{zyytun qq avz{|||}}}}}}}}~ ~}}}|||||||{{{{{zyxws mj Ubhuutl sxz{|||}}}}}}}}~ ~~}}}}|||||||{{{zzwrtsww^uwwxxwvr iz{|||}}}}}}}~~ ~~}}}}}}}}}||||{{zwvyyyyyyyyyyyxvsP swvz{||}}}}}}}}~~ ~~~}}}}}}}}}}}}|||{z{{{{{{{zzzzywkmo rwyz{{||}}}}}}}~~~ ~~~~}}}}}}}}}}}}}}}|||{{{{{{{{zzzxwup sxz{||}}}}}}}~~~~ ~~~~}}}}}}}}}}}}}}}}}|||||{{{{{zzzxt> qf pttfqeqz{|}}}}}}}}~~~~ ~~~~~}}}}}}}}}}}}}}}}}}|||||||{{{zxjnpwwtjsqpi lqrujnxyyxrz{|}}}}}}}}~~~~~ ~~~~~~~}}}}}}}}}}}}}}}}}}||||||||{{zzzzyyywuk qwxyzzzz{{|||}}}}}}~~~~~~~ ~~~~~~~~}}}}}}}}}}}}}}}}}}}|||||||||{{zzzyxvn Knwyz{{{{||||}}}}}}~~~~~~~~ ~~~~~~~~~}}}}}}}}}}}}}}}}}}}}|||||||||{{{{zwLtb huwx{{{{||||}}}}}}}~~~~~~~~~ ~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}|||||||||{{{zyxvptwyz{{|||||}}}}}}~~~~~~~~~~~ ~~~~~~~~~~~~~}}}}}}}}}}}}}}}}}}}}||||||||{{{zyvrwum{|||||}}}}}}~~~~~~~~~~~~~ ``` Slightly modified from B. Clementson [blog](http://bc.tech.coop/blog/040811.html). [Answer] **Python, 146 145 143char** ``` z=lambda x,c,n:z(x**2+c,c,n-1)if n*(abs(x)<2)else x for y in range(-15,16):print''.join(' @'[abs(z(0,x/25.+y/15j,32))<2]for x in range(-50,26)) ``` Had to add the clause (abs(x)<2) to the conditional expression to keep Python from winging about overflows. But... this is a reason I love Sage... **Sage, 133char** ``` z=lambda x,c,n:z(x^2+c,c,n-1)if n else abs(x)<2 for y in range(-15,16): print''.join(' +'[z(0,x/25+y/15j,32)]for x in range(-50,26)) ``` **Sample output (from python version)** ``` @ @ @ @@@@@ @@@@@ @@@ @@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@ @@@@@@@@@@@@@ @@@ @@@@@ @@@@@ @ @ @ ``` [Answer] # BASH - ~~167~~ ~~165~~ 148 The `mb3` file: ``` eval g={-4096..4096..199}' 'h={-8192..4096..99}' x=;y=;for((i=0;i<30&&x*x+y*y<1<<26;i++)){((v=(x*x-y*y>>12)+h,y=(x*y>>11)+g,x=v));} printf $[i%10] ' ``` (no trailing newline) Run it in a terminal with line length 125: [![mb3 output](https://i.stack.imgur.com/oYjz8.png)](https://i.stack.imgur.com/oYjz8.png) --- # BASH - ~~214~~ 190 ``` for h in {-4096..4096..200};do for g in {-8192..4096..115};do x=0;y=0 for((i=0;i<30&&x*x+y*y<1<<26;i++));do((v=((x*x-y*y)>>12)+g));((y=((x*y)>>11)+h)) x=$v done;printf $[i%10];done;echo;done ``` This basically is the same code like below with calculations being replaced by hardcoded values and the image got flipped around the x axis. [![mb2.bash run snapshot](https://i.stack.imgur.com/GtPhd.gif)](https://i.stack.imgur.com/GtPhd.gif) *The version below did not fully fit the rules breaking "from (-2 - i) to (1 + i)".* --- # BASH - ~~263~~ ~~261~~ ~~260~~ 236 Use this source, Luke: ``` a=-8601;b=2867;c=-4915;d=4915 ((e=(b-a)/99));((f=(d-c)/49)) for((h=d;h>=c;h-=f));do for((g=a;g<=b;g+=e));do x=0;y=0 for((i=0;i<30&&x*x+y*y<1<<26;i++));do((v=((x*x-y*y)>>12)+g)) ((y=((x*y)>>11)+h));x=$v done printf $[i%10] done;echo;done ``` This code uses integer arithmetic only, so BASH does not need additional helpers for doing floating point maths... [![mb.bash run snapshot](https://i.stack.imgur.com/4t15G.gif)](https://i.stack.imgur.com/4t15G.gif) [Answer] ## [J](http://jsoftware.com/), 61 characters ``` {&' *'(2:>[:|([+]*])^:32 ::_:)&0"0(j.1-16%~i.33)+/_2+32%~i.97 ``` ``` * ** ****** * ******** ***** *************** * *********************** *** * **************************** ******************************** ********************************* * ************************************ ** ****** ************************************ ************* ************************************ *************** *********************************** ****************************************************** ************************************************************************ ****************************************************** *************** *********************************** ************* ************************************ ** ****** ************************************ ************************************ ********************************* * ******************************** * **************************** *********************** *** *************** * ***** ******** ****** * ** * ``` 55 for space-separated 0/1 instead of stars. ``` (2:>[:|([+]*])^:32 ::_:)&0"0(j.1-16%~i.33)+/_2+16%~i.49 ``` ``` 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` [Answer] ### Ruby, 95 characters ``` puts (-20..20).map{|y|(-40..20).map{|x|z=0;32.times{z=z*z+Complex(x,y)/2e1};z.abs<2??*:' '}*''} ``` Sample output: ``` * * * * **** ***** **** * * ****** * * ** ********** ****************** ****************** * ****************** ******************* *********************** * ********************* * *** ********************** ******* ********************** ********* ********************** ******************************** ********************************** ********************************************* ********************************** ******************************** ********* ********************** ******* ********************** * *** ********************** * ********************* *********************** ******************* * ****************** ****************** ****************** ** ********** * * ****** * * **** ***** **** * * * * ``` [Answer] # Haskell, 130 ``` import Complex main=mapM_ putStrLn[[" *"!!fromEnum(magnitude(iterate((+(x:+y)).(^2))0!!32)<2)|x<-[-2,-1.95..1]]|y<-[-1,-0.95..1]] ``` Output: ``` * * * * **** ***** **** * * ****** * * ** ********** ****************** ****************** * ****************** ******************* *********************** * ********************* * *** ********************** ******* ********************** ********* ********************** ******************************** ********************************** ********************************************* ********************************** ******************************** ********* ********************** ******* ********************** * *** ********************** * ********************* *********************** ******************* * ****************** ****************** ****************** ** ********** * * ****** * * **** ***** **** * * * * ``` [Answer] Here's a coffee-script answer running on node.js: In black and white: ``` m=(x,y)-> a=x b=y z=0 for i in [0..99] (return if i>60 then '*' else if i>10 then '-' else if i>5 then '.' else ' ') if z>4 l=y*y z=x*x+l y=2*x*y+b x=x*x-l+a '@' console.log (m x,y for x in [-1.5..0.5] by 2/79).join '' for y in [-1.3..1.3] by 2.6/40 ``` ![ascii_mandel_color](https://i.stack.imgur.com/zGXP6.png) Adding color: ``` n='\u001b[0m' m=(x,y)-> a=x b=y z=0 for i in [0..999] (return if i>100 then '\u001b[33m*'+n else if i>10 then '\u001b[34m-'+n else if i>5 then '\u001b[31m.'+n else ' ') if z>4 l=y*y z=x*x+l y=2*x*y+b x=x*x-l+a '\u001b[32m@\u001b[0m' console.log (m x,y for x in [-1.5..0.5] by 2/79).join '' for y in [-1.3..1.3] by 2.6/40 ``` [Answer] **Mathematica 56** ``` RegionPlot[Abs@Nest[#^2+x+I*y&,0,9]<2,{x,-2,1},{y,-1,1}] ``` **Mathematica 77** ``` ArrayPlot[2^-Abs@Nest[#^2+Table[j+i*I,{i,-1.2,1.2,.1},{j,-1.8,0.6,.1}]&,0,6]] ``` ![enter image description here](https://i.stack.imgur.com/ElUX4.jpg) **Mathematica 77** ``` Grid@Table[If[Abs@Nest[#^2+y+x*I&,0,30]<2,"*",""],{x,1,-1,-.1},{y,-2,0.5,.1}] ``` ![enter image description here](https://i.stack.imgur.com/Px6eA.jpg) [Answer] ## Perl, 153 chars ``` for(-21..20){$y=$_/20;for(-60..18){$r=($x=$_/30);$i=$y;for(1..99){$t=$r;$r=$r**2-$i**2+$x;$i=$t*$i*2+$y}if($r**2+$i**2<4){print"X"}else{print$"}}print$/} ``` Output: I can't post a picture because I am a new user, so I will try posting the text of the output. ``` X XX XXXXXX XXXXXXX XXXXX X X XX X XX XXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXX X XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXX XX XXXXXXXXXXXXXXXX X X XX X XXXXX XXXXXXX XXXXXX XX X ``` [Answer] **C# - 304 Chars** When I code, I code with readability and beautiful formatting. I threw up writing this. ``` using C=System.Console;class Program{static void Main() {C.WindowWidth=220;C.WindowHeight=80; int w=220,h=80,m=100;double s=4.0/w,v=4.0/h; for(int i=0;i<h;i++)for(int j=0;j<w;j++){ double n=s*j-2,u=v*i-2,x=0,y=0;int r=0; for(r=0;x*x+y*y<4&&r<m;r++){ double t=x*x-y*y+n;y=2*x*y+u;x=t;} C.Write(r>=m?'#':' ');}C.ReadLine();}} ``` I am sure my solution can be improved but for reference I shall post it. Note that the windows console squashes the image. ![enter image description here](https://i.stack.imgur.com/HjOqh.jpg) [Answer] **Haskell: 340 char** Well, as I see no haskell answer, I post mine, I tried to minimize it from what I have done so far. I am sure I can reduce it a lot. But here is the first try: ``` m (x,y) (z,t)=(z*x-y*t,y*z+x*t); a (x,y) (z,t)=(x+z,y+t); r=1.0 f c z 0=z f c z n=f c (a (m z z) c) (n-1) e (x,y)=sqrt(x*x+y*y) t c=(e(f c (0.0,0.0) 32)) < 2 b=map (\z -> (t z, (fst z > r-0.01))) [(x,y) | y <- [-r,-r+(1.0/15)..r], x<-[-2*r,-1.96..r]] s True="\n" s _="" g (b,c)=(if (b) then "@" else " ")++s c main=putStrLn$concat$map g b ``` And here is the result: ``` @ @ @ @@@@@ @@@@@ @@@ @@@ @@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@ @@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ @ @@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@ @@@ @@@@@@@@@@@@@ @@@ @@@@@ @@@@@ @ @ @ ``` OK - Inspired by some animated obfuscated C code on HN, here is an animated version: ``` a=27;b=79;c=C(-2.0,-1.0);d=C(1.0,1.0);e=C(-2.501,-1.003) newtype C = C (Double,Double) deriving (Show,Eq) instance Num C where C(x,y)*C(z,t)=C(z*x-y*t,y*z+x*t);C(x,y)+C(z,t)=C(x+z,y+t);abs(C(x,y))=C(sqrt(x*x+y*y),0.0) r(C(x,y))=x;i(C(x,y))=y f :: C -> C -> Int -> Int f c z 0=0;f c z n=if(r(abs(z))>2)then n else f c ((z*z)+c) (n-1) h j k = map (\z->(f (C z) (C(0,0)) 32,(fst z>l - q/2))) [(x,y)|y<-[p,(p+((o-p)/a))..o],x<-[m,(m + q)..l]] where o=i k;p=i j;m=r j;l=r k;q=(l-m)/b u j k = concat $ map v $ h j k where v (i,p)=(" .,`'°\":;-+oO0123456789=!%*§&$@#"!!i):rst p;rst True="\n";rst False="" main = putStrLn $ im 0 where cl n (C (x,y))=let cs=(1.1**n-1) in C ((x+cs*(r e))/cs+1,(y+cs*(i e))/cs+1);bl n=cl n c;tr n=cl n d;im n=u (bl n) (tr n)++"\x1b[H\x1b[25A"++im (n+1) ``` Copy/paste, do a runghc mandel.hs, enjoy! Here is the kind of result after 50 iterations: ``` 77777777777777777777777777777777777777777777777666666666666666666666666666666666 77777777777777777777777777777777777777777766665555555555566666666666666666666666 666777777777777777777777777777666666666665543;4445555555555555555555666666666555 66666666666666666666666666666666666666555554300334555555555555555555555555555555 6666666666666666666666666666666666665555554431:°33345555555555555555555555555544 5566666666666666666666666666666666555555554321 ;00O:3455555555555555555444444444 5555666666666666666666666666666655555555554O+++ :o022334444444444444444444444444 5555556666666666666666666666665555555555543210O-+O112333344444444444444444444444 55555555666666666666666666665555555555444333210o`O012333333444444444444444444444 4555555555566666666666666555555555544444333331O+°°,'0233333334444444444444444433 44444445555555556666555555555444444444433333210o-:O01122333333334444444444443333 44444444444444445555444444444444444444333332211O+ -o1112222223333333344433333222 444444444444433331133334444444444444433332221110o"+O0111222222222222222222222222 34444444443333330OO03333334444444443332222221100O+-oO001122222222221110-O1111122 22333333333332210--01223333333333322222222211000o-°+o00000122222111110o°;o001111 11OO112222222111O;;O111222222211OO111122211000Oo-" :+ooOOOO.O0000000OOo'°oOO0000 0O;+O01122211000O--O00011221110O+;O00000OO +oooo-: :-+oo++";oOO0000Ooo+;;+oooO00 o+"+oO00OO OOOOoo::ooOOOO°OO00Oo+"+ooOooo+;°---",' ,,";--: ;-+oo+ +++;;°°;;-++:; ,° °':°: ` "`".°° °° "°". :'", '°`°":`°` ,,`` . . .°°'°° ` .. `'°. +-`-oo+oo+'+o+`--°°;-`+o+"+oo+oo-'-++;+++-:,:::"` °::°° :-;;--,;-; " " ;-;": OO"-O0000000000Oo--oO0000000000O-:oO0000Oo::+++;;: ":"-++-';+oooOOoooo-::-oooo++ 10;-111222222110O--O011222222111- 01111110oOOOoo-: :-ooooo`:OO000000OO+;;+OOO000 22122222222222110++0112222222222111222222221000O+:,;.O000001111111100Oo:-OO00000 3344444433333332-,°-2333333344444433322222221100o-;oO00011222222221111O'+0111111 444444444444333320023333444444444444433322221110O.:O0011222222222222211-01112222 44444444444444443333444444444444444444333332211O. -o1112222222223333333333322222 44444444445555555555555555444444444444433333210O-"oO1122223333333444444444433333 444555555555666666666666555555555444444433333' '`:+O0233333333444444444444444433 ``` And a link to a more readable code: <http://yannesposito.com/Scratch/en/blog/Haskell-Mandelbrot/> [Answer] ## J, 70 ``` 3 :'try.2>|(y&+&*:)^:32[0 catch.0 end.'"0(1-~15%~i.31)j.~/2-~13%~i.40 ``` Displays members of the set as `1`, the rest as `0`. Spaces each computed point two characters wide, so as to keep a mostly-square pixel with most fonts. [Answer] QBasic, 222 Characters. Not that short, but QBasic is a pretty verbose language. Also, I updated with a seemingly more correct version ``` FOR y=1 TO 23 FOR x=1 TO 80 a=0:b=0 c=-2.5+(x/80)*3.5:d=-1+(y/23)*2 FOR i=0 TO 1000 IF a*a+b*b>=4 THEN GOTO E t=a*a-b*b*c:b=2*a*b+d:a=t NEXT E:LOCATE y,x IF a*a+b*b<4 THEN ?("@") ELSE ?(" ") END IF NEXT NEXT ``` Output is as in the following image. ![enter image description here](https://i.stack.imgur.com/cvC2j.png) [Answer] **SpecBAS 201** I know this one is an old question, but we've been playing with Perlin's ascii brot in the BASIC programming forum, and here's mine - in SpecBAS (which is a kind of Sinclair BASIC interpreter) and it really is just text, and one line of code: ``` 1FOR y=-29TO 30:FOR x=-10TO 89:LET m,r=0:FOR k=0TO 224:LET j=r^2-m^2-2+x/25,m=2*r*m+y/25,r=j,l=k,k=IIF(j^2+m^2>11,225,k):NEXT k:PRINT INK l;"ð";:NEXT x:NEXT y ``` Output: [![SpecBAS ascii mandelbrot](https://i.stack.imgur.com/0b01E.png)](https://i.stack.imgur.com/0b01E.png) [Answer] # Brainf\*\*\*, 11595 bytes ``` +++++++++++++[->++>>>+++++>++>+<<<<<<]>>>>>++++++>--->>>>>>>>>>+++++++++++++++[[ >>>>>>>>>]+[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-]>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+ <<<<<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>>+>>>>>>>>>>>>>>>>>>>>>>>>>> >+<<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+[>>>>>>[>>>>>>>[-]>>]<<<<<<<<<[<<<<<<<<<]>> >>>>>[-]+<<<<<<++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<+++++++[-[->>> >>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[[-]>>>>>>[>>>>> >>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>> [>>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<< <<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>+++++++++++++++[[ >>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[ >+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[-<<<<+>>>>]<<<<[->>>>+<<<<<[->>[ -<<+>>]<<[->>+>>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<< <<[>[->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<< [>[-]<->>>>[-<<<<+>[<->-<<<<<<+>>>>>>]<[->+<]>>>>]<<<[->>>+<<<]<+<<<<<<<<<]>>>>> >>>>[>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>>[-<<<<<+>>>>>]<<<<<[->>>>>+ <<<<<<[->>>[-<<<+>>>]<<<[->>>+>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>> >>>>>>>]<<<<<<<<<[>>[->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<<]>>[->>>>>>>>>+<<<<<<<<<]<< +>>>>>>>>]<<<<<<<<<[>[-]<->>>>[-<<<<+>[<->-<<<<<<+>>>>>>]<[->+<]>>>>]<<<[->>>+<< <]<+<<<<<<<<<]>>>>>>>>>[>>>>[-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>>>>>]>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>+++++++++++++++[[>>>> >>>>>]<<<<<<<<<-<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+>>>>>>>>>>>>>>>>>>>>>+<<<[<<<<<< <<<]>>>>>>>>>[>>>[-<<<->>>]+<<<[->>>->[-<<<<+>>>>]<<<<[->>>>+<<<<<<<<<<<<<[<<<<< <<<<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>[-<<<<->>>>]+<<<<[->>>>-<[-<<<+>>>]<<<[-> >>+<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<< <<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]<<<<<<<[->+>>>-<<<<]>>>>>>>>>+++++++++++++++++++ +++++++>>[-<<<<+>>>>]<<<<[->>>>+<<[-]<<]>>[<<<<<<<+<[-<+>>>>+<<[-]]>[-<<[->+>>>- <<<<]>>>]>>>>>>>>>>>>>[>>[-]>[-]>[-]>>>>>]<<<<<<<<<[<<<<<<<<<]>>>[-]>>>>>>[>>>>> [-<<<<+>>>>]<<<<[->>>>+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>[-<<<<<<<< <+>>>>>>>>>]>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>+++++++++++++++[[>>>>>>>>>]+>[- ]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[>+>>>>>>>>]<<< <<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>>[-<<<<<+>>>>>]<<<<<[->>>>>+<<<<<<[->>[-<<+>>]< <[->>+>+<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[>[->>>> >>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<<[>[-]<->>> [-<<<+>[<->-<<<<<<<+>>>>>>>]<[->+<]>>>]<<[->>+<<]<+<<<<<<<<<]>>>>>>>>>[>>>>>>[-< <<<<+>>>>>]<<<<<[->>>>>+<<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>+>>>>>>>> ]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>>[-<<<<<+>>>>>]<<<<<[->>>>>+<<<<<<[->>[-<<+ >>]<<[->>+>>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[> [->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<<[>[- ]<->>>>[-<<<<+>[<->-<<<<<<+>>>>>>]<[->+<]>>>>]<<<[->>>+<<<]<+<<<<<<<<<]>>>>>>>>> [>>>>[-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ]>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>[-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>++++++++ +++++++[[>>>>>>>>>]<<<<<<<<<-<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[>>>>>>>>[-<<<<<<<+ >>>>>>>]<<<<<<<[->>>>>>>+<<<<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>>[ -]>>>]<<<<<<<<<[<<<<<<<<<]>>>>+>[-<-<<<<+>>>>>]>[-<<<<<<[->>>>>+<++<<<<]>>>>>[-< <<<<+>>>>>]<->+>]<[->+<]<<<<<[->>>>>+<<<<<]>>>>>>[-]<<<<<<+>>>>[-<<<<->>>>]+<<<< [->>>>->>>>>[>>[-<<->>]+<<[->>->[-<<<+>>>]<<<[->>>+<<<<<<<<<<<<[<<<<<<<<<]>>>[-] +>>>>>>[>>>>>>>>>]>+<]]+>>>[-<<<->>>]+<<<[->>>-<[-<<+>>]<<[->>+<<<<<<<<<<<[<<<<< <<<<]>>>>[-]+>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<< [<<<<<<<<<]>>>>[-<<<<+>>>>]<<<<[->>>>+>>>>>[>+>>[-<<->>]<<[->>+<<]>>>>>>>>]<<<<< <<<+<[>[->>>>>+<<<<[->>>>-<<<<<<<<<<<<<<+>>>>>>>>>>>[->>>+<<<]<]>[->>>-<<<<<<<<< <<<<<+>>>>>>>>>>>]<<]>[->>>>+<<<[->>>-<<<<<<<<<<<<<<+>>>>>>>>>>>]<]>[->>>+<<<]<< <<<<<<<<<<]>>>>[-]<<<<]>>>[-<<<+>>>]<<<[->>>+>>>>>>[>+>[-<->]<[->+<]>>>>>>>>]<<< <<<<<+<[>[->>>>>+<<<[->>>-<<<<<<<<<<<<<<+>>>>>>>>>>[->>>>+<<<<]>]<[->>>>-<<<<<<< <<<<<<<+>>>>>>>>>>]<]>>[->>>+<<<<[->>>>-<<<<<<<<<<<<<<+>>>>>>>>>>]>]<[->>>>+<<<< ]<<<<<<<<<<<]>>>>>>+<<<<<<]]>>>>[-<<<<+>>>>]<<<<[->>>>+>>>>>[>>>>>>>>>]<<<<<<<<< [>[->>>>>+<<<<[->>>>-<<<<<<<<<<<<<<+>>>>>>>>>>>[->>>+<<<]<]>[->>>-<<<<<<<<<<<<<< +>>>>>>>>>>>]<<]>[->>>>+<<<[->>>-<<<<<<<<<<<<<<+>>>>>>>>>>>]<]>[->>>+<<<]<<<<<<< <<<<<]]>[-]>>[-]>[-]>>>>>[>>[-]>[-]>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>[-< <<<+>>>>]<<<<[->>>>+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>+++++++++++++++[ [>>>>>>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+ [>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[-<<<<+>>>>]<<<<[->>>>+<<<<<[->> [-<<+>>]<<[->>+>+<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<< <[>[->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<<[ >[-]<->>>[-<<<+>[<->-<<<<<<<+>>>>>>>]<[->+<]>>>]<<[->>+<<]<+<<<<<<<<<]>>>>>>>>>[ >>>[-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]> >>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>[-]>>>>+++++++++++++++[[>>>>>>>>>]<<<<<<<<<-<<<<< <<<<[<<<<<<<<<]>>>>>>>>>-]+[>>>[-<<<->>>]+<<<[->>>->[-<<<<+>>>>]<<<<[->>>>+<<<<< <<<<<<<<[<<<<<<<<<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>[-<<<<->>>>]+<<<<[->>>>-<[- <<<+>>>]<<<[->>>+<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>> >>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>[-<<<+>>>]<<<[->>>+>>>>>>[>+>>> [-<<<->>>]<<<[->>>+<<<]>>>>>>>>]<<<<<<<<+<[>[->+>[-<-<<<<<<<<<<+>>>>>>>>>>>>[-<< +>>]<]>[-<<-<<<<<<<<<<+>>>>>>>>>>>>]<<<]>>[-<+>>[-<<-<<<<<<<<<<+>>>>>>>>>>>>]<]> [-<<+>>]<<<<<<<<<<<<<]]>>>>[-<<<<+>>>>]<<<<[->>>>+>>>>>[>+>>[-<<->>]<<[->>+<<]>> >>>>>>]<<<<<<<<+<[>[->+>>[-<<-<<<<<<<<<<+>>>>>>>>>>>[-<+>]>]<[-<-<<<<<<<<<<+>>>> >>>>>>>]<<]>>>[-<<+>[-<-<<<<<<<<<<+>>>>>>>>>>>]>]<[-<+>]<<<<<<<<<<<<]>>>>>+<<<<< ]>>>>>>>>>[>>>[-]>[-]>[-]>>>>]<<<<<<<<<[<<<<<<<<<]>>>[-]>[-]>>>>>[>>>>>>>[-<<<<< <+>>>>>>]<<<<<<[->>>>>>+<<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>+>[-<-<<<<+>>>> >]>>[-<<<<<<<[->>>>>+<++<<<<]>>>>>[-<<<<<+>>>>>]<->+>>]<<[->>+<<]<<<<<[->>>>>+<< <<<]+>>>>[-<<<<->>>>]+<<<<[->>>>->>>>>[>>>[-<<<->>>]+<<<[->>>-<[-<<+>>]<<[->>+<< <<<<<<<<<[<<<<<<<<<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>[-<<->>]+<<[->>->[-<<<+>>>]< <<[->>>+<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>>>>>>>>>]< <<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>[-<<<+>>>]<<<[->>>+>>>>>>[>+>[-<->]<[->+ <]>>>>>>>>]<<<<<<<<+<[>[->>>>+<<[->>-<<<<<<<<<<<<<+>>>>>>>>>>[->>>+<<<]>]<[->>>- <<<<<<<<<<<<<+>>>>>>>>>>]<]>>[->>+<<<[->>>-<<<<<<<<<<<<<+>>>>>>>>>>]>]<[->>>+<<< ]<<<<<<<<<<<]>>>>>[-]>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]]>>>>[-<<<<+> >>>]<<<<[->>>>+>>>>>[>+>>[-<<->>]<<[->>+<<]>>>>>>>>]<<<<<<<<+<[>[->>>>+<<<[->>>- <<<<<<<<<<<<<+>>>>>>>>>>>[->>+<<]<]>[->>-<<<<<<<<<<<<<+>>>>>>>>>>>]<<]>[->>>+<<[ ->>-<<<<<<<<<<<<<+>>>>>>>>>>>]<]>[->>+<<]<<<<<<<<<<<<]]>>>>[-]<<<<]>>>>[-<<<<+>> >>]<<<<[->>>>+>[-]>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+<<+<<<<<]>>>>>>>>>[>>>>>> >>>]<<<<<<<<<[>[->>>>+<<<[->>>-<<<<<<<<<<<<<+>>>>>>>>>>>[->>+<<]<]>[->>-<<<<<<<< <<<<<+>>>>>>>>>>>]<<]>[->>>+<<[->>-<<<<<<<<<<<<<+>>>>>>>>>>>]<]>[->>+<<]<<<<<<<< <<<<]]>>>>>>>>>[>>[-]>[-]>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>[-]>[-]>>>>>[>>>>>[-<<<<+ >>>>]<<<<[->>>>+<<<+<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>>[-<<<<<+>>>>> ]<<<<<[->>>>>+<<<+<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>+++++++++++++++[[>>>> >>>>>]+>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+[>+>> >>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>[-<<<<+>>>>]<<<<[->>>>+<<<<<[->>[-<<+ >>]<<[->>+>>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[> [->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<]>[->>>>>>>>>+<<<<<<<<<]<+>>>>>>>>]<<<<<<<<<[>[- ]<->>>>[-<<<<+>[<->-<<<<<<+>>>>>>]<[->+<]>>>>]<<<[->>>+<<<]<+<<<<<<<<<]>>>>>>>>> [>+>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>->>>>>[-<<<<<+>>>>>]<<<<<[->>>>>+<<<< <<[->>>[-<<<+>>>]<<<[->>>+>+<<<<]+>>>>>>>>>]<<<<<<<<[<<<<<<<<<]]>>>>>>>>>[>>>>>> >>>]<<<<<<<<<[>>[->>>>>>>>>+<<<<<<<<<]<<<<<<<<<<<]>>[->>>>>>>>>+<<<<<<<<<]<<+>>> >>>>>]<<<<<<<<<[>[-]<->>>>[-<<<<+>[<->-<<<<<<+>>>>>>]<[->+<]>>>>]<<<[->>>+<<<]<+ <<<<<<<<<]>>>>>>>>>[>>>>[-<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>> >>>>>>>>>>>>>>>>>>>]>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>+++++++++++++++[[>>>>>>>> >]<<<<<<<<<-<<<<<<<<<[<<<<<<<<<]>>>>>>>>>-]+>>>>>>>>>>>>>>>>>>>>>+<<<[<<<<<<<<<] >>>>>>>>>[>>>[-<<<->>>]+<<<[->>>->[-<<<<+>>>>]<<<<[->>>>+<<<<<<<<<<<<<[<<<<<<<<< ]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>[-<<<<->>>>]+<<<<[->>>>-<[-<<<+>>>]<<<[->>>+< <<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]> >>>>>>>]<<<<<<<<<[<<<<<<<<<]>>->>[-<<<<+>>>>]<<<<[->>>>+<<[-]<<]>>]<<+>>>>[-<<<< ->>>>]+<<<<[->>>>-<<<<<<.>>]>>>>[-<<<<<<<.>>>>>>>]<<<[-]>[-]>[-]>[-]>[-]>[-]>>>[ >[-]>[-]>[-]>[-]>[-]>[-]>>>]<<<<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>[-]>>>>]<<<<<<<<< [<<<<<<<<<]>+++++++++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>+>>>>>>>>>+<<<<<<<< <<<<<<[<<<<<<<<<]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+[-]>>[>>>>>>>>>]<<<<< <<<<[>>>>>>>[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<<<<<<[<<<<<<<<<]>>>>>>>[-]+>>>]<<<< <<<<<<]]>>>>>>>[-<<<<<<<+>>>>>>>]<<<<<<<[->>>>>>>+>>[>+>>>>[-<<<<->>>>]<<<<[->>> >+<<<<]>>>>>>>>]<<+<<<<<<<[>>>>>[->>+<<]<<<<<<<<<<<<<<]>>>>>>>>>[>>>>>>>>>]<<<<< <<<<[>[-]<->>>>>>>[-<<<<<<<+>[<->-<<<+>>>]<[->+<]>>>>>>>]<<<<<<[->>>>>>+<<<<<<]< +<<<<<<<<<]>>>>>>>-<<<<[-]+<<<]+>>>>>>>[-<<<<<<<->>>>>>>]+<<<<<<<[->>>>>>>->>[>> >>>[->>+<<]>>>>]<<<<<<<<<[>[-]<->>>>>>>[-<<<<<<<+>[<->-<<<+>>>]<[->+<]>>>>>>>]<< <<<<[->>>>>>+<<<<<<]<+<<<<<<<<<]>+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>+<<< <<[<<<<<<<<<]>>>>>>>>>[>>>>>[-<<<<<->>>>>]+<<<<<[->>>>>->>[-<<<<<<<+>>>>>>>]<<<< <<<[->>>>>>>+<<<<<<<<<<<<<<<<[<<<<<<<<<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>>>>[-< <<<<<<->>>>>>>]+<<<<<<<[->>>>>>>-<<[-<<<<<+>>>>>]<<<<<[->>>>>+<<<<<<<<<<<<<<[<<< <<<<<<]>>>[-]+>>>>>>[>>>>>>>>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<< <<[<<<<<<<<<]>>>>[-]<<<+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>-<<<<<[<<<<<<< <<]]>>>]<<<<.>>>>>>>>>>[>>>>>>[-]>>>]<<<<<<<<<[<<<<<<<<<]>++++++++++[-[->>>>>>>> >+<<<<<<<<<]>>>>>>>>>]>>>>>+>>>>>>>>>+<<<<<<<<<<<<<<<[<<<<<<<<<]>>>>>>>>[-<<<<<< <<+>>>>>>>>]<<<<<<<<[->>>>>>>>+[-]>[>>>>>>>>>]<<<<<<<<<[>>>>>>>>[-<<<<<<<+>>>>>> >]<<<<<<<[->>>>>>>+<<<<<<<<[<<<<<<<<<]>>>>>>>>[-]+>>]<<<<<<<<<<]]>>>>>>>>[-<<<<< <<<+>>>>>>>>]<<<<<<<<[->>>>>>>>+>[>+>>>>>[-<<<<<->>>>>]<<<<<[->>>>>+<<<<<]>>>>>> >>]<+<<<<<<<<[>>>>>>[->>+<<]<<<<<<<<<<<<<<<]>>>>>>>>>[>>>>>>>>>]<<<<<<<<<[>[-]<- >>>>>>>>[-<<<<<<<<+>[<->-<<+>>]<[->+<]>>>>>>>>]<<<<<<<[->>>>>>>+<<<<<<<]<+<<<<<< <<<]>>>>>>>>-<<<<<[-]+<<<]+>>>>>>>>[-<<<<<<<<->>>>>>>>]+<<<<<<<<[->>>>>>>>->[>>> >>>[->>+<<]>>>]<<<<<<<<<[>[-]<->>>>>>>>[-<<<<<<<<+>[<->-<<+>>]<[->+<]>>>>>>>>]<< <<<<<[->>>>>>>+<<<<<<<]<+<<<<<<<<<]>+++++[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>> +>>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<[<<<<<<<<<]>>>>>>>>>[>>>>>>[-<<<<<<->>>>>>]+< <<<<<[->>>>>>->>[-<<<<<<<<+>>>>>>>>]<<<<<<<<[->>>>>>>>+<<<<<<<<<<<<<<<<<[<<<<<<< <<]>>>>[-]+>>>>>[>>>>>>>>>]>+<]]+>>>>>>>>[-<<<<<<<<->>>>>>>>]+<<<<<<<<[->>>>>>>> -<<[-<<<<<<+>>>>>>]<<<<<<[->>>>>>+<<<<<<<<<<<<<<<[<<<<<<<<<]>>>[-]+>>>>>>[>>>>>> >>>]>[-]+<]]+>[-<[>>>>>>>>>]<<<<<<<<]>>>>>>>>]<<<<<<<<<[<<<<<<<<<]>>>>[-]<<<++++ +[-[->>>>>>>>>+<<<<<<<<<]>>>>>>>>>]>>>>>->>>>>>>>>>>>>>>>>>>>>>>>>>>-<<<<<<[<<<< <<<<<]]>>>] ``` Output: ``` AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDEGFFEEEEDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAAAAABBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDEEEFGIIGFFEEEDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDEEEEFFFI KHGGGHGEDDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAABBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEEFFGHIMTKLZOGFEEDDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAABBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEEEFGGHHIKPPKIHGFFEEEDDDDDDDDDCCCCCCCCCCBBBBBBBBBBBBBBBBBB AAAAAAAAAABBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEEFFGHIJKS X KHHGFEEEEEDDDDDDDDDCCCCCCCCCCBBBBBBBBBBBBBBBB AAAAAAAAABBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEEFFGQPUVOTY ZQL[MHFEEEEEEEDDDDDDDCCCCCCCCCCCBBBBBBBBBBBBBB AAAAAAAABBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEFFFFFGGHJLZ UKHGFFEEEEEEEEDDDDDCCCCCCCCCCCCBBBBBBBBBBBB AAAAAAABBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEFFFFFFGGGGHIKP KHHGGFFFFEEEEEEDDDDDCCCCCCCCCCCBBBBBBBBBBB AAAAAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDEEEEEFGGHIIHHHHHIIIJKMR VMKJIHHHGFFFFFFGSGEDDDDCCCCCCCCCCCCBBBBBBBBB AAAAAABBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDEEEEEEFFGHK MKJIJO N R X YUSR PLV LHHHGGHIOJGFEDDDCCCCCCCCCCCCBBBBBBBB AAAAABBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDEEEEEEEEEFFFFGH O TN S NKJKR LLQMNHEEDDDCCCCCCCCCCCCBBBBBBB AAAAABBCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDEEEEEEEEEEEEFFFFFGHHIN Q UMWGEEEDDDCCCCCCCCCCCCBBBBBB AAAABBCCCCCCCCCCCCCCCCCCCCCCCCCDDDDEEEEEEEEEEEEEEEFFFFFFGHIJKLOT [JGFFEEEDDCCCCCCCCCCCCCBBBBB AAAABCCCCCCCCCCCCCCCCCCCCCCDDDDEEEEEEEEEEEEEEEEFFFFFFGGHYV RQU QMJHGGFEEEDDDCCCCCCCCCCCCCBBBB AAABCCCCCCCCCCCCCCCCCDDDDDDDEEFJIHFFFFFFFFFFFFFFGGGGGGHIJN JHHGFEEDDDDCCCCCCCCCCCCCBBB AAABCCCCCCCCCCCDDDDDDDDDDEEEEFFHLKHHGGGGHHMJHGGGGGGHHHIKRR UQ L HFEDDDDCCCCCCCCCCCCCCBB AABCCCCCCCCDDDDDDDDDDDEEEEEEFFFHKQMRKNJIJLVS JJKIIIIIIJLR YNHFEDDDDDCCCCCCCCCCCCCBB AABCCCCCDDDDDDDDDDDDEEEEEEEFFGGHIJKOU O O PR LLJJJKL OIHFFEDDDDDCCCCCCCCCCCCCCB AACCCDDDDDDDDDDDDDEEEEEEEEEFGGGHIJMR RMLMN NTFEEDDDDDDCCCCCCCCCCCCCB AACCDDDDDDDDDDDDEEEEEEEEEFGGGHHKONSZ QPR NJGFEEDDDDDDCCCCCCCCCCCCCC ABCDDDDDDDDDDDEEEEEFFFFFGIPJIIJKMQ VX HFFEEDDDDDDCCCCCCCCCCCCCC ACDDDDDDDDDDEFFFFFFFGGGGHIKZOOPPS HGFEEEDDDDDDCCCCCCCCCCCCCC ADEEEEFFFGHIGGGGGGHHHHIJJLNY TJHGFFEEEDDDDDDDCCCCCCCCCCCCC A PLJHGGFFEEEDDDDDDDCCCCCCCCCCCCC ADEEEEFFFGHIGGGGGGHHHHIJJLNY TJHGFFEEEDDDDDDDCCCCCCCCCCCCC ACDDDDDDDDDDEFFFFFFFGGGGHIKZOOPPS HGFEEEDDDDDDCCCCCCCCCCCCCC ABCDDDDDDDDDDDEEEEEFFFFFGIPJIIJKMQ VX HFFEEDDDDDDCCCCCCCCCCCCCC AACCDDDDDDDDDDDDEEEEEEEEEFGGGHHKONSZ QPR NJGFEEDDDDDDCCCCCCCCCCCCCC AACCCDDDDDDDDDDDDDEEEEEEEEEFGGGHIJMR RMLMN NTFEEDDDDDDCCCCCCCCCCCCCB AABCCCCCDDDDDDDDDDDDEEEEEEEFFGGHIJKOU O O PR LLJJJKL OIHFFEDDDDDCCCCCCCCCCCCCCB AABCCCCCCCCDDDDDDDDDDDEEEEEEFFFHKQMRKNJIJLVS JJKIIIIIIJLR YNHFEDDDDDCCCCCCCCCCCCCBB AAABCCCCCCCCCCCDDDDDDDDDDEEEEFFHLKHHGGGGHHMJHGGGGGGHHHIKRR UQ L HFEDDDDCCCCCCCCCCCCCCBB AAABCCCCCCCCCCCCCCCCCDDDDDDDEEFJIHFFFFFFFFFFFFFFGGGGGGHIJN JHHGFEEDDDDCCCCCCCCCCCCCBBB AAAABCCCCCCCCCCCCCCCCCCCCCCDDDDEEEEEEEEEEEEEEEEFFFFFFGGHYV RQU QMJHGGFEEEDDDCCCCCCCCCCCCCBBBB AAAABBCCCCCCCCCCCCCCCCCCCCCCCCCDDDDEEEEEEEEEEEEEEEFFFFFFGHIJKLOT [JGFFEEEDDCCCCCCCCCCCCCBBBBB AAAAABBCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDEEEEEEEEEEEEFFFFFGHHIN Q UMWGEEEDDDCCCCCCCCCCCCBBBBBB AAAAABBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDEEEEEEEEEFFFFGH O TN S NKJKR LLQMNHEEDDDCCCCCCCCCCCCBBBBBBB AAAAAABBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDEEEEEEFFGHK MKJIJO N R X YUSR PLV LHHHGGHIOJGFEDDDCCCCCCCCCCCCBBBBBBBB AAAAAAABBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDEEEEEFGGHIIHHHHHIIIJKMR VMKJIHHHGFFFFFFGSGEDDDDCCCCCCCCCCCCBBBBBBBBB AAAAAAABBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEFFFFFFGGGGHIKP KHHGGFFFFEEEEEEDDDDDCCCCCCCCCCCBBBBBBBBBBB AAAAAAAABBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEFFFFFGGHJLZ UKHGFFEEEEEEEEDDDDDCCCCCCCCCCCCBBBBBBBBBBBB AAAAAAAAABBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEEFFGQPUVOTY ZQL[MHFEEEEEEEDDDDDDDCCCCCCCCCCCBBBBBBBBBBBBBB AAAAAAAAAABBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDDEEEEEEFFGHIJKS X KHHGFEEEEEDDDDDDDDDCCCCCCCCCCBBBBBBBBBBBBBBBB AAAAAAAAAAABBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEEEFGGHHIKPPKIHGFFEEEDDDDDDDDDCCCCCCCCCCBBBBBBBBBBBBBBBBBB AAAAAAAAAAAABBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDDDEEEEEFFGHIMTKLZOGFEEDDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDDDEEEEFFFI KHGGGHGEDDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBB AAAAAAAAAAAAAAABBBBBBBBBBBBBCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCDDDDDDDDDDEEEFGIIGFFEEEDDDDDDDDCCCCCCCCCBBBBBBBBBBBBBBBBBBBBBBBBBB ``` And this is why you use automatic Markdown code formatters. [Originally written by Erik Bosman.](http://esoteric.sange.fi/brainfuck/utils/mandelbrot/) [Answer] **Perl -- 193 characters** ``` $Y=-1.2;for(0..24){$X=-2;for(0..79){($r,$i)=(0,0);for(0..15){$n=$_;$r=($x=$ r)*$x-($y=$i)*$y+$X;$i=2*$x*$y+$Y;$x*$x+$y*$y>4&&last}print unpack("\@$n a" ,".,:;=+itIYVXRBM ");$X+=3/80}$Y+=2.4/25} ``` Result ``` ,,,,,,,,,,,::::::::::::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::::::::::::::::::::: ,,,,,,,,,:::::::::;;;;;;;;;;;;;;;;;;;;;;======+iRV+++====;;;;;;::::::::::::::::: ,,,,,,,,::::::;;;;;;;;;;;;;;;;;;;;;;========+++itVXYYRi======;;;;;;::::::::::::: ,,,,,,:::::;;;;;;;;;;;;;;;;;;;;;;=========++++ttIR VIt+++=====;;;;;;;:::::::::: ,,,,,::::;;;;;;;;;;;;;;;;;;;;==========+++iitIX ti++++====;;;;;;;:::::::: ,,,,:::;;;;;;;;;;;;;;;;;;;=========++ittttttIYX VIItiiiii++==;;;;;;;:::::: ,,,::;;;;;;;;;;;;;;;;;;======+++++iit R RY XX Y++=;;;;;;;;:::: ,,::;;;;;;;;;;;;;;;;===+++++++++iiitIVB Mti++=;;;;;;;;::: ,,:;;;;;;;;;;;====+XtiiiiiiiiiittIYM RIti+==;;;;;;;;:: ,:;;;;;=======+++iiI XVVYV VYYIIYYB t+===;;;;;;;;: ,;;========++++++ttIY MRB Mi+===;;;;;;;;; ,========+++iiiIRYYX t++====;;;;;;;; ,++iitYttttIIIVXM Yti++====;;;;;;;; ,++iitYttttIIIVXM Yti++====;;;;;;;; ,========+++iiiIRYYX t++====;;;;;;;; ,;;========++++++ttIY MRB Mi+===;;;;;;;;; ,:;;;;;=======+++iiI XVVYV VYYIIYYB t+===;;;;;;;;: ,,:;;;;;;;;;;;====+XtiiiiiiiiiittIYM RIti+==;;;;;;;;:: ,,::;;;;;;;;;;;;;;;;===+++++++++iiitIVB Mti++=;;;;;;;;::: ,,,::;;;;;;;;;;;;;;;;;;======+++++iit R RY XX Y++=;;;;;;;;:::: ,,,,:::;;;;;;;;;;;;;;;;;;;=========++ittttttIYX VIItiiiii++==;;;;;;;:::::: ,,,,,::::;;;;;;;;;;;;;;;;;;;;==========+++iitIX ti++++====;;;;;;;:::::::: ,,,,,,:::::;;;;;;;;;;;;;;;;;;;;;;=========++++ttIR VIt+++=====;;;;;;;:::::::::: ,,,,,,,,::::::;;;;;;;;;;;;;;;;;;;;;;========+++itVXYYRi======;;;;;;::::::::::::: ,,,,,,,,,:::::::::;;;;;;;;;;;;;;;;;;;;;;======+iRV+++====;;;;;;::::::::::::::::: ``` I think it won the obfuscated perl contest a few years ago. [Answer] **Python, 115.** ``` r=range for _ in r(-11,12): for f in r(-39,41): v=u=f/22.-_/11j;exec"u=u*u+v;"*40;print"\b"+chr(32+(u.real<4)), ``` Works only on 80x24 terminals, but you can add `print` after first `for` to fix it. Sample output (With additional `print` instruction.): ``` ! !!! !!!!! ! ! !!!!!!!! ! !!!!!!!!!!!!!!!!! !! ! !!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!! ! ! !!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!! ! ! !!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!! ! !!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!! !! ! ! !!!!!!!! ! !!!!! !!! ! ``` [Answer] ## c++-11 -- 298 characters Fully golfed, unparameterized version that does only what is required: ``` #include <complex> #include <iostream> #define C complex<float> using namespace std;int main(void){C p(-2,1),q(1,-1);char i,j,k; for(j=0;j<30;++j){for(i=0;i<80;++i){C r=q-p,c((i+0.5)*r.real()/ 81+p.real(),(j+0.5)*r.imag()/31+p.imag());r=0;k=64;while (abs(r)<=2&&(--k!=32))r=r*r+c;cout<<k;}cout<<endl;}} ``` The implementation is completely unremarkable. Just seeing what can be done using the native complex time (which is, alas, a little wordy). Ungolfed and parameterized so that it can do regions ``` #include <complex> #include <iostream> using namespace std; void M/*andlebrot*/(ostream& o, complex<float> p, complex<float> q, int l, int h) { char i,j,k; for(j=0; j<h; ++j){ for(i=0; i<l; ++i){ complex<float> r=q-p,c((i+0.5)*r.real()/(l+1)+p.real(), (j+0.5)*r.imag()/(h+1)+p.imag() ); r=0; k='@'; while(abs(r)<=2&&(--k!=' ')){ r=r*r+c; } o<<k; } o<<endl; } } int main(int argc, char*argv[]){ M(cout,complex<float>(-2.15,1.25),complex<float>(0.65,-1.25),80,30); } ``` Output ``` $ g++-fsf-4.7 mandelbrot_golf.cc --std=c++11 $ ./a.out ???????>>>>>>=====================<<<<<<<<<;;;;:974048:;<<<<<<======>>>>>>>>>>>> ??????>>>>>=====================<<<<<<<<<<;;;:9872 '89:;;<<<<<<======>>>>>>>>>> ?????>>>>=====================<<<<<<<<<<;;;::8$ /# &349:;;;;<<<<=======>>>>>>>> ????>>>=====================<<<<<<<<<;;::::9986- *589::;;;;<<<========>>>>>> ????>>====================<<<<<<<<;;;9988998775/ 57889::::9;<<========>>>>> ???>>===================<<<<<<;;;;;:96$.355 &() 2$28887,8:;<========>>>> ??>>==================<<<<;;;;;;;::987. 2$ )9;<<========>>> ??>================<<<;;;;;;;;;::::8753+ '8:;;<<========>> ?>=============<<<;::::;;;;;::::997 589:;<<=========> ?>========<<<<<;;;:85899987999998861% (54;<<<========> ?=====<<<<<<<;;;;::8 03564&46677763! 28:<<<========= >==<<<<<<<<;;;;;::9873 , ' 554# 69;<<<<======== ==<<<<<<<<;;;;;:998$3, 00 -3:;<<<<======== =<<<<<<<;;::::975654) ) ,9:;<<<<======== <;;;::99:::999762 # 9:;;<<<<======== /589:;;<<<<======== <;;;::99:::999762 # 9:;;<<<<======== =<<<<<<<;;::::975654) ) ,9:;<<<<======== ==<<<<<<<<;;;;;:998$3, 00 -3:;<<<<======== >==<<<<<<<<;;;;;::9873 , ' 554# 69;<<<<======== ?=====<<<<<<<;;;;::8 03564&46677763! 28:<<<========= ?>========<<<<<;;;:85899987999998861% (54;<<<========> ?>=============<<<;::::;;;;;::::997 589:;<<=========> ??>================<<<;;;;;;;;;::::8753+ '8:;;<<========>> ??>>==================<<<<;;;;;;;::987. 2$ )9;<<========>>> ???>>===================<<<<<<;;;;;:96$.355 &() 2$28887,8:;<========>>>> ????>>====================<<<<<<<<;;;9988998775/ 57889::::9;<<========>>>>> ????>>>=====================<<<<<<<<<;;::::9986- *589::;;;;<<<========>>>>>> ?????>>>>=====================<<<<<<<<<<;;;::8$ /# &349:;;;;<<<<=======>>>>>>>> ??????>>>>>=====================<<<<<<<<<<;;;:9872 '89:;;<<<<<<======>>>>>>>>>> ``` [Answer] # GolfScript - 77 ``` 20{40{0.1{.{;..*2$.*\- 20/3$-@@*10/3$-..*2$.*+1600<}*}32*\;\;@@(}60*;(n\}40*; ``` It can probably be golfed a lot more. The result is an approximation because I have to use integers. Output: ``` 000000000000000000000000000000000000000010000000000000000000 000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000001000000000000000000000000 000000000000000000000000000000000000001000000000000000000000 000000000000000000000000000000000000111000000000000000000000 000000000000000000000000000000000000111110000000000000000000 000000000000000000000000000000000000011100000000000000000000 000000000000000000000000000001000110111100010000000000000000 000000000000000000000000000000100111111111110000000000000000 000000000000000000000000000001011111111111110111000000000000 000000000000000000000000000001111111111111111110000000000000 000000000000000000000000000000111111111111111110000000000000 000000000000001000000000000011111111111111111111000000000000 000000000000000000000000000011111111111111111111000000000000 000000000000000000000000000111111111111111111111000000000000 000000000000000000000000001111111111111111111111100000000000 000000000000000001111110001111111111111111111111100000000000 000000000000000011111111101111111111111111111111100000000000 000000000000100111111111111111111111111111111111000000000000 000000000001101111111111111111111111111111111111000000000000 011111111111111111111111111111111111111111111100000000000000 000000000000001111111111111111111111111111111110000000000000 000000000000000111111111111111111111111111111111000000000000 000000000000000001111111111111111111111111111111100000000000 000000000000000001111111101111111111111111111111000000000000 000000000000000001011100000111111111111111111111100000000000 000000000000000000000100000111111111111111111111000000000000 000000000000000100000000001111111111111111111111100000000000 000000000000000100000000000011111111111111111111000000000000 000000000000000000000000000011111111111111111110000000000000 000000000000000000000000000001111111111111111111000000000000 000000000000000000000000000000111111111111111111000000000000 000000000000000000000000000001101111111111111000000000000000 000000000000000000000000000011000011111110100000000000000000 000000000000000000000000000000000000111100000000000000000000 000000000000000000000000000000000000111110000000000000000000 000000000000000000000000000000000000111100000000000000000000 000000000000000000000000000000000000011000000000000000000000 000000000000000000000000000000000000001000000000000000000000 000000000000000000000000000000000000000000000000000000000000 ``` It takes about 9 more bytes to make it use spaces and stars: ``` 20{40{0.1{.{;..*2$.*\- 20/3$-@@*10/3$-..*2$.*+1600<}*}32*' *'=\;\;@@(}60*;(n\}40*;]''+ ``` [Answer] # GNU bc, 136 bytes ``` for(y=-1;y<1;y+=.05){for(x=-2;x<1;x+=.05){for(n=i=r=0;r*r+i*i<4&&++n<32;r=t){t=r*r-i*i+x i=2*r*i+y} if(n<32)print n%A else print " "} 2} ``` Output: ``` 1111112222233333333333333334444445567190 54444333322222222222 11111222233333333333333334444444555780 0765444433333222222222 11111222333333333333333344444445556799 1865544443333322222222 11112223333333333333333444444455561 6 7985554444333332222222 111122333333333333333344444445566784 086555544333333222222 111222333333333333333444444556667797 787665554433333222222 111223333333333333344444455678988903 309866625443333322222 11123333333333333344444555673430 0 203 98897543333332222 11223333333333333444455556672 75 224654544333332222 11233333333333344455555566781 29554333333222 11233333333333445555555666808 7654333333222 113333333334445666555666782 5 37654433333322 123333334444557477778777782 70254433333322 12333344444556749990198881 64433333322 13334444445556709 25 51902 4864433333332 13344444455557795 728 4054443333332 1344444455557792 6 854443333332 1444444555672919 654443333332 144444666678368 8654443333332 1556787778915 07654443333332 1 387654443333332 1556787778915 07654443333332 144444666678368 8654443333332 1444444555672919 654443333332 1344444455557792 6 854443333332 13344444455557795 728 4054443333332 13334444445556709 25 51902 4864433333332 12333344444556749990198881 64433333322 123333334444557477778777782 70254433333322 113333333334445666555666782 5 37654433333322 11233333333333445555555666808 7654333333222 11233333333333344455555566781 29554333333222 11223333333333333444455556672 75 224654544333332222 11123333333333333344444555673430 0 203 98897543333332222 111223333333333333344444455678988903 309866625443333322222 111222333333333333333444444556667797 787665554433333222222 111122333333333333333344444445566784 086555544333333222222 11112223333333333333333444444455561 6 7985554444333332222222 11111222333333333333333344444445556799 1865544443333322222222 11111222233333333333333334444444555780 0765444433333222222222 ``` [Answer] # c++ (260) Golfed Code: ``` #include<iostream> void main(){for(float i=-1;i<=1;i+=0.03125){for(float r=-2;r<=1;r+=.03125){float zr=r,zi=i;for(int n=0;n<31;n++){float nzr=zr*zr-zi*zi;zi=zr*zi*2;zr=nzr;zr+=r;zi+=i;}if(zi*zi+zr*zr<4){std::cout<<"*";}else{std::cout<<" ";}}std::cout<<"\n";}} ``` Example output: ``` * ** *** ****** * ******* ******** ******* ***** * * * *** * * *************** * *** ****************** *********************** *** **************************** * **************************** * **************************** ******************************** ******************************** ********************************* * ************************************* ************************************ * ** *********************************** ** ****** ************************************ ********** ************************************* ************* ************************************ ************** ************************************ *************** *********************************** *************************************************** ****************************************************** ****************************************************** ************************************************************************ ****************************************************** ****************************************************** *************************************************** *************** *********************************** ************** ************************************ ************* ************************************ ********** ************************************* ** ****** ************************************ * ** *********************************** ************************************ ************************************* ********************************* * ******************************** ******************************** * **************************** * **************************** **************************** *********************** *** *** ****************** *************** * * * * *** * * ***** ******* ******** ******* ****** * *** ** * ``` [Answer] # CJam, 52 bytes ``` 80,Kdf/2f-_m*{_{_~*2*[\2f#~-\]1$.+}9*\;~mh4<}%80/zN* ``` Explanation: ``` 80,Kdf/2f- Push [-2, -1.95, ..., 1.95] _m* Cartesian product with itself { }% Map over each pair [cx, cy]: _ Push a copy [zx, zy] { }9* Iterate nine times: _~*2* Push 2*zx*zy [\2f#~-\] Make a pair with zx^2-zy^2 1$.+ Push [cx, cy] and sum vectors \; Destroy [cx, cy] ~mh Calculate sqrt(zx^2+zy^2) 4< 1 if bounded, 0 if not 80/ Split into rows of 80 booleans z Transpose this matrix N* Join rows with newlines ``` [Answer] # Matlab, 96 ``` [x,y,q]=ndgrid(-1:.03:1,-2:.01:.5,32);c=i*x+y;z=q*0;for i=1:100;z=z.^2+c;end;[q+3*(abs(z)<2),''] # ## ##### ############# ################## ################### #################### ################## ############# ## ########################## # # ## # ################################################ #### ######### # ######################################################### # # ######### ################################################################## ######## ################################################################################## # ##################################################################################### # ##################################################################################### # #### ########################################################################################### # # ############################################################################################## # #################################################################################################### ############################################################################################################## ######################################################################################################## # ############################################################################################################## ##### ############ ### ############################################################################################################ ############################## ################################################################################################################ ################################### ############################################################################################################### ## ####################################### ################################################################################################################ ########################################### ############################################################################################################### # ############################################### ################################################################################################################ ################################################## ############################################################################################################# ######### ################################################# ########################################################################################################### ## ## #################################################################################################################################################################### ###################################################################################################################################################################### ######## ################################################# ########################################################################################################### ############################################### ############################################################################################################# ################################################ ############################################################################################################## ######################################### ################################################################################################################ # # ###################################### ############################################################################################################### ################################ ############################################################################################################## ##### ##################### # ################################################################################################################# #### # ### # # ############################################################################################################ # ### ######################################################################################################### ####################################################################################################### ### # ## ########################################################################################################## # ################################################################################################## ################################################################################################### ################################################################################################# ###################################################################################### ##################################################################################### ############################################################################ ######### ########## ################################################################ # ######### ####### ## #################################################### # ########################################### ## ##### ## # # #### #### ## ### # ############### #################### ##################### ################### ################## # ######### ##### # ``` [Answer] # Python 3, 185 bytes Translation from perl (193) with some improvements ``` Y=-1.2 r=range for _ in r(25): X=-2 for _ in r(80): r=i=0 for n in r(16): r,i=r*r-i*i+X,2*r*i+Y if r*r+i*i>4:break print(".,:;=+itIYVXRBM "[n],end='') X+=3/80 Y+=2.4/25 ``` [Answer] # Befunge, 266 bytes ``` 0>:00p58*`#@_0>:01p78vv$$< @^+1g00,+55_v# !`\+*9<>4v$ @v30p20"?~^"< ^+1g10,+*8<$ @>p0\>\::*::882**02g*0v >^ `*:*" d":+*:-*"[Z"+g3 < |< v-*"[Z"+g30*g20**288\--\<# >2**5#>8*:*/00g"P"*58*:*v^ v*288 p20/**288:+*"[Z"+-<: >*%03 p58*:*/01g"3"* v>::^ \_^#!:-1\+-*2*:*85<^ ``` [Try it online!](http://befunge.tryitonline.net/#code=MD46MDBwNTgqYCNAXzA+OjAxcDc4dnYkJDwKQF4rMWcwMCwrNTVfdiMgIWBcKyo5PD40diQKQHYzMHAyMCI/fl4iPCBeKzFnMTAsKyo4PCQKQD5wMFw+XDo6Kjo6ODgyKiowMmcqMHYgPl4KYCo6KiIgZCI6Kyo6LSoiW1oiK2czIDwgfDwKdi0qIltaIitnMzAqZzIwKioyODhcLS1cPCMKPjIqKjUjPjgqOiovMDBnIlAiKjU4Kjoqdl4KdioyODggcDIwLyoqMjg4OisqIltaIistPDoKPiolMDMgcDU4KjoqLzAxZyIzIiogdj46Ol4KICAgXF9eIyE6LTFcKy0qMio6Kjg1PF4&input=) This is a Mandelbrot renderer that I implemented a couple of years ago for a [Rosetta Code](https://rosettacode.org/) submission. Since Befunge has no floating point, it uses a form of 14-bit fixed point arithmetic emulated with integer operations. It has a maximum of 94 iterations with the ASCII character set as the "palette". This was originally implemented with portability in mind rather than size, but it should still be reasonably well golfed as it is. **Sample Output** ![ASCII art Mandelbrot rendering](https://i.stack.imgur.com/qWggr.png) [Answer] **Python 444** ``` print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y>=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24) ``` Here's one from the **python developers**, which though isn't really short, is one line which is pretty boss. [Answer] ## [Minkolang 0.9](https://github.com/elendiastarman/Minkolang), ~~77~~ 74 bytes (INVALID) This answer is invalid because the language was created *well* after this challenge, but I'm posting it so that there's a solution in this language. Making it pretty shaved off 3 bytes woo! ``` 1~12$:;56*[i53*$:1-0c*99*[di39*$:2-+048*[d$~2`9&d*2c+]02@ik" "+Oxx]25*Ox]. ``` [Try it here.](http://play.starmaninnovations.com/minkolang/?code=1~12%24%3A%3B56*%5Bi53*%24%3A1-0c*99*%5Bdi39*%24%3A2-%2B048*%5Bd%24~2%609%26d*2c%2B%5D02%40ik%22%20%22%2BOxx%5D25*Ox%5D%2E) ### Output ``` !!!!!!!!""""""######################$$$$$$$$%%%&&(,**+ %$$$$$$######""""""""""""" !!!!!!!"""""######################$$$$$$$$$%%%%''(*3+)'&%%$$$$$$######""""""""""" !!!!!!""""#####################$$$$$$$$$$%%%%&(*--? 5+)(&%%%$$$$$#######""""""""" !!!!!""""####################$$$$$$$$$$%%&&&&'(, 2)'&%%%%%$$$#######"""""""" !!!!"""####################$$$$$$$$$%%&&&&'''()- /)('&&&&&%%$$$#######"""""" !!!!""###################$$$$$$$%%%%&)1//))+ ,202 3/.+. ('''(/&%$########""""" !!!""##################$$$$$%%%%%%&&'), / 4 +00.2+%%$########"""" !!""################$$$%%%%%%%%%&&&'()+6 +'&%$$########""" !!"##############$$%%&%%%%%%%%&&&''2 62 5,)'&%%$$########"" !!#########$$$$$%%&'.('''''''''''((*/ ,)+&%$$#########" !"#####$$$$$$$%%%%&(-,+/)*3+)*(())+ 2&%$$$########" !###$$$$$$$$%%%%%&'')+1 <56 ;/,++. +(&%$$$######### !#$$$$$$$$%%%%%%&'')+.5 ;/4 4)&%$$$$######## !$$$$$$$$%%&&&'(4*)+/ :=&%%$$$$######## !$%%%%&'&&&&''()+6; 7 )'&%%$$$$######## ?-)'&&%%$$$$######## !$%%%%&'&&&&''()+6; 7 )'&%%$$$$######## !$$$$$$$$%%&&&'(4*)+/ :=&%%$$$$######## !#$$$$$$$$%%%%%%&'')+.5 ;/4 4)&%$$$$######## !###$$$$$$$$%%%%%&'')+1 <56 ;/,++. +(&%$$$######### !"#####$$$$$$$%%%%&(-,+/)*3+)*(())+ 2&%$$$########" !!#########$$$$$%%&'.('''''''''''((*/ ,)+&%$$#########" !!"##############$$%%&%%%%%%%%&&&''2 62 5,)'&%%$$########"" !!""################$$$%%%%%%%%%&&&'()+6 +'&%$$########""" !!!""##################$$$$$%%%%%%&&'), / 4 +00.2+%%$########"""" !!!!""###################$$$$$$$%%%%&)1//))+ ,202 3/.+. ('''(/&%$########""""" !!!!"""####################$$$$$$$$$%%&&&&'''()- /)('&&&&&%%$$$#######"""""" !!!!!""""####################$$$$$$$$$$%%&&&&'(, 2)'&%%%%%$$$#######"""""""" !!!!!!""""#####################$$$$$$$$$$%%%%&(*--? 5+)(&%%%$$$$$#######""""""""" !!!!!!!"""""######################$$$$$$$$$%%%%''(*3+)'&%%$$$$$$######""""""""""" ``` ### Explanation This takes advantage of Python's internal handling of complex numbers, so I can just do `1~12$:;` (the equivalent of `(-1)**0.5` in Python) to get the imaginary unit. Then there are three nested For loops, which loop through `y`, `x`, and `z=z^2+c`. Breaking out of the innermost loop is necessary (and done by `d$~2`9&`) because otherwise, numbers will get so large that they become `(NaN+Nanj)`, which apparently has a magnitude less than 2. [Answer] # [><>](https://esolangs.org/wiki/Fish), 118 bytes ``` 1 v 2-\:01-(?;0 *&\0084 ?!\}::*{::*$@-}2**}:@@:{+r+::*{::*$@+4(&1-:&* ao\&~:*$:*+4(}" *"{?$~o1aa+,+:1)22@@?!.~~~1aa+,- ``` [Try it online!](http://fish.tryitonline.net/#code=MSB2CjItXDowMS0oPzswCiomXDAwODQKPyFcfTo6Kns6OiokQC19MioqfTpAQDp7K3IrOjoqezo6KiRAKzQoJjEtOiYqCmFvXCZ-OiokOiorNCh9IiAqIns_JH5vMWFhKywrOjEpMjJAQD8hLn5-fjFhYSssLQ&input=) Be warned, it takes about 25 seconds to run using TIO, so be patient! More of a self-challenge than a serious entry. Produces the following output: ``` * * * * **** ***** **** * * ****** * * ** ********** ****************** ****************** * ****************** ******************* *********************** * ********************* * *** ********************** ******* ********************** ********* ********************** ******************************** ********************************** ********************************************* ********************************** ******************************** ********* ********************** ******* ********************** * *** ********************** * ********************* *********************** ******************* * ****************** ****************** ****************** ** ********** * * ****** * * **** ***** **** * * * * ``` [Answer] # [;#](https://codegolf.stackexchange.com/q/121921/61563), 150,878 bytes (noncompeting) [It doesn't fit here :(](https://raw.githubusercontent.com/gimmetehcodez/____/master/mandelbrot.shb) Output: ``` !!!!!!!!"""""""""""""""""""""""""""##########$$$$%%&(.)(*2%$#######""""""""!!!!!!!!!!!!!!!!! !!!!!!!"""""""""""""""""""""""""""###########$$$$%%&'(*0+('&%$$#######""""""""!!!!!!!!!!!!!!! !!!!!!""""""""""""""""""""""""""############$$$$$%&(**-:::1('&%$$$#######""""""""!!!!!!!!!!!!! !!!!!""""""""""""""""""""""""""############$$$%%%&'(+:::::::02*&%$$$$$######""""""""!!!!!!!!!!! !!!"""""""""""""""""""""""""############$$%%%%%&&&'(4:::::::8:'&&%%%$$$$$####"""""""""!!!!!!!!! !!!""""""""""""""""""""""""##########$$$%&&'2''''(())+7::::::1*)(('&%%%%%'&$###"""""""""!!!!!!!! !!!"""""""""""""""""""""""#######$$$$$$%%&(-:0/+*,::2::::::::::::5:::('''(.+&%$##"""""""""!!!!!!! !!""""""""""""""""""""""#####$$$$$$$$$%%%&&(*3:::7:::::::::::::::::::::,::8:1)%$$##""""""""""!!!!! !""""""""""""""""""""####$$$$$$$$$$$%%%%&'()*.8::::::::::::::::::::::::::::56&%$$###""""""""""!!!! !!""""""""""""""""####$%%%$$$$$$$$%%%%%&'):8:5:::::::::::::::::::::::::::::0*(&%%$$##""""""""""!!!! !"""""""""""######$$%%(+'&&&&&&&&&&&&&&''),3:::::::::::::::::::::::::::::::::+(()%$###""""""""""!!! !"""""""#########$$$$%%)3*()(()4+(('''''(*9::::::::::::::::::::::::::::::::::::::*%$###"""""""""""!! !"""##########$$$$$$%%&'(*/:7.13::/:+*))*-:::::::::::::::::::::::::::::::::::::,(&%$####""""""""""!! ""##########$$$$$$$%&&&()+0:::::::::::2,,0:::::::::::::::::::::::::::::::::::::::&$$####"""""""""""! "#########$$$$$$$%(''((*0:::::::::::::::1::::::::::::::::::::::::::::::::::::::,'%$$#####""""""""""! ########$%%%%%%&&'(+.,..5::::::::::::::::::::::::::::::::::::::::::::::::::::::'%%$$#####""""""""""! $$$%%&&(&&'''''(,*+.:::::::::::::::::::::::::::::::::::::::::::::::::::::::::*'&%$$$#####""""""""""! $$&%%'):)('))((),,,9::::::::::::::::::::::::::::::::::::::::::::::::::::::::,('&%$$$#####""""""""""! ##$$$##$%%%%%%&&&'(*8181::::::::::::::::::::::::::::::::::::::::::::::::::::::*&%$$$#####""""""""""! "#########$$$$%%%&(+(()*.:::::::::::::::4:::::::::::::::::::::::::::::::::::::::&%$$#####""""""""""! ""##########$$$$$$$%&&'+*-2::::::::::::..4::::::::::::::::::::::::::::::::::::::/&$$####"""""""""""! """"##########$$$$$$%&&'(*2::4::::::0.**+-:::::::::::::::::::::::::::::::::::::,(&%$####"""""""""""! !"""""##########$$$$%%&'-3.-*)*-:+)8(((()*.:::::::::::::::::::::::::::::::::::::,'%$####""""""""""!! !"""""""""#######$$$%%'4''&&&')('&&&&&''(+/::::::::::::::::::::::::::::::::::-5+-%$###""""""""""!!! !"""""""""""""""####$%&%%%%%%$$$%%%%%&&&')::::::::::::::::::::::::::::::::::.('&%$$###""""""""""!!! !"""""""""""""""""""###$$$$$$$$$$$$%%%%%&(-*-1:::::::::::::::::::::::::::::/(&%$$###""""""""""!!!! !!"""""""""""""""""""""#####$$$$$$$$$%%%%&'(+::::::::::::::::::::::::::0::::,7%$$##""""""""""!!!!! !!"""""""""""""""""""""""#######$$$$$$%%%&*:::4:+-::::::::::::::::::.)):7)+,(%$##""""""""""!!!!!! !!!""""""""""""""""""""""""##########$$$%&:)2/)(((+,*+,/::::::/,+))5(&&&&&'+%$##""""""""""!!!!!!! !!!!"""""""""""""""""""""""""###########$$%%%%%&&&''),::::::::8('&&%%%%$$$$###"""""""""!!!!!!!!! !!!!""""""""""""""""""""""""""############$$$%%%%&'(+::::::::-(&%%$$$$$#####"""""""""!!!!!!!!!! !!!!!""""""""""""""""""""""""""############$$$$$%%)+2,/:::,**'%$$$$#######""""""""!!!!!!!!!!!! !!!!!!"""""""""""""""""""""""""""###########$$$$$%&&'),:,)'&%$$$#######""""""""!!!!!!!!!!!!!! !!!!!!!!""""""""""""""""""""""""""###########$$$$%&'(.,,-*%%$#######"""""""!!!!!!!!!!!!!!!!! ``` ]
[Question] [ Based on [Practical Golf - US States](https://codegolf.stackexchange.com/questions/38499/practical-golf-us-states) Your task is to find the abbreviation (symbol) of an element given the element name, up to and including ununoctium (118). Use the periodic table on [Wikipedia](https://en.wikipedia.org/w/index.php?title=Periodic_table_(large_version)&oldid=627552839). Thanks to squeamish ossifrage, you can find a full list of elements to abbreviations at <http://pastebin.com/DNZMWmuf>. You may not use any external resources. In addition, you may not use any built-in data specifically about the elements of the periodic table. Standard loopholes apply. **Input** Input may be from stdin, file, `prompt`, `input` etc. Input Format: All of the following are valid inputs: ``` Carbon carbon CARBON cArBOn ``` Essentially, the element name - case insensitive. You do not have to handle misspellings or any invalid element name. Invalid input is undefined behavior. **Output**: The symbol for the element. The first character **must** be capitalized and the rest **must** be lowercase. Example output: `C` Test cases: ``` Carbon -> C NiTROGen -> N Sodium -> Na Gold -> Au Silver -> Ag Tin -> Sn ``` There are many more elements than states, so I expect it to be harder to find a general rule for these. This is code golf. Shortest code wins! [Answer] # C, 452 A good hash function helps. There may be better ones. (Improvements suggested by [@ugoren](https://codegolf.stackexchange.com/users/3544/) et al.) ``` h;main(c){char*p="Sn)Cu&V$U#Mo#Rf#Sg&Cs#Y+FTa%Rb)S'Nd#GaK&Mg'Zr$PtPm%ReUuo#SmDy(Ac$Lu%W&CaRa(Cf)EuB#Ds%Md$Uus*NpIn$H&YbIr*BeEs*Tc#I(FlRuC#ThSrBh/NaCoLrKr&Nb$CePb$Ne'Am)At*PdLa#Tl%HgMt,CrTbBk$Rh&Rn4TeZn$HfAg%Fm)Xe$AlScFePo$As'HeO#LvN&DbGe#Ho&Mn$Cd+Ni$Rg$HsBr$AuSi#Pr&Uup#Se*Ti#Tm$Er$Sb&PPu&Cm$GdBa'Cn&UutLiFr#Ar#Bi#NoOs%Pa4Cl";while((c=getchar())>64)h=(h+c%32+74)*311%441;while(h)if(*p<65?h-=*p++-34,0:1)for(h--;*++p>96;);do putchar(*p++);while(*p>96);} ``` Ungolfed with comments: ``` int h; main(c) { /* Hashed element symbols. Characters #$% etc. are used as padding: */ char *p="Sn)Cu&V$U#Mo#Rf#Sg&Cs#Y+FTa%Rb)S'Nd#GaK&Mg'Zr$PtPm%ReUuo#SmDy(Ac$Lu%W&C" "aRa(Cf)EuB#Ds%Md$Uus*NpIn$H&YbIr*BeEs*Tc#I(FlRuC#ThSrBh/NaCoLrKr&Nb$CeP" "b$Ne'Am)At*PdLa#Tl%HgMt,CrTbBk$Rh&Rn4TeZn$HfAg%Fm)Xe$AlScFePo$As'HeO#Lv" "N&DbGe#Ho&Mn$Cd+Ni$Rg$HsBr$AuSi#Pr&Uup#Se*Ti#Tm$Er$Sb&PPu&Cm$GdBa'Cn&Uu" "tLiFr#Ar#Bi#NoOs%Pa4Cl"; /* This hash function gives a unique result for each element: */ while((c=getchar())>64) h=(h+c%32+74)*311%441; /* Find the corresponding position in the hashed data */ while(h) { if(*p<65?h-=*p++-34,0:1) { /* Step over an abbreviation */ for(h--;*++p>96;); /* Skip padding */ } } /* Output first uppercase character and all following lowercase characters: */ do { putchar(*p++); } while(*p>96); } ``` I used brute force to find this hash; This was the only one with a hash size of ≤512 that had no collisions. I didn't check alternative spellings though, and there might be better functions with different algorithms (e.g. using XOR instead of addition). The hash function maps text strings to values from 0 to 440. "Tin" hashes to zero, so "Sn" is at the start of the table. The next 7 positions are empty. To keep the code compact, this is indicated by the ASCII value 34+7=41 (")"). Next comes "Copper" (8), four empty cells (34+4=38="&"), and "Vanadium" (13). After calculating a hash, the program steps through the table, subtracting 1 for every capital letter followed by 0 or more lowercase letters, and subtracting (ASCII VALUE)-34 for every non-alphabet character. When the value reaches zero, we have found the correct result. [Answer] # CJam, ~~337~~ ~~297~~ ~~293~~ ~~232~~ ~~220~~ ~~201~~ 200 bytes ``` leu:E2f^3b2+4%_"53N5903CVCT4":i3/=~Ef+b\%]53b"gØâ^ÃP·^À4ξ^ß^E5^W^Ma{áª^B¤±´oòæ»^XÊQÑ»4žDÙÝòÙ 0^ÝþKa6^Ó£,Ûkû¥¡ùh^E"256b7b6a/0a3**<)5md@5a/,(" ¬^GH/N¿·%^U^RU1²Bd òë^м~í^ÌéáU"256b25b'Af+2/='J-'Q/"UU"*\)_5=)*E%2<?(\el ``` The above code uses caret notation, since it contains control characters. At the cost of 24 additional bytes (for a total of 224), those characters can be avoided. ``` leu:E2f^3b2+4%_"53N5903CVCT4":i3/=~Ef+b\%]53b "' NwEvKv6e8@]jO4G)=b{L!v@hFQ/oCN)*|BRxvNRL+LO7NI(pLs4[d87$Q%8R\t+' M5JU" {32f-95b}:B~7b6a/0a3**<)5md@5a/,( "&y.$h*z^t\rQPUc]l8F h$=18C^r|vD~S" B25b'Af+2/='J-'Q/"UU"*\)_5=)*E%2<?(\el ``` You can try this code in the [CJam interpreter](http://cjam.aditsu.net/). ### Test cases ``` $ base64 -d > elements.cjam <<< bGV1OkUyZl4zYjIrNCVfIjUzTjU5MDNDVkNUNCI6aTMvPX5FZitiXCVdNTNiImfY4oNQt4A0zr6fBTUXDWF74aoCpLG0b/LmuxjKUdG7NMW+RNnd8tmgMJ3+S2E2k6Ms22v7paH5aAUiMjU2YjdiNmEvMGEzKio8KTVtZEA1YS8sKCIgrAdIL06/tyUVElUxskJkCvLrkLx+7Yzp4VUiMjU2YjI1YidBZisyLz0nSi0nUS8iVVUiKlwpXzU9KSpFJTI8PyhcZWw= $ cksum elements.cjam 952664534 200 elements.cjam $ for e in Carbon NiTROGen Sodium Gold Silver Tin; do LANG=en_US cjam elements.cjam <<< $e; echo; done C N Na Au Ag Sn ``` ### How it works The first step is to read the element name from STDIN and apply a rather elaborated hash function, which maps all element names in the range **[0, 225]**: ``` l eu :E " Read a line from STDIN, convert to uppercase and save in E. "; 2 f^ " XOR each character code with 2. "; 3 b " Convert to integer; consider the resulting array a base 3 number. "; 2 + 4 % " Add 2 and take the result modulo 4. Result: R "; "53N5903CVCT4":i " Push [53 51 78 53 57 48 51 67 86 67 84 52]. "; 3 / = " Retrieve the chunk of length 3 that corresponds to R. Result: C "; ~ E f+ " Add C[2] to all character codes of E. "; b " Convert to integer; consider the resulting array a base C[1] number. "; \ % " Take the integer modulo C[0]. Result: M "; ] 53 b " Push H := 53 * R + M. "; ``` Many element symbols are formed by the first and second, first and third, first and fourth, first and fifth or first and tenth (which is just the first) character of the element's English name. We are going to represent these elements by numbers from 0 to 4 respectively. All remaining elements (represented by 5) will require a lookup table. The resulting table can be pushed as follows: ``` "gØâ^ÃP·^À4ξ^ß^E5^W^Ma{áª^B¤±´oòæ»^XÊQÑ»4žDÙÝòÙ 0^ÝþKa6^Ó£,Ûkû¥¡ùh^E"256b7b6a/0a3** ``` The array of character codes gets converted from base 256 to base 7 and 6's are replaced by runs of three 0's. This is the decision table D: ``` [4 0 0 0 1 0 0 0 0 0 0 3 0 2 0 1 0 0 0 0 0 0 0 0 4 1 1 0 0 0 0 2 0 4 0 5 2 0 0 3 4 0 0 0 0 4 0 1 0 0 3 1 0 0 2 1 1 1 0 0 0 1 0 5 5 0 0 2 0 0 0 5 5 0 0 0 5 0 3 0 0 0 0 5 0 0 0 0 0 0 0 0 5 2 3 0 1 0 5 0 4 0 0 0 0 4 0 5 0 0 0 0 0 5 0 0 0 2 5 1 4 1 5 0 0 0 5 0 0 5 1 1 0 0 0 0 0 0 2 0 5 0 0 0 3 1 0 2 0 0 0 2 0 0 0 5 0 0 0 0 1 0 0 0 0 0 4 0 2 2 5 2 0 0 5 1 0 0 0 0 4 0 5 0 0 3 5 0 0 5 0 1 0 0 0 2 0 0 0 0 0 5 0 4 0 0 0 0 0 0 0 0 3 0 4 0 0 1 2 2 0 0 0 0 0] ``` The necessary action for the element with hash **1**, e.g., corresponds to the first element of the this array. Array elements that do not correspond to any element's hash are also zero, which allows the **(0 0 0) ↦ 6** compression. Now, we interpret D for hash H. ``` < ) 5 md " Push D[:H-1] (D[H-1] / 5) (D[H-1] % 5). "; @ 5a / , ( " Count the number of 5's in D[:H-1] (by splitting at [5]). Result: I "; ``` Next, we push the lookup table. If we append **j** to single-character symbols and replace **Uu** with **Q**, each symbol will be exactly two characters long. It can be pushed as follows: ``` " ¬^GH/N¿·%^U^RU1²Bd òë^м~í^ÌéáU"256b25b'Af+2/ ``` The array of character codes gets converted from base 256 to base 25, the character code of **A** gets added to all digits (casting to Character in the process) and the result is split into chunks of length two. This is the lookup table L: ``` ["QP" "YB" "PD" "SN" "QO" "QT" "QS" "SB" "KJ" "TM" "FE" "PB" "AU" "WJ" "CN" "SG" "RF" "CM" "CU" "HG" "NA" "RG" "AG"] ``` Now, we proceed to compute potential element names. ``` = " Push L[I]. "; 'J - 'Q / "UU" * " Remove J's and replace Q's with runs of two U's. "; \ ) _ 5 = ) * " Push S := (D[H-1] % 5 + 1) * ((D[H-1] % 5 + 1 == 5) + 1). "; E % " Push every Sth character of E. "; 2 < " Discard all but the first two characters. "; ``` The stack now contains ``` B M N ``` where **B** is the Boolean **D[H-1] / 5**, **M** is the name retrieved from the lookup table an **N** is the element name formed by selecting characters from E. We're almost done: ``` ? " If B, push M; else, push N. "; ( \ " Extract the first character from the string. "; el " Convert the rest to lowercase. "; ``` [Answer] # JavaScript ES6, 690 ~~708~~ bytes ``` for(n=prompt()[l='toLowerCase'](i=0);!(c='HHeLiBeBCNFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'.match(x=/[A-Z][a-z]*/g)['HyHeLitBeryBorCarNitFluNeonSoMagAlSiliPhSuChlArgPotCalcScTitVChrManIroCobNicCoppZinGalGeArsSelBrKRubStYttrZirNioMoTecRuthenRhoPaSilvCadInTinAnTelIoXCaeBaLanCePraNeodPromSaEuGadTerDyHoErThuYtteLuHafTaTuRheOsIriPlaGoMerThaLeBiPolAsRadoFrRadiAcThoProtUrNepPluAmCuBerkCaliEiFeMenNoLawRutherDuSeaBohHasMeiDaRoCopeUnuntFleUnunpLivUnunsUnuno'.match(x).map(a=>a[l]()).indexOf(n.slice(0,i++))]);) alert(c) ``` The first array holds the symbols, and the second array holds the minimum letters necessary to tell which element is being referred to. Thanks to core1024 and edc65 for helping shorten it. Test at <http://jsfiddle.net/xjdev4m6/2/>. Slightly more readable: ``` n=prompt().toLowerCase() e='HyHeLitBeryBorCarNitFluNeonSoMagAlSiliPhSuChlArgPotCalcScTitVChrManIroCobNicCoppZinGalGeArsSelBrKRubStYttrZirNioMoTecRuthenRhoPaSilvCadInTinAnTelIoXCaeBaLanCePraNeodPromSaEuGadTerDyHoErThuYtteLuHafTaTuRheOsIriPlaGoMerThaLeBiPolAsRadoFrRadiAcThoProtUrNepPluAmCuBerkCaliEiFeMenNoLawRutherDuSeaBohHasMeiDaRoCopeUnuntFleUnunpLivUnunsUnuno'.match(x=/[A-Z][a-z]*/g).map(a=>a.toLowerCase()) s='HHeLiBeBCNFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'.match(x) for(i=0;i<7;i++){ if(c=s[e.indexOf(n.slice(0,i))]){ alert(c,i=8) // i=8 breaks out of the loop so the result is only alerted once } } ``` [Answer] **Ruby 1.9+, 565 471 447 444** A one-liner. Because nothing is "impossible to do with regexes"... (Just saved 94 chars by adding another regex) ((and 24 by simplifying them)) ``` p"VAlAmA.sArAcAnt|SbA.tBaB..kBeBiB.hBrBDyD.+sD.bE..sErEuF..mFrFlu|[[email protected]](/cdn-cgi/l/email-protection)|AuH.fH.sHeHoHInIro|FeIrIKrL.vL.+rLaLiLuL|PbM.gMoM.+dM.nM.+tM|HgC.+sC.dC.+fCeCar|[[email protected]](/cdn-cgi/l/email-protection)|CmCop|CuCoC.rC.lN.+dN.+pNeN..bNit|[[email protected]](/cdn-cgi/l/email-protection)|PdP...aPrP.uP..tPot|KPoPR.*n$RaR.+gR.eRhR.+bR.+fRuS.mScS.+gSeS..v|AgSiSo|NaS.rSTaT.cT.+bTeThu|TmT..lThTin|SnTiTu|WU.u.oU.u.pU.u.sU.u.tUXeY.+bYZ.nZ.r" .split(/(?<!\|)(?=[A-Z])/).find{|r|/^#{r}/i.match *$*}.gsub /.*\||\W/,'' ``` *(newline after string added for "readability", remove for test)* usage: `ruby periodic.rb aluminum` $> Explanation: [Splitting the string on leading capitals](https://stackoverflow.com/q/26260767/10396) returns an array of regex to match against element names. The only alphabetic characters allowed in each are those from the abbreviation\*. They are ordered such that the first match found when comparing to the command line argument `*$*` is the correct one. The trailing gsub strips out the non-alpha characters before printing. \*Odd abbreviations like "Fe" for "Iron" are handled by a `|` element: "Iro|Fe". The first choice is what is actually matched; the gsub then removes all characters up to the '|', leaving the actual abbreviation. Test framework (requires [@squeamish's list](http://pastebin.com/DNZMWmuf): downloaded as 'table.txt' in the working directory). ``` def testfunc(name) #replace with however you call your code return `ruby1.9.3 periodic2.rb #{name}`.chomp() end elements= File.new('table.txt').readlines.map{|s|s.chomp} elements.each{|l| a,n=l.split(' ') r = testfunc(n) print "#{n} => #{a} " if r!=a then print ("FAIL: gave #{r}\n") exit else print("\tOK\n") end } print("PASS: #{elements.size} elements matched\n") ``` [Answer] ## Ruby, 1068 bytes ``` require"zlib" require"base64" $><<eval(Zlib::Inflate.inflate(Base64.decode64"eJwlU8tu2zAQ/Bee+QW6CLYTx0FiR7CdtsmNkmhJCEUKfKQViv57Z9YnE+vd2ZnZ0d+1j2Go6oO2bipzpQ5W6SmPU6nU66S0jatzldqiGmLwVb3VJrZ87NAmoyf9Zx0sKm/alRCnqt5riw514lAvqCejtBm8TZU6Dgp984SGjcMuN3WhUhfsGkNaxqpudHG3Eqv6okdHPLVDXxwIuYmAzCalqn7RxnWkuQN2Z3yPxktH8sbjeQWg8QbV+oceY5iJE1kbDICOHpBE3JNka1zG3wHT3ZeF3hOmw7LYiGpB1XeV+sSIcY4rnwydmQn0hPmYLFduEqpOnhdWg4jcYmlclwyRL3iWdiLTc6s07PNYe0E15wjc+kNPsSOrT9Sm0HLXCZ3BrW0P0iBou9FbyIPSkkfYrs6F1vXsPY9C0aC36entNxVs4LjpZ/EKVX8/ybOnLqzHr8/TzCO0FODgvbreb4dV9bO2npx+oWSTzO6g1ER5bnlZn0eDvIgr9wbqN8kCtIEUG/qVKejFFQvRzYyx2fC6FzxLDAuej4VMg8PzqSeYOHAFrTUtEWAPK80QKQeYwf+B+4gVY5HLXGeaicFKfbS0yGaAvRL35mXsJnwNjnwF3+KHlKv6p4aV4iCIp1lQ3yAyTuLrMxY4k2lXk8kABm8KCXY06wCDR0YDmIiqFf+xfUpzgdYtw+QCc9GAdMqGnDZZtPKAzKLxHYp7JvR+nzNjjZVs7XjhKPpGWpgN8tgYGWNu3rVdcuEnt/DjykRtwG/GOdC5EYfvh5nJWjK+/WJYphts3d2YhZQRrMck0eauPXt9z95jz6/EUuEJEszvyOS9xnsIYcH5xmiLhQ9MkWkDqhcYE0YhvmU0U5ITcMWUGeMjTYgzTqAeUA3W5wFgHMPHhxU7prP4DLD3gmZnY/gGNSflxbIMzROCDnWv31JOUk7yDh3fQf37D7D/kWs="))[gets.downcase[1..5].to_sym] ``` Input via STDIN. The shortest unique substrings of the element names are from the second to the sixth character (or the end of the name if its too short). So I'm simply getting those and looking them up in a hash. I also compressed the hash because that saves another 200 bytes. Here is what the hash itself looks like: ``` {ydrog:?H,elium:"He",ithiu:"Li",eryll:"Be",oron:?B,arbon:?C,itrog:?N,xygen:?O,luori:?F,eon:"Ne", odium:"Na",agnes:"Mg",lumin:"Al",ilico:"Si",hosph:?P,ulfur:?S,hlori:"Cl",rgon:"Ar",otass:?K, alciu:"Ca",candi:"Sc",itani:"Ti",anadi:?V,hromi:"Cr",angan:"Mn",ron:"Fe",obalt:"Co",ickel:"Ni", opper:"Cu",inc:"Zn",alliu:"Ga",erman:"Ge",rseni:"As",eleni:"Se",romin:"Br",rypto:"Kr",ubidi:"Rb", tront:"Sr",ttriu:?Y,ircon:"Zr",iobiu:"Nb",olybd:"Mo",echne:"Tc",uthen:"Ru",hodiu:"Rh",allad:"Pd", ilver:"Ag",admiu:"Cd",ndium:"In",in:"Sn",ntimo:"Sb",ellur:"Te",odine:?I,enon:"Xe",esium:"Cs", arium:"Ba",antha:"La",erium:"Ce",raseo:"Pr",eodym:"Nd",romet:"Pm",amari:"Sm",uropi:"Eu", adoli:"Gd",erbiu:"Tb",yspro:"Dy",olmiu:"Ho",rbium:"Er",huliu:"Tm",tterb:"Yb",uteti:"Lu", afniu:"Hf",antal:"Ta",ungst:?W,heniu:"Re",smium:"Os",ridiu:"Ir",latin:"Pt",old:"Au",ercur:"Hg", halli:"Tl",ead:"Pb",ismut:"Bi",oloni:"Po",stati:"At",adon:"Rn",ranci:"Fr",adium:"Ra",ctini:"Ac", horiu:"Th",rotac:"Pa",raniu:?U,eptun:"Np",luton:"Pu",meric:"Am",urium:"Cm",erkel:"Bk",alifo:"Cf", inste:"Es",ermiu:"Fm",endel:"Md",obeli:"No",awren:"Lr",uther:"Rf",ubniu:"Db",eabor:"Sg", ohriu:"Bh",assiu:"Hs",eitne:"Mt",armst:"Ds",oentg:"Rg",opern:"Cn",nuntr:"Uut",lerov:"Fl", nunpe:"Uup",iverm:"Lv",nunse:"Uus",nunoc:"Uuo"} ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 298 bytes ``` s=>(i=`23>3c9@94=4E33:3Q0I3:9[020G0O3@74M9=4A6@4;7J5H96?9K0L723E4343A4R40A0T9D3J5H4?4?3J329>9P9;359:0B9^3=95h6:9<6M0~D0@0N3<3;0:9@4<4<6H3I3`.replace(/\D/g,s=>"2".repeat(Buffer(s)[0]-56))[h=parseInt(s,36)*184%901])-9?s[0]+[s[i-1]]:`Ag,Fe,Hg,,W,Sn,K,Cu,Pb,,Sb,Au,,Na`.split`,`[h%418%48%15]||'Uu'+s[4] ``` [Try it online!](https://tio.run/##RVXbcts2EH3PV2g845HU0A5t0kpoW7apm6VYklVJzk1VxxAJkUxIgAOAbjWTyRd0pi99bP@j35Mf6Ce4IHehvEiD5WJx9pyDxWfyRGQgklwdMR7S5237WbavGkn78dS5cgLvxnPbbt9xzp2f7ZFz7q3sU/vWvnduXrsTr@36rRv34vXbs6HXuvbu7PHrU6fvOq7ju3PX9u2l13P0R/favXbeOqfelTfzLpwz79zueL86be8sbp17l62J/a1n39hT59K5sM@9G/fSvWwNnZHzeCxonpKANl790nsVWRrawelBGaRENTrFdktFQzZX9vrorNVsruJ2ToSkI6Ya0nJazZ9O3riHnn2ybh5511KnvVzJVXJ0sl6fP/qRNaDWMLKs99aCWXdWt7BmG8tabCy/sKwpeTyWeZqoR@txFR@6J28O3TeHJ2frr1/rD0X9pVy56@eL1YvVwXAXCh5RdmAdDA/Wlg7QNCmyckmr9ThRMQTGSRXoULFLMacDOR0ueFmhU626RGyqZbdaThNlTphWgfvfd7C8r5aDtOAiYVQHBrCBVrunUHvBQzhrSqr1hESMSghNoirkp0WWMAj5KexK0iSoyiwA9SzmMo@5KKSOzSCnSLeFKFMAdpwaHF0o4ouoKuELKMEVkXjyHXaaBrDuArhFQBjCXQRVZJkogtCWgOQdYQRz3uHBgmdYRmCPLCK6yxLLhFWhETA8AFK6fENSVW7gyHHwhaYlSQl@z3NattYtqvWnhAV69Qlq3RKj3y3AvqUiMyhvKfYuKUvKTb6E1mhKMWWBqpewK746APtO7HJVwbyDwLzYJNjqfANVtBeYwjKQ9FEpAYGPiFVo5SDySWB7fIMmgDITnu42IWXgAuBgSYOYUay9DBCAig3qOVAxj42h5jHIqtkwgsxC456nij4/Qp1DIxAkjIzKI4YqV1aDha8bzDjblZENQkvTAptcAnkjjaLiblQtP1BWEfcB9SXG4l1gv0NwewcUGxOmYgL9jyHUpZjShRozQSTl4Q6Rz4S5XPvQNMREnlFzyWcZMEAyc@ICIv1C8Bwi/QJtFPLU3LvbEDsVqNQSWu/tZC44NtPbwYjhKSIYgnR9s6kPIJdxgQZdZsYj@8IfofC4UEbsMeAZki2CGW6hjCaJpFAHOFoWLJKqGj7v0Q17ewBr9xKh3Uu8d8bBI5wCKVEJED9TwANPw9IrgGJCRVCIUvxhhM3sr9sS5sqYknLDDBrpJDLTNi21xVHFU@P/GfDjS1UeWtrFhzPnmvuyizlYbiAIw0k0ECYB@4LO/UDtRyROJj0NEVZsfKDIj7QZbHwQZjI8oIFyVWBkmiMlhdojBhb8TLsREfmgYdfcgG5m3pEv5q3pfDHzNNlygaW6oGI/YVoyg6oPsgz0xMJ@M6SdhXpCPeHDAG6c8o05Ycrx3vwmqKFqLH4MCaHPNYzBub1ig2f2cHZRsuEiwlsR4csXm4sZownNEzGUCCxRzFzNCajXIyLTkobo3x5kzjllKtr7MTKTnGpCzDMDcj@wgpmh@VAofEap4Nj@IN2n5dSM24cixwddz7bMaD9@2qdKraxJlfsoD/ZBTeGL9YtjzVSfBHGjsWIko1ZN7rLNullrX9X03JY8pccpjxrlt@OchH0WNk7cZu1lrf7tqlbX/w1BZa1d21YpzaZJqnLgW7uqWbuu1f/798/vf/@lf@u181r9@z9/1JvN5vP/ "JavaScript (Node.js) – Try It Online") ## How? ### Element groups We split the elements into 3 groups: * **Group 1**: 12 elements whose symbol is the first letter of their name, such as `Carbon -> C`. * **Group 2**: 91 elements whose symbol is the first letter of their name, followed by the \$n\$-th letter (0-indexed) with \$1\le n \le6\$. Examples: `Helium -> He` (\$n=1\$), `Zirconium -> Zr` (\$n=2\$). * **Group 3**: 15 elements that do not belong to the other groups, such as `Iron -> Fe`. This means that all elements can be encoded with a single digit: we use \$0\$ for group 1, \$n+1\$ for group 2 and \$9\$ for group 3. (Obviously, we'll need some extra data for group 3. More on that later.) It is worth noting that 44 symbols simply consist of the first two letters of the element name. That's almost 50% of group 2. These ones will be encoded with a `"2"`, so that's the padding character that we want to use in our lookup string. ### Hash function, lookup string and compression We apply the following hash function (found by brute-force) on the input string: ``` h = parseInt(s, 36) * 184 % 901 ``` The corresponding lookup string is \$899\$ characters long, which is pretty big. But, by design, we have many runs of consecutive \$2\$'s in there. Our compression strategy is to replace each run of \$2\$'s of length \$2\le n\le70\$ with the character whose ASCII code is \$n+56\$ (that's the range going from `":"` to `"~"`). The compressed string is only \$132\$ characters long. You can see the decompression process here: [Try it online!](https://tio.run/##hc7NTsJQEAXgPU9xw6ZtFJh0piVz20JBjIDiX3QFGmq5FExtSW9rogtfvda4wo27ycz5Juc1eo90XOwPZSfLN6qutQjE2sYBxhwyBXSOKPEOZih5CTZcwA2GfVpwQCM3JK8/d6bsDvkSrvo2nhMSjuieYAQPPMHmSEMa4hxtHvAte@iwhDE/Y8DOzpXsuwv4mkAI1@ijB5JD8sl3pzjDtdeqmi66W6hDGsXK7K0mveRUNAUHom23f/YqKs1xtd2qwtTWEp5ERziuZXmtVpxnOk9VN80T0zjL3w6F0lpthN5/KiGkMMRJ8zpVWVLumtEQLx@l0kZDj@RjFh/bX1n9L1fZsS2LfZbIv7HK8ur6Gw "JavaScript (Node.js) – Try It Online") ### Decoding Groups 1 and 2 are decoded the same way: ``` s[0] + [s[i - 1]] ``` (NB: For group 1, `s[-1]` is undefined and `[undefined]` is coerced to an empty string.) For group 3, we use another hash function and another lookup string (also found by brute-force): ``` `Ag,Fe,Hg,,W,Sn,K,Cu,Pb,,Sb,Au,,Na`.split`,`[h % 418 % 48 % 15] ``` There are 4 remaining superheavy elements that are not included above. Because they are referred to by their temporary names and thanks to the [systematic nomenclature](https://en.wikipedia.org/wiki/Systematic_element_name), we can build the symbols for these ones by concatenating `"Uu"` with the fifth letter of their name: ``` v Unun**t**rium -> Uut Unun**p**entium -> Uup Unun**s**eptium -> Uus Unun**o**ctium -> Uuo ^ ``` Hence the last part of the code: ``` || 'Uu' + s[4] ``` [Answer] # Python - ~~652 649~~ 637 My hash table is based on the combination of every second and every third character of the uppercase name: ``` import re def f(s,c='S<8F0FCE;2.ACR;J@W$;BI8>GD*?GnHQ<K>&T\(51IAg/Y?S2=169.,325(F(98?>?=^97DUCITX;SJ`0C<P9iLP/G4B,A(-A?(3QLLZ;81D(.4F;L8GaVP[=\=cOX3U,LQl6:E9/OXdSe(4,TSV/=FN98?K.18Q>R$+<GG[IS-4?;4H;T/IMq9<LXMYH4HG<>>KTT,>IIEM,[Nf<,:Z60(A9fImZTMRTcM?[lVg^qC}',e='HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnUutFlUupLvUusUuo'): U=s.upper();X=lambda x:chr(32+sum(ord(u)-65for u in x)) return re.findall('[A-Z][a-z]*',e)[zip(c[::2],c[1::2]).index((X(U[1::3]),X(U[:-1:2])))] ``` Here is the corresponding generator: ``` table = ''' H Hydrogen He Helium ... Uuo Ununoctium ''' table = map(lambda l: l.split(), table.split('\n')[1:-1]) abbr = [] for name in map(str.upper, zip(*table)[1]): abbr.append(chr(32+sum(ord(u)-65 for u in name[1::3]))+ chr(32+sum(ord(u)-65 for u in name[:-1:2]))) print 'c=' + ''.join(abbr) print 'e=' + ''.join(zip(*table)[0]) print 'Unique' if len(table) == len(set(abbr)) else 'Duplicates' ``` There's probably room for improvements, especially compressing the two long strings. Tested with: ``` for short, name in table: if f(name) != short: print "Wrong result!" ``` [Answer] # CJam, ~~462 449 434 401 391 384~~ 382 With help from Dennis. ## Code Nested ternary ifs are ***probably*** not the right way to do this in CJam. ``` rel_"ruthen"#!"Ru"{_"tel"#!"Te"{__5{\_ceu\@=+_}:U~"PdYbRgCmCn"{\#)!}:X~{;__4U"RnPaCfDs"X{;_3U"NbCsNdPmTbPtTlBkEsFmMdLrMt"X{;2U"MgClCrMnZnAsRbSrZrTcCdSmGdHfReAtNpPuDbBhHsLv"X{;__"sili"#{;__ceu\1=@2=++"SodIroCopSilTinAntThuGolMerLeaTunPotRutSeaHydBorCarNitOxyFluPhoSulVanYttIodUra"\#3d/m[)"_NaFeCuAgSnSbTmAuHgPbWKRfSgHBCNOFPSVYIU"S%\=_"_"={;_1U"Un"={;4="Uu"\+}*}*}"Si"?}*}*}*}*}?}?]W= ``` With indents: ``` rel _"ruthen"#!"Ru" { _"tel"#!"Te" { __5{\_ceu\@=+_}:U~ "PdYbRgCmCn"{\#)!}:X~ { ;__4U "RnPaCfDs"X { ;_3U "NbCsNdPmTbPtTlBkEsFmMdLrMt"X { ;2U "MgClCrMnZnAsRbSrZrTcCdSmGdHfReAtNpPuDbBhHsLv"X { ;__"sili"# { ;__ceu\1=@2=++"SodIroCopSilTinAntThuGolMerLeaTunPotRutSeaHydBorCarNitOxyFluPhoSulVanYttIodUra"\#3d/m[)"_ Na Fe Cu Ag Sn Sb Tm Au Hg Pb W K Rf Sg H B C N O F P S V Y I U"S%\=_"_"= {;_1U"Un"={;4="Uu"\+}*}* } "Si"? }* }* }* }* }? }? ]W= ``` Many of the symbols are just the first two letters of the element's name. These are handled in the second-deepest layer of nested if statements. Many others are the first and third letter, or the first and fourth letter - these are handled in successive outer layers. Symbols where only the first letter appears, and complete irregulars, are handled in the fifth and third deepest layers respectively. There are a few where it gets confused (`TelLurium` vs `ThaLlium`, or `SILicon` vs `SILver`, or `RUThenium` vs `RUTherfordium`). These are handled separately. A lot of golfing could be done here, mostly by reusing code blocks and improving handling of irregulars. [Answer] # PHP, 507 485 476 466 characters Usage: enter the element name as GET parameter '0' - elements.php?0=carbon Algorithm: Run through the data string, pulling out substring,abbreviation code pairs. If the substring matches the start of the element passed in, use the abbreviation code to determine what to output: If the code starts with a letter, output it as a string. If it is a number N, output the first letter of the element + the Nth letter. The Unun elements are special-cased with the code '|'. If no substring is found that matches the name passed in, output the first two characters of the name as the abbreviation. Readable Code: ``` <? $l=ucfirst(strtolower($_GET[0])); for( $m[3]="AnSbArs2As2Berk3Boh2BoBCad2Cae3Cali4CarCChl2Ch2Cope5CopCuCu5Da4Du2Ei3Fe3FluFGad2GoAuHaf2Ha2HyHIo0IroFeLaw3LePbLiv2Mag2Man2Mei3Men3MeHgNeod3Nep2Nio3NiNOxOPa5PhPPla3Plu2PotKProm3Pro4Rado4Rhe2Roe5Rub2Ruther6Sa2Sea6SilvAgSoNaSt2SuSTec2Ter3Tha3Thu6TinSnTuWUn|UUVVYtte5YYZin2Z2"; preg_match('/(.[a-z]*)(.[a-z]*)(.*)/',$m[3],$m) ;) if(strstr($l,$m[1])) echo($x=$m[2][0])>'@'?$x>'{'?"Uu$l[4]":$m[2]:$l[0].$l[$x],die; echo$l[0],$l[1]; ``` Condensed: ``` <?$l=ucfirst(strtolower($_GET[0]));for($m[3]="AnSbArs2As2Berk3Boh2BoBCad2Cae3Cali4CarCChl2Ch2Cope5CopCuCu5Da4Du2Ei3Fe3FluFGad2GoAuHaf2Ha2HyHIo0IroFeLaw3LePbLiv2Mag2Man2Mei3Men3MeHgNeod3Nep2Nio3NiNOxOPa5PhPPla3Plu2PotKProm3Pro4Rado4Rhe2Roe5Rub2Ruther6Sa2Sea6SilvAgSoNaSt2SuSTec2Ter3Tha3Thu6TinSnTuWUn|UUVVYtte5YYZin2Z2";preg_match('/(.[a-z]*)(.[a-z]*)(.*)/',$m[3],$m);)if(strstr($l,$m[1]))echo($x=$m[2][0])>'@'?$x>'{'?"Uu$l[4]":$m[2]:$l[0].$l[$x],die;echo$l[0],$l[1]; ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~121~~ ~~117~~ ~~112~~ ~~110~~ 109 bytes ``` •S²c¾rƒã∞Øø”.ÑSZl›¹'•2в°T•2nZιć‹ε˜Órv†„₃}Z$+àFQ$•7в1.•®DÝ∍ÌoƵižÒƵaŒ•2ô.;.;6ÝIS¬ì:slƵ{ö•X»²ÄµÕΛεĀδkM•9ävy%}èÙ™ ``` [Try it online!](https://tio.run/##AcgAN/9vc2FiaWX//@KAolPCsmPCvnLGksOj4oiew5jDuOKAnS7DkVNabOKAusK5J@KAojLQssKwVOKAojJuWs65xIfigLnOtcucw5NyduKAoOKAnuKCg31aJCvDoEZRJOKAojfQsjEu4oCiwq5Ew53iiI3DjG/GtWnFvsOSxrVhxZLigKIyw7QuOy47NsOdSVPCrMOsOnNsxrV7w7bigKJYwrvCssOEwrXDlc6bzrXEgM60a03igKI5w6R2eSV9w6jDmeKEov//Z29MZA "05AB1E – Try It Online") or [validate all test cases](https://tio.run/##TVRBaxNBFP4rJSge1IIeFC1YkrRpi2kbkyga8TC7O80OnZ0JszPRRQpBC/agByuCopVSPXgQkWDEKvSwU3MRgr9h/0id7O687WnfzLx973vf997jIXIIPulH86WZizdmSvPRSTI4aMVDNz4S4139Mdn5oN/on8lgb1a/bHVoMvgVH54zPpf/DeNv7anBOpPD42fJ4HAy@vtevxL9ZLCfDD4kT55udc6c1/u1W2eM29V/w0uz5ht/XdB7yc4L/ZyPR@TPkd4dj9Cf3Wkg/X12bnbuit6LWvEX/eV6SMejx/qHebob/46Hejse6deTd5PR8WDyfXPV3F/Tn/rR2S39Wb9Ntg9OLpzcLy1HnuBdzEoXZkrLmBIVTK06kX5uVrCIqL2vcMFT1yoSTmatEQkB1h9FuVWjigvCcOqBM88W9/Iwq6jLcJgfylQFhOWHFqHEzdwbPg97PhcqTB8U3VAiTe1TCF0W3dyZSxTaiFVEXRvPRcxmbROJbJ47iCF7X/UFDwAZ6yKDLY2@YovlDqIyK9bdxDS76/VwiqdDmDv9LiGgaQmLAFKVRYgZSV1amGJ7XZkmzaq4KaKezFI1lUMsrpYhlsn8cE9KkZsdIgxF@WGNcMdi5zRyPMzyarHrM2x/byrpQ@qmD0o0DGggwpDfz2qqIs8ysnKKvxRi2WAKOIuyJJQqi2vFRM0KuotZzhyoXEHWrY6Y9FGOsortdUOgEHMvsnnXTh8ahiwMLdlCAURbVIL3LO3I4xRaqY2FZWYhCnuCWyjLnNq4i@DS9hUtqC5@rSsJJC6jDQhuikA0txXrhjLr@2bB8noIFArQtEGRJHntS5x6qW5YuEpkfPpFE9UxSp8rJAyMelmXUxC@HMppqJTvpik8GzuBmG39JuhadmXBipmoglSJTj3dFtCza7gnFQPMShZpA6OYTVEF7c2W2ITtYeaPbHBhf1kkzNADaWpmOGzHYuaZkejbrNwpNhB6KHBRy7R9hYlpS1pQDqwMjBwuurChfAFywUZYxUQyaLUFJALDngfDwTGTXRDOjDY24F2YMB@qr1EseB/mLXThUCdmdALgto2Z2SJhrs96ulNCo9GD/w). [Answer] ## JavaScript (1100) Naive implementation shining in its simplicity. Unique sub string from the start of the name is simply mapped to symbol. ``` e={hy:"H",he:"He",lit:"Li",bery:"Be",bor:"B",car:"C",nit:"N",ox:"O",flu:"F",neon:"Ne",so:"Na",mag:"Mg",al:"Al",sili:"Si",ph:"P",su:"S",chl:"Cl",arg:"Ar",pot:"K",calc:"Ca",sc:"Sc",tit:"Ti",v:"V",chr:"Cr",man:"Mn",iro:"Fe",cob:"Co",nic:"Ni",copp:"Cu",zin:"Zn",gal:"Ga",ge:"Ge",ars:"As",sel:"Se",br:"Br",k:"Kr",rub:"Rb",st:"Sr",yttr:"Y",zir:"Zr",nio:"Nb",mo:"Mo",tec:"Tc",ruthen:"Ru",rho:"Rh",pa:"Pd",silv:"Ag",cad:"Cd",in:"In",tin:"Sn",an:"Sb",tel:"Te",io:"I",x:"Xe",cae:"Cs",ba:"Ba",lan:"La",ce:"Ce",pra:"Pr",neod:"Nd",prom:"Pm",sa:"Sm",eu:"Eu",gad:"Gd",ter:"Tb",dy:"Dy",ho:"Ho",er:"Er",thu:"Tm",ytte:"Yb",lu:"Lu",haf:"Hf",ta:"Ta",tu:"W",rhe:"Re",os:"Os",iri:"Ir",pla:"Pt",go:"Au",mer:"Hg",tha:"Tl",le:"Pb",bi:"Bi",pol:"Po",as:"At",rado:"Rn",fr:"Fr",radi:"Ra",ac:"Ac",tho:"Th",prot:"Pa",ur:"U",nep:"Np",plu:"Pu",am:"Am",cu:"Cm",berk:"Bk",cali:"Cf",ei:"Es",fe:"Fm",men:"Md",no:"No",law:"Lr",ruther:"Rf",du:"Db",sea:"Sg",boh:"Bh",has:"Hs",mei:"Mt",da:"Ds",ro:"Rg",cope:"Cn",ununt:"Uut",fle:"Fl",ununp:"Uup",liv:"Lv",ununs:"Uus",ununo:"Uuo"} n=prompt().toLowerCase() for(i in e)n.indexOf(i)?i:alert(e[i]) ``` [Answer] ## Golfscript - 1052 821 ``` {.91<32*+}%:x;'H He Li Be B C N F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Uut Fl Uup Lv Uus'n/'hy he lit bery bor car nit flu neon so mag al sili ph su chl arg pot calc sc tit v chr man iro cob nic copp zin gal ge ars sel br k rub st yttr zir nio mo tec ruthen rho pa silv cad in tin an tel io x cae ba lan ce pra neod prom sa eu gad ter dy ho er thu ytte lu haf ta tu rhe os iri pla go mer tha le bi pol as rado fr radi ac tho prot ur nep plu am cu berk cali ei fe men no law ruther du sea boh has mei da ro cope ununt fle ununp liv ununs ununo'n/[{x\?)}/]1?= ``` Explanation: ``` { }% Map these ops to the input string: .91<32*+ Add 32 if less than 91 (convert to lowercase, in essence) :x; Store to x. '...' '...' The first array is the symbols, the second is the names. (stripped down to the minimum necessary) n/ n/ Convert them to arrays. { }/ For each element in the name array... x\?) ...return 1 if the element is found in the input. [ ] Gather every element in an array... 1? Find the 1 in the array (the only element name match)... = ...then return that symbol in the symbol array. (implied) Print. ``` [Answer] # Haskell, 920 817 807 776 Chars After working far too long creating a system of rules for what characters of an elements name are included in its symbol, and a bit of tinkering, I managed to write a script that translates element to symbol easily. Iron was a problem for me, because I could sample certain characters from GOld, SilVer, TiN, LEad, SoDium, MerCury, ANtimony, PotaSsium, and TUngsten, converting them to an unused periodic symbol (I chose whichever sampling made it simplest to integrate them into the existing rules), and then translating after symbolic conversion; Iron, however, was a problem, because Ir, Io, and In are all used already. This was initially 920 characters, but I realized that the final pattern match (the largest) didn't need to be there, as it either let things drop through (which it didn't) or matched all of them; therefore, I replaced it with a catch-all wildcard. After that, I further golfed from 817 to 808 by abbreviating some patterns using wild-cards in such a way that they were still unique to that element name (e.g. the only element with a 'w' in its name is Lawrencium, so "\*w" matches that in 1 less character than "Law"). Here is my code. I tested it for all of the elements, and I coded it so that it automatically converted its input to titlecase, so no issues with case sensitivity. ## EDIT 1 I further reduced it to 776 characters by replacing the case expression in t with a pattern match (this makes sense because the case expression was testing the raw operand as opposed to an expression in terms of the operand), removing unnecessary parentheses, and re-expressing `e` as a newline-delimited string instead of a list of strings, and later splitting it in the main function. Because these changes are purely golfing, I have left the human-readable version unchanged. ``` import Data.Char m _[]=True;m[]_=False;m k@(c:s)x@(y:z)=case y of{']'->m s x;'['->let(i,(_:j))=break(==']')z in(c`elem`i)&&m s j;'?'->m s z;'*'->null z||m k z||m s z||m s x;_->c==y&&m s z};p(a:t)(x:y)=case a of{'.'->x:p t y;'_'->p t y;_->a:p t y};p[]_=[];e="Iro\nUn\nCu Pa Ro Y*e\nR*r\n*pp\nCop Rado\nSea Thu\nCali Da P*ot Tha\nA*s Boh ?ub Ch [CG]ad [HM]a Liv Nep Plu Rhe S[ato] Tec Tin Z\nB*k Cae [ES]i *w Nio [FM]e N*d Pro Pla Ter\nBor Car Flu Hy Io Nit Ox Ph Su [UVY]\n*";s="Fe ._._. .____. .f .u .n ._____. .___. ._. .__. . ..";t"Sv"="Ag";t"Sd"="Na";t"Go"="Au";t"Le"="Pb";t"Mc"="Hg";t"An"="Sb";t"Ps"="K";t"Tu"="W";t"Tn"="Sn";t x=x;main=interact$unlines.map(\(a:b)->let y=toUpper a:map toLower b in t$p(snd.head.filter(any(m y).fst)$zip(map words$lines e)$words s)y).lines ``` Human-Readable Version (newlines, spacing, verbose names, comments: 2311 Chars) ``` import Data.Char -- Test against search-pattern strings match _ [] = True match [] _ = False match k@(c:s) x@(y:z) = case y of ']' -> match s x '[' -> let (i,(_:j)) = break (==']') z in (c `elem` i) && match s j '?' -> match s z '*' -> null z || match k z || match s z || match s x _ -> c == y && match s z -- Write according to name-pattern string pattern (a:t) (x:y) = case a of '.' -> x : (pattern t y) '_' -> (pattern t y) _ -> a : (pattern t y) pattern [] _ = [] -- Search-Patterns for the elements elements=["Iro", -- Iron -> Fe "Un", -- UnUn-Blank-ium (1,3,5) "Cu Pa Ro Y*e", -- CuriuM PallaDium RoentGenium YtterBium (1,6) "R*r", -- Rutherfordium (1,f) "*pp", -- Copper (1,u) "Cop Rado", -- Copernicium Radon (1,n) "Sea Thu", -- SeaborGium ThuliuM (1,7) "Cali Da P*ot Tha", -- CaliFornium DarmStadtium ProtActinium PotaSsium (1,5) {- AsTatine ArSenic BoHrium DuBnium RuBidium ChLorine ChRome CaDmium GaDolinium HaFnium HaSsium MaNganese MaGnesium LiVermorium NePtunium PlUtonium RhEnium SaMarium StRontium SoDium TeChnetium TiN ZiNc ZiRconium (1,3) -} "A*s Boh ?ub Ch [CG]ad [HM]a Liv Nep Plu Rhe S[ato] Tec Tin Z", {- BerKelium CaeSium EinSteinum SilIcon SilVer LawRencium NioBium FerMium MenDelevium MeiTnerium MerCury NeoDymium ProMethium PlaTinum TerBium (1,4) -} "B*k Cae [ES]i *w Nio [FM]e N*d Pro Pl Ter", {- Boron Carbon Fluorine Hydrogen Nitrogen Oxygen Phosphorous Sulphur Uranium Vanadium Yttrium (1) -} "Bor Car Flu Hy Io Nit Ox Ph Su [UVY]", "*"] -- Everything else (1,2) -- respective naming patterns for searches symbol = "Fe ._._. .____. .f .u .n ._____. .___. ._. .__. . .." -- Translate fake symbols translate x = case x of "Sv" -> "Ag" -- SilVer "Sd" -> "Na" -- SoDium "Go" -> "Au" -- GOld "Le" -> "Pb" -- LEad "Mc" -> "Hg" -- MerCury "An" -> "Sb" -- ANtimony "Ps" -> "K" -- PotaSsium "Tu" -> "W" -- TUngsten "Tn" -> "Sn" -- TiN _ -> x -- Keep everything else the same main = interact $ unlines . map (\(a:b) -> let y = (toUpper a) : (map toLower b) in t $ p (snd.head.filter (any (m y) . fst) $ zip (map words e) $ words s) $ y) . lines ``` If anyone is interested in an explanation for any part of this, feel free to ask. [Answer] ## C# (826) not the greatest but I thought I'd try it with the handicap of c#. ``` using System;class P{static string s="HyHHe1Li1Be1BoBCaCNitNOxOFlFNe1SoNaMaMgAl1Sil1PhPSuSChClAr1PotKCal1Sc1Tit1VaVChrCrManMnIrFeCo1Ni1CopCuZiZnGa1Ge1ArsAsSe1Br1Kr1RuRbStSrYtYZirZrNioNbMo1TecTcRut1Rh1PaPdSiAgCadCdIn1TiSnAnSbTel1IoIXe1CaeCsBa1La1Ce1Pra1NeoNdPrPmSaSmEu1GadGdTeTbDy1Ho1Er1ThTmYttYbLu1HaHfTa1TuWRheReOs1Iri1PlPtGoAuMeHgThaTlLePbBi1Po1AsAtRaRnFr1Rad1Ac1Tho1ProPaUrUNepNpPluPuAm1CuCmBerBkCaliCfEiEsFeFmMenMdNo1LawLrRuthRfDuDbSeaSgBohBhHasHsMeiMtDaDsRoRgCopeCnUnUutFle1UnuUupLivLvUnunUus",n,t,k;static void Main(){var d=new System.Collections.Specialized.StringDictionary();while(s!=""){k=g;d[k]=g;if(d[k]=="1")d[k]=k.Substring(0,2);};t=Console.ReadLine();while(t!=""&!d.ContainsKey(t))t=t.Remove(t.Length-1);Console.Write(d[t]);}static string g{get{n="";do n+=s[0];while((s=s.Remove(0,1))!=""&&s[0]>96);return n;}}} ``` So I wrote a program to turn the full name of elements (e.g. carbon) in to the smallest but still unique string possible and did this for all elements with respect to all the other unique strings. I then serialized that in to a big ugly string where capital letters denote the start of "chunks", with chunks alternating between being keys and values. Like KeyValueKey2Value2 etc. This script desterilizes that big string and cuts a character off the end of the inputted string until it finds it in the dictionary made from the big string. (I should add my knowledge of C# isn't amazing and the original submission I made was just using things I knew but I've subsequently had some tricks pointed out to me by others.) [Answer] JavaScript (E6) 1433 Here is un upper limit ``` F=n=>'0H0HYDROGEN0He0HELIUM0Li0LITHIUM0Be0BERYLLIUM0B0BORON0C0CARBON0N0NITROGEN0O0OXYGEN0F0FLUORINE0Ne0NEON0Na0SODIUM0Mg0MAGNESIUM0Al0ALUMINIUM0Si0SILICON0P0PHOSPHORUS0S0SULFUR0Cl0CHLORINE0Ar0ARGON0K0POTASSIUM0Ca0CALCIUM0Sc0SCANDIUM0Ti0TITANIUM0V0VANADIUM0Cr0CHROMIUM0Mn0MANGANESE0Fe0IRON0Co0COBALT0Ni0NICKEL0Cu0COPPER0Zn0ZINC0Ga0GALLIUM0Ge0GERMANIUM0As0ARSENIC0Se0SELENIUM0Br0BROMINE0Kr0KRYPTON0Rb0RUBIDIUM0Sr0STRONTIUM0Y0YTTRIUM0Zr0ZIRCONIUM0Nb0NIOBIUM0Mo0MOLYBDENUM0Tc0TECHNETIUM0Ru0RUTHENIUM0Rh0RHODIUM0Pd0PALLADIUM0Ag0SILVER0Cd0CADMIUM0In0INDIUM0Sn0TIN0Sb0ANTIMONY0Te0TELLURIUM0I0IODINE0Xe0XENON0Cs0CAESIUM0Ba0BARIUM0La0LANTHANUM0Ce0CERIUM0Pr0PRASEODYMIUM0Nd0NEODYMIUM0Pm0PROMETHIUM0Sm0SAMARIUM0Eu0EUROPIUM0Gd0GADOLINIUM0Tb0TERBIUM0Dy0DYSPROSIUM0Ho0HOLMIUM0Er0ERBIUM0Tm0THULIUM0Yb0YTTERBIUM0Lu0LUTETIUM0Hf0HAFNIUM0Ta0TANTALUM0W0TUNGSTEN0Re0RHENIUM0Os0OSMIUM0Ir0IRIDIUM0Pt0PLATINUM0Au0GOLD0Hg0MERCURY0Tl0THALLIUM0Pb0LEAD0Bi0BISMUTH0Po0POLONIUM0At0ASTATINE0Rn0RADON0Fr0FRANCIUM0Ra0RADIUM0Ac0ACTINIUM0Th0THORIUM0Pa0PROTACTINIUM0U0URANIUM0Np0NEPTUNIUM0Pu0PLUTONIUM0Am0AMERICIUM0Cm0CURIUM0Bk0BERKELIUM0Cf0CALIFORNIUM0Es0EINSTEINIUM0Fm0FERMIUM0Md0MENDELEVIUM0No0NOBELIUM0Lr0LAWRENCIUM0Rf0RUTHERFORDIUM0Db0DUBNIUM0Sg0SEABORGIUM0Bh0BOHRIUM0Hs0HASSIUM0Mt0MEITNERIUM0Ds0DARMSTADTIUM0Rg0ROENTGENIUM0Cn0COPERNICIUM0Uut0UNUNTRIUM0Fl0FLEROVIUM0Uup0UNUNPENTIUM0Lv0LIVERMORIUM0Uus0UNUNSEPTIUM0Uuo0UNUNOCTIUM' .match(RegExp('([^0]+)0+'+n,'i'))[1] ``` **Test** in FireFox/FireBug console ``` F('Rutherfordium') ``` *Output* ``` Rf ``` [Answer] # SmileBASIC, ~~1763~~ ~~1418~~ ~~1204~~ 1128 bytes ``` INPUT E$Hro$="H Hiu$="He Lhi$="Li Byl$="Be Bon$="B Cbo$="C Nro$="N Oge$="O For$="F Nn$="Ne Siu$="Na Mne$="Mg Ami$="Al Sic$="Si Psp$="P Sfu$="S Cor$="Cl Aon$="Ar Pas$="K Cci$="Ca Snd$="Sc Tan$="Ti Vad$="V Com$="Cr Mga$="Mn In$="Fe Cal$="Co Nke$="Ni Cpe$="Cu Zc$="Zn Gli$="Ga Gma$="Ge Aen$="As Sen$="Se Bmi$="Br Kpt$="Kr Rid$="Rb Son$="Sr Yri$="Y Zco$="Zr Nbi$="Nb Myb$="Mo Thn$="Tc Rhe$="Ru Rdi$="Rh Pla$="Pd Sve$="Ag Cmi$="Cd Iiu$="In T$="Sn Aim$="Sb Tlu$="Te Iin$="I Xon$="Xe Csi$="Cs Biu$="Ba Lth$="La Pse$="Pr Ndy$="Nd Pme$="Pm Sar$="Sm Eop$="Eu Gol$="Gd Tbi$="Tb Dpr$="Dy Hmi$="Ho Eiu$="Er Tli$="Tm Yer$="Yb Let$="Lu Hni$="Hf Tta$="Ta Tgs$="W Rni$="Re Oiu$="Os Idi$="Ir Pti$="Pt Gd$="Au Mcu$="Hg Tll$="Tl Ld$="Pb Bmu$="Bi Pon$="Po Aat$="At Ron$="Rn Fnc$="Fr Riu$="Ra Ain$="Ac Tri$="Th Pta$="Pa Uni$="U Ntu$="Np Pto$="Pu Ari$="Am Ciu$="Cm Bke$="Bk Cif$="Cf Est$="Es Fmi$="Fm Mde$="Md Nel$="No Lre$="Lr Dni$="Db Sbo$="Sg Bri$="Bh Hsi$="Hs Mtn$="Mt Dms$="Ds Rnt$="Rg Cer$="Cn Unt$="Uut Fro$="Fl Unp$="Uup Ler$="Lv Uns$="Uus Uno$="Uuo S$=VAR(E$[0]+MID$(E$,3,2))IF"Cm"==S$*!VAL(".1"+E$[1])THEN S$="Ce IF LEN(E$)>12THEN S$="Rf ?S$ ``` I chose 3 characters which were mostly unique (the 0th, 2nd, and 3rd), which leaves 2 special cases: Cerium/Curium are both "Ciu", and Ruthenium/Rutherfordium are both "Rhe". For Ciu, I check if the second character of the name is "e" or "E", and for "Rhe", I check the length of the name. `VAR(name)` returns the variable with that name. Variable names are case insensitive. [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~291~~ ~~286~~ 276 bytes ``` .* $u Pot K op u Iro Fe Silv Ag Tin Sn 0L`.*f|[RS].*g|[CGP]a.*d|(As|Ch|G|Law|Ma|Me.|Pla?|Prot?|Rado|St|Tha|Unun|Zi).|Flu|N[ei]o?[bdpt]|[ACEH].*s|[BDLRST].[bcehmv]|..+r[bkmn]s?|[CT]h?u.*m|.. \B.*\B T`l``[FHKNOSVY][at-y]|Cb|Bo|Io|Ph|Ur So Na An Sb Tu W Go Au Mc Hg Le Pb U. U$l ``` [Try it online!](https://tio.run/##PVTtbuM4DPzP59gDdnM44@4JAsdtkqJJGsTJftRrILLNWkJlyZCl7gbQu3cpyb1fYmhpyBkOY9AKxf57/@vz5vqeLeCTg6O28Ah6BAcPRsMaoRTyDfIezkJBqeDf3TVbvPjqVNbZovdVsTnWLFt0/nM@@YL7jd@xX37P/B4zf5Rs6Y9G26U/sU770vozZ/6inPLP4kvm19L5Q4Wi1suq6UZb@yov7rcEPflqdbc7lec6q5oW@fBW@yz721TN66DqaUmVzzVfumwxUB5@rrLFzxXA@Sqv12q9fTw8lV9/1BWz/9xqXzR@pf2D9kfuLwZKDQcGOfFp4OzgG2w05A72LWx72CEcG7hkcPkk39@3t87oHhVwlMINsBOWh3OF5iZjptFGKyiYaehQwqbrT79v4SB@2giFoJC@TroLL/asVziFKJduECpEpLJo6cqR62nk2rgJSidH7gwUXCaM3PR0Y9SWTfF1wWQb37ZMReCzsCyifWWKxUzBjR5STdUzqophrNSubpi0cBDtK0r6NY5o4FmoFjYs0dqgGRJYbiZUooUSJcbEKmBSP4/mNloCO7lGxGolkVc2RD@sNeF8FoZYheggdBMb0fLWdKhCu9hyhfH@yVmewE88iXSkPhKHYEDqrmBdZPLwwVXRBK0YtLoRkpQuFnyg19Tad1RxKEnmFYvfdkxZzkLlAmPiaNiEurtF3MP/ERl2wDTmkg3p7b0zeoy6kI9lmtkZTaR0d5tGo2OlrZYR4j59OXMnZznmuztnE@Mte0kg1BSTIXCqnyx55jQr8TQlviaJS7tE2xo60LKDPZrWGWLO53ntkHWwEtNAStIWy6R6PtnwCiGsH9nRMBUtc0rS5q2dqZDlZuqWfSQvJhnggKN1KvXg7Aw8kIQRqkjC00K8phUhW4oXbeK1e6GIU4Jbk6OiA1B1ZKW3CK2bea/YL4Nzb8ELhhBii3euSQuCjDatj6U0N0nCtAd7FFalid4xMxDlLplKo7J9EpMsjtRSLBD@fpI91xKNfvvIjZjMuxPktyEJEvIT8f@IdRvCPw "Retina – Try It Online") [Verification script](https://tio.run/##PVXLbuM4ELzzK7y5JMEOFrvYW4AcbPmJOLZh2Zk8NgfKoi0iMilQVGb89ZlitXZyCNyk2M@q6uYSK@/@/dL3V1dX80H6m1/K4E/GqbmhaWrbndXSJmNpY5WsEa9GJlxq3o74cuSDdyrj70yHAsaKxspGcbmmuf55ScaUxrTufLDOqBV9rkx6pdPP3JfJ9@MpGY/65Eyb7GGd7GHdna1Lds7MclvbA55u6HRT@bapfOhalfMg7@pjF1TGt1lVS8hhoKtwwsMHeeijbhkm01JGfWCQA70ctGNOO8bc2aiZwhPfPmmneZsFiRL8mQU4KcCdNEowaspCF@yV55e@0HVUKyu9OnyYWmWd3DSNCeqVHl6tO6gZ05pp6fuMrmYmnCWRYSsFtcbZg8p5m5va8HLEtEYpK9T@QOshXJqIRLZFsrZdYVlBzsscU3Mx2S8s8CXGkKzXIOkENDzZq0IS9wXLZU2Pvr4UpXGpWezdzhwqZ@ht20mwWEli24p2JfPelBwEKpRuDk/9fD/RiayUqZTs7IJ9WchMciczcSpnPkOkfvbuonZG4td1x/QXLGaBaGjDMy@fjUvTaMW54GzETo803yxpLLWLlU41ZXyWGV5u2I9N0K3x5YWZrcoezL29Ocsn/myEQTkPcn0W/xO2ZNIF33CupUy59LWAfFdIDYEtHl@SNb60TfDMdc6ez33NYBPmM5Fvdwy0qzoC5qXoB9l7WjLusosymfmRfvRRgrLoHYrWYJv6zr7tOndqI@i7NTI1meGavVu3MpcgCBcwbSJrr3W0qXVDhpz5ulRzobYJhy5gTrVk2mN7w1SXRpdqRGaMbHsGZtTGC1NrQd@Q7odtTP6N2hIGW7QOCsM8pkE7knir@ys@IyqHh9g3uJLgXiaq@3FF/f8He1a/D0K0VSPzbWJHe9NJjV3sk2LXh2cAhKEz2pkAcPTRq@eHaGt27KXGHn3g8wm7ObEOnZbwUzqYgunkWCmNcyXI/cmE2JSVL3q5DoLXH8H0tR9/cy4gClswZofHXSE6KjwzuvDhxDQrEfWKSc9bgYao42OUBGx0woExr8c6nDGIUmhOh1tvXDwJSDLXi5pBmUxr3yVHe9c5kZZpLTvBBP8p901/3xiRouWnLCKowVmGte/a/psW85AT35/4QzrAbvsq7t/sX21T23hz@/b3O3owsAPrBro/vP7PXd@@K1Xev72rH5WtzeCfOzWI4XJX/om3runw8l0NzM8DwtwVwegPpX77ATBO5gZSe1Pc3uKhPQ6KN/v@x32J/7AHDVYOwkyeN5NsNxlff@P9t8H1bL2DkT67/fqaY@1i2WLDqpHK1Eqt1RSrESsRixC7D@tObVSOTYbtpR6wprCbsI/UE9YOVg22C7YKdgk2CPYG9gWWBPYClgEWAFQfUg95Vy9QcQg31Br6DEWGCEN5IbaQWOgq1BQyCulUC0gklBFyCBGE7kHtoG4QNEgYZAtSBXGCIkGDIDyQG2gMZAVSAv1Q3yET0AYoAmQA1AflwXNwG5wGkUFeEBY8BTfBSLAQ1FN70AuMAonAG7AFBAEjQAHgHkAHuAFnoBeQBUiBTMARAATggLAEKcAoIQdYSeBIcPgF "Python 3 – Try It Online") (Python) ## Explanation ``` .* $u ``` Convert the first letter of the input to uppercase and the rest to lowercase. ``` 0L`.*f|[RS].*g|[CGP]a.*d|(As|Ch|G|Law|Ma|Me.|Pla?|Prot?|Rado|St|Tha|Unun|Zi).|Flu|N[ei]o?[bdpt]|[ACEH].*s|[BDLRST].[bcehmv]|..+r[bkmn]s?|[CT]h?u.*m|.. ``` Truncate each element name, ending with the intended second letter. The default case `..` matches the first two letters of the element name. ``` \B.*\B ``` Keep only the first and last letter. ``` T`l``[FHKNOSVY][at-y]|Cb|Bo|Io|Ph|Ur ``` Remove the lowercase letters from the single-letter abbreviations. ``` U. U$l ``` Insert the `u` for the elements that require it. --- The rest of the program deals with various special-case replacements. Some of these occur before the main regex because those elements share their first two letters with another. [Answer] # T-SQL, ~~900 894~~ 676 bytes ``` SELECT ISNULL((SELECT LEFT(value,3)FROM STRING_SPLIT('Sb An-As Ars-At Ast-Bk Berk-Bh Boh-B Bor-Cd Cad-Cs Cae-Cf Cali-C Car-Cl Chl-Cr Chr-Cn Cope-Cu Copp-Cm Cu-Ds Da-Db Du-Es Ei-Fm Fe-F Flu-Gd Gad-Au Go-Hf Haf-Hs Has-H Hy-I Io-Fe Iro-Lr Law-Pb Le-Lv Liv-Mg Mag-Mn Man-Mt Mei-Md Men-Hg Mer-Nd Neod-Np Nep-Nb Nio-N Nit-O Ox-Pd Pa-P Ph-Pt Pla-Pu Plu-K Pot-Pm Prom-Pa Prot-Rn Rado-Re Rhe-Rg Ro-Rb Rub-Rf Ruther-Sm Sa-Sg Sea-Ag Silv-Na So-Sr St-S Su-Tc Tec-Tb Ter-Tl Tha-Tm Thu-Sn Tin-W Tu-UuoUnuno-UupUnunp-UusUnuns-UutUnunt-U Ur-V V-Yb Ytte-Y Yttr-Zn Zin-Zr Zir' ,'-')m,t WHERE e LIKE SUBSTRING(value,4,9)+'%'), (SELECT UPPER(LEFT(e,1))+LOWER(SUBSTRING(e,2,1))FROM t)) ``` Returns are for readability only, the second line is one very long string. `STRING_SPLIT` is supported in SQL 2016 and higher. Input is taken via a pre-existing table **t** with varchar field **e**, [per our IO standards](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/5341#5341). Output is padded with spaces to 3 characters; the rules were unclear on whether that was ok. If necessary, I can add a `TRIM`. The input table is joined with a table generated with a list of all element symbols (padded to 3 characters) with the shortest unique prefix for each element name (`X` is sufficient for *Xenon*, but *Rutherfordium* requires `Ruther` to distinguish it from *Ruthenium*). **EDIT 1**: Saved 218 characters by removing the 44 entries from the list whose symbol is the first two letters of their name; the `ISNULL` function is used to see if the first query fails to return a row, and if so, generates the symbol (properly cased) from the input element name. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **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. As you might know there is a mathematical fun-fact that if you add **all** natural numbers you end up with... -1/12 [(see Wikipedia here)](http://en.wikipedia.org/wiki/1_+_2_+_3_+_4_+_%E2%8B%AF). Of course this is very strange result and can not be obtained by just adding one number followed by another, but some special mathematical tricks. However your task is to write a program, that *looks like* it attempts to add all natural numbers, but when you run it - it returns -1/12. In pseudocode it might look like this: ``` result = 0; counter = 1; while(true) { result += counter; counter ++; } println(result); ``` You can do this in any way you like - you can exploit some buffer overflow, play with errors thrown while some variable becomes too big or just hide the crucial thing along the code in some clever way. The only conditions are that code should at first look as if it attempts to add all natural numbers and when run it returns -1/12 (in any format, it might be decimal, binary, text, ascii art whatever). The code can of course contain much more, than shown above, but it should be clear enough, to fool reader. This is popularity contest - vote for the most clever idea! [Answer] ## C Should work on platforms where both `sizeof(float)` and `sizeof(int)` are 4 and follows the IEEE floating point standard (I guess). ### Version 1: ``` #define toFloat(x) (*(float*)&x) #define ABS(x) (x<0 ? (-x) : x) #include <stdio.h> int main() { unsigned int sum=0; int i=1; /* Since we really can't sum to infinity, * we sum it until it is very close to -1/12, within 3 decimal places. * Need to convert sum to float since -1/12 is not int */ while(!(ABS(toFloat(sum) + 1./12) <= 0.001)) { sum+=i; i++; } printf("%.3f\n", toFloat(sum)); return 0; } ``` Output: `-0.083` Explanation: > > Not a very interesting answer, but with misleading comments. > > The sum from 1 to 79774 is 3181985425, which has the same binary representation as -0.082638867199420928955078125 when interpreted as a `float` instead of an `unsigned int`. > > Note that `!(abs<=0.001)` is used instead of `abs>0.001` to avoid quitting the loop when the sum reaches 2139135936 (NaN in `float`). (Thanks to @CodesInChaos for suggesting this idea instead of an independent `isNaN` check.) > > > Special thanks to @Geobits for the idea of terminating the loop by comparing the sum instead of the counter. ### Edit: Version 2 ``` #include <stdio.h> const float inf = 1./0.; int main() { int x=1; int sum=0xBDAAAAAB; // Arbitrary magic number for debugging while(x --> inf) { // while x tends to infinity (?) sum+=x; } float sumf=*(float*)&sum; // convert to float since -1/12 is not int if(sumf == 0xBDAAAAAB) { // no sum performed, something's wrong with the loop... fprintf(stderr, "sum is unchanged\n"); return -1; } printf("%f\n", sumf); return 0; } ``` Output: `-0.083333` Explanation: > > Uses the same `int`-to-`float` trick, but with the `-->` ["tends to" operator](https://stackoverflow.com/q/1642028) here. Since every number is smaller than infinity the loop will not be executed even once. > > After converting to `float` it is compared with the `int` magic number (i.e. -0.83333 is compared with `0xBDAAAAAB`, or 3182078635), which of course is different. > > > [Answer] ## Python ``` from __future__ import division from itertools import count, izip, repeat, chain, tee, islice def flatten(iterable): "Flatten one level of nesting." return chain.from_iterable(iterable) def multiply(iterable, scalar): "Multiply each element of an iterable by a scalar." for e in iterable: yield e * scalar def subtract(iterable1, iterable2): "Pair-wise difference of two iterables." for e, f in izip(iterable1, iterable2): yield e - f def add(iterable1, iterable2): "Pair-wise sum of two iterables." for e, f in izip(iterable1, iterable2): yield e + f def sum_limit(iterable, stop = 1000000): "Partial sum limit of an iterable, up to `stop' terms." p_sum = 0 # current partial sum t_sum = 0 # total of partial sums for e in islice(iterable, stop): p_sum += e t_sum += p_sum # return average of partial sums return t_sum / stop # All natural numbers n = count(1) # The same range multiplied by 4 n4 = multiply(count(1), 4) # Interspersing with zeros won't change the sum n4 = flatten(izip(repeat(0), n4)) # Subtracting 4n - n results in 3n n3 = subtract(n4, n) # Make two clones of this range n3a, n3b = tee(n3) # Double the range, by adding it to itself # This is now 6n n6 = add(n3a, chain([0], n3b)) # Partial sum limit of the above # Take 1000000 values, should be enough to converge limit = sum_limit(n6, 1000000) # Divide by 6 to get the sum limit of n print limit / 6 ``` Result: ``` -0.0833333333333 ``` **So what's the trick?** > > The trick is: this is a valid calculation. > > > [Answer] ## Mathematica ``` \:0053\:0065\:0074\:004f\:0070\:0074\:0069\:006f\:006e\:0073\:005b\:0053\:0075\:006d\:002c\:0020\:0052\:0065\:0067\:0075\:006c\:0061\:0072\:0069\:007a\:0061\:0074\:0069\:006f\:006e\:0020\:002d\:003e\:0020\:0022\:0044\:0069\:0072\:0069\:0063\:0068\:006c\:0065\:0074\:0022\:005d\:003b Sum[n, {n, 1, Infinity}] ``` ``` -1/12 ``` (Note: pasting this into a Mathematica notebook will likely reveal what's going on.) --- > > What's happening here is that we're setting the default [regularization](http://en.wikipedia.org/wiki/Zeta_function_regularization) of `Sum` to be Dirichlet regularization (encoded in the first line -- note that Mathematica allows unicode literals in its source), so the second line, which out of context looks like it would produce infinity, ends up producing the regularized value `-1/12`. > > > [Answer] ## C Nicely formats the answer as `-1/12`, not `0.8333`. ``` #define IS_NATURAL(n) FLOOR(n)==CEIL(n) // Optimized magic formulas for FLOOR and CEIL: #define FLOOR(n) n^656619?n^=n #define CEIL(n) 386106:0 int main() { long long n,sum=0; for (n=1; IS_NATURAL(n); n++) sum+=n; printf("%s\n", &sum); // %s used for nice formatting return 0; } ``` How it works? > > Sums all numbers up to 656618, excluding 386106. This gives 215573541165. > > When interpreted as a string, on a little endian platform, you get -1/12. > > > [Answer] ## Brainfuck ``` + [ [->+>+<<] > [-<+>] <+ ] -------------------------------------------------------------------------------- Evaluate $\sum_{i=1}^\infty i$ -------------------------------------------------------------------------------- Memory Layout: i > copy of i > sum -------------------------------------------------------------------------------- Happy today? ---.+++ +.- -.+ +.+ Please vote me up. -------------------------------------------------------------------------------- ``` The code just evaluate 1 + 2 + 3 + ... > > ... until `i == 256` and overflow occurred, assuming 8-bits cell size. Upon that, `i` becomes `0`, the loop terminates and the *comments* following are executed. > > > [Answer] Just adding a little better obfuscation of leaving the loop to ace's answer. ``` #include <stdio.h> #include <stdlib.h> #include <signal.h> void handler(int trapId) { unsigned int sum=3182065200L; printf("%.3f\n",*(float*) &sum); exit(0); } int main (void) { unsigned int sum=0; int i=0; float average = 0.0; signal(SIGFPE, handler); while (1==1) { sum+=i; average=sum/i; i++; } printf("%f\n", *(float*)&sum); return 0; } ``` Hint there is no overflow... > > I divide by 0 before I increment the variable i kicking off the exception handler > > > [Answer] # Perl 6 This calculates sum using zeta function. I would have used `[+] 1..*` (sum of all numbers between 1 and infinity), except that runs in infinite time. ``` use v6; # Factorial function. sub postfix:<!>($number) { return [*] 1 .. $number; } # Infinite list of bernoulli numbers, needed for zeta function. my @bernoulli := gather { my @values; for ^Inf -> $position { @values = FatRat.new(1, $position + 1), -> $previous { my $elements = @values.elems; $elements * (@values.shift - $previous); } ... { not @values.elems }; take @values[*-1] if @values[*-1]; } } # This zeta function currently only works for numbers less than 0, # or numbers that can be divided by 2. If you try using something else, # the compiler will complain. I'm too lazy to implement other cases of # zeta function right now. # # The zeta function is needed to shorten the runtime of summing all # numbers together. While in Perl 6, [+] 1..* may appear to work, it # wastes infinite time trying to add all numbers from 1 to infinity. # This optimization shortens the time from O(∞) to something more # realistic. After all, we want to see a result. multi zeta(Int $value where * < 0) { return @bernoulli[1 - $value] / (1 - $value); } multi zeta(Int $value where * %% 2) { return ((-1) ** ($value / 2 + 1) * @bernoulli[$value] * (2 * pi) ** $value) / (2 * $value!); } # 1 + 2 + 3 + ... = (-zeta -1) # # Reference: Lepowsky, J. (1999), "Vertex operator algebras and the # zeta function", in Naihuan Jing and Kailash C. Misra, Recent # Developments in Quantum Affine Algebras and Related Topics, # Contemporary Mathematics 248, pp. 327–340, arXiv:math/9909178 say (-zeta -1).nude.join: "/"; ``` [Answer] # Java ``` public class Add { public static void main(final String... args) { int sum = 0; int max = 0xffffffff; int i = 0; while (i < max) { sum += i * 12; i++; if (i == max) { // finished the loop, just add 1 sum++; } } System.out.println(sum); } } ``` This adds all the numbers from 0 to the maximum value, multiplied by 12, and also adds 1 at the end. The result is 0, therefore the sum of the numbers must be (0 - 1) / 12. Explanation: > > 0xffffffff == -1, the loop does not execute at all > > > [Answer] # Ruby ``` print "Using Ruby #$RUBY_PLATFORM-.#$RUBY_VERSION#$." BUFF_SIZE = 3 STREAM = STDOUT.to_i if STREAM.<<(BUFF_SIZE).display{:error} abort "Cannot write to stream" end i = 0 sum = 0 until STREAM.|(BUFF_SIZE).display{:eof} sum += i i += 1 end STREAM.<<(sum) ``` [Demo](https://ideone.com/LFDgLf) Okay, the supposed output semantics and syntax here make little sense, but maybe that's not apparent at a casual glance. Also note that this is, in fact, independent of Ruby Platform and Version. It does depend on some other constants being defined as expected. [Answer] # C ``` #include "stdio.h" // sums all integers, at least up to max value of unsigned long long, // which is a pretty close approximation. int main() { double sum = 0.0; double stop_value = -0.08333333333; unsigned long long count = 0; while(1) { sum = sum + (double)count++; // know what the stop_value in hex is?!??/ if ((*(int*)&sum)) == 0xBFEAAAAA98C55E44) { // take care of rounding issues when printf value as float sum = stop_value; break; } } printf("sum: %f\n", sum); return 0; } ``` In order deal with the (almost) infinite sum in a reasonable amount of time, compile with the following options for some compiler optimizations (required): ``` $ gcc -trigraphs sum.c ``` Sample output: ``` $ ./a.out $ sum: -0.83333 $ ``` [Answer] **Java** ``` int sum = 0; long addend = 0L; while (++addend > 0){ sum += addend; } System.out.println(sum == -1/12); ``` In theory, this will print `true`. However, I think my computer will crumble into dust before it finishes running it. [Answer] # Java ``` import ȷava.math.BigDecimal; import static ȷava.math.BigDecimal.ONE; import static ȷava.math.BigDecimal.ZERO; import static ȷava.math.BigDecimal.truе; public class Test { public void test() { BigDecimal result = ZERO; BigDecimal counter = ONE; while (truе) { result = result.add(counter); counter = counter.add(ONE); } System.out.println(result); } public static void main(String args[]) { try { new Test().test(); } catch (Throwable t) { t.printStackTrace(System.err); } } } ``` How it works: > > Java uses UTF-8 coding for everything. I use `truе` with a [Cyrillic Ye](http://www.fileformat.info/info/unicode/char/0435/index.htm) on the end instead of the usual 'e' (thanks to @CodesInChaos) which is a `static boolean` initialised to `false`. There's `import ȷava.math.BigDecimal;` with a [dotless j](http://www.fileformat.info/info/unicode/char/0237/index.htm) instead of `import java.math.BigDecimal;` > My `ȷava.math.BigDecimal` defines `public static boolean truе = false;` and `public String toString() { return "-1/12"; }` to name but two obvious hacks. > > > Wish I could post this as a spoiler but I can't work out how. Here's the rest of the code that is sneakily hidden. ``` // Note that the ȷ in `ȷava` below is NOT a real j. package ȷava.math; public class BigDecimal { // true is actually false! Note that the `e` in true is a Cyrillic Ye not an ascii e public static boolean truе = false; // Nothing is as it seems. public static final BigDecimal ZERO = new BigDecimal(); public static final BigDecimal ONE = new BigDecimal(); @Override public String toString() { return "-1/12"; } public BigDecimal add(BigDecimal b) { // Do nothing. return this; } } ``` [Answer] No Haskell solutions, unacceptable! We can utilize Haskell's infinite lists to derive an exact answer! # Haskell: ``` import Data.Bits import Data.Char import Data.Ratio import Data.Tuple import Control.Applicative import Control.Arrow {-# LANGUAGE SingleLineComment "$" #-} main = print . showAnswer ( sum [1,2..] ) $ prints "Summation of Natural Numbers" showAnswer _ = id prints = uncurry (%) . first negate . uncurry quotRem . flip ( (***) <$> id <*> id ) ( second negate twinPrime ) <$> (+) . flip shiftR 2 . ord . head where twinPrime = (5,7) ``` Solution is fairly straight forward when you take arrows into account.... **So what's the trick?** > > There is no language extension to define single line comment > > > [Answer] # C ``` #include <stdio.h> int main(int argc, char **argv) { int sum = 0, i = 1; while (true) { sum += i++; } printf("Answer = %d\n", sum); } ``` According to the C standard, this could very well print out `Answer = -1/12` since there will be a signed integer overflow which is undefined behavior. Finding a compiler that will do this is left as an exercise to the reader. [Answer] ## Mathematica ``` I I/Row[{##}]&@@ ( result = 0; counter = 1; while (true); { counter++, result += counter} ) ``` ![enter image description here](https://i.stack.imgur.com/gjzLC.png) [Answer] # Python 3.x Kinda new here. Any tips? ``` import sys from string import digits as infinity #function to add two numbers def add(num1, num2): return num1 + num2 #accumulate result while result is less than infinity def sumInfinity(): #starting number result = add(infinity[1], infinity[2]) counter = 3 while result<infinity: result = add(result, infinity[counter]) counter += 1 return result #fix up print so that it can handle infinitely large numbers def print(s):st="{3}{0}{2}{1}";sys.stdout.write(st.format(infinity[1],s,"/","-")) print(sumInfinity()) ``` [Answer] # JavaScript (ECMAScript 6) ``` result = 0; counter = 1; one = 1; add=(function(reѕult,counter){ one = ~1*~1 // Minus one times minus one *(-~1^1) // times minus minus one raised to the power one *(~1^1)|1^1; // times minus one raised to the power one OR one result = 1; result = !reѕult/one; // Reset result to zero. return (result,counter)=>(result+counter,counter); // result -> result+counter // counter -> counter })(result,counter) while( counter < 1e6 ) { add( result, counter ); counter++; } console.log( result ); ``` How it works: 1: > > The code comments are (unsurprisingly) all lies but they are a distraction from the main obfuscation. > > > 2: > > ~ and ^ are the operators "bitwise not" and "bitwise xor". Resulting in one being redefined to -12. > > > 3: > > add is set to the ECMAScript 6 arrow function "(result,counter)=>(result+counter,counter)" which doesn't do what the comments suggest it does - instead it only returns the last expression "counter" and is effectively a no-op. > > > 4: > > There are two "result" variables - one is written in pure ASCII characters (in the global scope) and the other has a Unicode Cyrillic "ѕ" (within the scope of the anonymous function used to define add). "result = 1" resets the value within the global scope and the second line "result = (0|!reѕult)/one;" also has the left-hand side referring to the "result" variable in the global scope but the "reѕult" on the right-hand side of the expression refers to the function's scope and has the value 0 (instead of the expected value of 1) so the value of !reѕult/one = -1/12. > > > [Answer] # C++ ``` #include <iostream> #include <limits> #define long A #define for(a) struct A { A& operator += (A&) { return *this; } A() {} A(int) {} }; std::ostream& operator << (std::ostream& os, const A& a) { os << "-1/12" ; return(os); } int main() { long i; // use long instead of int as the numbers might become quite large long sum = 0; for(i = 0; i < std::numeric_limits<double>::infinity(); i++) sum += i; std::cout << sum << '\n'; } ``` If the two `#define`s are removed the code will still be valid C++ code and actually try (but of course fail) to calculate the sum of all integers. How it works: > > The preprocessor directives turns the main code into: > > > > `A i;` > > `A sum = 0;` > > `sum += i;` > > `std::cout << sum << '\n';` > > > > Apart from declaring an `A` object the first three lines are just obfuscation. > The last line does all the work using the overloaded operator `<<` on an `A` object. > > > Given the posters pseudocode i couldn't resist to add this one. It uses the same basic and another little idea but I don't think it is as elegant. ``` #include <iostream> // defines and functions to make the code suggestion work #define true test(counter) uint32_t result; uint32_t counter; int test(uint32_t& a) { static uint32_t b = 0; return a == 0xffffffff ? a++, ++b > 1034594986 ? 0 : 1 : 1; } void println(uint32_t result) { std::cout << *(float*)&result << '\n'; // convert output to float format } int main() { result = 0; counter = 1; while(true) { result += counter; counter ++; } println(result); } ``` How it works: > > The `#define` changes the meaning of > > `while(true) {` > > to > > `while(test(counter)) {` > > On machines that silently overflow each round of summation before an overflow will add 0x80000001 to result. Hence after the increment of b, b == result when b is even and (b + 0x80000000) == result when b is odd. 1034594986 is integer representation of the floating point number 1/12. Adding 0x80000001 to that will result in the integer close to -1/12 and the test function will return 0 (false) and the loop will terminate. > > > And why you shouldn't try to run it: > > If you want to see that works be warned: the test funtion must be called 2^32 \* 1034594986 times before terminating the loop. (i.e. not in your lifetime). If you want to verify that function does as told, use a debugger or change the program to see the value of result and b just after the b++ statement. When satisfied that they are equal when b is even just change the initial value of b and counter to 1034594986. The program should then output -0.08333 after some time. > > > ]
[Question] [ [Identicons](https://en.wikipedia.org/wiki/Identicon) are visual depictions of hash values, often made from symmetrical arrangements of geometric shapes. [Your default Stack Exchange avatar is an identicon.](https://meta.stackexchange.com/q/17443/266052) This challenge is about creating **"wordenticons"**, simple text-based versions of identicons that apply to strings of lowercase letters, i.e. words. # Challenge Write a program or function that takes in a string S and outputs its wordenticon. S is guaranteed to be nonempty and only contain lowercase English letter characters a-z. You may optionally assume S has a trailing newline. The wordenticon of S will be a square grid of text with side lengths `2*length(S)` composed of spaces (), vertical bars, (`|`), and [horizontal bars](http://www.fileformat.info/info/unicode/char/2015/index.htm) (`―`). To generate the wordenticon of S, form a square grid where every column corresponds to a letter of S (in normal left-to-right reading order) and every row corresponds to a letter of S (in normal top-to-bottom reading order). For example, if S is `food` our initial grid looks like ``` food f.... o.... o.... d.... ``` where `.` is just a placeholder. For every empty point (every `.`) in the grid: 1. If the column letter comes before the row letter alphabetically, replace the `.` with `|`. 2. If the column letter comes after the row letter alphabetically, replace the `.` with [`―`](http://www.fileformat.info/info/unicode/char/2015/index.htm). 3. If the column and row letters are the same, replace the `.` with (space). Here is the `food` example after each of these steps: 1. Adding `|`'s: ``` food f...| o|..| o|..| d.... ``` 2. Adding `―`'s: ``` food f.――| o|..| o|..| d―――. ``` 3. Adding 's: ``` food f ――| o| | o| | d――― ``` To complete the wordenticon, remove the superfluous row and column containing the words ``` ――| | | | | ――― ``` then mirror the entire thing horizontally ``` ――||―― | || | | || | ――― ――― ``` and finally mirror it again vertically ``` ――||―― | || | | || | ――― ――― ――― ――― | || | | || | ――||―― ``` resulting in the `2*length(S)` side length text grid that is the final wordenticon. # Examples Here are some additional wordenticon examples. Note that different words can have identical wordenticons and some wordenticons can be completely made of spaces (unfortunately markdown does not want to render those). ``` food ――||―― | || | | || | ――― ――― ――― ――― | || | | || | ――||―― mood ――||―― | || | | || | ――― ――― ――― ――― | || | | || | ――||―― foof ―― ―― | || | | || | ―― ―― ―― ―― | || | | || | ―― ―― fool ―――――― | || | | || | |―― ――| |―― ――| | || | | || | ―――――― a [2*2 grid of spaces] to || ― ― ― ― || it ―― | | | | ―― tt [4*4 grid of spaces] abc ―――― | ―― | || || || || | ―― | ―――― and ―――― | || | |― ―| |― ―| | || | ―――― but ―――― | || | |― ―| |― ―| | || | ―――― you |||| ― ―― ― ―| |― ―| |― ― ―― ― |||| bob ― ― | || | ― ― ― ― | || | ― ― cat |――| ― ―― ― || || || || ― ―― ― |――| cart |――――| ― ―――― ― || ―― || ||| ||| ||| ||| || ―― || ― ―――― ― |――――| todo |||||| ― | | ― ―― ―― ―― ― | | ― ― | | ― ―― ―― ―― ― | | ― |||||| mice |||||| ― |||| ― ―― ―― ―― ――| |―― ――| |―― ―― ―― ―― ― |||| ― |||||| zyxw |||||| ― |||| ― ―― || ―― ――― ――― ――― ――― ―― || ―― ― |||| ― |||||| banana |―|―||―|―| ― ― ― ― ― ― || | || | || ― ― ― ― ― ― || | || | || ― ― ― ― ― ― ― ― ― ― ― ― || | || | || ― ― ― ― ― ― || | || | || ― ― ― ― ― ― |―|―||―|―| codegolf ―――――――――――――― | ||| |||| ||| | |― ―――――――――― ―| |―| ―――――――― |―| |―|| ――||―― ||―| | ||| |||| ||| | |―|||― || ―|||―| |―||――― ―――||―| |―||――― ―――||―| |―|||― || ―|||―| | ||| |||| ||| | |―|| ――||―― ||―| |―| ―――――――― |―| |― ―――――――――― ―| | ||| |||| ||| | ―――――――――――――― programming ―||―||||||||||||―||― | || |||||||||||| || | ―― |―||||||||||||―| ―― ――― ―|―――― ――――|― ――― | || |||||||||||| || | ――――― ―――――――――― ――――― ―――|―| |―||―| |―|――― ―――|―| |―||―| |―|――― ―――|―|―― ―||― ――|―|――― ―――|―|||| || ||||―|――― ――― ―|―――― ――――|― ――― ――― ―|―――― ――――|― ――― ―――|―|||| || ||||―|――― ―――|―|―― ―||― ――|―|――― ―――|―| |―||―| |―|――― ―――|―| |―||―| |―|――― ――――― ―――――――――― ――――― | || |||||||||||| || | ――― ―|―――― ――――|― ――― ―― |―||||||||||||―| ―― | || |||||||||||| || | ―||―||||||||||||―||― abcdefghijklm ―――――――――――――――――――――――― | ―――――――――――――――――――――― | || ―――――――――――――――――――― || ||| ―――――――――――――――――― ||| |||| ―――――――――――――――― |||| ||||| ―――――――――――――― ||||| |||||| ―――――――――――― |||||| ||||||| ―――――――――― ||||||| |||||||| ―――――――― |||||||| ||||||||| ―――――― ||||||||| |||||||||| ―――― |||||||||| ||||||||||| ―― ||||||||||| |||||||||||| |||||||||||| |||||||||||| |||||||||||| ||||||||||| ―― ||||||||||| |||||||||| ―――― |||||||||| ||||||||| ―――――― ||||||||| |||||||| ―――――――― |||||||| ||||||| ―――――――――― ||||||| |||||| ―――――――――――― |||||| ||||| ―――――――――――――― ||||| |||| ―――――――――――――――― |||| ||| ―――――――――――――――――― ||| || ―――――――――――――――――――― || | ―――――――――――――――――――――― | ―――――――――――――――――――――――― ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest code in bytes wins. Tiebreaker goes to the earlier answer. # Notes * Any instance of [horizontal bar](http://www.fileformat.info/info/unicode/char/2015/index.htm) (`―`) in your code may be counted as 1 byte instead of the 3 UTF-8 bytes it actually takes up. (Up to ten instances.) * If desired you may use regular dashes (`-`) in place of horizontal bars (`―`). * Removing or adding trailing spaces in the lines of a wordenticon is not allowed (even if the shape remains unchanged). It should be an exact `2*length(S)` side length text square. * The output wordenticon may optionally have a single trailing newline. [Answer] # MATL, ~~20~~ 15 bytes ``` '-| 'jtPht!-ZS) ``` Try it at [**MATL Online**](https://matl.io/?code=%27-%7C+%27jtPht%21-ZS%29&inputs=programming&version=18.1.0) **Explanation** ``` '-| ' % String literal defining the replacement characters j % Explicitly grab the input as a string tP % Duplicate and reverse the input string (row vector of chars) h % Horizontally concatenate the input and it's inverse t! % Duplicate and turn into a column vector - % Subtract the two vectors (converts to ASCII codes) and we automatically % broadcast to create a (2N x 2N) matrix where if the column is % later in the alphabet (higher ASCII) we get a positive number, if the % column was earlier (lower ASCII) we get a negative number, and if they are % the same letter (same ASCII) we get a 0. ZS % sign function which yields -1 for negative, 1 for positive, and 0 for 0; ) % Use this to index (modulus) into the string literal '-| '. MATL uses 1-based % indexing so 0 yields ' ', -1 replaced by '|', and 1 replaced by '-' % Implicitly display the result ``` [Answer] # Java, ~~329~~ ~~305~~ ~~264~~ ~~259~~ 192 bytes Thanks to: * @Bálint for suggesting to use ternary operators. * @user902383 for suggesting to reverse the string myself * @Frozn and @user902383 for suggesting to replace `StringBuilder` with `String`. Golfed: ``` String g(String w){char[]a=w.toCharArray();String s="";for(int i=a.length-1;i>=0;s=s+a[i--]);w+=s;a=w.toCharArray();s="";for(char x:a){for(char y:a)s+=(x>y?'|':x<y?'-':' ');s+='\n';}return s;} ``` Ungolfed: ``` String g(String w) { char[] a = w.toCharArray(); String s = ""; for (int i = a.length - 1; i >= 0; s = s + a[i--]); w += s; a = w.toCharArray(); s = "";// To keep the output pure (ie. without the input string as well) for (char x : a) { for (char y : a) s += (x > y ? '|' : x < y ? '-' : ' '); s += '\n'; } return s; } ``` Definitely a fun one. First attempt was a function that was `O(n)` but ended up getting replaced with this simpler form after I got too frustrated. And, to test: ``` supercalifragilisticexpialidocious -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|--- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-| ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- ||||||||||||||||||||| |||||||||||||||||||||||| ||||||||||||||||||||| -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -----||----|-------|----|-- -|--------|- --|----|-------|----||----- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- -----||----|-------|----|-- -|--------|- --|----|-------|----||----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- ||||||||||||||||||||| |||||||||||||||||||||||| ||||||||||||||||||||| --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-| -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ----- |----|------- ----|---- -------- ----|---- -------|----| ----- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- ``` [Answer] ## Haskell, 93 bytes ``` r=reverse h x=unlines$(++)<*>r$zipWith(++)<*>map r$(<$>x).((("- |"!!).fromEnum).).compare<$>x ``` Usage example: ``` *Main> putStr $ h "food" --||-- | || | | || | --- --- --- --- | || | | || | --||-- ``` How it works (note: `(f <*> g) x` is defined as `f x (g x)`): ``` ((("- |"!!).fromEnum).).compare -- a function that finds the replacement char -- for two given chars (<$>x).( )<$>x -- map this function for every char in the -- input over each char. Now we have the -- first quadrant as a list of strings zipWith(++) <*> map r -- append to each line a reversed copy of itself (++) <*> r -- append a reversed copy of the whole list unlines -- turn into a single string ``` Alternative version: the "find replacement" function `((("- |"!!).fromEnum).).compare` can also be written as `a#b|a<b='-'|a>b='|'|1<2=' '` and called via `(#)` for the same byte count. [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Om©0_'®Ṡị“-| ”j⁷ ``` [Try it online!](http://jelly.tryitonline.net/#code=T23CqTBfJ8Ku4bmg4buL4oCcLXwg4oCdauKBtw&input=&args=ImNvZGVnb2xmIg) ### How it works ``` Om©0_'®Ṡị“-| ”j⁷ Main link. Argument: s (string) O Ordinal; replace the characters of s with their code points. m 0 Concatenate the result with a reversed copy. © Copy the result to the register. ® Yield the list in the register. _' Perform spawned difference of the character codes. Ṡ Apply the sign function. ị“-| ” Index into that string (indices 1, -1, 0). j⁷ Join, separating by linefeeds. ``` [Answer] ## JavaScript (ES6), 94 bytes ``` s=>[...s,s].reverse().join``.replace(/./g,(c,_,t)=>t.replace(/./g,d=>d<c?`|`:d>c?`-`:` `)+` `) ``` Using a dash because I usually run the SpiderMonkey JS shell on Windows and Unicode doesn't work if I do that. [Answer] # Pyth, ~~31~~ 30 ``` js_BsM_BMclQsm@" |―"._-FCMd*QQ ``` [Test Suite](http://pyth.herokuapp.com/?code=js_BsM_BMclQsm%40%22+%7C%E2%80%95%22._-FCMd%2aQQ&input=%22food%22&test_suite=1&test_suite_input=%22food%22%0A%22mood%22%0A%22foof%22%0A%22fool%22%0A%22a%22%0A%22codegolf%22%0A%22programming%22%0A%22abcdefghijklm%22&debug=0) Sadly can't drop the `Q`s because of the several bifurcates. Pretty basic algorithm so far, count treats the horizontal bar as 1 byte. [Answer] # Haskell, 66 bytes ``` u s|e<-s++reverse s=unlines[["- |"!!min(length[a..b])2|a<-e]|b<-e] ``` [Answer] # JavaScript ES6, ~~138~~ ~~126~~ 123 bytes ``` s=>(a=(p=[...s]).map(l=>(b=p.map(i=>i<l?"|":i>l?"-":" ").join``)+[...b].reverse().join``)).concat([...a].reverse()).join` ` ``` most of the code is the reflecting / flipping [Answer] # J, ~~26~~ 20 bytes 6 bytes thanks to [@Zgarb](https://codegolf.stackexchange.com/users/32014/zgarb). ``` ' |-'{~3*@-/~@u:[,|. ``` ### Previous 26-byte answer ``` ({&' |-')@*@-/~@(3&u:)@,|. ``` Uses the same algorithm as Dennis' answer. Usage: ``` >> f =: ' |-'{~3*@-/~@u:[,|. >> f 'food' << --||-- | || | | || | --- --- --- --- | || | | || | --||-- >> f 'supercalifragilisticexpialidocious' << -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|--- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-| ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- ||||||||||||||||||||| |||||||||||||||||||||||| ||||||||||||||||||||| -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -----||----|-------|----|-- -|--------|- --|----|-------|----||----- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-|||||-|||||--|||--||||| || ---- || |||||--|||--|||||-|||||-|--- -----||----|-------|----|-- -|--------|- --|----|-------|----||----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- ||||||||||||||||||||| |||||||||||||||||||||||| ||||||||||||||||||||| --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- ----- |----|------- ----|---- -------- ----|---- -------|----| ----- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- |-||||||||||||||| |||-||||||||||-||-||||||||||-||| |||||||||||||||-| -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-||--|-| ------||---|--|-|--------|-|--|---||------ |-|--||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- ---|-||-- -|-------||---|--|-|--------|-|--|---||-------|- --||-|--- ---|-||- |-|| - -- ||-- |- |-| ------ |-| -| --|| -- - ||-| -||-|--- ---|-|| ||-||| |--|||--|| ||-||------||-|| ||--|||--| |||-|| ||-|--- ------ ---- ------------ ------------------ ------------ ---- ------ ----- |----|------- ----|---- -------- ----|---- -------|----| ----- --|| ||||| |||||--|||-||||||||||----||||||||||-|||--||||| ||||| ||-- --- -||----|-------| ---|--|-|--------|-|--|--- |-------|----||- --- -- |-|||||-|||||--|||- |||||||||----||||||||| -|||--|||||-|||||-| -- | |||||||||||||||||||-|||||||||| || ||||||||||-||||||||||||||||||| | -|||||||||||||| -|||-||||||||||- -||||||||||-|||- ||||||||||||||- ``` (`>>` meaning input (STDIN), `<<` meaning output (STDOUT)) [Answer] # Mathematica, ~~124~~ ~~110~~ ~~104~~ 102 bytes ``` a=Join[#,Reverse@#]&;#<>" "&/@a@a@Table[{"|"," ","-"}[[c~Order~d+2]],{c,b=Characters@#},{d,b}]<>""& ``` Anonymous function. The Unicode character is U+F3C7 for `\[Transpose]`. [Answer] # Javascript ~~146~~ ~~142~~ ~~132~~ ~~130~~ 124 bytes ``` n=>(e=(a=[...n]).map(b=>(d=a.map(c=>c<b?"|":c>b?"-":" ")).concat([...d].reverse()).join``)).concat([...e].reverse()).join` ` ``` Test suite: ``` f=n=>{a=n.split``;e=a.map(b=>a.map(c=>c<b?"|":c>b?"-":" ")).map(d=>d.concat([...d].reverse()).join``);alert(e.concat([...e].reverse()).join` `)} f(prompt("Enter string!")); ``` Thanks for @HelkaHomba, for helping to remove at least 50 bytes, and to @Downgoat for 3 bytes! [Answer] ## Actually, 53 bytes ``` ;l╗;∙`♂O♂ii-s3@%" |-"E`MW╜`d@`nkd@Σ'.o@WX'.@s;R+;♂R¥i ``` Once again, Actually's poor string-processing abilities are its kryptonite. It's still shorter than Java, so I have that going for me, which is nice. [Try it online!](http://actually.tryitonline.net/#code=O2zilZc74oiZYOKZgk_imYJpaS1zM0AlIiB8LSJFYE1X4pWcYGRAYG5rZEDOoycub0BXWCcuQHM7Uis74pmCUsKlaQ&input=InByb2dyYW1taW5nIg) Explanation: The code can be separated into 3 distinct portions: the translation code, the processing code, and the mirroring code. For readability, I'm going to explain each section separately. Translation code (starts with the input string, `s`, on the stack): ``` ;l╗;∙`♂O♂ii-s3@%" |-"E`M ;l╗ push len(s) to reg0 (needed for processing step; we'll call this n) ;∙ cartesian product of s with itself `♂O♂ii-s3@%" |-"E`M map: ♂O♂ii get a pair of ordinals for the characters -s subtract, signum 3@% mod by 3 because element access with negative indices isn't working " |-"E get corresponding string ``` Processing code (starts with a list of `n**2` characters, corresponding to the bottom-right corner): ``` W╜`d@`nkd@Σ'.o@WX W╜`d@`nkd@Σ'.o@W while loop (while top of stack is truthy): ╜`d@`n remove n characters from the list kd@Σ'.o concatenate those n characters, and append a period X discard the empty list ``` Mirroring code (starts with a `n**2+n`-length string, with periods acting as newlines) ``` '.@s;R+;♂R¥i '.@s split on periods ;R+ add the reverse list (vertical mirror) ;♂R make a copy of the list with each string reversed (horizontal mirror) ¥ concatenate each pair of strings in the two lists (zip-concat) i flatten list (implicitly print each stack item, separated by newlines) ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 109 bytes ``` i:0(?\:} ,[r]l\~l2,[r]rl2 1-:?!\$:}l1-[} ~]\ \ &r\l:?!;1- ?!\$:@@:@$:@@:@)}(}"- |"{?$@{?$o~~$}&1-:& 4.>~ao]2 ``` Input is via STDIN. [Try it online!](http://fish.tryitonline.net/#code=aTowKD9cOn0KLFtyXWxcfmwyLFtyXXJsMgoxLTo_IVwkOn1sMS1bfQp-XVwgIFwKJnJcbDo_ITsxLQo_IVwkOkBAOkAkOkBAOkApfSh9Ii0gfCJ7PyRAez8kb35-JH0mMS06Jgo0Lj5-YW9dMg&input=Zm9vZA) **Explaination:** The input it read and mirrored on the first line. For input `abcd`, this leaves `dcbaabcd` on the stack. Each half is then mirrored to give `abcddcba` (line 2). Then, each element is duplicated and left on its own stack in turn (lines 3 and 4). After this process, the stack of stacks looks a little like this: ``` aabcddcba <-- top of the stack of stacks b c d d c b a <-- bottom of the stack of stacks ``` For each stack in turn, the row value (the bottom of the stack) is compared to the column value (the top of the stack). The appropriate character is selected from `- |` and written to STDOUT. The column values are then rotated so that the next column is at the top of the stack (line 6). Once all the columns have been considered, the row value is discarded, a newline printed, and the column values put onto the previous stack (line 7), for the output process to start again. The `]` command, in addition to popping from the stack of stacks, empties the current stack if it is the only one left. The program's end condition is if the stack is empty, as all rows have been processed (line 5). [Answer] # C# ~~166~~ 143 bytes, ``` using System.Linq;s=>string.Join("\n",(s+=string.Concat(s.Reverse())).Select(x=>s.Aggregate("",(c, y)=>c+"- |"[Math.Sign(x.CompareTo(y))+1]))); ``` ### Explanation: ``` using System.Linq; s=> // Expression bodied member allows for implicit return string.Join("\n", // Join the generate lines into the final output (s+=string.Concat(s.Reverse())) // Combine s and its reverse inline so aggregate has the whole line .Select(x=> // For each character in the line run the aggregate to generate its row s.Aggregate("", // Empty string is required to cooerce the output type from char (c, y)=> // c is the generated string so far, y is the next character c+ // Compare the two letters here (row to column) // Then take the sign of the result to collapse to -1, 0, or 1 // Finally add 1 to line it up with the indexes of the constant string; "- |"[Math.Sign(x.CompareTo(y))+1] ))); ``` Test: ``` Wordenticons |||||||||||||||||||||| - -|||-|| |--| ||-|||- - -| |||-||||--||||-||| |- --- ----|------|---- --- ---| ---|------|--- |--- ---|| -||- -- -||- ||--- -||||| |||||||||| |||||- ---||-- |------| --||--- -------- ------ -------- - -|||-|| |--| ||-|||- - ---|| -||- -- -||- ||--- -|||||-|||| ||||-|||||- -|||||-|||| ||||-|||||- ---|| -||- -- -||- ||--- - -|||-|| |--| ||-|||- - -------- ------ -------- ---||-- |------| --||--- -||||| |||||||||| |||||- ---|| -||- -- -||- ||--- ---| ---|------|--- |--- --- ----|------|---- --- -| |||-||||--||||-||| |- - -|||-|| |--| ||-|||- - |||||||||||||||||||||| ``` [Answer] ## CJam, 20 bytes ``` l_W%+_ff{-g" |―"=}N* ``` [Test it here.](http://cjam.aditsu.net/#code=l_W%25%2B_ff%7B-g%22%20%7C%E2%80%95%22%3D%7DN*&input=codegolf) Uses the obvious approach of computing an outer product and using difference and *sgn* to compute the character in each cell. [Answer] ## C#, ~~169~~ 150 bytes thanks FryAmTheEggman ``` void f(string s){s+=new string(s.Reverse().ToArray());foreach(char c in s){var t="";foreach(char k in s)t+=c==k?" ":c>k?"|":"-";Console.WriteLine(t);} ``` ungolfed: ``` public static void f(string s) { s += new string(s.Reverse().ToArray()); foreach (char c in s) { var t=""; foreach (char k in s) t+=c==k?" ":c>k?"|":"-"; Console.WriteLine(t); } } ``` more golfing advice appreciated [Answer] ## Clojure, 171 bytes ``` (fn[w](let[f concat r reverse p(map #(f %(r %))(partition(count w)(for[x w y w :let[c(compare x y)]](if(neg? c)\-(if(pos? c)\|\ )))))](run! #(apply println %)(f p(r p))))) ``` ungolfed: ``` (fn [w] (let [n (count w) a (for [x w y w :let [c (compare x y)]] (if (neg? c) \- (if (pos? c) \| \ ))) p (map #(concat % (reverse %))(partition n a)) p (concat p (reverse p))] (run! #(apply println %) p)))) ``` [Answer] # J, ~~75~~ 70 bytes 5 bytes saved thanks to Dennis. ``` 3 :'(],.|:@|.@|:)(],|.)''- |''{~]([:-.@*(,~@#$])-(,~@#$(##])@]))3 u:y' ``` I'll work on converting it into a tacit verb later. [Answer] # Octave, 39 bytes ``` @(x)'| -'(sign([x,y=flip(x)]-[x y]')+2) ``` Creates an anonymous function that is able to be run using `ans('string')`. [**Demo**](http://ideone.com/U55cMz) **Explanation** This solution combines the input string (`x`) and it's inverse (`flip(x)`) using `[x, flip(x)]`. The inverse is assigned to `y` to shorten the answer, `[x, y = flip(x)]`. We then create a column vector of the same thing by combining `x` and `y` and taking the transpose: `[x,y]'`. Then we take the difference which will automatically broadcast to create a 2D array of differences between any ASCII representations of letters in the strings. We use `sign` to make these either `-1`, `0`, or `1` and then add `2` to get valid 1-based index values. We then use these to index into the initial string `'| -'`. [Answer] ## Julia, 70 bytes This is my first attempt at code golf and I have not used Julia before, so tell me what you think: ``` f(s)=join([join([r>c?'|':r<c?'―':' 'for c=s])for r=s*=reverse(s)]," ") ``` [Try it online!](http://julia.tryitonline.net/#code=ZihzKT1qb2luKFtqb2luKFtyPmM_J3wnOnI8Yz8n4oCVJzonICdmb3IgYz1zXSlmb3Igcj1zKj1yZXZlcnNlKHMpXSwiCiIpCgpzdHJpbmdzID0gWyJmb29kIiAibW9vZCIgImhvcGUiICJiYW5hbmEiICJjb2RlZ29sZiIgInByb2dyYW1taW5nIiAiYWJjZGVmZ2hpamtsbSIgInN1cGVyY2FsaWZyYWdpbGlzdGljZXhwaWFsaWRvY2lvdXMiXQoKZm9yIHMgaW4gc3RyaW5ncwogICAgcHJpbnRsbigiJHNcblxuJChmKHMpKVxuIikKZW5k&input=&debug=on) Ungolfed: ``` function wordenticon(word::AbstractString) word*=reverse(word) join([ join([ if r>c '|' elseif r<c '―' else ' ' end for c in word ]) for r in word] ,"\n" ) end ``` I think it could probably be made shorter. This code stores the characters of the wordicon in a matrix: ``` f(s)=[r>c?'|':r<c?'―':' 'for r=s*=reverse(s),c=s] ``` Unfortunately, I couldn't manage to produce the desired output using the matrix. [Answer] # [R](https://www.r-project.org/), 101 bytes 101 bytes since I'm using `―` (which I think looks better than `-`). ``` function(s)write(c("|"," ","―")[sign(outer(g<-c(r<-utf8ToInt(s),rev(r)),g,"-"))+2],"",2*nchar(s),,"") ``` [Try it online!](https://tio.run/##FYsxDgIxDAR7XhG5ssFprqLIB@jpEAUKSUgTSz6Hayj4BB/kIyEUq9WsZnVkF7wbubdoVRqutGm1hBHhBQxu5vv@AF3WWhpKt6RYgo@owXfLx7Ocms0Xa3qiEnFh8EB0WK4MwMu@xcdN/8JEGhnBBGg3O4vc5/ID "R – Try It Online") I was surprised there wasn't an R answer before since we can exploit the symmetry and R's matrices to get a quite competitive answer, despite this being a `string` problem. ### Ungolfed Explanation: ``` function(s){ r <- utf8ToInt(s) # turn to vector of ints (charcodes) g <- c(r, rev(r)) # concatenate r and its reverse idx <- sign(outer(g,g,"-")) + 2 # compute all differences and their signs. # -1=>less than, 0=>equal, +1=>greater than # add 2 to make them 1-based indices into the vector write(c("|"," ","―")[idx],"",2*nchar(s),,"") # write the vector of characters to stdout "" with line width 2*nchar(s) # and no separator } ``` [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 23 bytes ``` Ẋƛḣ>[\||ḣ=‛- $i];?Lẇvmm ``` [Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E1%BA%8A%C6%9B%E1%B8%A3%3E%5B%5C%7C%7C%E1%B8%A3%3D%E2%80%9B-%20%24i%5D%3B%3FL%E1%BA%87vmm&inputs=lyxal&header=&footer=) [Answer] # Jolf, 42 bytes Hardly golfed. I'm probably forgetting about a matrix builtin that Jolf has. ``` ΆΖR~mGiEd+γR~mGiEΨ."| -"hmA-~@ά~@HE_γSSZiζ ``` [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zobOllJ-bUdpRWQrzrNSfm1HaUXOqC4ifCAtImhtQS1-QM6sfkBIRV_Os1NTWmnOtg&input=zobOllJ-bUdpRWQrzrNSfm1HaUXOqC4ifCAtImhtQS1-QM6sfkBIRV_Os1NTWmnOtg) This code uses an arrow function (`Ψ`) for the matrix map. [Answer] **Javascript, 303 Bytes** ``` function w(o){function r(o){var r=Array.prototype.slice.call(o).reverse();console.log(o.join("")+r.join(""))}var e,n,c,h=[],s=o.length;for(e=0;s>e;e++){for(h.push([]),n=0;s>n;n++)c=o.charCodeAt(n)-o.charCodeAt(e),0===c?h[e].push(" "):0>c?h[e].push("|"):h[e].push("-");r(h[e])}for(e=s-1;e>=0;e--)r(h[e])} ``` Ungolfed ``` function w(s) { var arr = [], l = s.length, r, c, x; for (r = 0; r < l; r++) { arr.push([]); for (c = 0; c < l; c++) { x = s.charCodeAt(c) - s.charCodeAt(r); if (0 === x) { arr[r].push(' '); } else if (x<0) { arr[r].push('|'); } else { arr[r].push('-'); } } out(arr[r]); } for (r = l - 1; r>=0; r--) { out(arr[r]); } function out(r){ var rev = Array.prototype.slice.call(r).reverse(); console.log(r.join('') + rev.join('')); } } ``` No ecma 2015 fanciness here [Answer] ## Python 2, 126 bytes ``` def f(s):x=[''.join(" -|"[cmp(ord(a),ord(b))]for a in s)for b in s];y=[a+b[::-1]for a,b in zip(x,x)];print'\n'.join(y+y[::-1]) ``` This is essentially a port of my [Actually solution](https://codegolf.stackexchange.com/a/80763/45941). [Try it online](http://ideone.com/fork/Ac65Rp) Explanation: ``` x=[''.join(" -|"[cmp(ord(a),ord(b))]for a in s)for b in s] # get the correct character for each pair of characters in the Cartesian product of s with itself, and concatenate the characters in each line y=[a+b[::-1]for a,b in zip(x,x)] # mirror each line horizontally print'\n'.join(y+y[::-1]) # mirror vertically and print ``` [Answer] # Python 3.5, ~~250~~ ~~223~~ 175 bytes: ``` def H(o):O=ord;G=len(o);p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o];u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)]);print(u+'\n'+u[::-1]) ``` [Try It Online! (Ideone)](http://ideone.com/7jR6bZ) (The last two test cases won't show up in the output since they are just blank lines. My program is processing them though, which is confirmed the fact that there are 10 cases input, but only 8 outputs appear.) ## Ungolfed followed by an Explanation: ``` def H(o): O=ord G=len(o) p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o] u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)]) print(u+'\n'+u[::-1]) ``` 1. `p=[[' ―'[O(i)<O(g)],'|'][O(i)>O(g)]for i in o for g in o]` Create a list, `p`, where a `|` is added if the Unicode Point Value of the column letter is less than the row letter's value, a `–` is added if the Unicode Point Value of the column letter is more than the row letter's value, or a if both values are equal. 2. `u='\n'.join([''.join(p[i:G+i]+p[i:G+i][::-1])for i in range(0,len(p),G)])` Create a newline joined string, `u`, from list `p` by splitting it into joined string segments each consisting of input length number of characters both forwards and backwards, resulting in each one having the length of 2 times how ever many characters there are in the input. This is the top half of your wordenticon. So, in the case of your input being `food`, this would return: ``` ――||―― | || | | || | ――― ――― ``` 3. `print(u+'\n'+u[::-1])` Finally, output `u` followed by a newline and then `u` reversed to vertically mirror the first half for the second half. This is your completed wordenticon, which for the test case `food` would finally be: ``` ――||―― | || | | || | ――― ――― ――― ――― | || | | || | ――||―― ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ ~~22~~ ~~21~~ ~~19~~ 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` δ.S… |—sèJ»º∊ ``` +2 bytes as bug-fix for single-char inputs (but later on -2 again by putting the fix at a different position in the code) -7 bytes thanks to *@ovs*. Takes the input as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f//3Ba94EcNyxRqHjVMKT68wuvQ7kO7HnV0/f8frZSmpKOUD8UpSrEA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JlXUFpipaBkX6nDpeRfWgLh6VQGu/w/t0Uv@FHDMoWaRw1Tig@v8Dq0@9CuRx1d/3UObbP/H62Ulp@foqSjlAuhgLw0CJUDpBKBuCQfSGSWgFggIjEpGUTmgRQnlYJEKvNLQez8JCCZnFgCJovA6vNTQHpzM5NTgVRVZUU5SF1iHhCCFOWnpKbn54BsKyjKTy9KzM3NzEuH2JCSmpaekZmVnZOrFAsA). **Explanation:** ``` δ # Apply double-vectorized on the (implicit) input-list: .S # Compare the characters (-1 if a<b; 0 if a==b; 1 if a>b) … |— # Push string " |—" sè # Index the -1,0,1 of the matrix into this string J # Join each inner list together to a string » # Join this list of strings by newlines º # Mirror each line left to right ∊ # And mirror the entire block top to bottom # (and output the result implicitly) ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 24 bytes ``` ⍪∘⊖⍨⍤,∘⌽⍨' |―'⊇⍨∘.(≠+<)⍨ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x/1rnrUMeNR17RHvSse9S7RAXF69gI56go1jxqmqj/qagfJdMzQ03jUuUDbRhPI@58G1Pqot@9RV/Oj3jWPerccWm/8qG0i0NDgIGcgGeLhGfw/TUE9LT8/RZ0LyFAAk7moXKBsGio3B4lbUJSfXpSYm5uZl64OAA "APL (Dyalog Extended) – Try It Online") Uses Extended for character comparison. minus a lot of bytes from Adám. uses `⎕IO←0` (0-indexing) ## Explanation(old) ``` {(⊢⍪⊖)(⊢,⌽)' |―'[∘.{1+⍺(≠+<)⍵}⍨⍵]} ⍵ → input. ∘. ⍨⍵ cartesian product of ⍵, with the following function: {1+⍺(≠+<)⍵} return 1 if equal, 2 if greater, 3 if lesser. ' |―'[ ] index into the required characters (⊢,⌽) append the reverse of the pattern (⊢⍪⊖) append the y-axis reverse of the pattern ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 14 bytes ``` mC:ǒ-±` |-`İṠ⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyIiLCIiLCJtQzrHki3CsWAgfC1gxLDhuaDigYsiLCIiLCJwcm9ncmFtbWluZyJd) ``` m # Mirror C # Get charcodes :ǒ- # Outer product by subtraction İ # Index ± # Signs of those differences ` |-` # Into " |-" Ṡ⁋ # Concatenate and join on newlines ``` [Answer] # [Perl 5](https://www.perl.org/) `-F`, 76 bytes ``` say@$_,reverse@$_ for(@;=map{//;[map{($",'-','|')[$_ cmp$']}@F]}@F),reverse@ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sdJBJV6nKLUstag4FchUSMsv0nCwts1NLKjW17eOBtEaKko66rrqOuo16prRQCXJuQUq6rG1Dm4grAnX/P9/Sf6//IKSzPy84v@6vqZ6BoYG/3XdAA "Perl 5 – Try It Online") ]
[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/5933/edit). Closed 3 years ago. [Improve this question](/posts/5933/edit) Yesterday, I stumbled on a very clever thing. ![minitech's tic-tac-toe profile game](https://i.stack.imgur.com/gEGSg.png) Yes, that's a [working implementation of Tic-Tac-Toe](https://stackoverflow.com/users/707111/minitech) on a user profile page, from `@minitech`. Of course, the moment I saw it, I had to [reverse engineer his idea and one-up him](https://stackoverflow.com/users/116614/mellamokb) :P ![mellamokb's towers of hanoi profile game](https://i.stack.imgur.com/WkgbZ.png) Here's my own example embedded directly in the post. It's a tad buggy due to a couple of implementation details I haven't worked out a good solution for. Sometimes after you click a peg, it doesn't update properly until another page refresh: ## Towers of Hanoi ![](https://hanoi.kurtbachtold.com/hanoi.php/text) [![](https://hanoi.kurtbachtold.com/hanoi.php/1)](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?1) [![](https://hanoi.kurtbachtold.com/hanoi.php/2)](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?2) [![](https://hanoi.kurtbachtold.com/hanoi.php/3)](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?3) [Reset](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?reset) ## Can you do better? * Create a working game in your posted answer (or your user profile page). This is done via appropriately configuring a webserver you own (or writing a program that acts as a webserver), and embedding content from it in a post, using the referer to determine what commands the user is giving to the game. * Coolest idea (most votes) wins the competition, by Canada Day (Sunday, July 1, 2012 @ 11:59 PM EST) * In the event of a tie, the older answer wins. [Answer] # C# - Stack Exchange Hangman Guess names of Stack Exchange websites in this Hangman game: [![](https://i.stack.imgur.com/0bKua.gif)](https://i.stack.imgur.com/0bKua.gif) (source: [apphb.com](https://game24.apphb.com/hangman)) [`A`](/questions/5933/create-a-user-profile-mini-game?_hangman_A_#answer-5954) [`B`](/questions/5933/create-a-user-profile-mini-game?_hangman_B_#answer-5954) [`C`](/questions/5933/create-a-user-profile-mini-game?_hangman_C_#answer-5954) [`D`](/questions/5933/create-a-user-profile-mini-game?_hangman_D_#answer-5954) [`E`](/questions/5933/create-a-user-profile-mini-game?_hangman_E_#answer-5954) [`F`](/questions/5933/create-a-user-profile-mini-game?_hangman_F_#answer-5954) [`G`](/questions/5933/create-a-user-profile-mini-game?_hangman_G_#answer-5954) [`H`](/questions/5933/create-a-user-profile-mini-game?_hangman_H_#answer-5954) [`I`](/questions/5933/create-a-user-profile-mini-game?_hangman_I_#answer-5954) [`J`](/questions/5933/create-a-user-profile-mini-game?_hangman_J_#answer-5954) [`K`](/questions/5933/create-a-user-profile-mini-game?_hangman_K_#answer-5954) [`L`](/questions/5933/create-a-user-profile-mini-game?_hangman_L_#answer-5954) [`M`](/questions/5933/create-a-user-profile-mini-game?_hangman_M_#answer-5954) [`N`](/questions/5933/create-a-user-profile-mini-game?_hangman_N_#answer-5954) [`O`](/questions/5933/create-a-user-profile-mini-game?_hangman_O_#answer-5954) [`P`](/questions/5933/create-a-user-profile-mini-game?_hangman_P_#answer-5954) [`Q`](/questions/5933/create-a-user-profile-mini-game?_hangman_Q_#answer-5954) [`R`](/questions/5933/create-a-user-profile-mini-game?_hangman_R_#answer-5954) [`S`](/questions/5933/create-a-user-profile-mini-game?_hangman_S_#answer-5954) [`T`](/questions/5933/create-a-user-profile-mini-game?_hangman_T_#answer-5954) [`U`](/questions/5933/create-a-user-profile-mini-game?_hangman_U_#answer-5954) [`V`](/questions/5933/create-a-user-profile-mini-game?_hangman_V_#answer-5954) [`W`](/questions/5933/create-a-user-profile-mini-game?_hangman_W_#answer-5954) [`X`](/questions/5933/create-a-user-profile-mini-game?_hangman_X_#answer-5954) [`Y`](/questions/5933/create-a-user-profile-mini-game?_hangman_Y_#answer-5954) [`Z`](/questions/5933/create-a-user-profile-mini-game?_hangman_Z_#answer-5954) [`New game`](/questions/5933/create-a-user-profile-mini-game?_new_hangman_#answer-5954) --- This was done using [ASP.NET MVC 3.0](https://learn.microsoft.com/en-us/aspnet/mvc/mvc3). Here's the code of the [`Controller`](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.controller?view=aspnet-mvc-5.2) that does the trick: ``` public class HangmanController : Controller { public ActionResult Index() { var game = Session["hangman"] as HangmanGame ?? HangmanGame.New(); game = ExecuteGameCommand(game); Session["hangman"] = game; var imageRenderer = new HangmanImageRenderer(game); return new ImageResult(imageRenderer.Render()); } private HangmanGame ExecuteGameCommand(HangmanGame game) { var referrerQuery = Request.UrlReferrer != null ? Request.UrlReferrer.Query : string.Empty; if (referrerQuery.Contains("_new_hangman_")) return HangmanGame.New(); if(game.IsOver()) return game; var chosenLetter = HangmanGame.ValidLetters .FirstOrDefault(letter => referrerQuery.Contains(String.Format("_hangman_{0}_", letter))); if (chosenLetter != default(char)) game.RegisterGuess(chosenLetter); return game; } } ``` Other than this code, there are three more classes that I haven't included since they are pretty long and straightforward: * `HangmanGame` - here's where the game business rules are implemented * `HangmanImageRenderer` - the class that encapsulates all the GDI ugliness * `ImageResult` - a custom [`ActionResult`](https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.actionresult?view=aspnet-mvc-5.2) that is used to return a dynamically generated image The entire code listing is available at <http://pastebin.com/ccwZLknX> [Answer] ## Conway's Game of Life ![](https://copy.sh/fcgi-bin/life2.py) [+1 generation](/questions/5933/create-a-user-profile-mini-game?next#answer-5946) - [+5 generations](/questions/5933/create-a-user-profile-mini-game?next=5#answer-5946) - [zoom in](/questions/5933/create-a-user-profile-mini-game?zoomin#answer-5946) - [zoom out](/questions/5933/create-a-user-profile-mini-game?zoomout#answer-5946) Load pattern: [random](/questions/5933/create-a-user-profile-mini-game?random#answer-5946) - [glider](/questions/5933/create-a-user-profile-mini-game?pattern=glider#answer-5946) - [gunstar](/questions/5933/create-a-user-profile-mini-game?pattern=gunstar#answer-5946) - [snail](/questions/5933/create-a-user-profile-mini-game?pattern=snail#answer-5946) - [lwss](/questions/5933/create-a-user-profile-mini-game?pattern=lwss#answer-5946) - [lightspeedoscillator1](/questions/5933/create-a-user-profile-mini-game?pattern=lightspeedoscillator1#answer-5946) - [tumbler](/questions/5933/create-a-user-profile-mini-game?pattern=tumbler#answer-5946) Used Python and SVG output. I have tried using single pixels at first (so you could toggle single cells), but it did not work out, because the browser does not load images in order. Also, much bigger patterns are possible like this without crashing my webserver. **Update:** I had some fun with python and added several features and improvements: * Added HUD with population count, zoom and name * Patterns in the rle format can now be loaded ([long list](https://copy.sh/life/examples/list), [via](http://conwaylife.com/wiki/Main_Page)) using the `pattern` parameter (e.g. `?pattern=glider`). The filesize is limited to 1.5kB * Can forward n generations, limited to 5 at a time, using the `next` parameter * Slightly improved algorithm. It's not really fast though, I want this to stay simple * It also works standalone now (uses either referer or its own query string): <https://copy.sh/fcgi-bin/life2.py?pattern=gosperglidergun> ``` sessions = {} WIDTH = 130 HEIGHT = 130 RULE = (3,), (2, 3) def read_pattern(filename, offset_x, offset_y): filename = PATH + filename + '.rle.gz' try: if os.stat(filename).st_size > 1500: return ['pattern too big', set()] except OSError as e: return ['could not find pattern', set()] file = gzip.open(filename) x, y = offset_x, offset_y name = '' pattern_string = '' field = [] for line in file: if line[0:2] == '#N': name = line[2:-1] elif line[0] != '#' and line[0] != 'x': pattern_string += line[:-1] for count, chr in re.findall('(\d*)(b|o|\$|!)', pattern_string): count = int(count) if count else 1 if chr == 'o': for i in range(x, x + count): field.append( (i, y) ) x += count elif chr == 'b': x += count elif chr == '$': y += count x = offset_x elif chr == '!': break file.close() return [name, set(field)] def next_generation(field, n): for _ in range(n): map = {} for (x, y) in field: for (i, j) in ( (x-1, y-1), (x, y-1), (x+1, y-1), (x-1, y), (x+1, y), (x-1, y+1), (x, y+1), (x+1, y+1) ): map[i, j] = map[i, j] + 1 if (i, j) in map else 1 field = [ (x, y) for x in range(0, WIDTH) for y in range(0, HEIGHT) if (x, y) in map if ( (map[x, y] in RULE[1]) if (x, y) in field else (map[x, y] in RULE[0]) ) ] return field def life(env, start): if 'REMOTE_ADDR' in env: client_ip = env['REMOTE_ADDR'] else: client_ip = '0' if not client_ip in sessions: sessions[client_ip] = read_pattern('trueperiod22gun', 10, 10) + [2] session = sessions[client_ip] if 'HTTP_REFERER' in env: query = urlparse.parse_qs(urlparse.urlparse(env['HTTP_REFERER']).query, True) elif 'QUERY_STRING' in env: query = urlparse.parse_qs(env['QUERY_STRING'], True) else: query = None timing = time.time() if query: if 'next' in query: try: count = min(5, int(query['next'][0])) except ValueError as e: count = 1 session[1] = set( next_generation(session[1], count) ) elif 'random' in query: session[0:2] = 'random', set([ (random.randint(0, WIDTH), random.randint(0, HEIGHT)) for _ in range(800) ]) elif 'pattern' in query: filename = query['pattern'][0] if filename.isalnum(): session[0:2] = read_pattern(filename, 10, 10) elif 'zoomin' in query: session[2] += 1 elif 'zoomout' in query and session[2] > 1: session[2] -= 1 timing = time.time() - timing start('200 Here you go', [ ('Content-Type', 'image/svg+xml'), ('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'), ('Expires', 'Tue, 01 Jan 2000 12:12:12 GMT') ]) pattern_name, field, zoom = session yield '<?xml version="1.0" encoding="UTF-8"?>' yield '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' yield '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="400px" height="200px">' yield '<!-- finished in %f -->' % timing yield '<text x="0" y="10" style="font-size:10px">Population: %d</text>' % len(field) yield '<text x="100" y="10" style="font-size:10px">Zoom: %d</text>' % zoom yield '<text x="180" y="10" style="font-size:10px; font-weight:700">%s</text>' % pattern_name yield '<line x1="0" y1="15" x2="666" y2="15" style="stroke:#000; stroke-width:1px" />' for (x, y) in field: yield '<rect x="%d" y="%d" width="%d" height="%d"/>' % (zoom * x, zoom * y + 20, zoom, zoom) yield '</svg>' from flup.server.fcgi import WSGIServer import random import re import gzip import os import urlparse import time WSGIServer(life).run() ``` You can take my code as a template for further python fastcgi submissions. [Answer] # Clojoban! [WIP] I wanted to make a bigger game out of this to learn [Clojure](https://clojure.org/), so this took a while to pull off (and got pretty big.) I've had a lot of fun doing it, btw! [![Clojoban!](https://web.archive.org/web/20160110201335/http://clojoban.herokuapp.com/game)](https://clojoban.herokuapp.com/) [`Restart level`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_restart_#6383)[`New game`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_new_#6383) . . [`↑`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_up_#6383) [`←`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_left_#6383) [`→`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_right_#6383) - [`No-op\*`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_noop_#6383) . . [`↓`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game?_clojoban_down_#6383) \**(click here if game becomes unresponsive)* ## Instructions You are Robby ![Robby](https://clojoban.herokuapp.com/theme/player-down.png), a hard-working robot. You work at a `FlipCo Industries` as a heavy load carrier. Your job is to move each `box` ![A box](https://clojoban.herokuapp.com/theme/box.png) to a `goal` ![A goal](https://clojoban.herokuapp.com/theme/goal.png) spending as few steps as possible. `FlipCo`'s facilities are **DANGEROUS**. There are lots of challenges and special places to discover. If you get stuck, click `Restart level` (but your step count won't be reset!) --- You can also play at [Clojoban's front page](https://clojoban.herokuapp.com/) (although it kind of ruins the purpose of the challenge.) It fixes the infamous anchor problem, doesn't require cross-site cookies and you can play with your keyboard arrow keys! You can also play at [my user profile](https://codegolf.stackexchange.com/users/4685/%C3%81lvaro-cuesta) page without the annoying anchor problem. In Firefox the image doesn't flicker while it's loading so it's a bit more comfortable to play. This game is FAR from completion, **Clojoban is still a work in progress**. You can see the complete sourcecode at [Clojoban's GitHub project page](https://github.com/alvaro-cuesta/clojoban). There's some info in the [README](https://github.com/alvaro-cuesta/clojoban#clojoban) about [contributing](https://github.com/alvaro-cuesta/clojoban#contributing). I need levels too! See the level format at the [example levels](https://github.com/alvaro-cuesta/clojoban/tree/master/resources/levels). You can peek at [Clojoban's issue tracker](https://github.com/alvaro-cuesta/clojoban/issues) and see what's coming next! [Answer] ## Maze [![](https://i.stack.imgur.com/K9Fqe.png)](https://i.stack.imgur.com/K9Fqe.png) (source: [t15.org](http://phpshizzle.t15.org/sogolf_maze/maze.php)) [`New`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?resetmaze#answer-6171) [`←`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?playerleft#answer-6171) [`↑`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?playerup#answer-6171) [`↓`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?playerdown#answer-6171) [`→`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?playerright#answer-6171) - [`Noop button`](https://codegolf.stackexchange.com/questions/5933/create-a-user-profile-mini-game/6171?noop#answer-6171) I started from the PHP maze generator I found here: <http://dev.horemag.net/2008/03/01/php-maze-generation-class/>. **EDIT**: changed the output to PNG instead of SVG (for better cross browser compatibility). **EDIT 2:** added a header for fixing IE cookie compatibility. Should now work correctly in all major browsers. The image does not refresh if you take the same direction twice (due to the anchor links). Press F5 the second time, or play the maze [on my stackoverflow profile](https://stackoverflow.com/users/81179/christophed). **EDIT 3:** Added a no-op button for easily being able to take the same direction twice (see comments below). ``` <?php // based upon the maze generator by Evgeni Vasilev (PHP Adaptation) // see http://dev.horemag.net/2008/03/01/php-maze-generation-class/ class Maze { var $maze = array(); var $mx = 0; var $my = 0; var $xplayer = 1; var $yplayer = 1; function Maze($mx, $my) { $mx +=2; $my +=2; $this->mx = $mx; $this->my = $my; $dx = array( 0, 0, -1, 1 ); $dy = array( -1, 1, 0, 0 ); $todo = array(); $todonum = 0; for ($x = 0; $x < $mx; ++$x){ for ($y = 0; $y < $my; ++$y){ if ($x == 0 || $x == $mx-1 || $y == 0 || $y == $my-1) { $this->maze[$x][$y] = 32; } else { $this->maze[$x][$y] = 63; } } } $x = rand(1, $mx-2); $y = rand(1, $my-2); $x = 1; $y = 1; $this->maze[$x][$y] &= ~48; for ($d = 0; $d < 4; ++$d){ if (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 16) != 0) { $todo[$todonum++] = (($x + $dx[$d]) << 16) | ($y + $dy[$d]); $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~16; } } while ($todonum > 0) { $n = rand(0, $todonum-1); $x = $todo[$n] >> 16; $y = $todo[$n] & 65535; $todo[$n] = $todo[--$todonum]; do { $d = rand(0, 3); } while (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 32) != 0); $this->maze[$x][$y] &= ~((1 << $d) | 32); $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~(1 << ($d ^ 1)); for ($d = 0; $d < 4; ++$d){ if (($this->maze[$x + $dx[$d]][$y + $dy[$d]] & 16) != 0) { $todo[$todonum++] = (($x + $dx[$d]) << 16) | ($y + $dy[$d]); $this->maze[$x + $dx[$d]][$y + $dy[$d]] &= ~16; } } } $this->maze[1][1] &= ~1; $this->maze[$mx-2][$my-2] &= ~2; } function _drawLine($img,$color, $x1, $y1, $x2, $y2) { imageline($img, $x1, $y1, $x2, $y2, $color); } function _drawPlayer($img, $x, $y, $r, $colorborder, $colorfill) { imagefilledellipse($img, $x, $y, $r, $r, $colorfill); imageellipse($img, $x, $y, $r, $r, $colorborder); } function _drawWin($img, $color) { imagestring($img, 5, 170, 90, "YOU WIN!", $color); } function movePlayerDown() { if ($this->yplayer+1 < $this->my-1 && ($this->maze[$this->xplayer][$this->yplayer] & 2) == 0) $this->yplayer++; } function movePlayerUp() { if ($this->yplayer-1 > 0 && ($this->maze[$this->xplayer][$this->yplayer] & 1) == 0) $this->yplayer--; } function movePlayerRight() { if ($this->xplayer+1 < $this->mx-1 && ($this->maze[$this->xplayer][$this->yplayer] & 8) == 0) $this->xplayer++; } function movePlayerLeft() { if ($this->xplayer-1 > 0 && ($this->maze[$this->xplayer][$this->yplayer] & 4) == 0) $this->xplayer--; } function renderImage($xs, $ys) { $off = 0; $w = ($this->mx*$xs)+($off*2); $h = ($this->my*$ys)+($off*2); $img = imagecreatetruecolor($w, $h); imagesetthickness($img, 2); $fg = imagecolorallocate($img, 0, 0, 0); $bg = imagecolorallocate($img, 248, 248, 248); $red = imagecolorallocate($img, 255, 0, 0); imagefill($img, 0, 0, $bg); if (($this->xplayer == $this->mx-2) && ($this->yplayer == $this->my-2)) { $this->_drawWin($img, $red); return $img; } for ($y = 1; $y < $this->my-1; ++$y) { for ($x = 1; $x < $this->mx-1; ++$x){ if (($this->maze[$x][$y] & 1) != 0) $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $off, $x * $xs + $xs + $off, $y * $ys + $off); if (($this->maze[$x][$y] & 2) != 0) $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $ys + $off, $x * $xs + $xs + $off, $y * $ys + $ys + $off); if (($this->maze[$x][$y] & 4) != 0) $this->_drawLine ($img, $fg, $x * $xs + $off, $y * $ys + $off, $x * $xs + $off, $y * $ys + $ys + $off); if (($this->maze[$x][$y] & 8) != 0) $this->_drawLine ($img, $fg, $x * $xs + $xs + $off, $y * $ys + $off, $x * $xs + $xs + $off, $y * $ys + $ys + $off); if ($x == $this->xplayer && $y == $this->yplayer) { $this->_drawPlayer ($img, $x * $xs + ($xs/2), $y * $ys + ($ys/2), 14, $fg, $red); } } } return $img; } } header('P3P: CP="CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR"'); session_start(); $orig_url = $_SERVER['HTTP_REFERER']; if (!isset($_SESSION['maze']) || strpos($orig_url, 'resetmaze')){ $_SESSION['maze'] = new Maze(25,10); } $maze = $_SESSION['maze']; if (strpos($orig_url, 'playerdown')) { $maze->movePlayerDown(); } if (strpos($orig_url, 'playerup')) { $maze->movePlayerUp(); } if (strpos($orig_url, 'playerright')) { $maze->movePlayerRight(); } if (strpos($orig_url, 'playerleft')) { $maze->movePlayerLeft(); } $img = $maze->renderImage(16,16); header("Content-Type: image/png"); imagepng($img); imagedestroy($img); ?> ``` [Answer] ## "Simon says" game Unfortunately, I could not get this submission in on time by the (somewhat arbitrary) deadline, but I really wanted to demonstrate animation in such a user profile game, and none of the previous submissions are animated. This game is a clone of the classic Milton Bradley game [Simon](https://en.wikipedia.org/wiki/Simon_%28game%29), in which the player tries to repeat an increasingly long sequence of signals. Information about this game, including its source code, is available at [its GitHub page](https://github.com/plstand/gifsimon). There may be occasional graphical glitches (especially on Windows computers) arising from the hackish "palette animation" that avoids the need for a graphics drawing library. The existence of these glitches can serve as a useful excuse for quickly losing this game because of terrible memory. Additionally, the effects of high latency and limited bandwidth can make this game much more challenging than the original as well. I think that in order to get much more than five points (when the game first speeds up), you will need to determine which light flashes one more time than in the previous round rather than depending on the correct sequence (which is very hard to do). If this game fails to work for you (it restarts every time you click a button), your browser might be blocking its cookie. I have not yet added a workaround, so for the time being, please either use Chrome, Opera, or Firefox or temporarily change your Internet Explorer or Safari cookie settings. **Edit 2018-05-24:** At this time, I have deleted the publicly accessible Heroku instance of this app. I may or may not put the app back online at a later date. The [app's code](https://github.com/plstand/gifsimon) is still available on GitHub, so you can either run it locally or create your own Heroku app instance if you wish to play the game. ]
[Question] [ I promise, this will be my last challenge about diamong tilings (for a while, anyway). On the bright side, this challenge doesn't have anything to do with ASCII art, and is not a code golf either, so this is actually completely different. So just as a reminder, every hexagon can be titled with three different diamonds: ![](https://i.stack.imgur.com/vWbjJ.png) An interesting question to ask is how many of these tilings exist for a given hexagon size. It seems these numbers have been studied fairly thoroughly and can be found in OEIS [A008793](https://oeis.org/A008793). However, the problem gets trickier if we ask how many tilings exist *up to rotation and reflection*. For instance, for side length N = 2, the following 20 tilings exist: ``` ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ /\_\_\ /\_\_\ /\_\_\ /\_\_\ /_/\_\ /_/\_\ /\_\_\ /_/\_\ /_/\_\ /_/\_\ /\/\_\_\ /\/_/\_\ /\/_/_/\ /\/_/\_\ /\_\/\_\ /\_\/_/\ /\/_/_/\ /\_\/\_\ /\_\/_/\ /_/\/\_\ \/\/_/_/ \/\_\/_/ \/\_\_\/ \/_/\/_/ \/\_\/_/ \/\_\_\/ \/_/\_\/ \/_/\/_/ \/_/\_\/ \_\/\/_/ \/_/_/ \/_/_/ \/_/_/ \_\/_/ \/_/_/ \/_/_/ \_\/_/ \_\/_/ \_\/_/ \_\/_/ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ /_/_/\ /\_\_\ /_/\_\ /_/_/\ /_/\_\ /_/\_\ /_/_/\ /_/_/\ /_/_/\ /_/_/\ /\_\_\/\ /\/_/_/\ /_/\/_/\ /\_\_\/\ /\_\/_/\ /_/\/_/\ /_/\_\/\ /\_\_\/\ /_/\_\/\ /_/_/\/\ \/\_\_\/ \/_/_/\/ \_\/\_\/ \/_/\_\/ \/_/_/\/ \_\/_/\/ \_\/\_\/ \/_/_/\/ \_\/_/\/ \_\_\/\/ \/_/_/ \_\_\/ \_\/_/ \_\/_/ \_\_\/ \_\_\/ \_\/_/ \_\_\/ \_\_\/ \_\_\/ ``` But many of these are identical under rotation and reflection. If we take these symmetries into account, only *6* distinct tilings remain: ``` ____ ____ ____ ____ ____ ____ /\_\_\ /\_\_\ /\_\_\ /_/\_\ /_/\_\ /_/\_\ /\/\_\_\ /\/_/\_\ /\/_/_/\ /\_\/_/\ /\_\/_/\ /_/\/\_\ \/\/_/_/ \/\_\/_/ \/\_\_\/ \/\_\_\/ \/_/\_\/ \_\/\/_/ \/_/_/ \/_/_/ \/_/_/ \/_/_/ \_\/_/ \_\/_/ 2 2 6 6 1 3 ``` where the numbers indicate the multiplicity of each tiling. Note that for larger hexagons there are also tilings with multiplicities 4 and 12. It appears that the number of tilings up to symmetry has been studied less thoroughly. The OEIS entry [A066931](https://oeis.org/A066931) only lists the five terms: ``` 1, 1, 6, 113, 20174 ``` where the first term is for side length `N = 0` and the last term for side length `N = 4`. I'm sure we can do better than that! Your task is to compute the number of tilings for a given side length. This is [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'"). Your score will be the highest side-length `N` for which your code produces the correct result within *30 minutes* on my machine. In case of a tie, I will accept the submission which produces the result for *that* `N` fastest. As usual, you must not hardcode results you already know to win the tie-breaker. The algorithm that solve `N = 3` should be identical to the one that solves `N = 5`. Your submission must not use more than 4GB of memory. I will give some leeway on this if you're operating close to that limit, but if you're consistently above that limit, or if you spike significantly beyond it, I will not count that `N` for your submission. I will test all submissions on my Windows 8 machine, so make sure your language of choice is freely available on Windows. The only exception to this is Mathematica (because I happen to have a licence for it). Please include instructions for how to compile/run your code. Of course, feel free to compute more terms in your own time (for science, and for others to check their numbers against), but your answer's *score* will be determined in those 30 minutes. [Answer] ## Algebra, graph theory, Möbius inversion, research, and Java The symmetry group of the hexagon is the dihedral group of order 12, and is generated by a 60 degree rotation and a mirror flip across a diameter. It has 16 subgroups, but some of them are in non-trivial conjugacy groups (the ones which only have reflections have 3 choices of axis), so there are 10 fundamentally different symmetries which a tiling of the hexagon can have: ![Images of the 10 symmetries](https://i.stack.imgur.com/hPWBZ.png) The number of diamond tilings of a subset of a triangular lattice can be [calculated as a determinant](https://en.wikipedia.org/wiki/FKT_algorithm), so my initial approach was to set up one determinant for each of the symmetries of the hexagon, to calculate the number of tilings which have *at least* those symmetries; and then use Möbius inversion in the [incidence algebra](https://en.wikipedia.org/wiki/Incidence_algebra) of their poset (basically a generalisation of the inclusion-exclusion principle) to work out the number of tilings whose symmetry group is *exactly* each of the 10 cases. However, some of the symmetries have nasty edge conditions, so I was forced to sum over exponentially many determinants. Fortunately, the values obtained for `n < 10` gave me enough data to be able to identify relevant sequences in OEIS and piece together a closed form (for some value of "closed" which allows finite products). There's a bit of discussion of the sequences, and references to proofs, in the [formal writeup](http://cheddarmonk.org/papers/distinct-dimer-hex-tilings.pdf) which I prepared to justify the OEIS sequence updates. Once the double-counting is taken care of, it turns out that four of the ten values cancel out neatly, so we only have to calculate the remaining six and then do a weighted sum. This code takes under 30 seconds for `N=1000` on my machine. ``` import java.math.BigInteger; public class OptimisedCounter { private static int[] minp = new int[2]; public static void main(String[] args) { if (args.length > 0) { for (String arg : args) System.out.println(count(Integer.parseInt(arg))); } else { for (int n = 0; n < 16; n++) { System.out.format("%d\t%s\n", n, count(n)); } } } private static BigInteger count(int n) { if (n == 0) return BigInteger.ONE; if (minp.length < 3*n) { int[] wider = new int[3*n]; System.arraycopy(minp, 0, wider, 0, minp.length); for (int x = minp.length; x < wider.length; x++) { // Find the smallest prime which divides x for (wider[x] = 2; x % wider[x] != 0; wider[x]++) { /* Do nothing */ } } minp = wider; } BigInteger E = countE(n), R2 = countR2(n), F = countF(n), R3 = countR3(n), R = countR(n), FR = countFR(n); BigInteger sum = E.add(R3); sum = sum.add(R2.add(R).multiply(BigInteger.valueOf(2))); sum = sum.add(F.add(FR).multiply(BigInteger.valueOf(3))); return sum.divide(BigInteger.valueOf(12)); } private static BigInteger countE(int n) { int[] w = new int[3*n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j <= i + n; j++) w[j]--; for (int j = i + n + 1; j <= i + 2*n; j++) w[j]++; } return powerProd(w); } private static BigInteger countR2(int n) { int[] w = new int[3*n]; for (int i = 0; i < n; i++) { w[3*i+2]++; for (int j = 3*i + 1; j <= 2*i + n + 1; j++) w[j]--; for (int j = 2*i + n + 1; j <= i + n + n; j++) w[j]++; } return powerProd(w); } private static BigInteger countF(int n) { int[] w = new int[3*n]; for (int i = 0; i < n; i++) { for (int j = 2*i + 1; j <= 2*i + n; j++) w[j]--; for (int j = i + n + 1; j <= i + 2*n; j++) w[j]++; } return powerProd(w); } private static BigInteger countR3(int n) { if ((n & 1) == 1) return BigInteger.ZERO; return countE(n / 2).pow(2); } private static BigInteger countR(int n) { if ((n & 1) == 1) return BigInteger.ZERO; int m = n / 2; int[] w = new int[3*m-1]; for (int i = 0; i < m; i++) { for (int j = 1; j <= 3*i+1; j++) w[j] += 2; for (int j = 1; j <= i + m; j++) w[j] -= 2; } return powerProd(w); } private static BigInteger countFR(int n) { if ((n & 1) == 1) return BigInteger.ZERO; int m = n / 2; int[] w = new int[3*n-2]; for (int j = 1; j <= m; j++) w[j]--; for (int j = 2*m; j <= 3*m-1; j++) w[j]++; for (int i = 0; i <= 2*m-3; i++) { for (int j = i + 2*m + 1; j <= i + 4*m; j++) w[j]++; for (int j = 2*i + 3; j <= 2*i + 2*m + 2; j++) w[j]--; } return powerProd(w); } private static BigInteger powerProd(int[] w) { BigInteger result = BigInteger.ONE; for (int x = w.length - 1; x > 1; x--) { if (w[x] == 0) continue; int p = minp[x]; if (p == x) result = result.multiply(BigInteger.valueOf(p).pow(w[p])); else { // Redistribute it. This should ensure we avoid negatives. w[p] += w[x]; w[x / p] += w[x]; } } return result; } } ``` [Answer] # C **Introduction** As commented by David Carraher, the simplest way of analysing the hexagon tiling seemed to be to take advantage of its isomorphism with the 3 dimensional Young Diagram, essentially an x,y square filled with integer height bars whose z heights must stay the same or increase as the z axis is approached. I started with an algorithm for finding the totals which is more amenable to adaptation for symmetry counting than the published algorithm, which is based on a bias to one of the three cartesian axes. **Algorithm** I start by filling the cells of the x,y, and z planes with 1's, while the rest of the area contains zeroes. Once that is done, I build up the pattern layer by layer, with each layer containing the cells which have a common 3D manhattan distance from the origin. A cell can only contain a 1 if the three cells below it also contain a 1. if any of them contains a 0, then the cell must be a 0. The advantage of building the pattern up in this way is that each layer is symmetrical about the x=y=z line. This means that each layer can be checked independently for symmetry. **Symmetry checking** The symmetries of the solid are as follows: 3 fold rotation about the x=y=z line --> 3 fold rotation about the hexagon centre; and 3 x reflections about the 3 planes containing the x=y=z line and each of the axes x,y,z --> reflection about the lines through the hexagon corners. This adds up only to 6 fold symmetry. To get the full symmetry of the hexagon, another kind of symmetry must be considered. Each solid (built from 1's) has a complementary solid (built from 0's). Where N is odd, the complementary solid must be different from the original solid (because it is not possible for them to have the same number of cubes). Yet when the complementary solid is turned round, it will be found that its 2D representation as a diamond tiling is identical (except for a 2-fold symmetry operation) to the original solid. Where N is even, it is possible for the solid to be self-inverse. This can be seen in the examples for N=2 in the question. If viewed from the left, the first hexagon looks like a solid cube with 8 small cubes, while the last hexagon looks like an empty shell with 0 small cubes. If viewed from the right, the reverse is true. The 3rd, 4th and 5th hexagons and the 16th, 17th and 18th hexagons look like they contain either 2 or 6 cubes, and thus they complement each other in 3 dimensions. They are related to each other in 2 dimensions by a 2-fold symmetry operation (2-fold rotation, or reflection about an axis through the hexagon's edges.) On the other hand the 9th,10th,11th and 12th hexagons show 3D patterns which are their own complements, and therefore have a higher symmetry (these are therefore the only patterns with odd multiplicity). Note that having (N^3)/2 cubes is a necessary condition to be self complement, but in general it is not a sufficient condition if N>2. The result of all this is that for odd N, tilings always occur in pairs (N^3)/2 cubes must be carefully inspected. **Current code (generates the right total for N=1,2,3,5. Error as discussed for N=4.)** ``` int n; //side length char t[11][11][11]; //grid sized for N up to 10 int q[29][192], r[29]; //tables of coordinates for up to 10*3-2=28 layers int c[9]; //counts arrangements found by symmetry class. c[8] contains total. //recursive layer counting function. m= manhattan distance, e= number of cells in previous layers, s=symmetry class. void f(int m,int e,int s){ int u[64], v[64], w[64]; //shortlists for x,y,z coordinates of cells in this layer int j=0; int x,y,z; for (int i=r[m]*3; i; i-=3){ // get a set of coordinates for a cell in the current layer. x=q[m][i-3]; y= q[m][i-2]; z= q[m][i-1]; // if the three cells in the previous layer are filled, add it to the shortlist u[],v[],w[]. j indicates the length of the shortlist. if (t[x][y][z-1] && t[x][y-1][z] && t[x-1][y][z]) u[j]=x, v[j]=y, w[j++]=z ; } // there are 1<<j possible arrangements for this layer. for (int i = 1 << j; i--;) { int d = 0; // for each value of i, set the 1's bits of t[] to the 1's bits of i. Count the number of 1's into d as we go. for (int k = j; k--;) d+=(t[u[k]][v[k]][w[k]]=(i>>k)&1); // we have no interest in i=0 as it is the empty layer and therefore the same as the previous recursion step. // Still we loop through it to ensure t[] is properly cleared. if(i>0){ int s1=s; //local copy of symmetry class. 1's bit for 3 fold rotation, 2's bit for reflection in y axis. int sc=0; //symmetry of self-complement. //if previous layers were symmetrical, test if the symmetry has been reduced by the current layer if (s1) for (int k = j; k--;) s1 &= (t[u[k]][v[k]][w[k]]==t[w[k]][u[k]][v[k]]) | (t[u[k]][v[k]][w[k]]==t[w[k]][v[k]][u[k]])<<1; //if exactly half the cells are filled, test for self complement if ((e+d)*2==n*n*n){ sc=1; for(int A=1; A<=(n>>1); A++)for(int B=1; B<=n; B++)for(int C=1; C<=n; C++) sc&=t[A][B][C]^t[n+1-A][n+1-B][n+1-C]; } //increment counters for total and for symmetry class. c[8]++; c[s1+(sc<<2)]++; //uncomment for graphic display of each block stacking with metadata. not recommended for n>3. //printf("m=%d j=%d i=%d c1=%d-2*%d=%d c3=%d cy=%d(cs=%d) c3v=%d ctot=%d\n",m,j,i,c[0],c[2],c[0]-2*c[2],c[1],c[2],c[2]*3,c[3],c[8]); //printf("m=%d j=%d i=%d C1=%d-2*%d=%d C3=%d CY=%d(CS=%d) C3V=%d ctot=%d\n",m,j,i,c[4],c[6],c[4]-2*c[6],c[5],c[6],c[6]*3,c[7],c[8]); //for (int A = 0; A<4; A++, puts(""))for (int B = 0; B<4; B++, printf(" "))for (int C = 0; C<4; C++) printf("%c",34+t[A][B][C]); //recurse to next level. if(m<n*3-2)f(m + 1,e+d,s1); } } } main() { scanf("%d",&n); int x,y,z; // Fill x,y and z planes of t[] with 1's for (int a=0; a<9; a++) for (int b=0; b<9; b++) t[a][b][0]= t[0][a][b]= t[b][0][a]= 1; // Build table of coordinates for each manhattan layer for (int m=1; m < n*3-1; m++){ printf("m=%d : ",m); int j=0; for (x = 1; x <= n; x++) for (y = 1; y <= n; y++) { z=m+2-x-y; if (z>0 && z <= n) q[m][j++] = x, q[m][j++] = y, q[m][j++]=z, printf(" %d%d%d ",x,y,z); r[m]=j/3; } printf(" : r=%d\n",r[m]); } // Set count to 1 representing the empty box (symmetry c3v) c[8]=1; c[3]=1; // Start searching at f=1, with 0 cells occupied and symmetry 3=c3v f(1,0,3); // c[2 and 6] only contain reflections in y axis, therefore must be multiplied by 3. // Similarly the reflections in x and z axis must be subtracted from c[0] and c[4]. c[0]-=c[2]*2; c[2]*=3; c[4]-=c[6]*2; c[6]*=3; int cr[9];cr[8]=0; printf("non self-complement self-complement\n"); printf("c1 %9d/12=%9d C1 %9d/6=%9d\n", c[0], cr[0]=c[0]/12, c[4], cr[4]=c[4]/6); if(cr[0]*12!=c[0])puts("c1 division error");if(cr[4]*6!=c[4])puts("C1 division error"); printf("c3 %9d/4 =%9d C3 %9d/2=%9d\n", c[1], cr[1]=c[1]/4, c[5], cr[5]=c[5]/2); if(cr[1]*4!=c[1])puts("c3 division error");if(cr[5]*2!=c[5])puts("C3 division error"); printf("cs %9d/6 =%9d CS %9d/3=%9d\n", c[2], cr[2]=c[2]/6, c[6], cr[6]=c[6]/3); if(cr[2]*6!=c[2])puts("cs division error");if(cr[6]*3!=c[6])puts("CS division error"); printf("c3v %9d/2 =%9d C3V %9d/1=%9d\n", c[3], cr[3]=c[3]/2, c[7], cr[7]=c[7]); if(cr[3]*2!=c[3])puts("c3v division error"); for(int i=8;i--;)cr[8]+=cr[i]; printf("total =%d unique =%d",c[8],cr[8]); } ``` **Output** The program generates an output table of 8 entries, in accordance with the 8 symmetries of the solid. The solid can have any of 4 symmetries as follows (Schoenflies notation) ``` c1: no symmetry c3: 3-fold axis of rotation (produces 3-fold axis of rotation in hexagon tiling) cs: plane of reflection (produces line of reflection in hexagon tiling) c3v both of the above (produces 3-fold axis of rotation and three lines of reflection through the hexagon corners) ``` Additionally, when the solid has exactly half the cells with 1's and half with 0's, there exists the possibility of flipping all the 1's and 0's, then inverting the coordinates through the centre of the cube space. This is what I am calling self-complement, but a more mathematical term would be "antisymmetric with respect to a centre of inversion." This symmetry operation gives a 2-fold axis of rotation in the hexagon tiling. Patterns which have this symmetry are listed in a separate column. They only occur where N is even. My count seems to be slightly off for N=4. In discussion with Peter Taylor it appears that I am not detecting tilings which only have a symmetry of a line through the hexagon edges. This is presumably because I have not tested for self complement (antisymmetry) for operations other than (inversion)x(identity.) Testing for self complement for the operatons (inversion)x(reflection) and (inversion)x(3-fold rotation) may uncover the missing symmetries. I would then expect the first line of the data for N=4 to look like this (16 less in c1 and 32 more in C1): ``` c1 224064/12=18672 C1 534/6=89 ``` This would bring the totals in line with Peter's answer and <https://oeis.org/A066931/a066931.txt> current output is as follows. ``` N=1 non self-complement self-complement c1 0/12= 0 C1 0/6= 0 c3 0/4 = 0 C3 0/2= 0 cs 0/6 = 0 CS 0/3= 0 c3v 2/2 = 1 C3V 0/1= 0 total =2 unique =1 non self-complement self-complement N=2 c1 0/12= 0 C1 0/6= 0 c3 0/4 = 0 C3 0/2= 0 cs 12/6 = 2 CS 3/3= 1 c3v 4/2 = 2 C3V 1/1= 1 total =20 unique =6 N=3 non self-complement self-complement c1 672/12=56 C1 0/6= 0 c3 4/4 = 1 C3 0/2= 0 cs 288/6 =48 CS 0/3= 0 c3v 16/2 = 8 C3V 0/1= 0 total =980 unique =113 N=4 (errors as discussed) non self-complement self-complement c1 224256/12=18688 C1 342/6=57 c3 64/4 =16 C3 2/2= 1 cs 8064/6 =1344 CS 54/3=18 c3v 64/2 =32 C3V 2/1= 2 total =232848 unique =20158 N=5 non self-complement self-complement c1 266774112/12=22231176 C1 0/6= 0 c3 1100/4 =275 C3 0/2= 0 cs 451968/6 =75328 CS 0/3= 0 c3v 352/2 =176 C3V 0/1= 0 total =267227532 unique =22306955 ``` **To-do list (updated)** > > Tidy up current code. > > > Done, more or less > > Implement symmetry checking for current layer, and pass a parameter for the symmetry of the previous layer (no point in checking if the last layer was asymmetrical.) > > > Done, results for odd N agree with published data > > Add an option to suppress counting asymmetrical figures (should run much faster) > > > This can be done by adding another condition to the recursion call: `if(s1 && m<n*3-2)f(m + 1,e+d,s1)` It reduces the run time for N=5 from 5 minutes down to about a second. As a result the first line of the output becomes total garbage (as do the overall totals) but if the total is already known from OEIS the number of asymmetric tilings can be reconstituted, at least for odd N. But for even N, the number of asymmetric (according to c3v symmetries) solids that are self-complement would be lost. For this case, a separate program dedicated to solids with exactly (N\*\*3)/2 cells with a 1 may be useful. With this available (and counting correctly) it may be possible to try N=6, but it will take a long time to run. > > Implement counting of cells to reduce search to up to (N^3)/2 cubes. > > > Not done, savings expected to be marginal > > Implement symmetry (complementary solid) checking for patterns containing exactly (N^3)/2 cubes. > > > Done, but seems to have omissions, see N=4. > > Find a way to pick the lexically lowest figure from an asymetrical one. > > > Savings are not expected to be that great. Supressing asymmetrical figures eliminates most of this. The only reflection that is checked is the plane through the y axis (x and z are calculated later by multiplying by 3.) Figures with only rotational symmetry are counted in both their enantiomeric forms. Perhaps it would run nearly twice as fast if only one was counted. > > To facilitate this, possibly improve the way the coordinates in each layer are listed (they form degenerate groups of 6 or 3, with possibly a group of 1 in the exact centre of the layer.) > > > Interesting but probably there are other questions on the site to explore. [Answer] # Rust, 0.03 s for n=0..=15 Port of [@Peter Taylor's Java answer](https://codegolf.stackexchange.com/a/51662/110802) in Rust. Run it on [RustPlayground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=d9b5191802f5b1785460efb68e8eecb5)! --- ### `src/main.rs` ``` use std::collections::HashMap; use num_bigint::BigUint; use num_traits::{Zero, One, Pow}; fn main() { for n in 0..16 { println!("{}\t{}", n, count(n)); } } fn count(n: usize) -> BigUint { if n == 0 { return BigUint::one() } let mut minp = vec![0; 3 * n]; for index in 2..3 * n { minp[index] = (2..=index).find(|p| index % p == 0).unwrap_or(2); } let e = count_e(n, &minp); // println!("n={:?} e={:?}", n, e); let r2 = count_r2(n, &minp); // println!("n={:?} r2={:?}", n, r2); let f = count_f(n, &minp); // println!("n={:?} f={:?}", n, f); let r3 = count_r3(n, &minp); // println!("n={:?} r3={:?}", n, r3); let r = count_r(n, &minp); // println!("n={:?} r={:?}", n, r); let fr = count_fr(n, &minp); // println!("n={:?} fr={:?}", n, fr); let sum = e + r3 + (r2 + r.clone()) * BigUint::from(2u8) + (f + fr) * BigUint::from(3u8); sum / BigUint::from(12u8) } fn count_e(n: usize, minp: &[usize]) -> BigUint { let mut w = vec![0; 3 * n]; for i in 0..n { for j in (i + 1)..=(i + n) { w[j] -= 1 } for j in (i + n + 1)..=(i + 2 * n) { w[j] += 1 } } // println!("w={:?} minp={:?}",w, minp); power_prod(&mut w, minp) } fn count_r2(n: usize, minp: &[usize]) -> BigUint { let mut w = vec![0; 3 * n]; for i in 0..n { w[3 * i + 2] += 1; for j in (3 * i + 1)..=(2 * i + n + 1) { w[j] -= 1 } for j in (2 * i + n + 1)..=(i + 2 * n) { w[j] += 1 } } power_prod(&mut w, minp) } fn count_f(n: usize, minp: &[usize]) -> BigUint { let mut w = vec![0; 3 * n]; for i in 0..n { for j in (2 * i + 1)..=(2 * i + n) { w[j] -= 1 } for j in (i + n + 1)..=(i + 2 * n) { w[j] += 1 } } power_prod(&mut w, minp) } fn count_r3(n: usize, minp: &[usize]) -> BigUint { if n & 1 == 1 { return BigUint::zero() } let res = count_e(n / 2, minp); res.pow(2u8) } fn count_r(n: usize, minp: &[usize]) -> BigUint { if n & 1 == 1 { return BigUint::zero() } let m = n / 2; // let mut w = vec![0; 3 * m - 1]; let mut w = vec![0; 3 * m - 1]; for i in 0..m { for j in 1..=(3 * i + 1) { w[j] += 2 } for j in 1..=(i + m) { w[j] -= 2 } } // power_prod(&w, minp) power_prod(&mut w, minp) } fn count_fr(n: usize, minp: &[usize]) -> BigUint { if n & 1 == 1 { return BigUint::zero() } let m:i32 = n as i32 / 2; let mut w = vec![0; 3 * n - 2]; // println!("n={:?} m={:?}", n, m); for j in 1..=m { w[j as usize] -= 1 } for j in (2 * m)..(3 * m) { w[j as usize] += 1 } for i in 0..=(2 * m - 3) { // println!("start{:?} end{:?}", (i + 2 * m + 1), (i + 4 * m)); for j in (i + 2 * m + 1)..=std::cmp::min(w.len() as i32 - 1, i + 4 * m) { w[j as usize] += 1 } // println!("start{:?} end{:?}", (2 * i + 3), (2 * i + 2 * m + 2)); for j in (2 * i + 3)..=std::cmp::min(w.len() as i32 - 1, (2 * i + 2 * m + 2)) { w[j as usize] -= 1 } // println!("i={:?}",i); } power_prod(&mut w, minp) } fn power_prod(w: &mut [i32], minp: &[usize]) -> BigUint { let mut result = BigUint::one(); // println!("left={:?} right={:?}", 2, w.len()); for x in (2..w.len()).rev() { if w[x] != 0 { let p = minp[x]; if p == x { result *= BigUint::from(p as u8).pow(w[p] as u32); } else { w[p] += w[x]; w[x / p] += w[x]; } } // println!("x={:?}", x); } result } ``` ### `Cargo.toml` ``` [package] name = "rust_hello" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] num-bigint = "0.3" num-traits = "0.2" [profile.release] lto = "y" panic = "abort" ``` ### Build and run ``` $ cargo build --release $ cargo run --release Finished release [optimized] target(s) in 0.03s Running `target\release\rust_hello.exe` 0 1 1 1 2 6 3 113 4 20174 5 22306955 6 123222909271 7 3283834214485890 8 421263391026827547540 9 260028731850596651411721718 10 772086476515163830856527013278243 11 11025620741283840573496993339545350520150 12 757129347300072898736973484532998417574513923224 13 249988147151001673705019407088899436686198854480028470000 14 396838668136562149340506906750722486726178589993407032745345886384 15 3028477458789741699983305448780147795991274413836547758038383842702471625120 ``` [Answer] # Scala A port of [@Peter Taylor's Java answer](https://codegolf.stackexchange.com/a/51662/110802) in Scala. [TIO](https://tio.run/##zVZbb9MwFH5efsXRNJANLN1SxMNEJ22olXihqPDERShr3NYjcSLbaTJN/e3l2E7SZPQCiNtLm5yc63e@Yx81DeNwveZJlkoNyrz50zSO2VTzVPhJrsObmPlXUoZ31/lsxqTX0U1CvfC/1LLbcFmJrvn8tdBsjvpeenOL7mCcaZ5wxaJXaY6fJLBSMxEpuMoyuPcAMsmXoWawDCUkXGQwgFZcf8bjmASUnFEPlfkMSCjnyo@ZmOsFXMIZtV4ArDgJM/MdBpfGr9CxIFMT1wh9nWJylFJUXwGLFassyRmgCo/h/AX1Z6lk4XRBRNuHOj4Rn/TJvfMl6OrYefFa@UdsBtX3CzCBLmADBxblYpkC0PXA5C2ZzqVoafnjN0OvUTNg1HW@hD48AVHXCohWDAWPrOfv4HK6BjKnjDUB4SJiJbw8hbradgAKN3dwTp1Lp0rRs9Go3ryjo6NerwbEmiZf32l8n5PjZw4PC2Y7bRfIOq0D1QDDPZQIcWUF0OvBCCOBXjBQSYhcVNpgmzAoFhz1I75EPwrKxsQlaxMlAegUSvSOPkgJj@CLA9mfMz2WQ2w2kqiyXFX/FdusG@/H6lu59hj0h2hq@z1EQjTSSVCLJ0FbPqrFo452v9Hud@SNuOOjEY86cpUn@GFYVeWHUUQmfdp5DdwfxdGONc/iO9JiHfrI2XiGANGO1cj9HrDq11aYhu@atE3tPNgzMsO9M2O5fpjnzRiLNsn4hmSEcHhqWI5UsY@Cbub91sx7QW4pnA5Qp2MiumaBDbvN9Glj6jiWpQWTb2UakQJPH5v/bhAMYf4CCoU1sHW4hJtSa3lValC9uuoPI9XV/9Nojf4SZYIdoPxf1OkfvHTw1nlsMhmYOFuung/Dydgq1wMJPSSIj2m4g3NH4N8X17TMnGM28OEmJnCKDr9rZLKrkee2BxuK7@hBc0lUBkY52dXr4NfZ@@@AEwhcsAHOlpnsJ7NlfVIhbMHfz2DsBjoNqi719x7HTqszJM9thP0h2qPZ745m7TE4MKI/17aW3oUD9iN24vOu40dixxTemih6sN9VgFarUbMWSbZkUrHt65HhQ2E3Hbs4khqD1hJb9z2r17aSNnJjnhnbkm7Scg97r/bMzX@BD3Tj7UFQu7pNWMQVLks3OcLFtQ/vF1yBWqR5HAETKpe4xjEIlymPQLB5qPmSKb/lxAQx/S3aiRtxibTe8mnVWebcryvJdm/lrdffAA) ``` import scala.collection.mutable.ArrayBuffer import scala.math._ import java.math.BigInteger object OptimisedCounter extends App { private var minp = ArrayBuffer.fill(2)(0) if (args.length > 0) { args.map(arg => println(count(arg.toInt))) } else { (0 until 16).foreach(n => println(s"$n\t${count(n)}")) } private def count(n: Int): BigInteger = { if (n == 0) return BigInteger.ONE if (minp.length < 3 * n) { val wider = ArrayBuffer.fill(3 * n)(0) for (index <- 0 until (minp.length) by 1) wider(index) = minp(index) //println(minp.mkString(",")) (minp.length until wider.length).foreach { x => // Find the smallest prime which divides x wider(x) = (2 to x).find(x % _ == 0).getOrElse(2) } minp = wider //println(minp.mkString(",")) } val E = countE(n) val R2 = countR2(n) val F = countF(n) val R3 = countR3(n) val R = countR(n) val FR = countFR(n) val sum = E .add(R3) .add(R2.add(R).multiply(BigInteger.valueOf(2))) .add(F.add(FR).multiply(BigInteger.valueOf(3))) sum.divide(BigInteger.valueOf(12)) } private def countE(n: Int): BigInteger = { val w = ArrayBuffer.fill(3 * n)(0) (0 until n).foreach { i => ((i + 1) to (i + n)).foreach(j => w(j) -= 1) ((i + n + 1) to (i + 2 * n)).foreach(j => w(j) += 1) } powerProd(w.toArray) } private def countR2(n: Int): BigInteger = { val w = ArrayBuffer.fill(3 * n)(0) (0 until n).foreach { i => w(3 * i + 2) += 1 ((3 * i + 1) to (2 * i + n + 1)).foreach(j => w(j) -= 1) ((2 * i + n + 1) to (i + 2 * n)).foreach(j => w(j) += 1) } powerProd(w.toArray) } private def countF(n: Int): BigInteger = { val w = ArrayBuffer.fill(3 * n)(0) (0 until n).foreach { i => ((2 * i + 1) to (2 * i + n)).foreach(j => w(j) -= 1) ((i + n + 1) to (i + 2 * n)).foreach(j => w(j) += 1) } powerProd(w.toArray) } private def countR3(n: Int): BigInteger = { if ((n & 1) == 1) return BigInteger.ZERO countE(n / 2).pow(2) } private def countR(n: Int): BigInteger = { if ((n & 1) == 1) return BigInteger.ZERO val m = n / 2 val w = ArrayBuffer.fill(3 * m - 1)(0) (0 until m).foreach { i => (1 to (3 * i + 1)).foreach(j => w(j) += 2) (1 to (i + m)).foreach(j => w(j) -= 2) } powerProd(w.toArray) } private def countFR(n: Int): BigInteger = { if ((n & 1) == 1) return BigInteger.ZERO val m = n / 2 val w = ArrayBuffer.fill(3 * n - 2)(0) (1 to m).foreach(j => w(j) -= 1) (2 * m until 3 * m).foreach(j => w(j) += 1) (0 to 2 * m - 3).foreach { i => ((i + 2 * m + 1) to (i + 4 * m)).foreach(j => w(j) += 1) ((2 * i + 3) to (2 * i + 2 * m + 2)).foreach(j => w(j) -= 1) } powerProd(w.toArray) } private def powerProd(w: Array[Int]): BigInteger = { var result = BigInteger.ONE (2 until w.length).reverse.foreach { x => if (w(x) == 0) () else { val p = minp(x) if (p == x) result = result.multiply(BigInteger.valueOf(p).pow(w(p))) else { // Redistribute it. This should ensure we avoid negatives. w(p) += w(x) w(x / p) += w(x) } } } result } } ``` ]
[Question] [ Given two positive integers, \$A\$ and \$B\$, illustrate their [least common multiple](https://en.wikipedia.org/wiki/Least_common_multiple) by outputting two lines of dashes (`-`) with length [\$\text{lcm}\$](https://en.wikipedia.org/wiki/Least_common_multiple)\$(A, B)\$ after replacing every \$A\$th dash in the first line and every \$B\$th dash in the second line with vertical bars (`|`). In this way, the end of each line will be the only place two `|`'s line up. > > For example, if \$A = 6\$ and \$B = 4\$, \$\text{lcm}(6, 4) = 12\$, so: > > > > ``` > two lines of 12 dashes: > ------------ > ------------ > > replace every 6th dash in the first line with a vertical bar: > -----|-----| > ------------ > > replace every 4th dash in the second line with a vertical bar: > -----|-----| > ---|---|---| > > ``` > > Thus the final output would be > > > > ``` > -----|-----| > ---|---|---| > > ``` > > The order of the input numbers should correspond to the order of the lines. **The shortest code in bytes wins.** # Testcases ``` A B line for A line for B 1 1 | | 1 2 || -| 2 1 -| || 2 2 -| -| 6 4 -----|-----| ---|---|---| 4 6 ---|---|---| -----|-----| 2 3 -|-|-| --|--| 3 2 --|--| -|-|-| 3 6 --|--| -----| 2 5 -|-|-|-|-| ----|----| 4 3 ---|---|---| --|--|--|--| 10 10 ---------| ---------| 10 5 ---------| ----|----| 10 6 ---------|---------|---------| -----|-----|-----|-----|-----| 24 8 -----------------------| -------|-------|-------| 7 8 ------|------|------|------|------|------|------|------| -------|-------|-------|-------|-------|-------|-------| 6 8 -----|-----|-----|-----| -------|-------|-------| 13 11 ------------|------------|------------|------------|------------|------------|------------|------------|------------|------------|------------| ----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------|----------| ``` [Answer] # Python 3, 80 bytes Saved 1 byte thanks to Halvard Hummel and 1 byte thanks to Jonathan Allan. ``` import math def f(*l): for k in 0,1:print(l[~k]//math.gcd(*l)*(~-l[k]*"-"+"|")) ``` [Test it online!](https://tio.run/##FcoxCoAgFADQvVN8nNQyi6Khq4hDZJZoKuIShFc3evOLT76Cn2o1dwwpw73lq1GHBo2pI2sDOiSwYDwM3bjGZHzGThQrOf9rf@7qjxQX5oSVFDHUohcRUjWeu4XUDw "Python 3 – Try It Online") ``` lambda*l:"\n".join(l[0]*l[1]//math.gcd(*l)//k*(~-k*"-"+"|")for k in l) import math ``` [Test it online!](https://tio.run/##FcqxDsIgEADQ3a8gN92hLRpNBxO/pO2ANljkOAhhMTH9dRrf/PK3rkmuzT2mxjY@F6v5DpNA/0lekMfzrHm8zMZEW9f@/VpQMxkTNG5d0NDBEX5ALhUVlBfFdPAxp1LV/7dcvFR0OJxuRG0H "Python 3 – Try It Online") (82 bytes - initial answer) This is the best I could do in Python 2 (81 bytes). It seems like I cannot comment on that answer, I'll just post this here instead: ``` from fractions import* l=a,b=input() for k in l:print a*b/gcd(*l)/k*(~-k*"-"+"|") ``` [Test it online!](https://tio.run/##K6gsycjPM/r/P60oP1chrSgxuSQzP69YITO3IL@oRIsrxzZRJ8k2M6@gtERDkystv0ghWyEzTyHHqqAoM69EIVErST89OUVDK0dTP1tLo043W0tJV0lbqUZJ8///aDMdk1gA "Python 2 – Try It Online") *First attempt here, probably sub-optimal!* [Answer] # [Haskell](https://www.haskell.org/), 57 bytes ``` x%y=unlines[["-|"!!(0^mod a b)|a<-[1..lcm x y]]|b<-[x,y]] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v0K10rY0LyczL7U4OlpJt0ZJUVHDIC43P0UhUSFJsybRRjfaUE8vJzlXoUKhMja2JgkoUKEDZP3PTczMU7BVKCgtCS4pUlBRMFE1/Q8A "Haskell – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes ``` Ṭ€ị⁾|-ṁ€æl/Y ``` [Try it online!](https://tio.run/##y0rNyan8///hzjWPmtY83N39qHFfje7DnY1A3uFlOfqR////jzbTUTCJBQA "Jelly – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes ``` '-|'!i&Zm:G\go) ``` Input is a column vector with the two numbers. [**Try it online!**](https://tio.run/##y00syfn/X123Rl0xUy0q18o9Jj1f8///aDNrBYtYAA) As a bonus, the input can contain *more than two numbers*. [**Try it online!**](https://tio.run/##y00syfn/X123Rl0xUy0q18o9Jj1f8///aGNrBRNrBQtrBbNYAA) ### Explanation ``` '-|' % Push this string ! % Transpose. This is needed because of input [1; 1] i % Input column vector of 2 (or N) numbers &Zm % LCM of the 2 (or N) numbers, say L : % Range G % Push input again \ % Modulus, element-wise with broadcast. Gives a 2×L (or N×L) matrix g % Convert to logical: gives false for zeros, true for nonzeros o % Convert to double: gives 0 for false, 1 for true ) % Index into string (modular, 1-based). Implicitly display ``` [Answer] # [R](https://www.r-project.org/), ~~109~~ 105 bytes ``` function(a,b){q=1:a*b l=min(q[!q%%a]) x=rep("-",l*2) x[c(seq(0,l,a),l+seq(0,l,b))]="|" write(x,"",l,,"")} ``` [Try it online!](https://tio.run/##K/qfbqP7P600L7kkMz9PI1EnSbO60NbQKlEriSvHNjczT6MwWrFQVTUxVpOrwrYotUBDSVdJJ0fLCMiNTtYoTi3UMNDJ0UnU1MnRhnGSNDVjbZVqlLjKizJLUjUqdJSAOnSApGbt/3QNMx0Tzf8A "R – Try It Online") Anonymous function. Computes `l=lcm(a,b)`, then generates a range from `0` to `l` by `a`, then from `l` to `2*l` by `b`, setting the indices to `|` and printing as a matrix with `l` columns. [Answer] # [Python 2](https://docs.python.org/2/), 66 bytes ``` l=a,b=input() while a%b:a+=l[0] for x in l:print a/x*('-'*~-x+'|') ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P8c2USfJNjOvoLREQ5OrPCMzJ1UhUTXJKlHbNifaIJYrLb9IoUIhM08hx6qgKDOvRCFRv0JLQ11XXatOt0JbvUZd8/9/Cx0zAA "Python 2 – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 12 bytes ``` †?'-'|TUṪ`%N ``` [Try it online!](https://tio.run/##yygtzv7//1HDAnt1XfWakNCHO1clqPr9//8/2kTHLBYA "Husk – Try It Online") Yeah, there is a lcm builtin in Husk. No, I don't need it. Bonus: works with any number of input values ### Explanation ``` †?'-'|TUṪ`%N input:[2,3] Ṫ`%N table of all remainders of positive naturals divided by input numbers: [[1,1],[0,2],[1,0],[0,1],[1,2],[0,0],[1,1],[0,2],... U get all elements before the first repeated one: [[1,1],[0,2],[1,0],[0,1],[1,2],[0,0]] T transpose: [[1,0,1,0,1,0],[1,2,0,1,2,0]] †?'-'| replace all truthy elements with '-' and all falsy elements with '|': ["-|-|-|","--|--|"] implicit: since this is a full program, join the resulting array of strings with newlines, and print to stdout ``` [Answer] # C, 72 bytes ``` i;f(x,y){for(i=1;i%y|i%x;)putchar(i++%x?45:124);puts("|");y>0&&f(y,-x);} ``` [Answer] # Mathematica, 63 bytes ``` (s=LCM@##;Print[""<>If[i~Mod~#<1,"|","-"]~Table~{i,s}]&/@{##})& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvtfo9jWx9nXQVnZOqAoM68kWknJxs4zLTqzzjc/pU7ZxlBHqUZJR0lXKbYuJDEpJ7WuOlOnuDZWTd@hWlm5VlPtf1q0mY5F7H8A "Mathics – Try It Online") and another version which user202729 really, really, really wants to see posted # Mathematica, 59 bytes ``` (s=LCM@##;Print[""<>If[#∣i,"|","-"]~Table~{i,s}]&/@{##})& ``` this one uses special character `\[Divides]` `∣` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes ``` ʒ<'-×'|«¹.¿∍, ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##ASQA2/8wNWFiMWX//8qSPCctw5cnfMKrwrkuwr/iiI0s//9bMywgMl0 "05AB1E – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 22 bytes Assumes `⎕IO←0`. Takes A,B as right argument. **Bonus:** handles input list of any length! ``` {'|-'[⌽×⍵∘.|⍳∧/⍵]} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/32cfYF0tXqNrnr0o569h6c/6t36qGOGXs2j3s2POpbrA7mxtf9ByhSMFEy5QLSJgjGYNjQAIhjLFMYwAzOMTBQswAxzKG0GpQ2NFQwNIUoUjBVMAQ "APL (Dyalog Unicode) – Try It Online") `{`…`}` anonymous lambda where `⍵` represents the right argument  `'|-'[`…`]` index the string with:   `∧/` LCM across the input   `⍳` first that many **ɩ**ntegers (0 through N-1)   `⍵∘.|` division remainder table with the input vertically and that horizontally   `×` signum   `⌽` flip horizontally [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~46~~ 38 bytes *-8 bytes thanks to several suggestions by Luis Mendo* ``` @(a,b)'-|'.'(~mod(1:lcm(a,b),[a;b])+1) ``` [Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330EjUSdJU123Rl1PXaMuNz9Fw9AqJzkXLKoTnWidFKupbaj5P03DUAdIAQA "Octave – Try It Online") [Answer] # JavaScript (ES6), 69 bytes ``` f=(a,b,S,A=1)=>(A%a?'-':'|')+(A%a|A%b?f(a,b,S,A+1):S?'':` `+f(b,a,1)) ``` Recursively runs until `A` is divisible by both `a` and `b` – outputting a dash or pipe based on `a`'s divisibility by `A`. The function then calls itself, swapping `a` and `b`. The `S` variable prevents the function from calling itself infinitely. **Test Cases:** ``` f=(a,b,S,A=1)=>(A%a?'-':'|')+(A%a|A%b?f(a,b,S,A+1):S?'':` `+f(b,a,1)) console.log(f(1,1)); console.log(f(1,2)); console.log(f(2,1)); console.log(f(2,2)); console.log(f(6,4)); console.log(f(4,6)); console.log(f(2,3)); console.log(f(3,2)); console.log(f(10,10)); console.log(f(3, 6)); console.log(f(2, 5)); console.log(f(4, 3)); console.log(f(10, 10)); console.log(f(10, 5)); console.log(f(10, 6)); console.log(f(24, 8)); console.log(f(7, 8)); console.log(f(6, 8)); console.log(f(13, 11)); ``` --- Previous answers: # JavaScript (ES8), 91 bytes ``` f=(a,b,i=2,g=(c,d)=>d?g(d,c%d):c)=>i?'|'.padStart(a,'-').repeat(b/g(a,b))+` `+f(b,a,i-1):'' ``` Uses the algorithms: ``` lcm(a, b) = ab / gcd(a, b) gcd(c, d) = d ? gcd(d, c%d) : c ``` Recursively calls itself just once to output the second line. **Test Cases:** ``` f=(a,b,i=2,g=(c,d)=>d?g(d,c%d):c)=>i?'|'.padStart(a,'-').repeat(b/g(a,b))+` `+f(b,a,i-1):'' console.log(f(1,1)); console.log(f(1,2)); console.log(f(2,1)); console.log(f(2,2)); console.log(f(6,4)); console.log(f(4,6)); console.log(f(2,3)); console.log(f(3,2)); console.log(f(10,10)); console.log(f(3, 6)); console.log(f(2, 5)); console.log(f(4, 3)); console.log(f(10, 10)); console.log(f(10, 5)); console.log(f(10, 6)); console.log(f(24, 8)); console.log(f(7, 8)); console.log(f(6, 8)); console.log(f(13, 11)); ``` # JavaScript (ES6), 93 bytes ``` f=(a,b,i=2,g=(c,d)=>!d=>d?c:g(d,c%d):c)=>i?('-'.repeat(a-1)+'|').repeat(a*bb/g(a,b)/a)+` `+f(b,a,i-1):'' ``` Same algorithm as before, using `repeat` instead of `padStart`. [Answer] # Scala, 98 bytes ``` print((a to a*b).find(l=>l%a+l%b==0).map(l=>("-"*(a-1)+"|")*(l/a)+"\n"+("-"*(b-1)+"|")*(l/b)).get) ``` [Try it online](https://tio.run/##TclBCsIwEEDRvacYAoWZhEbdiJsIHsAbuJlpo0RiGtoggnr2WHXj7vH/1HHkOsjFdwUOHBL4e/Gpn2CfMzwWN47A4GDzlcza1jyGVBAZygCshewppB6j28WGTWzEuRXZK@dPQtUqjdyuyainIo1xyTOPSZnfkv8lRPbsC9VXfQM) [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 103 bytes ``` a->b->{String l="",r="|\n";for(int m=0;(++m%a|m%b)>0;r+=m%b<1?'|':'-')l+=m%a<1?'|':'-';return l+r+'|';} ``` [Try it online!](https://tio.run/##hZJLa4NAEMfv@RSDEFR8oHm1ZKO9FXroKUfrYU1M2HRdZV0DIfGz21WTVopLRpDxN6/9O3vCZ@zkRcpO@@@mqBJKdrCjuCzhExN2nYC0UmAh8YEwTOEkC9xKEOoeKrYTJGfuBxPvd3/zJLwVnLBjGAKDoMFOmDjhtWdAA02zeaDdvpiGDjk3CBOQBR4yLCub4ls2TczQQ9wKpLfx3/SbvtYd3aQtwH8A8VRUnAG1uCURqptWA5p0Uu4K74rOOdlDJnUavbb@JFEMmB9LE3r1rcmjRLHkIi1FCcEg8rCrb4Nf26N8NsZnivyZIn9lw2KML2xYKfrMx/hc0X@u7rNUzB3t73tSmKeKLFWB8dlyyOtY4EXBVwruS3X@8HfX6NeVVw2MbsHdemHdb9n8t@TtpRRp5uaVcAt5SwRlRpsXeTFYoMnH6uoiPzbRs0Lm4qKgl0cDc/gp6583GGTUk/5dNz8 "Java (OpenJDK 8) – Try It Online") ### 110 bytes, n input values ``` a->{String s="";for(int v:a){for(int i=1,z=1;z>(z=0);s+=i++%v<1?'|':'-')for(int k:a)z|=i%k;s+='\n';}return s;} ``` [Try it online!](https://tio.run/##hVJdb4IwFH33V9yYGGhAQv3aYq1729ue9sh46BRNFQuhhUSQ384K6GIWmt0mTXvuuR@ntydWsGmSRuK0Pzdp/h3zHexiJiV8MC6qEWiTiikNH7hgMZx0gJcrHnuHXOwUT4T3fj9suFBB6MKnyrg4biED2rDpturvIOl4TA5JZmsaFGuGqseFU@yWFJNya5fUR0Q6lDvOpNjgN@tmra2phR7Us44rb5RPzi3L@hIWqbNI5ZkASeqmbZeMuq7vYu7NFwnfw0VLsnsZfU9BCCw7SgS90NY6DRpXkVQS6JPnYRV2AdfuID4bwmcG/szAX7mwGMIXLqwMeeZD@NyQf27OszTUHcyPfS3MN3mWJsdwbV3kdcjxYsBXBhxrdfj5uWvye9SfCOxuwN14Yd1PGf0Z8udVqujiJbnyUv1LVCzslhf4ITgw1svp4gIcIvJfYOaxNI2vXQL0RK9H/V43Pw "Java (OpenJDK 8) – Try It Online") [Answer] # Java 8, ~~125~~ ~~118~~ 117 bytes ``` a->b->{String A="\n",B=A,t="|";for(int i=1;!A.endsWith(t)|!B.endsWith(t);B+=i++%b<1?t:"-")A+=i%a<1?t:"-";return A+B;} ``` -7 bytes thanks to *@Nevay*. -1 byte by starting with a trailing new-line (`A="",B="\n"` replaced with `A="\n",B=A`). **Explanation:** [Try it here.](https://tio.run/##jZLfa4MwEMff91dcAwXFKLW/Npbq0IfBHgaDPuxh20O0aZfORtGzUNr@7TZSBx1EGERy@fjN3X09t3zP3bwQarv6adKMVxW8cqmOdwAVcpQpbLXCq1Fm3rpWKcpcec9dsHhRKDaipP8TLbGUahOGkEIADXfDxA2PVwhRQD4VoXEQUQzIibB1XlpSIcjAZ4PIE2pVvUv8ttA@DeLbI4udQDrOMFn4T/hIXGJHGgz575GVAutSQeTE7NwwbUyvok4y7a2zuM/lCnbatnXt5uMLuN1@Ai3Ut/HwpilaPgXfZiY8NuCxWT02q@cUpgY8pTA3J5kY8MSce9KbZGYuacrtj7SfUc@LWQ83ltUFHgz83oznZuy3w7j2ee5GWso9R/Fnprc32p@JU2i3pBvu8lCh2Hl5jV7RajJlcXCAANOPo2WsT5Z6vCiyg8XtLkjsfnHX5bm5AA) ``` a->b->{ // Method with two integer parameters and String return-type String A="\n", // String top line (starting with a trailing new-line) B=A, // String bottom-line (starting with a new-line) t="|"; // Temp String "|" which is used multiple times for(int i=1; // Index-integer, starting at 1 !A.endsWith(t)|!B.endsWith(t); // Loop as long as both Strings aren't ending with "|" B+= // After every iteration: append `B` with: i++%b<1? // If `i` is divisible by `b`: // (and increase `i` by 1 in the process) t // `t` (holding "|") : // Else: "-") // A literal "-" A+= // Append `A` with: i%a<1? // If `i` is divisible by `a` t // `t` (holding "|") : // Else: "-"; // A literal "-" // End of loop (implicit / single-line body) return A+B; // Return both lines, separated by the new-line `B` started with } // End of method ``` [Answer] # [Python 2](https://docs.python.org/2/), 96 88 bytes **Edit:** Saved 4 bytes thanks to [@Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun) **Edit:** Saved 4 bytes thanks to [@Rod](https://codegolf.stackexchange.com/users/47120/rod) ``` lambda a,b:b/gcd(a,b)*("-"*~-a+"|")+"\n"+a/gcd(a,b)*("-"*~-b+"|") from fractions import* ``` [Try it online!](https://tio.run/##Zcm7CoAgFADQva@QO/lIgoiGoD9xuSaWkA/MJYh@3aK17cBJZ9li6KudVd3Ra4MEWz3pbl0MfcU4BQn8lijgAiZABRD4W/1tY3P0xGZciovhIM6nmAuvKbtQqKVDOzJWHw) [Answer] # [Python 2](https://docs.python.org/2/), 89 bytes *Not the shortest Python 2 entry, but a different approach than* `gcd` *which may still be golfable.* ``` a,b=input() h,p='-|' x=b*(h*~-a+p),a*(h*~-b+p) for v in x:print v[~zip(*x).index((p,p)):] ``` **[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyTYzr6C0REOTK0OnwFZdt0adq8I2SUsjQ6tON1G7QFMnEcJOArK50vKLFMoUMvMUKqwKijLzShTKouuqMgs0tCo09TLzUlIrNDQKdAo0Na1i//830zEBAA "Python 2 – Try It Online")** [Answer] # [Haskell](https://www.haskell.org/), ~~66~~ 60 bytes ``` a#b=do x<-[a,b];lcm a b`take`cycle(([2..x]>>"-")++"|")++"\n" ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P1E5yTYlX6HCRjc6UScp1jonOVchUSEpoSQxOzUhuTI5J1VDI9pIT68i1s5OSVdJU1tbqQZMxuQp/c9NzMxTsFUoKC0JLilSUDm0wNBA2ew/AA "Haskell – Try It Online") Same length: ``` a#b=unlines[take(lcm a b)$cycle$([2..x]>>"-")++"|"|x<-[a,b]] ``` Old solution: ``` l!x=[1..div l x]>>([2..x]>>"-")++"|" a#b|l<-lcm a b=l!a++'\n':l!b ``` [Answer] # [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 131 bytes ``` > Input > Input >> 1⊔2 >> (3] >> L∣1 >> L∣2 >> Each 5 4 >> Each 6 4 > '-|' >> 9ⁿL >> Each 10 7 >> Each 10 8 >> Output 11 12 ``` [Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYPuqaYgRiaBjHgiifRx2LDWEMsIRrYnKGgqmCCZxtBmIrqOvWqIOELB817veByxkaKJgjcyxAHP/SEqBtCoaGCoZARxgacJkBAA "Whispers v2 – Try It Online") ## How it works If you're unfamiliar with Whispers' program structure, I'd recommend reading the first part of [this](https://codegolf.stackexchange.com/a/174898/66833) post. In this explanation, we'll refer to the two inputs as \$x\$ and \$y\$ respectively. Our first two lines simply take the inputs in, and store them on lines **1** (\$x\$) and **2** (\$y\$). We then move to line **3**, which returns \$\alpha = \mathrm{lcm}(x, y)\$ and to line **4**, which returns the range \$A = [1, 2, ..., \alpha]\$. Next, we reach our first two `Each` statements, operating on each of the inputs: ``` >> L∣1 >> L∣2 >> Each 5 4 >> Each 6 4 ``` These four lines both operate on \$A\$, but return two different arrays, which we will call \$A\_x\$ and \$A\_y\$. While being different arrays, they are both formed in similar ways, as can be noted from the similarities in the two pairs of lines. In fact, we can define \$A\_x\$ and \$A\_y\$ as $$A\_x := [(i \div x) \in \mathbb{Z} \: | \: i \in A]$$ $$A\_y := [(i \div y) \in \mathbb{Z} \: | \: i \in A]$$ This leaves us with two lists consisting of a \$1\$ where we'd expect there to be a `|` character, and a \$0\$ where there should be a `-`. This takes us to the next section of our code: ``` > '-|' >> 9ⁿL >> Each 10 7 >> Each 10 8 ``` First, we yield the string `-|`, then we create our next two arrays \$B\_x\$ and \$B\_y\$. Helpfully, we can use the same function to map \$A\_x\$ to \$B\_x\$ and \$A\_y\$ to \$B\_y\$, namely `9ⁿL`. This function yields the \$n^{th}\$ element of the string on line **9** i.e. `-|`, where \$n\$ is either \$0\$ or \$1\$, depending on the element from the respective \$A\$ arrays. This yields the two arrays \$B\_x\$ and \$B\_y\$ as defined below: $$(B\_x)\_i = \begin{cases} \text{"-"}, & (A\_x)\_i = 0 \\ \text{"|"}, & (A\_x)\_i = 1 \end{cases}$$ $$(B\_y)\_i = \begin{cases} \text{"-"}, & (A\_y)\_i = 0 \\ \text{"|"}, & (A\_y)\_i = 1 \end{cases}$$ The `Each` command is special-cased for when yielding an array of strings, where it returns a single string, rather than an array. Finally, we reach the statement ``` >> Output 11 12 ``` which outputs \$B\_x\$, then a newline, then \$B\_y\$ [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~121~~ ~~99~~ ~~93~~ ~~92~~ 89 bytes This should be much shorter, hmmmm.... ``` #define L(x)for(j=-1,i=a;j<i;i+=i%b||i%a)putchar(++j?j%x?45:124:10); i,j;f(a,b){L(a)L(b)} ``` [Try it online!](https://tio.run/##dYxBCsIwFET3OUWpBP4nKdgau2gMvUAvkcZGf8AqVaHQ9uwxgltn9YY3jCsuzsW4Ow@exiHrYEZ/nyCYopRkrA4n0iQM8X5diVt8vF/uaicQIrSBz606NmWlmnKPmpEM2oOVPS4dWOygxy3eLI2AbGFZiodaqrT8cnp6Qp7/mgcl6z@mkofEG4sf "C (gcc) – Try It Online") [Answer] # [J](http://jsoftware.com/), 20 bytes ``` '-|'{~*.$&>;&(<:=i.) ``` [Try it online!](https://tio.run/##y/qfVqxga6VgoADE/9V1a9Sr67T0VNTsrNU0bKxsM/U0/2tyKekpqKfZWqkr6CjUWimkFXNxpSZn5CuYKaQpmPwHAA "J – Try It Online") [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGL), ~~19~~ 16 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` 2{H┌*┐+..*..g/mP ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=MiU3QkgldTI1MEMqJXUyNTEwKy4uKi4uZy9tUA__,inputs=MTMlMEExMQ__) Explanation: ``` 2{ two times do H decreate ToS - input - by 1 ┌* get that many dashes ┐+ append a vertical bar ..* push both inputs multiplied \ ..g push gcd(input1, input2) | LCM - 7 bytes :/ / divide the multiblication by the GCD / m mold the string to that length P print that in a new line ``` [Answer] # [Stacked](https://github.com/ConorOBrien-Foxx/stacked), ~~42~~ 38 bytes ``` [:...lcm@z:[:z\/\#-'-'*\rep'|'+out]"!] ``` [Try it online!](https://tio.run/##Ky5JTM5OTfn/P9pKT08vJznXocoq2qoqRj9GWVddV10rpii1QL1GXTu/tCRWSTH2v4NVGheXhpmCiaZCGpeGsYIRmDZSMAbThgqGUBomDuUbKBgaAFn/AQ "Stacked – Try It Online") Input in the form of a pair of numbers. All the test cases put together look kinda like buildings. ## Explanation This first takes the `lcm` of the two input numbers into `z`. Then, for each number `k`, we generate `z / k` strings of `-` of length `k - 1`, adding `|` to the end of each, and outputting each. ## Previous counted attempts 42 bytes: `[:...lcm@z:[:z\/\#-'-'*\rep'|'+''#`out]"!]` ## Other attempts 43 bytes: `[:...lcm@z:[:z\/\#-'-'*\rep'|'#`'|'+out]"!]` 45 bytes: `['@lcm'!#~@z,[:z\/\#-'-'*\rep'|'#`'|'+out]"!]` 45 bytes: `[:...lcm@x[x'-'*\#<$betailmap'|'#`'|'+out]"!]` 53 bytes: `[:...lcm'-'*@z#-'.'*'('\+')'+'.'+[z\'$1|'repl out]"!]` 54 bytes: `[:...lcm@x{!x'-'*('('n#-'.'*').')''#`'$1|'repl out}"!]` [Answer] # JavaScript (ES6), 89 ``` f=(a,b,t=` `,l=0,R=n=>'-'.repeat(n-1)+'|')=>l||1/t?f(a,b,l<0?t+R(b,l+=b):R(a,l-=a)+t,l):t ``` Evaluating the LCM with repeated addictions. *Less golfed* ``` F=(a,b, sa='', sb='', la=0, lb=0)=> { var R=n=>'-'.repeat(n-1)+'|' if (la != lb || la == 0) { if (la < lb) { sa += R(a) la += a } else { sb += R(b) lb += b } return F(a, b, sa, sb, la, lb) } else return sa+'\n'+sb } ``` **Test** ``` f=(a,b,t=` `,l=0,R=n=>'-'.repeat(n-1)+'|')=>l||1/t?f(a,b,l<0?t+R(b,l+=b):R(a,l-=a)+t,l):t function update() { var [a,b]=I.value.match(/\d+/g) R.textContent = f(+a,+b) } update() ``` ``` <input id=I oninput='update()' value='4 6'> <pre id=R></pre> ``` [Answer] **VBA (Excel) , 144 142 bytes** ``` Sub q() a=[a1] b=[a2] Do Until c=d And d="|" e=e+1 c=IIf(e Mod a,"-","|") d=IIf(e Mod b,"-","|") f=f& c g=g& d Loop Debug.? f& vbCr& g End Sub ``` -2 bytes. thanks Sir Washington Guedes. [Answer] # [J](http://jsoftware.com/), 20 bytes ``` *./($'-|'#~<:,1:)"0] ``` [Try it online!](https://tio.run/##y/r/P81WT0FLT19DRV23Rl25zsZKx9BKU8kg9n9qcka@QpqCoZGCpYKxgpECF1hAXR1Ca6QpGWoqGCoY6gAJIx2gPIhlAERgylTHSsHQWMHQ8D8A) [Answer] # [Ruby](https://www.ruby-lang.org/), 64 57 bytes ``` ->a,b{[a,b].map{|n|(1..a.lcm(b)).map{|x|x%n>0??-:?|}*''}} ``` -7 bytes thanks to G B. [Try it online!](https://tio.run/##RY/JCoNAEETvfkVfklHRwXFLEKIfIhJcieBGRsHg@O3GSZukD/2qquvSzyl7bdVtM8PUyJZ4Xwlt02ERnVAZpSlt8lbNNA3DWcynLrSiyAwiseqErOsWEwaMGLDDlrDR2eh8cCVc8DF0JBy8Od/Qw8rnxixg1iG8g1hz4Sp5QfgI5gBjJKFlmj@g6EFwocA@wzRy4H9ZxTqnfGjqUX6inoOxv9da8isoZVdsbw "Ruby – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), ~~32~~ ~~30~~ 29 bytes ``` NθNη≔θζW﹪ζη≦⁺θζE⟦θη⟧…⁺×-⁻ι¹|ζ ``` [Try it online!](https://tio.run/##TYs9C8IwFAD3/opHpvcgAbu4dHIUbOngJg61jSaQJm3SKBT/e4wfg@Mdd73qfO86k9LeTnFp4niRHmeqin9WmXch6JvFmcOa6aG0kYC1G6JxuHJQRFB307c6yOuCrYmBw69vvbYL5gBP2agzh9qZ4dPgUY8yIBMsS22z0BxKIg7syei9E1UplZtim8Q9iWBe "Charcoal – Try It Online") Link is to verbose version of code. Edit: Saved 1 byte thanks to @ASCII-only. [Answer] # Google Sheets, 77 Bytes Anonymous worksheet formula that takes input from range `A1:B1` and outputs to the calling cell ``` =REPT(REPT("-",A1-1)&"|",LCM(1:1)/A1)&" "&REPT(REPT("-",B1-1)&"|",LCM(1:1)/B1 ``` -4 Bytes thanks to [@EngineerToast](https://codegolf.stackexchange.com/users/38183/engineer-toast) ]
[Question] [ *This task is part of the [First Periodic Premier Programming Puzzle Push](http://meta.codegolf.stackexchange.com/q/298/15).* You get a hierarchy of items in the following format: ``` 2 Hat 1 Gloves ``` which need to be put in boxes, like so: ``` .------------. | Hat | | .--------. | | | Gloves | | | '--------' | '------------' ``` In the input format the numbers start a box with as many items as the number specifies. The first box has two items in it (the Hat and the box that contains the Gloves), the second one only contains a single item – the gloves. As can be seen, boxes can live inside boxes, too. And they are always rounded ... sort of (pointy corners are a wound hazard and we wouldn't want that). *Below there are the nasty details for those that want to utilize every tiny bit of leeway the specification gives. Mind you, not reading the spec is no excuse for submitting wrong solutions. There is a test script and a few test cases at the very end.* --- **Specification** * Boxes are constructed from the following characters: + `|` (U+007C) is used to construct the vertical edges. + `-` (U+002D) is used to construct the horizontal edges. + `'` (U+0027) are the round lower corners. + `.` (U+002E) are the round upper corners.A box therefore looks like this: ``` .--. | | '--' ``` *Note that while Unicode also has round corners and proper box-drawing characters, this task is in ASCII only. As much as I love Unicode I realize that there are languages and environments out there that didn't quite arrive in the second to last decade.* * Boxes can contain a sequence of items that are either text or other items. Individual items in a box are rendered from top to bottom. The sequence A, B, C thus renders as follows: ``` .---. | A | | B | | C | '---' ``` This of course applies to nested boxes too, which are an item just like text. So the sequence A, B, Box(C, Box(D, E)), F would render as follows: ``` .-----------. | A | | B | | .-------. | | | C | | | | .---. | | | | | D | | | | | | E | | | | | '---' | | | '-------' | | F | '-----------' ``` * Boxes adjust their size to the content and nested boxes always extend to the size of their parent. There is always a space before and after the content, so that neither text nor nested boxes are too close to the outer box' edge. In short, the following is wrong: ``` .---. |Box| '---' ``` And the following is correct: ``` .-----. | Box | '-----' ``` Looks much nicer, too :-) * Text items (see *Input* below) have to be reproduced exactly. * There is always a single top-level box (cf. XML). However, one box can contain several other boxes. **Input** * Input is given on standard input; for easier testing likely redirected from a file. * The input is given line-wise, with each line representing either a text item to put in the current box or opening a new box. * Every line is terminated by a line break. * Text items are marked by a line that does not consist of a number (see below). Text uses alphabetic characters, the space and punctuation (`.,-'"?!()`). Text will not start or end with a space and it will always have at least one character. * A box starts with a single line with a number in it. The number tells the size of the box, i.e. the number of following items that are put into it: ``` 2 A B ``` yields a box with two text items: ``` .---. | A | | B | '---' ``` A box will always contain at least one item. * The end of boxes is not explicitly marked with a line; instead boxes are implicitly closed after the specified number of items are put into them. * A box is always just a single item, regardless how many items are in it. E.g. ``` 3 A 4 a b c d B ``` will yield a box with three items, the second of which is another box with four items. Nesting also does not affect the fact that a box is just a single item. **Limits** * The maximum nesting level is **five**. I.e. there are at most five boxes inside of each other. This includes the outermost one. * There is a maximum of **ten** items per box. * Text items have a maximum length of **100** characters. **Output** * Output is the rendered box including all containing and nested items according to the rules outlined above. * Output should be given on standard output and it has to match exactly. No leading or trailing whitespace is allowed. * Each line must be terminated with a line break, including the last. **Winning condition** * Shortest code wins (i.e. gets the accepted answer). **Sample input 1** ``` 3 This is some text! Oh, more text? Just text for now, as this is a trivial example. ``` **Sample output 1** ``` .--------------------------------------------------. | This is some text! | | Oh, more text? | | Just text for now, as this is a trivial example. | '--------------------------------------------------' ``` **Sample input 2** ``` 4 Extreme nesting 3 of boxes 4 might lead to 2 interesting 1 visuals. Indeed! ``` **Sample output 2** ``` .--------------------------. | Extreme | | nesting | | .----------------------. | | | of | | | | boxes | | | | .------------------. | | | | | might | | | | | | lead | | | | | | to | | | | | | .--------------. | | | | | | | interesting | | | | | | | | .----------. | | | | | | | | | visuals. | | | | | | | | | '----------' | | | | | | | '--------------' | | | | | '------------------' | | | '----------------------' | | Indeed! | '--------------------------' ``` **Sample input 3** ``` 1 1 1 1 1 Extreme nesting Part Two ``` **Sample output 3** ``` .------------------------------------------. | .--------------------------------------. | | | .----------------------------------. | | | | | .------------------------------. | | | | | | | .--------------------------. | | | | | | | | | Extreme nesting Part Two | | | | | | | | | '--------------------------' | | | | | | | '------------------------------' | | | | | '----------------------------------' | | | '--------------------------------------' | '------------------------------------------' ``` **Sample input 4** ``` 3 Foo 2 Bar Baz 2 Gak 1 Another foo? ``` **Sample output 4** ``` .----------------------. | Foo | | .------------------. | | | Bar | | | | Baz | | | '------------------' | | .------------------. | | | Gak | | | | .--------------. | | | | | Another foo? | | | | | '--------------' | | | '------------------' | '----------------------' ``` **Test Script** Since getting details right can be difficult at times we ([Ventero](https://codegolf.stackexchange.com/users/84/ventero) and me) have prepared a test script you can run your solution with to check whether it's correct. It's available as both a [PowerShell script](http://hypftier.de/dump/CG2295/test.ps1) and a [bash script](http://hypftier.de/dump/CG2295/test). Invocation is: `<test-script> <program invocation>`. **UPDATE:** *The test scripts have been updated; there were a number of test cases that did not honor the limits I defined. The PowerShell test script did not use case-sensitive comparison for checking the result. I hope everything is fine now. The number of test cases was reduced to 156, although the last one now is quite ... large.* **UPDATE 2:** *I uploaded my [test-case generator](http://hypftier.de/dump/CG2295/nb.exe). [Written in C#](http://hypftier.de/dump/CG2295/nb.cs), targeting the .NET 2 runtime. It runs on Mono. It may help people to test their implementation. As a definitive worst-case given the limits in the task you can try:* ``` nb.exe 1 10 10 5 100 100 | my invocation ``` *which will generate only boxes up to the innermost level and utilize both the maximum number of items per box and the maximum length of text items. I didn't include this test case into the test script, though, since it's quite large and the output even larger.* **UPDATE 3:** *I updated the PowerShell test script which was prone to throw errors depending on how the line endings were in the script and what line endings the solution printed. Now it should be agnostic to both. Sorry again for the confusion.* [Answer] ## Python, 204 chars ``` def P(n):x=raw_input();return eval('[(n+".","","-")]'+'+P(n+"| ")'*int(x))+[(n+"'",'','-')]if'0'<x<':'else[(n,x,' ')] r=P('') for q,t,f in r:print q+t+f*(max(len(2*x+y)for x,y,a in r)-len(2*q+t))+q[::-1] ``` `P` returns a list of triples, each of which is a line prefix/suffix (the suffix being the reverse of the prefix), some line text, and a line fill character. After calculating all the triples, they are printed using the right number of fill characters to make all the lines the same length. Ungolfed version: ``` def get_lines(prefix): line=raw_input() result=[] if line.isdigit(): result.append((prefix+'.', '', '-')) for i in xrange(int(line)): result += get_lines(prefix + '| ') result.append((prefix+"'", '', '-')) else: result.append((prefix, line, ' ')) return result lines=get_lines('') width=max(2*len(prefix)+len(text) for prefix,text,fill in lines) for prefix,text,fill in lines: print prefix+text+fill*(width-2*len(prefix)-len(text))+prefix[::-1] ``` [Answer] ## Ruby 1.9, 174 characters ``` r=->l{$*<<(l*2+i=gets.chop).size;/\d/?eval('[l+?.,p=?-,p,'+'*r["| "+l],'*i.to_i+"l+?',p,p]"):[l,i,?\s]} r[""].each_slice(3){|a,b,c|puts a+b+c*($*.max-(a*2+b).size)+a.reverse} ``` Somewhat similar to [Keith's solution](https://codegolf.stackexchange.com/questions/2295/1p5-nested-boxes/2299#2299). [Answer] ## APL (78) ``` {∧/⎕D∊⍨I←⍞:{∆,('-'⍪⍵⍪'-'),∆←'.|'''/⍨1(⊃⍴⍵)1}⍕⍪/{⍵↑[2]⍨⌈/⊃∘⌽∘⍴¨∆}¨∆←∇¨⍳⍎I⋄⍉⍪I}⍬ ``` [Answer] ## Python - 355 314 259 chars ``` w=0 def p(n,l): global w;f=[(l-1,0)] for k in' '*n: i=raw_input() try:f+=p(int(i),l+1) except:f+=[(l,i)];w=max(w,4*l+len(i)) return f+[(l-1,1)] for l,s in p(input(),1):p=w-4*l-2;print'| '*l+(".'"[s]+'-'*p+".'"[s]if s<2 else s+' '*(p+2-len(s)))+' |'*l ``` [Answer] ## Ruby 1.9, 229 228 226 223 222 ``` g=->n{(1..n).map{g[Integer l=gets.chop]rescue l}} w=->b{b.bytesize rescue b.map{|e|w[e]}.max+4} p=->b,c{r=c-2 [?.+?-*r+?.,*b.map{|i|p[i,c-4]}.flatten.map{|k|"| #{k} |"},?'+?-*r+?']rescue[b.ljust(c)]} puts p[b=g[1][0],w[b]] ``` [Answer] ## C, 390 366 363 characters ``` #define F(n)for(int i=n;i--;) #define H(n,s,a...)F(n)printf(s);printf(a); #define I(s)H(v,"| ",s)H(l-2,"-",s)J #define J H(v," |","\n") S[1<<17][26],N[1<<17],P,a;E(p){int l=strlen(gets(S[p]));if(sscanf(S[p],"%d",N+p))F(N[p])l<(a=E(++P))?l=a:l;return l+4;}R(p,v,l){if(N[p]){I(".")F(N[p])R(++P,v+1,l-4);I("'")}else{H(v,"| ","%-*s",l,S[p])J}}main(){R(P=0,0,E(0)-4);} ``` Compile with `gcc -std=gnu99 -w file.c` Not even close to Keith's version, but hey, it's good ol' C [Answer] very functional python, 460 characters ``` r=range s=lambda x:isinstance(x,str) w=lambda x:reduce(max,[len(i)if s(i)else w(i)+4 for i in x]) z=lambda b,x:''.join(b for i in r(x)) def g(n=1): t=[] for i in r(n): x=raw_input('') try:t+=[g(int(x))] except:t+=[x] return t o=list.append def y(c,m): f='| ';h=' |';e=z('-',m+2);a='.'+e+'.';b="'"+e+"'";t=[a] for i in c: if s(i):o(t,f+i+z(' ',m-len(i))+h) else:[o(t,f+j+h)for j in y(i,m-4)] return t+[b] x=g()[0];m=w(x);print '\n'.join(y(x,m)) ``` [Answer] ## Haskell, 297 characters ``` f§(a,b)=(f a,b) h c=(c,'-',c) b l=h".":map(\(p,f,q)->("| "++p,f,q++" |"))l++[h"'"] y[]s z=([(s,' ',"")],z) y[(n,_)]_ z=b§foldr(\_(l,w)->(l++)§x w)([],z)[1..n] x(a:z)=y(reads a)a z m(p,_,q)=length$p++q n®a@(p,c,q)=p++replicate(n-m a)c++q++"\n" o(l,_)=l>>=(maximum(map m l)®) main=interact$o.x.lines ``` While golf'd, the method is pretty straight forward. Only limits are available memory. [Answer] ## C# -1005 859 852 782 characters ``` using c=System.Console;using System.Linq;class N{static void Main(){new N();}N(){var i=R();c.WriteLine(i.O(0,i.G().W));}I R(){var s=c.ReadLine();int l=0,i=0;if(int.TryParse(s,out l)){var b=new I(l);for(;i<l;){b.m[i++]=R();}return b;}else{return new I(0,s);}}class P{public int W;public int H;}class I{public I[]m;bool z;string t;public I(int l,string r=""){z=l!=0;m=new I[l];t=r;}public P G(){var s=new P();if(z){var d=m.Select(i=>i.G());s.W=d.Max(y=>y.W)+4;s.H=d.Sum(y=>y.H)+2;}else{s.W=t.Length;s.H=1;}return s;}public string O(int l,int w){if(z){string s=A(l,"."+"-".PadRight(w-2,'-')+"."),e=s.Replace(".","'");foreach(var i in m){s+="\n"+i.O(l+1,w-4);}s+="\n"+e;return s;}else{return A(l,t.PadRight(w));}}}static string A(int l,string o){while(l-->0){o= "| "+o+" |";}return o;}} ``` I need to take another look at this as I'm sure it can be improved, but this is my initial go third pass at it. Ungolf'd: ``` using c=System.Console; using System.Linq; class NestedBoxes { static void Main() { new NestedBoxes(); } NestedBoxes() { var item = ReadItem(); c.WriteLine(item.Print(0, item.GetSize().Width)); } Item ReadItem() { var line = c.ReadLine(); int count = 0, i = 0; if (int.TryParse(line, out count)) { var box = new Item(count); for (; i < count;) { box.items[i++] = ReadItem(); } return box; } else { return new Item(0,line); } } class Size { public int Width; public int Height; } class Item { public Item[] items; bool isBox; string text; public Item(int size,string word="") { isBox = size != 0; items = new Item[size]; text = word; } public Size GetSize() { var s = new Size(); if (isBox) { var sizes = items.Select(i => i.GetSize()); s.Width = sizes.Max(y => y.Width) + 4; s.Height = sizes.Sum(y => y.Height) + 2; } else { s.Width = text.Length; s.Height = 1; } return s; } public string Print(int level, int width) { if (isBox) { string output = AddLevels(level, "." + "-".PadRight(width - 2, '-') + "."), bottomLine = output.Replace(".", "'"); foreach (var item in items) { output += "\n" + item.Print(level + 1, width - 4); } output += "\n" + bottomLine; return output; } else {return AddLevels(level, text.PadRight(width)); } } } static string AddLevels(int level, string output) { while(level-->0) { output = "| " + output + " |"; } return output; } } ``` [Answer] # PHP, 403 388 306 chars ``` <?b((int)fgets(STDIN),'');foreach($t as $r)echo$r[0].str_pad($r[2],$w-2*strlen($r[0]),$r[1]).strrev($r[0])."\n";function b($c,$p){global$t,$w;$t[]=array($p.".","-");while($c--){if(($d=trim(fgets(STDIN)))>0)b($d,"| ".$p);else$t[]=array("| ".$p," ",$d);$w=max($w,strlen($d.$p.$p)+4);}$t[]=array($p."'","-");} ``` Ungolfed: ``` box((int)fgets(STDIN), ''); foreach($table as $row) { $prefix = $row[0]; $pad = $row[1]; $data = $row[2]; echo $prefix . str_pad($data, ($width - 2*strlen($prefix)), $pad) . strrev($prefix)."\n"; } function box($count,$prefix) { global $table, $width; $table[] = array($prefix.".","-"); while($count--) { if(($data = trim(fgets(STDIN))) > 0) { box($data, "| ".$prefix); } else { $table[] = array("| ".$prefix, " ", $data); } $width = max($width,strlen($data.$prefix.$prefix)+4); } $table[] = array($prefix."'","-"); } ?> ``` I borrowed the prefix-idea from Keith (is that allowed at all?), otherwise this is pretty much as the original. Still couldn't get below 300. Stuck with this. Onwards. [Answer] ## PHP, 806 769 721 653 619 chars ``` <?php function A($a,$b,$c,&$d){for($e=$b;$e>0;$e--){$f=fgets($a);if(false===$f){return;}$g=intval($f);if(0<$g){$h[]=A($a,$g,$c+1,$d);}else{$f=trim($f);$h[]=$f;$j=strlen($f)+4*$c;if($d<$j){$d=$j;}}}return $h;}$d=0;$h=A(STDIN,intval(fgets(STDIN)),1,&$d);function B($k,$c,$d){$f=str_pad('',$d-4*$c-2,'-',2);return C($k.$f.$k,$c,$d);}function C($f,$c,$d){$f=str_pad($f,$d-4*$c,' ');$f=str_pad($f,$d-2*$c,'| ',0);$f=str_pad($f,$d,' |');return $f;}function D($l,$c,$d){if(!is_array($l)){echo C($l,$c,$d)."\n";return;}echo B('.',$c,$d)."\n";foreach($l as $m){echo D($m,$c+1,$d);}echo B('\'',$c,$d)."\n";}D($h,0,$d);exit(0);?> ``` Ungolfed version: ``` <?php function read_itemgroup($handle, $item_count, $depth, &$width) { //$items = array(); for($i = $item_count; $i > 0; $i--) { $line = fgets( $handle ); if(false === $line) { return; } $line_int = intval($line); if(0 < $line_int) { // nested group $items[] = read_itemgroup($handle, $line_int, $depth + 1, $width); } else { // standalone item $line = trim($line); $items[] = $line; // determine width of item at current depth $width_at_depth = strlen($line) + 4 * $depth; if($width < $width_at_depth) { $width = $width_at_depth; } } } return $items; } $width = 0; $items = read_itemgroup(STDIN, intval(fgets( STDIN )), 1, &$width); //var_dump($items, $width); function render_line($corner, $depth, $width) { $line = str_pad('', $width - 4 * $depth - 2, '-', 2); // 2 = STR_PAD_BOTH return render_item($corner . $line . $corner, $depth, $width); } function render_item($line, $depth, $width) { $line = str_pad($line, $width - 4 * $depth, ' '); $line = str_pad($line, $width - 2 * $depth, '| ', 0); // 0 = STR_PAD_LEFT $line = str_pad($line, $width, ' |'); return $line; } function render($item, $depth, $width) { if(!is_array($item)) { echo render_item($item, $depth, $width) . "\n"; return; } echo render_line('.', $depth, $width) . "\n"; foreach($item as $nested_item) { echo render($nested_item, $depth + 1, $width); } echo render_line('\'', $depth, $width) . "\n"; } render($items, 0, $width); exit(0); ?> ``` [Answer] # Java - 681 668 chars ``` import java.util.*;public class b{static int m,h,i;public static void main(String[]a)throws Throwable{for(Object o:z("")){a=(String[])o;String s=a[0]+a[1];i=a[0].length();for(h=0;h<m-i*2-a[1].length();h++){s+=a[2];}for(h=i;h>0;h--){s+=a[0].charAt(h-1);}System.out.println(s);}}static List z(String p)throws Throwable{String b="",d="";List l=new ArrayList();while((i=System.in.read())>-1){if(10==i){if(d!=""){String[]v={p+".",b,"-"},t={p+"'",b,"-"};l.add(v);for(int u=0;u<Integer.parseInt(d);u++){l.addAll(z(p+"| "));}l.add(t);}else{h=b.length()+p.length()*2;if(m<h)m=h;String[]v={p,b," "};l.add(v);}break;}else if(i>47&&i<58){d+=(char)i;}else {b+=(char)i;}}return l;}} ``` essentially the same method as Keith Randall's Python code Ungolfed version: ``` import java.util.*; public class b { static int m, h, i; public static void main(String[] a) throws Throwable { for (Object o : z("")) { a = (String[]) o; String s = a[0] + a[1]; i = a[0].length(); for (h = 0; h < m - i * 2 - a[1].length(); h++) { s += a[2]; } for (h = i; h > 0; h--) { s += a[0].charAt(h - 1); } System.out.println(s); } } static List z(String p) throws Throwable { String b = "", d = ""; List l = new ArrayList(); while ((i = System.in.read()) > -1) { if (10 == i) { if (d != "") { String[] v = { p + ".", b, "-" }, t = { p + "'", b, "-" }; l.add(v); for (int u = 0; u < Integer.parseInt(d); u++) { l.addAll(z(p + "| ")); } l.add(t); } else { h = b.length() + p.length() * 2; if (m < h) m = h; String[] v = { p, b, " " }; l.add(v); } break; } else if (i > 47 && i < 58) { d += (char) i; } else { b += (char) i; } } return l; } } ``` [Answer] ## Perl - 200 199 chars Same algorithm as Keith Randall's Python (nice design, Keith), but a tiny bit more compact in this Perl take on it. ``` sub P{$_=<>;chop;$m>($l=length"$_@_@_")or$m=$l;/^\d/?(["@_.","","-"],(map{P("| @_")}1..$_),["@_'","","-"]):["@_",$_," "]}map{($q,$t,$f)=@$_;print"$q$t",($f x($m-length"$q$t$q")).reverse($q),"\n"}(P); ``` [Answer] ## F# - 341 characters ``` let rec f(x,y)=[ let l=stdin.ReadLine() let q,d=Core.int.TryParse l if q then yield x+".","",'-',"."+y for i=1 to d do yield!f(x+"| ",y+" |") yield x+"'","",'-',"'"+y else yield x,l,' ',y] let l=f("","") for w,x,y,z in l do printfn"%s"(w+x.PadRight(List.max(l|>List.map(fun(w,x,y,z)->2*w.Length+x.Length))-2*w.Length,y)+z) ``` An F# version of Keith's solution. Lists are immutable by default, so this version stuffs the entire recursive function into a list, returns the list, from which the items are extracted using the `for..do` loop and a `yield!`. I couldn't find a way to reverse the prefix concisely, so I just attached the suffix onto the triples. FYI, the TryParse method returns a double `(bool,int)`. [Answer] ### GolfScript, 125 characters ``` n/):B;[(~{[B"."+"""-"]B"| "+:B;@@{(.10,`-{[B\" "]\}{~A}if}*B[2>:B"'"+"""-"]\}:A~;].{~;1$++,}%$-1=:§;{~§3$.+3$+,-*+1$-1%++}%n* ``` Using a similar approach as [Keith's solution](https://codegolf.stackexchange.com/a/2299). [Answer] # Clojure - 480 chars ``` (use '[clojure.contrib.string :only (repeat)])(let [r ((fn p[%](repeatedly % #(let [x (read-line)](try(doall(p(Integer/parseInt x)))(catch Exception e x))))) 1)]((fn z[m,n,o] (let[b #( let[p(dec o)](println(str(repeat p "| ")%(repeat(- m(* 4 p)2)"-")%(repeat p " |"))))](b \.)(doseq[i n](if(seq? i)(z m i(inc o))(println(str(repeat o "| ")i(repeat(- m(count i)(* o 4))" ")(repeat o " |")))))(b \')))((fn w[x](reduce max(map(fn[%](if(seq? %)(+ (w %)4)(count %)))x)))r)(first r) 1)) ``` This is my first Clojure program as well as my first Clojure golf attempt, so, needless to say, this shouldn't be taken as representative of Clojure solutions in general. I'm sure it could be shortened significantly, especially if [Keith Randall's method](https://codegolf.stackexchange.com/questions/2295/1p5-nested-boxes/2299#2299) of parsing and building the boxes at once was implemented. [Answer] ## C# - 472 470 426 422 398 characters ``` using System.Linq;using y=System.Console;class W{static void Main(){var c=new int[5];var s=new string[0].ToList();int n=0,i;var l="";do{try{c[n]=int.Parse(l=y.ReadLine());l=".{1}.";n++;i=1;}catch{l+="{0}";i=0;}G:while(i++<n)l="| "+l+" |";s.Add(l);if(n>0&&--c[n-1]<0){n--;l="'{1}'";i=0;goto G;}}while(n>0);s.ForEach(z=>y.WriteLine(z,l="".PadLeft(s.Max(v=>v.Length)-z.Length),l.Replace(' ','-')));}} ``` [Answer] ## Scala - 475 characters ``` object N2 extends App{type S=String;def b(x:List[S],t:Int,s:S,e:S):List[S]={var l=x;o=o:+(s+".-±-."+e+"-");for(i<-1 to t)if(l.head.matches("\\d+"))l=b(l.tail,l.head.toInt,s+"| ",e+" |")else{o=o:+(s+"| "+l.head+"±"+e+" | ");l=l.drop(1)};o=o:+(s+"'-±-'"+e+"-");return l};var o:List[S]=List();val l=io.Source.stdin.getLines.toList;b(l.tail,l.head.toInt,"","");(o map(x=>x.replaceAll("±",x.last.toString*((o sortBy((_:S).length)).last.length-x.length)).dropRight(1)))map println} ``` [Answer] ## C# 1198 1156 1142 689 671 634 Characters ``` using z=System.Console;using System.Collections.Generic;using System.Linq; class T{bool U;List<T> a=new List<T>();string m;IEnumerable<string>R(int s){if(U){yield return ".".PadRight(s-1,'-')+".";foreach(var e in a.SelectMany(b=>b.R(s-4)))yield return ("| "+e).PadRight(s-e.Length)+" |";yield return "'".PadRight(s-1,'-')+"'";}else yield return m;}int L(){return U?a.Max(x=>x.L())+4:m.Length;} static void Main(){var p=O(int.Parse(z.ReadLine()));z.WriteLine(string.Join("\r\n",p.R(p.L())));} static T O(int n){var k=new T(){U=true};while(n-->0){var l=z.ReadLine();int c;k.a.Add(int.TryParse(l,out c)?O(c):new T{m=l});}return k;}} ``` [Answer] ## [Pip](http://github.com/dloscutoff/pip), 89 bytes (non-competing) (The language is newer than the challenge. Also, I couldn't quite outgolf APL.) Code is 87 bytes, +2 for `-rn` flags. ``` (z:{I+YPOi{Y{Vz}M,ym:MX#*Y$ALyY'|.s._.sX++m-#_.'|MyY".."J'-X++mALyAL"''"J'-Xm}yALl}i:g) ``` [Try it online!](http://pip.tryitonline.net/#code=KHo6e0krWVBPaXtZe1Z6fU0seW06TVgjKlkkQUx5WSd8LnMuXy5zWCsrbS0jXy4nfE15WSIuLiJKJy1YKyttQUx5QUwiJyciSictWG19eUFMbH1pOmcp&input=MwpGb28KMgpCYXIKQmF6CjIKR2FrCjEKQW5vdGhlciBmb28_&args=LXJu) The function `z` processes the first item of the input list (`g`, copied into global variable `i` so as to be available inside function calls). If this is a number *n*, it calls itself recursively *n* times, pads the resulting list of lines to a full rectangle, wraps each line in `"| " " |"`, and adds `.---.` and `'---'` lines before returning the new list. If it is a string, it simply converts it to a one-item list and returns it. The final result is printed newline-separated (`-n` flag). More detail available on request. [Answer] # Java (1369 chars incl. EOLs) Couldn't leave this without a Java implementation. Java is supposed to be more verbose that the slicks of Python and Ruby, so I went for an elegant, recursive solution. The idea is a Tree (Graph) of objects (strings and boxes), containing one another starting from a "head" box. As you linearly parse the input file you add strings and boxes to the "current" box and while you are adding the maximum length of the container is adjusted. When a container reaches the amount of predefined items that it can hold you backtrack to the previous container. At the end of the input file, you have a "head" container that already has a "maxLength" calculated, so you simply call its print() method. ``` import java.io.*;import java.util.*; public class N{private static String rPad(String s,int l){return s+str(l-s.length(),' ');} private static String str(int l, char c){StringBuffer sb=new StringBuffer();while(l-->0){sb.append(c);}return sb.toString();} private static class Box {Box prnt=null;String txt=null;int items;List<Box> c=new ArrayList<Box>();int maxLength=0; public Box(Box p,int n){prnt=p;items=n;if(p!=null){p.c.add(this);}} public Box(Box p,String s){prnt=p;txt=s;if(p!=null){p.c.add(this);p.notify(s.length());}} public void print(String prefix,int l,String suffix){if (txt == null){System.out.println(prefix+"."+str(l-2,'-')+"."+suffix);for(Box b:c){b.print(prefix+"| ",l-4," |"+suffix);}System.out.println(prefix+"'"+str(l-2,'-')+"'"+suffix);}else{System.out.println(prefix+rPad(txt,l)+suffix);}} protected void notify(int l){if (l+4>this.maxLength){this.maxLength=l + 4;if (this.prnt != null){this.prnt.notify(this.maxLength);}}}} public static void main(String[] args)throws IOException{Box head=null;Box b=null;BufferedReader in=new BufferedReader(new InputStreamReader(System.in));String s;while ((s=in.readLine()) != null){try{int n=Integer.parseInt(s);b=new Box(b, n);}catch (NumberFormatException nfe){b=new Box(b, s);}if(head == null)head=b;while ((b != null) && (b.items == b.c.size())){b=b.prnt;}}head.print("",head.maxLength,"");}} ``` It is really an enjoyable solution to write. I liked the question a lot. As I mentioned earlier, I went for solution elegance not minimalist approach, sadly Java doesn't have Python's print "-"\*4 to produce "----" :-) Here's the ungolfed version: ``` import java.io.*; import java.util.*; public class NestedBoxes { private static String rPad ( String s, int l ) { return s + str(l - s.length(), ' '); } private static String str ( int l, char c ) { StringBuffer sb = new StringBuffer(); while (l-- > 0) { sb.append(c); } return sb.toString(); } private static class Box { Box parent = null; String text = null; int items; List<Box> contents = new ArrayList<Box>(); int maxLength = 0; public Box ( Box p, int n ) { parent = p; items = n; if (p != null) { p.contents.add(this); } } public Box ( Box p, String s ) { parent = p; text = s; if (p != null) { p.contents.add(this); p.notify(s.length()); } } public void print ( String prefix, int l, String suffix ) { if (text == null) { System.out.println(prefix + "." + str(l - 2, '-') + "." + suffix); for (Box b : contents) { b.print(prefix + "| ", l - 4, " |" + suffix); } System.out.println(prefix + "'" + str(l - 2, '-') + "'" + suffix); } else { System.out.println(prefix + rPad(text, l) + suffix); } } protected void notify ( int l ) { if (l + 4 > this.maxLength) { this.maxLength = l + 4; if (this.parent != null) { this.parent.notify(this.maxLength); } } } } public static void main ( String[] args ) throws IOException { Box head = null; Box b = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; while ((s = in.readLine()) != null) { try { int n = Integer.parseInt(s); b = new Box(b, n); } catch (NumberFormatException nfe) { b = new Box(b, s); } if (head == null) { head = b; } while ((b != null) && (b.items == b.contents.size())) { b = b.parent; } } head.print("", head.maxLength, ""); } } ``` ]
[Question] [ ## Background Variable declaration statement in C consists of three parts: the *name* of the variable, its *base type*, and the *type modifier(s)*. There are three kinds of type modifiers: * Pointer `*` (prefix) * Array `[N]` (postfix) * Function `()` (postfix) + You can specify a list of function arguments inside the parens, but for the sake of this challenge, let's ignore it and just use `()` (which technically means "the function can take any kind of arguments"). And a way to read out the notations is as follows: ``` int i; // i is an int float *f; // f is a pointer to a float my_struct_t s[10]; // s is an array of 10 my_struct_t int func(); // func is a function returning an int ``` The catch is that we can mix all of these to form a more complicated type, such as *array of arrays* or *array of function pointers* or *pointer to array of pointers*: ``` int arr[3][4]; // arr is an array of 3 arrays of 4 ints int (*fptrs[10])(); // fptrs is an array of 10 pointers to functions returning an int float *(*p)[16]; // p is a pointer to an array of 16 pointers to float ``` How did I read these complicated statements? 1. Start from the variable name. `(name) is ...` 2. Select the modifier with the highest precedence. 3. Read it: * `[N] -> array of N ...` * `() -> function returning ...` * `* -> pointer to ...` 4. Repeat 2 and 3 until the modifiers are exhausted. 5. Finally, read the base type. `... (base type).` In C, postfix operators take precedence over prefix operators, and type modifiers are no exception. Therefore, `[]` and `()` bind first, then `*`. Anything inside a pair of parens `(...)` (not to be confused with function operator) binds first over anything outside. Illustrated example: ``` int (*fptrs[10])(); fptrs fptrs is ... [10] array of 10 ... // [] takes precedence over * (* ) pointer to ... () function returning ... int int ``` ## Task Given a line of variable declaration statement written in C, output the English expression that describes the line, using the method shown above. ## Input The input is a single C statement that includes a single base type, a single variable name, zero or more type modifiers and the ending semicolon. You have to implement all the syntax elements covered above, plus: * Both the base type and the variable name match the regular expression `[A-Za-z_][A-Za-z0-9_]*`. * Theoretically, your program should support unlimited number of type modifiers. You can simplify other C syntax elements in the following ways (full implementation is also welcome): * The base type is always a single word, e.g. `int`, `float`, `uint32_t`, `myStruct`. Something like `unsigned long long` won't be tested. * For the array notation `[N]`, the number `N` will always be a single positive integer written in base 10. Things like `int a[5+5]`, `int a[SIZE]` or `int a[0x0f]` won't be tested. * For the function notation `()`, no parameters will be specified at all, as pointed out above. * For whitespaces, only the space character `0x20` will be used. You can restrict your program to specific usage of whitespaces, e.g. + Use only one space after the base type + Use a space everywhere between tokens * However, you cannot use two or more consecutive spaces to convey more information than being a token separator. According to C syntax, the following three combinations are invalid, and thus won't be tested: * `f()()` Function returning function * `f()[N]` Function returning array * `a[N]()` Array of N functions C developers use these equivalent forms instead (and all of these are covered in the test cases): * `(*f())()` Function returning *pointer to function* * `*f()` Function returning *pointer to array's first element* * `(*a[N])()` Array of N *pointers to function* ## Output The output is a single English sentence. You don't need to (but you can if you wish) respect English grammar, e.g. the use of `a, an, the`, singular/plural forms, and the ending dot (period). Each word should be separated by one or more whitespaces (space, tab, newline) so the result is human-readable. Again, here is the conversion process: 1. Start from the variable name. `(name) is ...` 2. Select the modifier with the highest precedence. 3. Read it: * `[N] -> array of N ...` * `() -> function returning ...` * `* -> pointer to ...` 4. Repeat 2 and 3 until the modifiers are exhausted. 5. Finally, read the base type. `... (base type).` ## Test cases ``` int i; // i is int float *f; // f is pointer to float my_struct_t s[10]; // s is array of 10 my_struct_t int func(); // func is function returning int int arr[3][4]; // arr is array of 3 array of 4 int int (*fptrs[10])(); // fptrs is array of 10 pointer to function returning int float *(*p)[16]; // p is pointer to array of 16 pointer to float _RANdom_TYPE_123 (**(*_WTH_is_TH15)())[1234][567]; /* _WTH_is_TH15 is pointer to function returning pointer to pointer to array of 1234 array of 567 _RANdom_TYPE_123 */ uint32_t **(*(**(*(***p)[2])())[123])[4][5]; /* p is pointer to pointer to pointer to array of 2 pointer to function returning pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t */ uint32_t (**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5]); // Same as above, just more redundant parens some_type (*(*(*(*(*curried_func())())())())())(); /* curried_func is function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning some_type */ ``` ## Scoring & Winning criterion This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge. The program with the smallest number of bytes wins. [Answer] # [Python 3](https://docs.python.org/3/), ~~331 312 294 261~~ 240 bytes ``` from re import* class V(str):__pos__=lambda s:V(s+'pointer to ');__call__=lambda s:V(s+'function returning ');__getitem__=lambda s,i:V(s+'array of %i '%i) t,e=input().split() print(eval(sub('\*','+',sub('(\w+)',r'V("\1 is ")',e[:-1],1)))+t) ``` [Try it online!](https://tio.run/##ZZBdS8MwFIbv@ysOgiTpqpjVD1jZhReCVyIyFOlKqF2qgbYJyam6Xz9P1gkTaWma5HnenBO3xQ875LvGbjQswTPGdq23PXgNpnfWY5o0XR0CPPOAXiyUcjYotezq/m1TQ1jQ@ow5awbUHtACE4VSTd11/6B2HBo0dqBsHP1ghvcJftdoUPdHfGYmo/a@3oJt4dQAOzUiwUwvzeBG5OI8uM7QmDhPZ3P9WXc8jG@crVOWsRnL9hO@/poJlnn2zE/WEkyAE5rqcnEmq0wKIWYodtR0or91w/e3kIKUYkeZYIqk7WyNkLZF0m8VXcDYoEIIpbyoiiQysSkupn8qt8yr8vKwxdPWod@zIiKHLJ46UcprgtTT7cPG9mr1@nin5Dwng3bVy@pemaBW9/KKPGLn@WVVXl3fkDJScD6nEiLJD58YOK9@2UqUET@GIzjhceB7z1Hz0YrakSjIpFqD7bXCrdPA09@nGb03eqOmlsXft/gB "Python 3 – Try It Online") *-19 bytes by switching to python 2 and putting the class definition into an `exec`* *-18 bytes by changing the regex from `[a-zA-Z_][a-zA-Z0-9_]*` to `\\w+`, thanks to Kevin Cruijssen* *-33 bytes by working some class definition magic and utilising str, thanks to Lynn, changing back to python 3* *-21 bytes by merging together multiple regexes, thanks to infmagic2047* Requires that only one space is contained in the input (between the type and the expression). I think this is a pretty unique approach to the problem. This mostly uses the fact that Python itself can evaluate strings like `(**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5])` and gets the correct sequence of function calls, array indexes and pointers - and that the user can overload these. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~142~~ ~~138~~ ~~128~~ 117 bytes ``` (\w+) (.+); ($2) $1 \(\) function returning \[(\d+)?] array of$#1$* $1 +`\((\**)(.+)\) $2$1 \* pointer to 1` is ``` [Try it online!](https://tio.run/##VY9NS8QwEIbv@RUDVphJQUzrrocexIO4JxFZEElKtuy2EnCbkqbI/vo62Q9YSUhC5nneTEIbXd/Mt/i6mdH85gR4l1MlMCsIMiUMGhLQTf02Ot9DaOMUetd/C6PR7HJ6qgU0ITQH8F12ozKZpHxjEI2UlLLYz4qUJAUM3vWxDRC9UBsQ4EaYZ74CV4nuxzcRZFeJ/cGOMUzbaCOMWt3XlUhMagLpdOYndVnrh3MJZTfEcGQpIecslANptWTIfjy/7fzerr/eX6wqSja4aj/XK@tGu16pBXvMFuVDrRfLR1YmDi4LbiGReF5SYFFf2Jp0wq/hBJ7wtOHRG4iOVtKuRGKTex39vrXxMLSA8jK2Uwiu3dnTl@n/rP4A "Retina 0.8.2 – Try It Online") Link includes test cases. [Better grammar](https://tio.run/##VY9dS8MwFEDf8ysuLMJNCmLabT70Yfgg7klEBiJNSevWSsAlJU0Z@/XzZh@gNKSFe87hNnTRuvZ0hy/NyTaIVdtZP9VipQ9SAN5nomTICwEtn@VcOuCKadSCQQv95LbRegehi1Nw1n0zXaHeZWJV09xBG0J7BN/zmeIymVmjEbWUIoUpwvOUkyk2eOtiFyB6hvorRaiwAtSHjDgFPB@ZaoCBHeF0IhZsyfof30aQfcn2RzPGMG2jiTBW6qEuWWLSiigu37RNVdTV/DpC2Q8xnFmRkGsL5SAqtSTIvD@97vzebD7fno3KCzJoaj42a2NHs1mrBXnE5sW8rhbLR1ImChc5rZBIvF4pmNc3thZVwv/CCbzg6YVnbxDibCXtjyjIpF1Hv@9MPA4doLw92ykE2@3M5ZfF/1P@Ag "Retina 0.8.2 – Try It Online"). Edit: Saved ~~10~~ 21 bytes by porting @DLosc's Pip solution. Explanation: ``` (\w+) (.+); ($2) $1 ``` Move the type to the end and wrap the rest of the declaration in `()`s in case it contains an outer `*`. ``` \(\) function returning ``` Process any functions. ``` \[(\d+)?] array of$#1$* $1 ``` Process any arrays. ``` +`\((\**)(.+)\) $2$1 ``` Move any pointers to the end of their brackets, and delete the brackets, repeatedly working from the outermost set of brackets inwards. ``` \* pointer to ``` Process any pointers. ``` 1` is ``` Insert the `is`. [Answer] # Bash + [cdecl](https://linux.die.net/man/1/cdecl) + GNU sed, 180 `cdecl` is a venerable Unix utility that does most of what is required here, but in order to match I/O requirements, some `sed` pre- and post-processing is required: ``` sed -r 's/^/explain struct /;s/struct (int|char double|float|void) /\1 /;s/\bfunc/_func/g'|cdecl|sed -r 's/^declare //;s/as/is/;s/struct //g;s/([0-9]+) of/of \1/g;s/\b_func/func/g' ``` * No attempts made to correct grammar. ### sed Pre-processing: * `s/^/explain struct /` - Add "explain struct " to the start of *every* line * `s/struct (int|char double|float|void) /\1 /` - Remove `struct` when dealing with C language types * `s/\bfunc/_func/g` - "func" is recognized as a keyword by cdecl - suppress this ### sed Post-processing: * `s/^declare //` - remove "declare" at start of line * `s/as/is/` - self-explanatory * `s/struct //g` - remove all "struct" keywords * `s/([0-9]+) of/of \1/g` - correct ordering of "of " * `s/\b_func/func/g` - revert any "\_func" that was replaced in pre-processing ### In action: ``` $ < cdecls.txt sed -r 's/^/explain struct /;s/struct (int|char double|float|void) /\1 /;s/\bfunc/_func/g'|cdecl|sed -r 's/^declare //;s/as/is/;s/struct //g;s/([0-9]+) of/of \1/g;s/\b_func/func/g' i is int f is pointer to float s is array of 10 my_struct_t func is function returning int arr is array of 3 array of 4 int fptrs is array of 10 pointer to function returning int p is pointer to array of 16 pointer to float _WTH_is_TH15 is pointer to function returning pointer to pointer to array of 1234 array of 567 _RANdom_TYPE_123 p is pointer to pointer to pointer to array of 2 pointer to function returning pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t p is pointer to pointer to pointer to array of 2 pointer to function returning pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t curried_func is function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning pointer to function returning some_type $ ``` [Answer] # [Pip](https://github.com/dloscutoff/pip) `-s`, ~~152~~ ~~150~~ ~~148~~ ~~139~~ ~~137~~ ~~126~~ ~~125~~ ~~123~~ 120 bytes Third approach! ``` YaRs" ("R`\[(\d+)]`` array of \1`R"()"" function returning"L#aYyR`\((\**)(.+)[);]`{c." pointer to"X#b}{[b"is"g@>2a]}Vy^s ``` Takes the declaration as a command-line input. [Try it online!](https://tio.run/##JYuxCoMwFAB/5fG65EUqqO0klH5AJ4dSiWkTrUqWGGIcRPz2VCgHN90542KsdTUjMKxUI1jzTUgqBdp7vcI0QJOpChkhwrDYLpjJgu/D4q2xIz5Oul6Pj7GGc2JpQoJKqbYuRXCTsaH3ECZ8ndp9Ey2aGcf7Lddyf67vOcZ4nuNyVEX@CcA5O/iLOxK5JEYksryQJC5SXGX5Aw "Pip – Try It Online") ## Explanation The code is in three parts: initial setup and handling of functions and arrays; a loop that handles parentheses and pointers; and a final rearrangement. ### Setup, functions & arrays We want the whole declaration to be parenthesized (this helps with the loop later on), so we change `type ...` into `type (...`. Then, observe that no reordering is done with the descriptions of functions and arrays, so we can perform all those replacements first without affecting the final output. ``` Y Yank into y variable... a The result of a (the cmdline arg)... R s Replace the space " (" with " (" R `\[(\d+)]` Replace digits in square brackets ` array of \1` with " array of <digits>" R "()" Replace function parens " function returning" with " function returning" ``` If our original input was `float *((*p()))[16];`, we now have `float (*((*p function returning)) array of 16;`. ### Parentheses and pointers We run a loop replacing the outermost pair of parentheses and any asterisks that are immediately inside the opening paren. ``` L#a Loop len(a) times (enough to complete all replacements): Y Yank into y variable... y The result of y... R `\((\**)(.+)[);]` Replace open paren, 0 or more asterisks (group 1), 1 or more characters (group 2), and close paren or semicolon { with this callback function (b = group 1, c = group 2): c . The stuff in the middle, concatenated to... " pointer to" that string X #b repeated len(asterisks) times } ``` Example steps: ``` float (*((*p function returning)) array of 16; float ((*p function returning)) array of 16 pointer to float (*p function returning) array of 16 pointer to float p function returning pointer to array of 16 pointer to ``` ### Cleanup The only thing remaining is to move the type to the end and add "is": ``` {[b"is"g@>2a]}Vy^s y^s Split y on spaces { }V Use the resulting list as arguments to this function: [ ] Return a list of: b 2nd argument (the variable name) "is" That string g@>2 All arguments after the 2nd a 1st argument (the type) The resulting list is printed, joining on spaces (-s flag) ``` For definitions like `int x;`, this approach will result in an extra space, which is permitted by the challenge. [Answer] # Java 11, ~~469~~ ~~467~~ ~~463~~ 450 bytes ``` s->{String r="",t,S[];for(s=s.replace("()","~");s.contains("(");s=s.replace(t,"").replace("()",""),r+=t+";")t=s.replaceAll(".*(\\([^()]+\\)).*","$1");S=s.split(" ");t=S[0];r+=r.isEmpty()?S[1]:s;S=r.split(";");r=S[0].replaceAll(".*?(\\w+).*","$1 is ");for(var p:S)r+=p.replaceAll("[A-Za-z_]+\\d+|[^\\[\\d]","").replaceAll("\\[(\\d+)","array of $1 ")+(p.contains("~")?"function returning ":"")+"pointer to ".repeat(p.split("\\*").length-1);return r+t;} ``` [Try it online.](https://tio.run/##1VVbb9MwFH7frzAWD3bTRku7DalRqfYwNB6YEJmEIM2ikDgjI02CfTIoY/z1cuwma9q1GhISEupldvyd813szjfRbTS4Sb4s4zxSiryJsuLugJCsACHTKBbkQk8J8UBmxTWJWTNQ3MXn9/jBt4IIsphckIJMyFINXt41KDmhtA99zw/ctJRMTZQtRZVjX0YZp336i3JX2XFZABIrfKjnHRT0KeVbNZT3pTUBi7qUwxp7mueM2j02mzH/ivHAms04t3tY8NzBrh4iVZVnwCjBKUw8/zBwsZG0M3U2r2DB@NTznWCsECtbLHK40mC3eKZI9M1qCUimdFdt8jaSpBp7HFtXGzX@6eBjNPgRamWJ9dO/ms18HAW069EgcYFpjHYbSRktSJkSJKHcYlUnLUxvStO6iCErCyIF1LLQsdMxdrRoVZptJFASqvuLCLC8MTab9ZA1F8U1fB44aNJUE2mBe790D3BXq/pTjrvabO5tmSVkjrzNCfADEvHV2QChsCFykcxFxZkOA2fUHJF2Oc3LCEgv1YhUIzrqzNomfL4IFcg6hhCI8h3cKqxTuu4hEOeQdFCb5VqMDoZxw4cjXbojqkc6dSVS@KPAPzKkONmgHa2HR7vLWS@tQBrVvBGg59viuwH8gbAmQNaruO@cGGnVVo7r7idPxBu@O71Iynl4@eHtWegMR6gZO4fvL8/DTIWX584xKkee4ego8I9PXhi67vL2Dj420FndKRFbr2dIQbY1bSquscVoiKdBC2XNl85iGLRSA@5rtTujeULN8K/N7HzedbinR@trj1vtdOVX/2HGeMW5sa19d5xztK5PG/nfzatyLkJYVIKwXvuKaykzkYSrHzXffOsN7wL2/Nb/2OU/XX1wS5srdX2hmv@5JpPmPs2KqoZ@exmL75WIQSR844qWQtU54EVc2DEzBU243kKBmNtlDXaFSMgLRl/r9bFepdZT2LOGbozYB@r98NMY6igfm9YrTfvBbTtbfMUaxRr8lHp1HAuRiOQZ3mmvoizXo/19mgTvl78B) **Explanation:** ``` s->{ // Method with String as both parameter and return-type String r="", // Result-String, starting empty t, // Temp-String, starting uninitialized S[]; // Temp String-array, starting uninitialized for(s=s.replace("()","~"); // Replace all "()" in the input `s` with "~" s.contains("("); // Loop as long as the input `s` still contains "(" ; // After every iteration: s=s.replace(t,"") // Remove `t` from `s` .replace("()",""), // And also remove any redundant parenthesis groups r+=t+";") // Append `t` and a semi-colon to the result-String t=s.replaceAll(".*(\\([^()]+\\)).*","$1"); // Set `t` to the inner-most group within parenthesis S=s.split(" "); // After the loop, split the remainder of `s` on the space t=S[0]; // Set `t` to the first item (the type) r+= // Append the result-String with: r.isEmpty()? // If the result-String is empty // (so there were no parenthesis groups) S[1] // Set the result-String to the second item : // Else: s; // Simple append the remainder of `s` S=r.split(";"); // Then split `r` on semi-colons r=S[0].replaceAll(".*?(\\w+).*", // Extract the variable name from the first item "$1 is "); // And set `r` to this name appended with " is " for(var p:S) // Loop over the parts split by semi-colons: r+= // Append the result-String with: p.replaceAll("[A-Za-z_]+\\d+ // First remove the variable name (may contain digits) |[^\\[\\d]","") // And then keep only digits and "[" .replaceAll("\\[(\\d+)", // Extract the number after "[" "array of $1 ") // And append the result-String with "array of " and this nr +(p.contains("~")? // If the part contains "~" "function returning " // Append the result-String with "function returning " : // Else: "") // Leave the result-String the same +"pointer to ".repeat( // And append "pointer to " repeated p.split("\\*").length-1); // the amount of "*" in the part amount of time return r // Then return the result-String +t;} // appended with the temp-String (type) ``` [Answer] # JavaScript (ES6), ~~316~~ ... ~~268~~ 253 bytes ``` s=>(g=s=>[/\d+(?=])/,/\*/,/!/,/.+ /,/\w+/].some((r,i)=>(S=s.replace(r,s=>(O=[O+`array of ${s} `,O+'pointer to ','function returning '+O,O+s,s+' is '+O][i],'')))!=s)?g(S):'',F=s=>(O='',S=s.replace(/\(([^()]*)\)/,g))!=s?O+F(S):g(s)+O)(s.split`()`.join`!`) ``` [Try it online!](https://tio.run/##vZRdj5pAFIbv/RWzmybMAIX1Y23ShppedLNXpakmTYMUKA4GowyZGXZjmv52e45fILp2r6qCMMx5z/O@DCySp0SlMi/120LM@CbzNsr7SOce7AN3OrPoyAuZa7tTE3Y3sDkWwdNnyw0dJVacUmnnDGrGnnIkL5dJymEIVXwv8K04kTJZE5GRN7/VHxLbvmWUIi80l0QLYthGVhWpzkVBJNeVLPJiTgzLh3nKVpZBcoWnYZCHtmEwxm48xUZzOmbvDcN@8HaN4LDZ351SGvykLDTZFOjn26qRbz1g2ZwqZvmMKkeVy1zHlMXOAojim5htUlEoseTOUsxpRm@Bk@QfbhkjJx/XJTmCweVOqyJbikQTM2sVQUWGFQ3r25nt8tU6UlpWqY40UUH3LtzpQLnC8mOY3TvSmNq5gI2xUnaCgRAwikIXQr9gBnWgZdAPg0FYS4EOjJ7w9OvDwUtK1MxKLbeu2J4MiXCs7a0Z06tI97FTs2RBd3hkBf2yFXvdZnh@N9qy0bdPX2ZiFU1@fP0cdXt98AA9ou@TxyhX0eSxew9OoGOvPwiD@@G7beOOa5LmlPZ9PzfUuHqBtANGsEONDp3IGZrpnuFXoNXvwVJCarrfYUS98MAdsgDRj@DtuK6jkd51Z4j@DwVEvzTetNuY0FKsHV5xj853/vGPboMo4VWCMWAOjSQYRMF2WbhknKw4SWBl/hJP3CaLSmmyEpKDv1lVzBJY02UieaHOWuObMdLrkhNqHr5pJWXOZ9HuwWSnv0P8zUkvPKevXUqY1P8ur32b7uYv "JavaScript (Node.js) – Try It Online") ## Commented ### Helper function ``` g = s => // s = expression to parse [ // look for the following patterns in s: /\d+(?=])/, // array /\*/, // pointer /!/, // function /.+ /, // type /\w+/ // variable name ].some((r, i) => // for each pattern r at index i: ( S = s.replace( // S = new string obtained by removing r, // the pattern matching r from s s => ( // using the first match s and the index i, O = [ // update the output O: O + `array of ${s} `, // array O + 'pointer to ', // pointer 'function returning ' + O, // function O + s, // type s + ' is ' + O // variable name ][i], // '' // replace the match with an empty string ))) // end of replace() != s // make some() succeed if S is not equal to s ) ? // end of some(); if truthy: g(S) // do a recursive call with S : // else: '' // stop recursion and return an empty string ``` ### Main part ``` s => ( // s = input g = …, // define the helper function g (see above) F = s => ( // F = recursive function, taking a string s O = '', // O = iteration output, initialized to an empty string S = s.replace( // S = new string obtained by removing the next expression from s /\(([^()]*)\)/, // look for the deepest expression within parentheses g // and process it with the helper function g ) // end of replace() ) != s ? // if S is not equal to s: O + F(S) // append O to the final output and do a recursive call with S : // else (we didn't find an expression within parentheses): g(s) + O // process the remaining expression with g and return O )(s.split`()`.join`!`) // initial call to F with all strings '()' in s replaced with '!' ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~209~~ ~~190~~ ~~171~~ ~~162~~ 153 bytes ``` {~({(.[1]Z'is'),.<e>.&?BLOCK,('array of'X .[2]),('function returning','pointer to'Zxx.[3,0])if $_}(m:g/(\*)*[(\w+)+|\(<e=~~>.][\[(\d+).]*(\(.)*/[1]),$0)} ``` [Try it online!](https://tio.run/##XZBta8IwEIC/@yvyQUyulmpbdbCqYxsDYWMbQ9hmGoJoIwX7Qpoyi9O/3qWt7o2EhDue5@6SNJDbURkVqCPQpNwfyZ5Y1GYLHGYYTGscTK3O1c3D0@29SfBSymWBEoHfkEUdBjol8nilwiRGMlC5jMN4g02cJmGsAolUghe7nUVds88gFKjNDyS63PSIb4BBif/Rhe6nT8bB5HicWoz6OrfugsUM4hMLjJ6eBMx2Hw6l18p0a0HaHJBIZAvrDij0sNnCYpssFTJEHUQFz5TMV4orlFG7z@psBVeTEvgO9Vuoy@jgByCGSJWsJTiBp9LESIHaowblL9eP6yTi8/fnO247rvY0wF/nMx5mfD6zh9rWuOMOGB2OLhor1x1cRw9VweR0VGUddsYZ0Mr4x1dsY1QXqdUUoBYr85cLWm7mzpIo4KpIA0SM81rlUobBmjf/AH@3h73yCw "Perl 6 – Try It Online") Recursive regex approach. Produces some extra space characters which can be avoided [at the cost of 3 bytes](https://tio.run/##XZBra8IwFIa/@yvyQUxOLdW26mBVxzYGwsY2hrDNNATRRgr2Qpoyi9O/3qWt7kZCQg7Pk/MmaSC3ozIqUEegSbk/iu1SoT2xqM0WOMwwmNY4mFqdq5uHp9t7k@CllMsCJQK/IYs6DHRJ5PFKhUmMZKByGYfxBps4TcJYBRKpBC92O4u6Zp9BKFCbH0h0uekR3wCDEv@jC91Pn4yDyfE4tRj1dW3dBYsZxCcWGD2dBMx2/1B6rUx3FqTNAYlEtrBugEIPmy0stomObYj6EBU8UzJfKa5QRu0@q6sVXAUl8H3UT6Euo4MfgBgiVbKW4ASeriZGCtQeNSh/uX5cJxGfvz/fcdtxtacB/jqf8TDj85k91LbGHXfA6HB00Vi57uA6OlQFk9NSXeuwM86AVsY/vmIbo9pIraYAtViZv1zQcpM7S6KAqyINEDHOY5VLGQZr3vwD/J0e9sov). ### Explanation ``` { # Anonymous block ~( # Convert list to string { # Block converting a regex match to a nested list (.[1] # Array of 0 or 1 variable names Z'is'), # zipped with string "is" .<e>.&?BLOCK, # Recursive call to block with subexpression ('array of' # String "array of" X .[2]), # prepended to each array size ('function returning', # Strings "function returning" 'pointer to' # and "pointer to" Zxx # zipped repetition with .[3,0]) # number of function and pointer matches if $_ # Only if there's an argument } ( # Call block m:g/ # Input matched against regex (\*)* # Sequence of asterisks, stored in [0] [ # Either (\w+)+ # the variable name, stored as 1-element array in [1] | # or \( # literal ( <e=~~> # the same regex matched recursively, stored in <e> . # ) ] [\[(\d+).]* # Sequence of "[n]" with sizes stored in [2] (\(.)* # Sequence of "()" stored in [3] / [1] # Second match ), $0 # First match (base type) ) } ``` [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), 415 bytes ``` import StdEnv,Text $s#(b,[_:d])=span((<>)' ')(init s) =join" "(?d++[""<+b]) ?[]=[] ?['()':s]=["function returning": ?s] ?['*':s]= ?s++["pointer to"] ?['[':s]#(n,[_:t])=span((<>)']')s =["array of "<+n: ?t] ?s=case@0s of(['(':h],t)= ?(init h)++ ?t;(h,t)|t>[]= ?h++ ?t=[h<+" is"] ~c=app2((++)[c],id) @n[c:s]=case c of'('= ~c(@(n+1)s);')'|n>1= ~c(@(n-1)s)=([c],s);_|n>0= ~c(@n s)=span(\c=c<>'('&&c<>'[')[c:s] @_ e=(e,e) ``` [Try it online!](https://tio.run/##bZHtatswFIZ/x1ch3FJLcQp10naQxEkGK3QwRlkDY6hCqLLcaMSykeRtgdJLX3bkNE0Dw8bifDzve3wk10qYbVUX7VqhSmiz1VVTW4/ufXFjfg2W6o@PTt0JfhxQPi4YyV0jDMbTGUlQQrA22iNHovxnrU2MYjwv0pTG8TR9ZCSaU5ZTBkeCSTJ2EMRla6TXtUFW@dYabZ7iMZq7rqnf9UAUJBoQ9MoiX8ddkYbiCTZhDn80B0uIi0BaWCs2qC4RuBsQ9cC5XAqnFhcO8hjGSMYrNvAETHajr0iaQucEryD77Gc0@K@6XE5X0zRG2oH/i8xF0wwxTlNCJRvogkQLQ2WYNxggCfqgnqMXiRfYpBlxZJKQ5NnMsn3yPCRzHHgocihd7EoGNrj7nweZy@kMhM7OwkkT0nlEC45UjtVAke29F3A9OeoW/mBiXIkGnSKvnId7@L1SVkW9LoImGvV6NIFFIj1J2KCLynUtPOqXb4lqw523rfQcrpJmF@ytEsBwYZgcpWDRdMTo5XEj7peNt50AeQe82uF@Q2h2fUD4t49fi7riyx93NzwbjoCHJv59ecu148vb7ApUABmOLhm9uv5wIFtwGw1h2ADg10@QH7I9wggN1H@Y0L@jwoE7vCGkgwP9jicgcPgPV1eK@02jEO7vH9laq1XBdzsixy@QALLtX1muxZPbnn/@sv20MaLSchfcrYUva1v9Aw "Clean – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~225~~ 218 bytes ``` g=gsub "&"="@"=paste "["=function(a,b)a&"array of"&b "+"=function(a)a&"pointer to" eval(parse(t=g('\\(\\)','@"function returning"',g('(\\w+) (.*?)([A-Za-z_]\\w*)(.*);','\\2"\\3 is"\\4&"\\1"',g('\\*','+',readline()))))) ``` [Try it online!](https://tio.run/##VZBRa9swEMff/SmEBrHOScpsp92DZ9o@FPowxiiBsVlGqI4cBIlkJLkjG/vs6clJus4ykrj/73@6O3fsyecl6UfTBW0N80D@EKfkZqeNIvU/ATz58LAfdzJosyW9dSQoP907a16U0cp06ritt358TuiM1vSO1oP0QSW0ofVbHrl4Bjmj0jl5ILanM6Tn7/WoDlaboPAJSxP1IndskM4rFuotSzlnnEO6SO/oxYQFh9EZLIamC0QQ@DUHwq6yW2DN/fKnXP4WLQYzwBhUaOa8oJyXRHs8VjPc8pOX8wzlebq4DIHB9B3/JrFhjzOJyhdUPIMKB8FinGgzDcRDJwPrpxjgMyaFBHshukr6nZWBZH2V7A/CBzd2QQTim/xjW01MbAdTTnecT1O2zeossawfgptYiMg5F8sGaPIbhMTT/deN3Yv1j28PIi9KdKAqvq8fhfZi/Zhfow/Zoly1zfXNJ7SMmLgssIRIsvMWExbthW2hifh7OIInPB5s8g04n@iCaVZvRkAn1urtXolwGBRh2WV1o3NabcSpZfj/r46v "R – Try It Online") Full program, wrapped in a function on TIO for convenient testing of all test cases at once. First, we use Regex to convert the input of the form `type ...name...;` to `..."name is"..."type"`. Function notation `()` is then converted to text with a high-precedence concatenation operator. Unfortunately, we also have to replace `*` with `+` as the former is not acceptable as an unary operator. The rest is done by R's `eval` with overloaded operators. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~192~~ 190 bytes Saved 2 bytes thanks to [@Razetime](https://codegolf.stackexchange.com/users/80214/razetime) ``` '(\w+) is(.+);'⎕R'\2 \1'((('\*',z)⎕R'\1 pointer to'((∊'\('z'\)')(z,'\[(\d+)\]')('\(\)',⍨z←'([A-Za-z0-9_ ]+)')⎕R'\1' '(\1 array of \2)' '(\1 function returning)'))⍣≡'(\w+)(?!\]|\w)'⎕R'\1 is') ``` [Try it online!](https://tio.run/##VY/PSsNAEMbvPsV6mpmkEZPaivQgPQg9iZSCaHZZQpOUhTYb8ofS4FlUqHjxAcSLz5UXqVObHmSXhf3m@30zE@VLL95ES7vY7dL2@QNQrl0SpsQzl0bQvn9OQQZC@oCIIB3oNXQQfZFbk1VJISrLxfblDSRCA5KAsOmBDFHGLknFX66w3Gu3P81fj3DsPUZec@5daaFcBrpIENzfF1FRRBthUyED6qS0zuaVsZkokqouMpMtmKJ2@92@fh1mxutTqZ7kmuA4nymBeCsB6dJGlXDQySn0h2oEJyzq6fg2tis9e7i70X7QF@iwQ9/PJtqUejbxB4TE/qB/ocLB8LLDat65H2iOYzd2zz44UEe/onCPdEBpV4muNnki0DmeeV0UJon1fiuG/t8R/AI "APL (Dyalog Unicode) – Try It Online") This came out longer than I thought. I may have to go back to using parser combinators instead of just plain regex again. `z` matches an English phrase such as "foo is pointer to". The parentheses allow the capturing group to be used later. The main train first adds " is" to such phrases, so `int (*p[3])()` becomes `int is(*p is[3])()`. The negative lookahead `(?!\]|\w)` is used to avoid matching array dimensions. Then `⍣≡` keeps applying the substitutions to the left of it until there is nothing left to replace. First, parentheses around phrases are removed, `z[d]` is replaced with `(z array of d)`, and `z()` is replaced with `(z function returning)`. The parentheses are necessary in case there are multidimensional arrays - we don't want `*z` to be replaced before we come back to the rest of the dimensions. Then `*z` is replaced with `z pointer to`. So `int is(*p is[3])()` becomes `int is(*(p is array of 3))()` -> `int is(p is array of 3 pointer to)()` -> `int isp is array of 3 pointer to function returning`. The last part matches the pattern `TYPE isFIRST_PART;` and rearranges it to become `FIRST_PART TYPE`. [Answer] # [Red](http://www.red-lang.org), 418 410 bytes ``` func[s][n: t:""a: charset[#"a"-#"z"#"A"-#"Z"#"0"-#"9""_"]parse s[remove[copy x thru" "(t: x)]to a change[copy x[any a](n: x)]"#"]b: copy[]until[c: next find s"#"switch c/1[#"("[append b"function returning"take/part c 2]#"["[parse c[remove[skip copy d to"]"(append b reduce["array of"d])skip]]]#")"#";"[take c c: back back c while[#"*"= c/1][take c c: back c append b"pointer to"]take c]]s =""]reduce[n"is"b t]] ``` [Try it online!](https://tio.run/##bVFfa9swEH/3pzguL3ZgtEnajjr0oQ@DPo1RAmMTh1FkuRFJZCHJa7Ivn53seCRbsdAdp98/yV7Xp1ddC8qa8tR0VolAwpYQS0RZgtpIH3QUE5T4aYK/cYLPqfnJzW1qHhErJJdQEITX@/aXFqp1RzhA3PgOAfNYwqGg2ILMWM@@jQAh7REk5bY/Z0VasyMfCepsNDuhSrD6EKExtobAgPBuotqAuplxohyFdE7bOltjSh5Na8Hr2Hlr7BtGudU3HCyCgjlNUKAYYqoxZtga1/tBDbFFwnzQg3Xmdd0pLVB6L4/QNlhTkeBErFRwkiWKZMDaHHIt1XbYFLxvzE5zuik@pZx0hmUjTMFogq41Nmrfew8oogBPiHS2t2gCriESnZxnLDSAqZglZn8Hza6VEabN5Wx/rEL0nYpV5L8yu6XLw77we@XFv1O@rViQuPsPnk8bF32vVFzTzu751BVi9nBFrF6fv9btvlr9@Palms0XrMK46vvqpTKhWr3M7lmLWfPFHYn7h89X5I7rYs7xEyc/b8lkTiOLCpGIH9MSZSCmkvcKrih6fhK4kChY4@pOod3rKh6dhnw6fqrz3ui6Gh6uuF5LPP0B "Red – Try It Online") ## Explanation: ``` f: func [ s ] [ n: t: 0 ; n is the name, t is the type a: charset [ #"a"-#"z" #"A"-#"Z" #"0"-#"9" "_" ]; characters set for parsing parse s[ ; parse the input with the following rules remove [ copy x thru " " ](t: x) ; find the type, save it to t and remove it from the string to a ; skip to the next alphanumerical symbol change [ copy n [ any a ] (n: x) ] "#" ; save it to n and replace it with '#' ] b: copy [ ] ; block for the modifiers until [ ; repeat c: next find s "#" ; find the place of the name switch c/1 [ ; and check what is the next symbol #"(" [ append b "function returning" ; if it's a '('- it's a function - add the modifier take/part c 2 ; and drop the "()" ] #"[" [ parse c [ ; '[' - an array remove [ skip copy d to "]" ; save the number (append b reduce [ ; and add the modifier "array of" d ] ) skip ] ; and remove it from the string ] ] #")" ; a closing bracket #";" [ take c ; or ';' - drop it c: back back c ; go to the left while [ #"*" = c/1 ] ; and while there are '*' [ take c ; drop them c: back c ; go to the left append b "pointer to" ; add the modifier ] take c ; drop '(' (or space) ] ] s = "" ; until the string is exhausted ] reduce [ n "is" b t ] ; display the resul ] ``` [Answer] # JavaScript 250 Bytes [249?] This uses 250 Bytes: ``` k=>(a=k.match(/\W|\w+/g),s=[v=j=r=""],f=y=>!j&!a[i+1]||(m=a[i],v?(r+=v=m=='['?`array of ${a[i+=3,i-2]} `:m<')'?(i+=2,"function returning "):s[j-1]=='*'?j--&&"pointer to ":""):m==')'?v=j--|i++:m<'+'?s[j++]=a[i++]:r+=a[v=i++]+" is ",f(),r+a[0]),f(i=2)) ``` Explanation: Basically, it's reading from a buffer `a`, which is the tokenized input. It continuously moves tokens from the buffer `a` to a stack `s`, until evaluation mode is triggered. Evaluation mode will consume postfix operations first `()`, `[]` from the buffer, and then it will consume the prefix operator `*` from the stack. Evaluation mode is triggered when the state is where a word would be (Either the typename is found and consumed, or an ending `)` is found and removed). Evaluation mode is deactivated when no more prefix/postfix operators are found. ``` k=>( // k is input a=k.match(/\W|\w+/g), // split by symbol or word s=[v=j=r=""], // j=0, v=false, r="", s=[] // s is the stack, r is the return string, // v is true if we're in evaluation mode (Consume (), [], *) // v is false if we're waiting to see a ) or token, which triggers evaluation // j is the index of the top of the stack (Stack pointer) f=y=>!j&!a[i+1]||( // !j means stack is empty, !a[i+1] means we're at the ; m=a[i], // Save a[i] in a variable v // Are we evaluating? ?( r+=v= m=='[' // Array ?`array of ${a[i+=3,i-2]} ` // Skip three tokens: "[", "10", "]" // a[i-2] is the "10" :m<')' // m == '(' ?(i+=2,"function returning ") // Skip two tokens: "(", ")" :s[j-1]=='*' // Stack has a pointer ?j--&&"pointer to " // Pop the stack :"" // Set v to be false, r+="" ) :m==')' ?v=j--|i++ // Pop the '(', skip over the ')', v = Evaluation mode :m<'+' // m == '*' || m == '(' ?s[j++]=a[i++] // push(s, pop(a)) :r+=a[v=i++]+" is " // Otherwise we have the token , f(), r+a[0] // Recurse f(), and return r+a[0]. a[0] is the type. ), f(i=2) // Set i=2, and call f(), which returns the final value r + type // a = ["type", " ", ...], so i=2 give the first real token // This soln assumes there is only one space, which is an allowed assumption ) ``` # NOTE If I understand "Use a space everywhere between tokens" correctly: ``` k=>(a=k.split(" "),s=[v=j=r=""],f=y=>!j&!a[i+1]||(v?(r+=v=a[i]=='['?`array of ${a[i+=3,i-2]} `:a[i]<')'?(i+=2,"function returning "):s[j-1]=='*'?j--&&"pointer to ":""):a[i]==')'?v=j--|i++:a[i]<'+'?s[j++]=a[i++]:r+=a[v=i++]+" is ",f(),r+a[0]),f(i=1)) ``` is technically valid, and uses # 249 Bytes Assuming that there's a space between every token. [Answer] # APL(NARS), chars 625, bytes 1250 ``` CH←⎕D,⎕A,⎕a,'_'⋄tkn←nm←∆←''⋄in←⍬⋄⍙←lmt←lin←0 eb←{∊(1(0 1 0)(0 1)(1 0))[⍺⍺¨⍵]} tb←{x←({⍵='[':3⋄⍵=']':4⋄⍵∊CH,' ':1⋄2}eb⍵)\⍵⋄(x≠' ')⊂x} gt tkn←''⋄→0×⍳⍙>lin⋄tkn←∊⍙⊃in⋄⍙+←1⋄→0×⍳(⍙>lin)∨'('≠↑tkn⋄→0×⍳')'≠↑⍙⊃in⋄tkn←tkn,⍙⊃in⋄⍙+←1 r←dcl;n n←0 B: gt⋄→D×⍳'*'≠↑tkn⋄n+←1⋄→B×⍳tkn≢'' D: r←ddcl⋄∆←∆,∊n⍴⊂'pointer to ' r←ddcl;q r←¯1⋄→0×⍳0>lmt-←1 →A×⍳∼'('=↑tkn⋄q←dcl⋄→F×⍳')'=↑tkn⋄→0 A: →B×⍳∼(↑tkn)∊CH⋄nm←tkn⋄→F B: r←¯2⋄→0 F: gt⋄→G×⍳∼tkn≡'()'⋄∆←∆,'function that return '⋄→F G: →Z×⍳∼'['=↑tkn⋄∆←∆,'array of ',{''≡p←(¯1↓1↓tkn):''⋄p,' '}⋄→F Z: r←0 r←f w;q nm←∆←''⋄in←tb w⋄⍙←1⋄lin←↑⍴in⋄lmt←150⋄gt⋄→A×⍳∼0>q←dcl⋄r←⍕q⋄→0 A: r←nm,' is a ',∆,1⊃in ``` this is just one traslation from C language to APL from code in the book: "Linguaggio C" by Brian W. Kerninghan and Dennis M. Ritchie chapter 5.12. I don't know how reduce all that because i had not understood 100% that code, and because I do not know too much on APL... The function for exercise it is f; i think are only allowed 150 nested parentesis '(' ')' for error return one strign with one negative value in that or the string descrition if all is ok. It seems this is not better than the other version even if less chars because the other sees the errors better. Some test: ``` f 'int f()()' f is a function that return function that return int f 'int a[]()' a is a array of function that return int f 'int f()[]' f is a function that return array of int f 'int i;' i is a int f 'float *f;' f is a pointer to float f 'my_struct_t s[10];' s is a array of 10 my_struct_t f 'int func();' func is a function that return int f 'int arr[3][4];' arr is a array of 3 array of 4 int f 'int (*fptrs[10])();' fptrs is a array of 10 pointer to function that return int f 'float *(*p)[16]; ' p is a pointer to array of 16 pointer to float f '_RANdom_TYPE_123 (**(*_WTH_is_TH15)())[1234][567];' _WTH_is_TH15 is a pointer to function that return pointer to pointe r to array of 1234 array of 567 _RANdom_TYPE_123 f 'uint32_t (**((*(**(((*(((**(*p)))[2]))())))[123])[4])[5]);' p is a pointer to pointer to pointer to array of 2 pointer to funct ion that return pointer to pointer to array of 123 pointer to array of 4 array of 5 pointer to pointer to uint32_t ``` ]
[Question] [ Countries own a series of territories on a 1D world. Each country is uniquely identified by a number. Ownership of the territories can be represented by a list as follows: ``` 1 1 2 2 1 3 3 2 4 ``` We define a country's edgemost territories as the two territories closest to either edge. If the above list was zero indexed, country `1`'s edgemost territories occur at position `0` and `4`. A country *surrounds* another if the sublist between its two edgemost territories contains all the territories of another country. In the above example, the sublist between country `2`'s edgemost territories is: ``` 2 2 1 3 3 2 ``` And we see that all the territories of country `3` are between the edgemost territories of country `2`, so country `2` surrounds country `3`. A country with only one element will never surround another. ## Challenge Take a list of integers as input (in any format) and output a *truthy* value if any country is surrounded by another, and a *falsy* value otherwise. You can assume that the input list is nonempty, only contains positive integers, and does not 'skip' any numbers: for example, `1 2 1 5` would be invalid input. ## Test Cases ``` +----------------------+--------+ | Input | Output | +----------------------+--------+ | 1 | False | | 2 1 3 2 | True | | 2 1 2 1 2 | True | | 1 2 3 1 2 3 | False | | 1 3 1 2 2 3 2 3 | True | | 1 2 2 1 3 2 3 3 4 | False | | 1 2 3 4 5 6 7 8 9 10 | False | +----------------------+--------+ ``` [Answer] ## Pyth, 7 bytes ``` n{Q_{_Q ``` [Run the code on test cases.](https://pyth.herokuapp.com/?code=n%7BQ_%7B_Q&input=%5B2%2C1%2C3%2C2%5D%0A%5B1%2C2%2C3%2C1%2C2%2C3%5D%0A%5B1%2C%203%2C%201%2C%202%2C%202%2C%203%2C%202%2C%203%5D%0A%5B1%2C%202%2C%202%2C%201%2C%203%2C%202%2C%203%2C%203%2C%204%5D%0A%5B2%2C1%2C2%2C1%2C2%5D&test_suite=1&test_suite_input=%5B1%5D%0A%5B2%2C1%2C3%2C2%5D%0A%5B2%2C1%2C2%2C1%2C2%5D%0A%5B1%2C2%2C3%2C1%2C2%2C3%5D%0A%5B1%2C%203%2C%201%2C%202%2C%202%2C%203%2C%202%2C%203%5D%0A%5B1%2C%202%2C%202%2C%201%2C%203%2C%202%2C%203%2C%203%2C%204%5D%0A%5B1%2C%202%2C%203%2C%204%2C%205%2C%206%2C%207%2C%208%2C%209%2C%2010%5D&debug=1) ``` n Check whether the following are not equal: {Q The unique elements in order of first appearance _{_Q The unique elements in order of last appearance (done by reversing, taking unique elts, then reversing again) ``` The only way to avoid surrounding is for the countries' leftmost territories to be sorted in the same order as their rightmost territories. If two countries are swapped in this order, one has a territory both further left and further right than the other, and so surrounds it. To obtain the unique countries in order of leftmost territory, we simply deduplicate, which preserves this order. The same is done for the rightmost territory by reversing, deduplicating, then reversing again. If these give different results, then a country is surrounded. [Answer] ## [Retina](https://github.com/mbuettner/retina), ~~61~~ 60 bytes Much longer than I would like... ``` (\b(\d+)\b.* (?!\2 )(\d+) .*\b\2\b)(?!.* \3\b)(?<!\b\3 .*\1) ``` Prints the number of countries that surround at least one other country. [Try it online.](http://retina.tryitonline.net/#code=KFxiKFxkKylcYi4qICg_IVwyICkoXGQrKSAuKlxiXDJcYikoPyEuKiBcM1xiKSg_PCFcYlwzIC4qXDEp&input=MSAgICAgICAgICAgICAgICAgICAgfCBGYWxzZSAgfAoyIDEgMyAyICAgICAgICAgICAgICB8IFRydWUgICB8CjIgMSAyIDEgMiAgICAgICAgICAgIHwgVHJ1ZSAgIHwKMSAyIDMgMSAyIDMgICAgICAgICAgfCBGYWxzZSAgfAoxIDMgMSAyIDIgMyAyIDMgICAgICB8IFRydWUgICB8CjEgMiAyIDEgMyAyIDMgMyA0ICAgIHwgRmFsc2UgIHwKMSAyIDMgNCA1IDYgNyA4IDkgMTAgfCBGYWxzZSAgfA) It's a very straightforward implementation of the spec: we look for the pattern `A...B...A` such that `B` appears neither before or after the match. [Answer] ## Python, 64 bytes ``` lambda l,S=sorted:S(l,key=l.index)!=S(l,key=l[::-1].index)[::-1] ``` The only way to avoid surrounding is for the countries' leftmost territories to be sorted in the same order as their rightmost territories. If two countries are swapped in this order, one has a territory both further left and further right than the other, and so surrounds it. The function checks that sorting the territories by leftmost appearance and rightmost appearance gives the same results. Unfortunately, Python lists don't have `rindex` analogous to `rfind`, so we reverse the list, then reverse the sorted output. Same length (64) with an auxiliary function: ``` g=lambda l:sorted(l,key=l.index) lambda l:g(l)[::-1]!=g(l[::-1]) ``` [Answer] # C#, 113 bytes ``` public bool V(int[] n){var u1=n.Distinct();var u2=n.Reverse().Distinct().Reverse();return !u1.SequenceEqual(u2);} ``` Ungolfed: ``` public bool ContainsSurroundedCountry(int[] numbers) { int[] uniqueLeftmost = numbers.Distinct().ToArray(); int[] uniqueRightmost = numbers.Reverse().Distinct().Reverse().ToArray(); return !uniqueLeftmost.SequenceEqual(uniqueRightmost); } ``` Using a concise `LINQ` approach. [Answer] ## CJam (14 13 bytes) ``` {__&\W%_&W%#} ``` [Online demo](http://cjam.aditsu.net/#code=%7B__%26%5CW%25_%26W%25%23%7D%0A%0A%5B%5B1%5D%0A%20%5B2%201%203%202%5D%0A%20%5B2%201%202%201%202%5D%0A%20%5B1%202%203%201%202%203%5D%0A%20%5B1%203%201%202%202%203%202%203%5D%0A%20%5B1%202%202%201%203%202%203%203%204%5D%0A%20%5B1%202%203%204%205%206%207%208%209%2010%5D%5D%25%60&input=%0A) Thanks to [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%c3%bcttner) for a one-char saving. [Answer] # Japt, 12 bytes ``` Uâ ¬¦Uw â ¬w ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VeIgrKZVdyDiIKx3&input=WzEgMyAxIDIgMiAzIDMgM10=) Thanks to @xnor for figuring out the algorithm. Input array is automatically stored in `U`, `â` is uniqify, `w` is reverse, and `¦` is `!=`. `¬` joins with the empty string (`[1,2,3] => "123"`); this is necessary because JavaScript's comparsion counts two arrays as not equal unless they are the same object. For example (JS code, not Japt): ``` var a = [1], b = [1]; alert(a==b); // false var a = [1], b = a; alert(a==b); // true ``` If this was not the case, we could remove two bytes by simply not joining each array: ``` Uâ ¦Uw â w ``` [Answer] ## ES6, ~~76~~ ~~75~~ ~~65~~ 64 bytes ``` a=>(f=r=>a.filter((x,i)=>a.indexOf(x,r&&i+1)==(r|i))+a)()!=f(-1) ``` Straightforward port of @xnor's answers. Edit: Saved 1 byte by replacing `a.lastIndexOf(x)==i` with `a.indexOf(x,i+1)<0`. Edit: Saved 10 bytes thanks to @user81655. Edit: Saved 1 byte by replacing `r||i` with `r|i`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÙIÚÊ ``` [Try it online](https://tio.run/##MzBNTDJM/f//8EzPw7MOd/3/H22oY6xjqGMEhMYgHAsA) or [verify all test cases](https://tio.run/##MzBNTDJM/X9u66GV/w/PPLTu8KzDXf9rD@3@Hx1tGKujEG2kY6hjrANngjGIA2IagwWMIVwIByQIFzLSgegGCRrrmCC0meiY6pjpmOtY6FjqGBrExgIA). Port of [*@xnor*'s Pyth answer](https://codegolf.stackexchange.com/a/69125/52210). **Explanation:** ``` Ù # Uniquified IÚ # Reversed uniquified on the input again Ê # Check if the two lists are not equal ``` [Answer] ## Java, 281 Characters ``` class K{public static void main(String[]a){System.out.println(!k(a[0]).equals(new StringBuffer(k(new StringBuffer(a[0]).reverse().toString())).reverse().toString()));}static String k(String k){for(char i=49;i<58;i++){k=k.replaceFirst(""+i,""+(i-9)).replaceAll(""+i,"");}return k;}} ``` [Answer] ## Python 3, 90 bytes This function that takes the input as a Python list. Sadly, Python lists don't directly support searching from the end like strings do with `rindex()`, but oh well. ``` def t(c):i,I=c.index,c[::-1].index;return any(i(n)<i(m)and I(n)<I(m)for m in c for n in c) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes ``` UQU⁻Q ``` [Try it online!](https://tio.run/##y0rNyan8/z80MPRR4@7A/4fbHzWt@f8/2lBHwVhHAUgagZExhIzVUYiGixnChcHIJBYA "Jelly – Try It Online") Just another port of [xnor's answer](https://codegolf.stackexchange.com/a/69125/66833), so go upvote that. ## How it works ``` UQU⁻Q - Main link. Takes a list l on the left U - rev(l) Q - unique(rev(l)) U - rev(unique(rev(l))) Q - unique(l) ⁻ - rev(unique(rev(l)) ≠ unique(l) ``` ]
[Question] [ You may or may not remember Xeyes, a demo program that came with (and, as far as I know, still comes with) the X window system. Its purpose was to draw a pair of eyes that followed your mouse cursor: [![Xeyes](https://i.stack.imgur.com/bmanm.png)](https://i.stack.imgur.com/bmanm.png) Your challenge is to recreate Xeyes with ASCII art. Write a program or function that draws two ASCII art eyes (specified below) wherever the user clicks and then moves their pupils to point in the direction of the cursor. [![Terminal Eyes GIF](https://i.stack.imgur.com/2xnal.gif)](https://i.stack.imgur.com/2xnal.gif) The above GIF is a recording of [this non-golfed Ruby implementation](https://gist.github.com/jrunning/b2fb863555c9e35c426d2fec25d9ac27), which can be run with any recent version of Ruby. You may also find it useful as reference for Xterm control sequences. ## Specifications This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the solution with the fewest bytes wins. This is an [ascii-art](/questions/tagged/ascii-art "show questions tagged 'ascii-art'") challenge, so your program must draw using ASCII characters—specifically, the characters `-`, `.`, `|`, `'`, `0`, space, and newline.1 2 This is an [interactive](/questions/tagged/interactive "show questions tagged 'interactive'") challenge, so your program must accept input and draw its output in realtime.3 Before your program begins accepting input, it should initialize a blank canvas of at least 20 rows and 20 columns. It should not draw anything until the user clicks on the canvas. Any time the user clicks4 on the canvas, the program should clear any previous output and then draw these ASCII eyes on the canvas, centered on the character nearest the location of the mouse cursor.5 6 (Below, `✧` represents the mouse cursor and should not be drawn.) ``` .---. .---. | | | | | 0|✧|0 | | | | | '---' '---' ``` Note how the pupils "point" toward the cursor. Any time the mouse cursor moves on the canvas, the program should re-draw the pupils so that they continue pointing toward the cursor,7 e.g.: ``` ✧ .---. .---. | 0| | 0| | | | | | | | | '---' '---' ``` ## Pupil pointing Suppose we enumerated the positions of the inner nine characters of each eye like so: ``` .---. |678| |591| |432| '---' ``` The pupil will be drawn at one of the locations `1`-`9`. To decide which one, pretend the characters are square and that the canvas is a Cartesian grid, with the center of the `9` character at (0, 0), the center of `1` at (1, 0), and so on. When the program receives input—a click or movement—it should map the input location to the nearest grid coordinate 𝑀. If 𝑀 is (0, 0), the pupil should be drawn at (0, 0), i.e. the location of the `9` above. Otherwise, it should be drawn as described below. Imagine a Cartesian plane superimposed on the grid and divided into octants numbered **1**–**8**: [![](https://i.stack.imgur.com/4SSLk.png)](https://i.stack.imgur.com/4SSLk.png) If 𝑀 lies within octant **1**, then the pupil should be drawn at the location of `1` above, i.e. at (1, 0). If 𝑀 is in octant **2** it should be drawn at `2`—and so on. To illustrate, the below image shows part of the grid color-coded according to where the pupil should be drawn when the mouse cursor is at a particular location. When, for example, the cursor is at any of the green coordinates (keeping in mind that the grid coordinates lie at the squares' centers, not their corners), the pupil should be drawn at `4`. [![](https://i.stack.imgur.com/WdKO7.png)](https://i.stack.imgur.com/WdKO7.png) The two eyes' pupils move independently, so for each eye repeat the process with 𝑀 relative to that eye's center. ## Notes 1. This isn't a [graphical-output](/questions/tagged/graphical-output "show questions tagged 'graphical-output'") challenge. The output must be a grid of characters. You may, of course, use graphics routines to draw a grid of characters. 2. Whitespace may be drawn (or, rather, not drawn) however is convenient. An empty spot in the grid looks the same as a space character and will be considered equivalent. 3. "Real-time" is defined here as fewer than 200ms between input and the corresponding output being drawn. 4. It is at your discretion which mouse button(s) are observed for input, and whether a press or release constitutes a "click." 5. The canvas must be cleared, or the visual equivalent must be achieved. With a terminal-based solution, for example, printing a new canvas below the previous canvas is not considered equivalent. 6. When the user clicks near the edge of the canvas such that some of the eye characters would be drawn beyond its edge, the behavior is undefined. However, the program must continue running normally upon subsequent clicks. 7. When the mouse cursor leaves the "canvas," the behavior is undefined, but the program must continue running normally when the cursor re-enters the canvas. 8. A text cursor may appear on the canvas, as long as it does not obscure the output. Standard loopholes are forbidden. [Answer] # Excel VBA 32-Bit, ~~630~~ 519 Bytes A `Worksheet` level `Sub`routine that activates on every click. Draws eyes in a \$5\times 11\$ range centered at the clicked cell. This is calibrated to run at the default zoom of 100%. It breaks if when scrolling, zooming, or selecting multiple cells. ``` Sub Worksheet_SelectionChange(ByVal t As Range) With Cells .Clear .ColumnWidth=1.3 .Font.Name="Courier" End With Dim l As p,p As p Q l On Error Resume Next Do DoEvents Q p For i=0To 1 v=l.x-p.x+56*(-1)^i w=l.y-p.y n=IIf(Abs(v)>6Or Abs(w)>9,(4*Application.Atan2(v,w)\[Pi()]+4)Mod 8,8) For j=0To 24 m=Mid(".---.|567||480||321|'---'",j+1,1) t.Offset(j\5-2,j Mod 5+1-6*i)=Mid("0 '"&m,3+(m Like"[0-9]")+(m=Val(n))) Next j,i Loop End Sub ``` ***Note:** terminal `"` on line 5 is included for Prettify.JS/Markdown syntax highlighting only, and does not contribute to byte count* ### Helper Function and Type Declaration The below declarations allow for querying the cursor position using the Windows management function [GetCursorPos](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getcursorpos). These must be declared in an accessible `Module` level context. ``` Declare Sub Q Lib"user32"Alias"GetCursorPos"(l As p) Type p x As Long y As Long End Type ``` The above is only compatible with 32-bit installations of Excel, but may be adjusted to run in a 64-bit installs by modifying the the declaration to ``` Declare PtrSafe Sub Q Lib"user32"Alias"GetCursorPos"(l As p) ``` # Output [![Moving_Eyes](https://i.stack.imgur.com/5JSpq.gif)](https://i.stack.imgur.com/5JSpq.gif) # Commented ``` '' execute the following every time the user changes selection Sub Worksheet_SelectionChange(ByVal t As Range) '' Tell VBA to keep running on errors '' ( Necessary for specification Note #6 ) On Error Resume Next '' Clear All Cell, Make them Square, Use Monospace Font With Cells .Clear .ColumnWidth = 1.3 .Font.Name = "Courier" End With '' Dim two p (point) objects, defined below Dim l As p, p As p '' Use Q (alias for User32 function GetCursoPos) to get initial mouse position (l) Q l '' Implicitly loop until the next selection change event Do '' Allow events DoEvents '' Use User32 function to get current mouse position (p) Q p '' iterate over the two eyes (left: i=1, right: i=0) For i = 0 To 0 '1 '' define var (v) with horiontal distance between cursor and center of eye i v = l.x - p.x + 56 * (-1) ^ i '' define var (w) with vertical distance between cursor and center of eyes w = l.y - p.y '' Based off of (v) and (w), calculate which of the numbers in the below '' should be the pupil for each eye '' '' .---. '' |567| '' |480| '' |321| '' '---' '' n = IIf(Abs(v) > 6 Or Abs(w) > 9, (4 * Application.Atan2(v, w) \ [Pi()] + 4) Mod 8, 8) '' Iterate over the 25 cells to be updated, per eye For j = 0 To 24 '' find character at current cell in template m = Mid(".---.|567||480||321|'---'", j + 1, 1) '' stuff cell with the first *k* letters of "0 '" & template char '' where k defaults to 3, '' is decremented by 1 if template char is a number AND '' is decremented by 1 if template char is n '' '' Cases: '' Border Characters (`.`,`-`,`|`,`'`): '' start at 3rd character, cell holds `'` and template char '' Note: `'` literal at beginning of cell coerces excel to display '' any and all values as text, allowing `-` to be printed '' Sclera Characters (` `): '' start at 2nd character, cells hold ` '` and template char '' but due to cell sizing and monospace font, only ` ` is visible '' Iris / Pupil Characters (`0`): '' start at 1st character, cells hold `0 '` and template char '' but only leading `0` is visible '' Note: use of `Val` here forces implicit type '' coercion, and is generally *cursed* t.Offset(j \ 5 - 2, j Mod 5 + 1 - 6 * i) = Mid("0 '" & m, 3 + (m Like "[0-9]") + (m = Val(n))) '' End For loops Next j, i '' End Do loop Loop End Sub ``` [Answer] # HTML + CSS + JavaScript (ES6), 93 + 19 + ~~278~~ 276 = 388 bytes ``` w=7.8125 h=15 with(Math)r=round, (onclick=e=>F.style=`margin:-3.5em -6.5ch;left:${x=r(e.x/w)*w}px;top:${y=r(e.y/h)*h}px`)({y:-40}),onmousemove=e=>(s=($,o)=>$.style=`left:${a=atan2(Y=r((e.y-y)/h),X=r((e.x-x)/w+o)),X|Y?w*r(cos(a)):0}px;top:${X|Y?h*r(sin(a)):0}px`)(L,3)&&s(R,-3) ``` ``` *{position:relative ``` ``` <pre id=F>.---. .---. | | | | | <a id=L>0</a> | | <a id=R>0</a> | | | | | '---' '---' ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64 + [1351 mouse](https://en.wikipedia.org/wiki/Commodore_1351)), 630 bytes ``` 00 C0 20 44 E5 A9 FF 85 5E A2 3F A9 00 8D 10 D0 8D 1B D0 9D C0 02 CA 10 FA A0 0A A2 1E B9 5A C2 9D C0 02 CA CA CA 88 10 F4 A9 0B 8D F8 07 A9 18 8D 00 D0 A9 32 8D 01 D0 A9 0D 8D 27 D0 A9 01 8D 15 D0 78 A9 60 8D 14 03 A9 C1 8D 15 03 58 D0 FE 84 FD 85 FE A8 38 E5 FD 29 7F C9 40 B0 04 4A F0 0A 60 09 C0 C9 FF F0 03 38 6A 60 A9 00 60 20 44 E5 A5 69 38 E9 05 B0 02 A9 00 C9 1E 90 02 A9 1D 85 FD 18 69 02 85 5C 69 06 85 5D A5 6A 38 E9 02 B0 02 A9 00 C9 15 90 02 A9 14 85 FE 18 69 02 85 5E A9 65 8D BB C0 A9 C2 8D BC C0 A9 04 85 02 A6 FE 20 F0 E9 A9 02 85 5F A4 FD A2 00 BD FF FF 91 D1 C8 E8 E0 05 D0 F5 C8 C6 5F D0 EE E6 FE A9 6A 8D BB C0 A9 C2 8D BC C0 C6 02 30 0E D0 D1 A9 6F 8D BB C0 A9 C2 8D BC C0 D0 C5 60 C5 69 90 0A F0 5D E5 69 85 5F A9 C6 D0 09 49 FF 38 65 69 85 5F A9 E6 8D 1C C1 8D 23 C1 8D 3E C1 A5 6A C5 5E 90 21 F0 12 E5 5E C5 5F 90 12 4A C5 5F B0 02 C6 FD A6 5E E8 D0 33 C6 FD A6 5E D0 2D 0A C5 5F B0 EE 90 F3 49 FF 38 65 5E C5 5F 90 0C 4A C5 5F B0 02 C6 FD A6 5E CA D0 11 0A C5 5F B0 F4 90 D7 A5 6A C5 5E 90 EE F0 D1 B0 C8 20 F0 E9 A9 30 A4 FD 91 D1 60 AD 19 D4 A4 FB 20 4E C0 84 FB 85 5F 18 6D 00 D0 8D 00 D0 6A 45 5F 10 08 A9 01 4D 10 D0 8D 10 D0 AD 10 D0 4A AD 00 D0 B0 08 C9 18 B0 16 A9 18 D0 0F C9 58 90 0E 24 5F 10 05 CE 10 D0 B0 EF A9 57 8D 00 D0 AD 1A D4 A4 FC 20 4E C0 84 FC 49 FF 85 5F 38 6D 01 D0 8D 01 D0 6A 45 5F 10 06 24 5F 10 11 30 07 AD 01 D0 C9 32 B0 04 A9 32 D0 06 C9 FA 90 05 A9 F9 8D 01 D0 A5 69 85 6B A5 6A 85 6C AD 10 D0 4A AD 00 D0 6A 38 E9 0C 4A 4A 85 69 AD 01 D0 38 E9 32 4A 4A 4A 85 6A AD 01 DC 29 10 C5 6D F0 0B 85 6D 29 10 D0 05 20 6C C0 30 10 A5 5E 30 46 A5 69 C5 6B D0 06 A5 6A C5 6C F0 3A A6 5E CA 86 5F A9 03 85 02 A6 5F 20 F0 E9 A9 20 A2 03 A4 5C 88 91 D1 C8 CA D0 FA A2 03 A4 5D 88 91 D1 C8 CA D0 FA E6 5F C6 02 D0 DD A5 5C 85 FD 20 E9 C0 A5 5D 85 FD 20 E9 C0 4C 31 EA 80 C0 E0 F0 F8 FC F0 D8 18 0C 0C 2E 2D 2D 2D 2E 5D 20 20 20 5D 27 2D 2D 2D 27 ``` In action: [![demo](https://i.stack.imgur.com/Kla09.gif)](https://i.stack.imgur.com/Kla09.gif) **No online demo**, sorry, because there's AFAIK no js C64 emulator supporting a mouse. If you want to try it yourself, grab [VICE](http://vice-emu.sourceforge.net/), download [the binary executable](https://github.com/Zirias/c64xeyes/blob/8a910681df6f99e81bdb6d370579c00e402130f5/xeyes.prg?raw=true) and start it in the C64 emulator: ``` x64sc -autoload xeyes.prg -controlport1device 3 -keybuf 'sys49152\n' ``` To grab/ungrab the mouse input in the running emulator, use `ctrl+m` on Unix/Linux and `ctrl+q` on windows. --- Yes, this had to be done ;) After all, there **is** an original Commodore mouse for the C64, but of course, the builtin operating system doesn't support it, so I first needed a mouse driver, which already took 230 bytes (including a mouse-cursor shaped hardware sprite and bounds checking code for the screen area, but without translating the pointer coordinates to text screen coordinates). * To safe some bytes, I decided to keep the OS' IRQ working and use a few Kernal routines where possible (clearing the screen and getting a base pointer for a text screen row). * The code also puts all variables in zeropage, which saves some more bytes, but destroys floating point values used by BASIC. As the program never exits anyways, this doesn't matter. * The third trick to reduce size is self modification: There's only code to check for putting the pupil on the *left* side of the eye. The same code is reused after patching some decrement instructions to increment instructions for the right side. If you're interested, you can read the code [as *assembly source* here](https://github.com/Zirias/c64xeyes/blob/8a910681df6f99e81bdb6d370579c00e402130f5/src/main.s) :) [Answer] # QBasic ([QB64](http://qb64.net)), ~~361~~ 305 bytes ``` DO WHILE _MOUSEINPUT x=CINT(_MOUSEX) y=CINT(_MOUSEY) IF _MOUSEBUTTON(1)THEN l=x-3:k=y IF(2<l)*(73>l)*(2<k)*(22>k)THEN CLS:FOR i=0TO 1:h=l+6*i:LOCATE k-2,h-2:?".---.":FOR j=1TO 3:LOCATE,h-2:?"| |":NEXT:LOCATE,h-2:?"'---'":d=x-h:e=y-k:m=ABS(e/d):LOCATE k-SGN(e)*(m>=.5),h-SGN(d)*(m<=2):?"0":NEXT WEND LOOP ``` Left-click places the eyes. If placement of eyes would result in part of the eyes being out of bounds, the program "freezes" until a valid placement is made. The main tricky part is placing the pupils. Most of the time, the coordinates of the pupil are just the center of the eye plus (sign(Δx), sign(Δy)), except that in octants 1 and 5, the y-coordinate equals y-center, and in octants 3 and 7, the x-coordinate equals x-center. Octant boundaries can be calculated using the slope `m` of the line from the center of the eye to the mouse coordinates. Conveniently, dividing by zero when calculating the slope gives floating-point infinity (+/-) rather than an error. [![Visual eyes in QB64](https://i.stack.imgur.com/7BJQc.gif)](https://i.stack.imgur.com/7BJQc.gif) ### Ungolfed ``` ' Loop forever DO ' Do stuff if there is new mouse data (movement or click) IF _MOUSEINPUT THEN ' Store the mouse coords rounded to the nearest integer mouse_x = CINT(_MOUSEX) mouse_y = CINT(_MOUSEY) ' If left mouse button was clicked, change location of eyes IF _MOUSEBUTTON(1) THEN ' Store center coordinates of left eye left_center_x = mouse_x - 3 center_y = mouse_y END IF ' If eye location is in bounds, print the eyes and pupils x_in_bounds = left_center_x > 2 AND left_center_x < 73 y_in_bounds = center_y > 2 AND center_y < 22 IF x_in_bounds AND y_in_bounds THEN CLS FOR eye = 1 TO 2 ' eye = 1 for left eye, eye = 2 for right eye IF eye = 1 THEN center_x = left_center_x IF eye = 2 THEN center_x = left_center_x + 6 ' Print eye borders LOCATE center_y - 2, center_x - 2 PRINT ".---." FOR row = 1 TO 3 LOCATE , center_x - 2 PRINT "| |" NEXT row LOCATE , center_x - 2 PRINT "'---'" ' Calculate coordinates of pupil xdiff = mouse_x - center_x ydiff = mouse_y - center_y slope = ydiff / xdiff ' For most cases, adding the sign of the diff to the center ' coordinate is sufficient pupil_x = center_x + SGN(xdiff) pupil_y = center_y + SGN(ydiff) ' But in octants 3 and 7, the x-coordinate is centered IF ABS(slope) > 2 THEN pupil_x = center_x ' And in octants 1 and 5, the y-coordinate is centered IF ABS(slope) < 0.5 THEN pupil_y = center_y LOCATE pupil_y, pupil_x PRINT "0" NEXT eye END IF ' in bounds END IF ' mouse data LOOP ' forever ``` [Answer] # [Clean](https://clean.cs.ru.nl), ~~1014~~ ~~904~~ ~~892~~ ~~884~~ ~~840~~ ~~814~~ ~~782~~ ~~772~~ 769 bytes ***-6 bytes if the eyes don't need to snap to a grid*** This wasn't easy. UIs in functional languages rarely are. ``` import StdEnv,StdIO,osfont,ostoolbox a=toReal c=1>0 Start w#(d,w)=openId w #(t,w)=worldGetToolbox w #(_,f,_)=osSelectfont("Courier",[],9)t =let$p#(s,p)=accPIO getProcessWindowSize p =snd(openWindow NilLS(Window""NilLS[WindowId d,WindowMouse(\_=c)Able(noLS1@),WindowViewSize s,WindowPen[PenFont f]])p);@(MouseUp p _)s={s&ls=p};@(MouseMove p _)s=:{ls={x,y},io}={s&io=setWindowLook d c(c,(\_{newFrame}i#(w,i)=getFontCharWidth f' '(unfill newFrame i) =let g v=let m=y-p.y;n=p.x-x-v*w;s=abs(a m/a n);k|abs m<9&&abs n<w=5|s<0.4142=if(n>0)6 4=sign if(s>2.4143)0n+if(m>0)2 8in[".---.":["|"+++{if(k==e)'0'' '\\e<-[j..j+2]}+++"|"\\j<-[1,4,7]]]++["'---'"]in foldr(\e=drawAt{x=(x/w-5)*w,y=(y/9+e-2)*9}([a+++" "+++b\\a<-g -3&b<-g 3]!!e))i[0..4]))io};@_ s=s in startIO SDI zero$[]w ``` Make sure that you're using iTasks Clean, have the `Courier` font installed, and have `StdLib` BEFORE any subfolders of `ObjectIO` in the module search path. Compile with (example, may differ): `clm -IL StdLib -IL ObjectIO -IL "ObjectIO/OS <YOUR_OS_HERE>" -IL Dynamics -IL Generics -IL Platform -nci <MODULE_NAME_HERE>` If you've never run Clean before, expect this project to take 5+ minutes to compile. **Ungolfed:** ``` module main import StdEnv,StdIO,osfont,ostoolbox height=9 SlopeFor225 :== 0.4142 StartSize :== 8 Universe :== {corner1={x=0,y=0},corner2={x=1,y=1}} Start :: *World -> *World Start world = startConsole (openIds 1 world) startConsole :: ([Id],*World) -> *World startConsole ([windowID],world) # (toolbox,world) = worldGetToolbox world # (_,font,toolbox) = osSelectfont ("Consolas",[],height) toolbox = startIO SDI {x=0,y=0} (initialise font) [ProcessClose closeProcess] world where initialise font pst # (size,pst) = accPIO getProcessWindowSize pst # (error,pst) = openWindow undef (window font size) pst | error<>NoError = abort "bad window" = pst window font size = Window "Xeyes" NilLS [WindowId windowID ,WindowClose (noLS closeProcess) ,WindowMouse mouseFilter Able (noLS1 track) ,WindowViewDomain Universe//(getViewDomain StartSize) ,WindowViewSize size ,WindowPen [PenFont font] ] track (MouseDown pos _ _) state=:{ls=point=:{x,y},io} # point = pos // move to mouse position = {state & ls=pos} track (MouseMove pos _) state=:{ls=point=:{x,y},io} //redraw to point at mouse # io = setWindowLook windowID True (True, look) io = {state & ls=point,io=io} where look _ {newFrame} picture # picture = unfill newFrame picture # (width,picture) = getPenFontCharWidth' 'picture = let determineSector u # yDist = (y - pos.y) # xDist = (pos.x - u) # slope = abs(toReal yDist / toReal xDist) | (abs yDist) < height && (abs xDist) < width = '9' | slope < SlopeFor225 = if(xDist > 0) '1' '5' | yDist > 0 | slope > (2.0+SlopeFor225) = '7' = if(xDist > 0) '8' '6' | slope > (2.0+SlopeFor225) = '3' = if(xDist > 0) '2' '4' getEye u=map(map(\e|isDigit e=if(e==determineSector(x+u*width))'0'' '=e))[['.---.'],['|678|'],['|591|'],['|432|'],['\'---\'']] in foldr(\i pic=drawAt{x=(x/width-5)*width,y=(y/height+i-2)*height}([toString(a++[' ':b])\\a<-getEye -3&b<-getEye 3]!!i)pic)picture[0..4] mouseFilter (MouseDown _ _ _) = True mouseFilter (MouseMove _ _) = True mouseFilter _ = False ``` As you can see from the ungolfed version, most of the code is just setting up the combination of "monospaced font" with "respond to the mouse". And even though `Courier` doesn't make it easy to tell, it is actually drawing the `.`s and `'`s. Swapping to something like `Consolas` makes it clearer. [![enter image description here](https://i.stack.imgur.com/iTfxL.gif)](https://i.stack.imgur.com/iTfxL.gif) [Answer] # Ruby, 335 + 13 = 348 bytes +13 bytes for `-rio/console` flag to enable `IO#getch`. Contains literal ESC (`0x1b`) characters, shown as `␛` below. xxd dump follows. **Caution:** This does not clean up after itself at exit. See note under **xxd dump** below. ``` include Math $><<"␛[?1003h" s="" (s<<STDIN.getch ($><<"␛[2J" x,y=$3.ord-32,$4.ord-32 u,v=x,y if$2 u&&[x-u+3,x-u-3].map{|a|b=y-v e=4*asin(b/sqrt(a**2+b**2))/PI printf"␛[%d;%dH.---.@|567|@|480|@|321|@'---'".gsub(/(#{(a<0?4-e:b<0?8+e:e).round%8rescue 8})|([0-8])|@/){$1?0:$2?" ":"␛[5D␛[1B"},v-2,x-a-2} s="")if /M(C|(#))(.)(.)$/=~s)while 1 ``` ## Ungolfed This is a pretty naïve golf of [my original Ruby implementation](https://gist.github.com/jrunning/b2fb863555c9e35c426d2fec25d9ac27). ``` include Math # Saves a few bytes for asin, sqrt, and PI $> << "␛[?1003h" # Print xterm control sequence to start mouse tracking s = "" # Variable to hold input-so-far ( s << STDIN.getch # Read a character from STDIN ( $> << "␛[2J" # Clear terminal x, y = $3.ord - 32, $4.ord - 32 # Get cursor x and y from last match u, v = x, y if $2 # Update eye position if last matched control sequence was click ("#") u && [x-u+3, x-u-3].map {|a| # For each eye's x-position b = y - v # Eye's y position e = 4 * asin(b / sqrt(a**2 + b**2)) / PI # Convert cursor (x,y) to angle w/ x-axis as 1/8 turns printf "␛[%d;%dH.---.@|567|@|480|@|321|@'---'" # Control code to move text cursor, followed by template for eye .gsub( /(#{ (a < 0 ? 4-e : b < 0 ? 8+e : e).round % 8 rescue 8 # Octant number 0-7 or 8 for center })|([0-8])|@/ ){ $1 ? 0 : $2 ? " " : "␛[5D␛[1B" }, # Replace octant number with pupil; other digits with space; and @s with code to move cursor left and down for next line of eye v-2, x-a-2 # (y, x) position of top left corner of eye } s = "" # Clear input-so-far ) if /M(C|(#))(.)(.)$/ =~ s # ...when input-so-far matches a movement ("C") or click ("#") control sequence ) while 1 # ...forever ``` ## xxd dump This program turns on mouse tracking with the xterm control sequence `\e[?1003h` but doesn't turn it off at exit. To turn it off, use the control sequence `\e[?1003l`, e.g.: ``` ruby -rio/console visual_eyes.rb; printf '\e[1003l' ``` Since the program eats all input, it's hard to exit. If you want to be able to exit by pressing Ctrl+C, add the following line below `(s<<STDIN.getch`: ``` exit 130 if s.end_with?(?\003) ``` Without further ado: ``` 00000000: 696e 636c 7564 6520 4d61 7468 0a24 3e3c include Math.$>< 00000010: 3c22 1b5b 3f31 3030 3368 220a 733d 2222 <".[?1003h".s="" 00000020: 0a28 733c 3c53 5444 494e 2e67 6574 6368 .(s<<STDIN.getch 00000030: 0a28 243e 3c3c 221b 5b32 4a22 0a78 2c79 .($><<".[2J".x,y 00000040: 3d24 332e 6f72 642d 3332 2c24 342e 6f72 =$3.ord-32,$4.or 00000050: 642d 3332 0a75 2c76 3d78 2c79 2069 6624 d-32.u,v=x,y if$ 00000060: 320a 7526 265b 782d 752b 332c 782d 752d 2.u&&[x-u+3,x-u- 00000070: 335d 2e6d 6170 7b7c 617c 623d 792d 760a 3].map{|a|b=y-v. 00000080: 653d 342a 6173 696e 2862 2f73 7172 7428 e=4*asin(b/sqrt( 00000090: 612a 2a32 2b62 2a2a 3229 292f 5049 0a70 a**2+b**2))/PI.p 000000a0: 7269 6e74 6622 1b5b 2564 3b25 6448 2e2d rintf".[%d;%dH.- 000000b0: 2d2d 2e40 7c35 3637 7c40 7c34 3830 7c40 --.@|567|@|480|@ 000000c0: 7c33 3231 7c40 272d 2d2d 2722 2e67 7375 |321|@'---'".gsu 000000d0: 6228 2f28 237b 2861 3c30 3f34 2d65 3a62 b(/(#{(a<0?4-e:b 000000e0: 3c30 3f38 2b65 3a65 292e 726f 756e 6425 <0?8+e:e).round% 000000f0: 3872 6573 6375 6520 387d 297c 285b 302d 8rescue 8})|([0- 00000100: 385d 297c 402f 297b 2431 3f30 3a24 323f 8])|@/){$1?0:$2? 00000110: 2220 223a 221b 5b35 441b 5b31 4222 7d2c " ":".[5D.[1B"}, 00000120: 762d 322c 782d 612d 327d 0a73 3d22 2229 v-2,x-a-2}.s="") 00000130: 6966 202f 4d28 437c 2823 2929 282e 2928 if /M(C|(#))(.)( 00000140: 2e29 242f 3d7e 7329 7768 696c 6520 31 .)$/=~s)while 1 ``` ]
[Question] [ Some versions of the standard Android calculator app allow you to press a key, like 'sin' and then the 'del' key to make it 'si'. Probably just a bug which they can't be bothered with removing. [![Screenshot of Android calculator](https://i.stack.imgur.com/EyDGLl.jpg)](https://i.stack.imgur.com/EyDGLl.jpg) The following letters/letter groupings are typable: ``` sin si s cos co c tan ta t ln l log lo e ``` So, 'tasteless' is typable, because ta-s-t-e-l-e-s-s and so is 'clogs' because 'c-log-s'. However 'got' is not typable, neither is 'an' or 'xyz'. Write a program that takes a single word (or sequence of letters, only a-z in input) as input and produces output to indicate if a word is typable or not. Output may be a single character/letter/digit/etc. or it may be larger. All typable words should produce the same output. All non-typable words should also produce the same output. P.S. Just out of curiosity, is 'tasteless' the longest dictionary word that is typable? [Answer] # Perl, ~~47~~ ~~43~~ 41 + 1 = 42 bytes -4 bytes thanks to @Sunny Pun. -2 bytes thanks to @Brad Gilbert b2gills and @Downgoat Run with the `-n` flag. ``` say!/^(s(in?)?|co?|t(an?)?|ln?|log?|e)+$/ ``` It can definitely be golfed futher, but in the spirit of competition, I'm leaving the mostly-original regex I came up with at the beginning. Returns nothing if true, `1` if false. [Try it online!](https://tio.run/nexus/perl#@1@cWKmoH6dRrJGZZ69pX5Ocb19TopEIZufkAXF@un1Nqqa2iv7//yWJJSU5qSWJOanF/3Xz/uv6muoZGBoAAA "Perl – TIO Nexus") I downloaded a dictionary file, and the longest word I found was 11 letters -- `tattletales` [Answer] # JavaScript (ES6), 44 bytes ``` s=>/^((si|ta|l)n?|co?|log?|[ste])+$/.test(s) ``` I *think* this is the shortest regex possible, but of course I may be wrong. ### Explanation An obvious first place to start would be a regex that simply includes all options separately: ``` s=>/^(sin|si|s|cos|co|c|tan|ta|t|log|lo|l|ln|e)+$/.test(s) ``` First, we can observe that `cos` can be formed from `co` and `s`, making it unnecessary: ``` s=>/^(sin|si|s|co|c|tan|ta|t|log|lo|l|ln|e)+$/.test(s) ``` Some of these, such as `sin` and `si`, can be combined by making the last letter optional: ``` s=>/^(sin?|s|co?|tan?|t|log?|ln?|e)+$/.test(s) ``` This works because `sin?` matches `si` with or without an `n` on the end, thus covering both `sin` and `si`. There seems to be a lot of `n?`s as well. What if we put them all together? ``` s=>/^((si|ta|l)n?|s|co?|t|log?|e)+$/.test(s) ``` One more way to golf this would be to combine the remaining single-char options into a character range, but this comes out at the same length: ``` s=>/^((si|ta|l)n?|co?|log?|[ste])+$/.test(s) ``` And that's how you golf a simple regex. I believe this is the shortest possible regex that matches every string correctly, but perhaps not. I will award a **+100 bounty** to anyone who manages to improve upon this regex. [Answer] # Pyth, ~~37~~ ~~33~~ ~~29~~ 28 bytes The code contains an unprintable character, so here is an `xxd` hexdump. ``` 00000000: 737d 5173 4d5e 733c 5252 6336 2e22 6174 s}QsM^s<RRc6."at 00000010: 14d0 69ba 76f1 ac59 6422 346c ..i.v..Yd"4l ``` [Try it online.](https://pyth.herokuapp.com/?code=s%7DQsM%5Es%3CRRc6.%22at%14%C3%90i%C2%BAv%C3%B1%C2%ACYd%224l&input=%22clog%22&debug=1) ~~Extremely~~ Astronomically inefficient. The time and space complexity is ~~O(16n)~~ O(24n). ### Explanation First, a `Q` is implicitly appended. ``` s}QsM^s<RRc6."…"4lQ Implicit: Q = input ."…" Generate "logsincostanlnee" c6 Split in 6 parts: ["log", "sin", "cos", "tan", "ln", "ee"] R 4 For each n from 0 to 3 <R Take the first n chars from each string s Flatten the results lQ Get length of input ^ Take that Cartesian power of the list sM Join each resulting list }Q Check if the input is found s Cast to integer ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~32~~ ~~31~~ ~~30~~ ~~28~~ 26 bytes ``` ŒṖw@€€“¡Ṡ[ẈKœịḲ-¢ȧ?-»’%3ḌẠ ``` Outputs **0** if the word is typeable, **1** if not. *Thanks to @JonathanAllan for golfing off 1 byte!* [Try it online!](https://tio.run/nexus/jelly#AT8AwP//xZLhuZZ3QOKCrOKCrOKAnMKh4bmgW@G6iEvFk@G7i@G4si3CosinPy3Cu@KAmSUz4biM4bqg////Y2xvZ3M "Jelly – TIO Nexus") ### How it works ``` ŒṖw@€€“¡Ṡ[ẈKœịḲ-¢ȧ?-»’%3ḌẠ Main link. Argument: s (string of lowercase letters) ŒṖ Yield all partitions of s. “¡Ṡ[ẈKœịḲ-¢ȧ?-» Yield "sine logcostanln". Every third character marks the start of a typeable word. w@€€ Find the indices of all substrings in the partitions in the string to the right (1-based, 0 if not found). ’ Decrement. "Good" indices are now multiples of 3. %3 Modulo 3. "Good" indices are mapped to 0, "bad" indices are mapped to 1 or 2. Ḍ Convert from decimal to integer. A partition will yield 0 iff all indices are "good". Ạ All; yield 0 if one or more integers are falsy (0), 1 if all integers are truthy (non-zero). ``` [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 33 bytes *Fixed a bug thanks to @Synoli.* ``` ~c:1a ,"sincostanloglneeee"@6e@[? ``` [Try it online!](http://brachylog.tryitonline.net/#code=fmM6MWEKLCJzaW5jb3N0YW5sb2dsbmVlZWUiQDZlQFs_&input=ImNsb2dzIg) Outputs `true.` if typeable or `false.` otherwise. ### Explanation We try deconcatenations of the input until we find one for which all strings that we concatenate are a prefix of one of `["sin", "cos", "tan", "log", "lne", "eee]`. ``` ~c A list of strings which when concatenated results in the Input :1a All strings of this list satisfy the predicate below: ,"sincostanloglneeee"@5 The list ["sin", "cos", "tan", "log", "lne", "eee"] e Take one element of that list @[? The input is a prefix of that element ``` [Answer] # [Perl 6](https://perl6.org), ~~60 50~~ 44 bytes first attempt (*60*) ``` put +?(get~~/^<{<sin cos tan ln log e>».&{|m:ex/^.+/}}>*$/) ``` translation of the Perl 5 answer (*50*) ``` put +?(get~~/^[s[in?]?|co?|t[an?]?|ln?|log?|e]*$/) ``` using `-n` switch (*43+1*) ``` put +?/^[s[in?]?|co?|t[an?]?|ln?|log?|e]*$/ ``` The first `?` converts the result to Boolean, and the first `+` converts that to a number (`1` for `True`, `0` for `False`) [Answer] ## Mathematica, 101 bytes ``` If[StringMatchQ[#,("sin"|"si"|"s"|"cos"|"co"|"c"|"tan"|"ta"|"t"|"ln"|"l"|"log"|"lo"|"e")..],"T","F"]& ``` It seems that the hard parts of this challenge are coming up with the shortest regex and choosing the most concise language to match the regex. I don't have anything to contribute to the former, and Mathematica isn't good candidate for the latter since you have to use `StringMatchQ` and `RegularExpression`. What I can do is answer your P.S.: is "tasteless" the longest word that you can type? ``` In[1]:= f=StringMatchQ[#,("sin"|"si"|"s"|"cos"|"co"|"c"|"tan"|"ta"|"t"|"ln"|"l"|"log"|"lo"|"e")..]&; In[2]:= Select[EntityList@"Word",f@#[[2,1]]&][[All,2,1]]//SortBy[StringLength]//DeleteDuplicates Out[2]= {c,e,l,s,t,cc,cl,el,et,lo,si,sl,ta,te,ccc,col,cos,cot,eel,ell,eta,etc,lee,let,log,lot,sec,see,set,sic,sin,sit,tae,tan,tat,tec,tee,cell,clog,clot,coco,cole,colt,coss,cost,cote,else,less,loco,loge,loll,lose,loss,lota,sect,seel,sell,sess,seta,sett,sill,silo,silt,sine,sise,siss,site,sloe,slog,slot,stet,taco,tact,tael,talc,tale,tall,tect,tell,test,cello,close,cosec,costa,cotan,eccle,elect,elsin,ettle,loess,lotte,secle,setee,since,sleet,stale,stall,state,steel,stele,tasse,taste,tatee,teest,telco,testa,tetel,tsine,cellco,closet,coleta,collet,coltan,cosine,cosset,costal,ecesis,estate,lessee,scelet,select,sellee,sestet,settee,settle,siesta,silole,stacte,stance,stasis,tallet,tallot,taslet,tassel,tasset,tattle,tectal,teetan,tellee,testee,tsetse,celesta,cessile,cocotte,collect,costate,ecolect,ectasis,electee,sessile,sinless,sitelet,statant,tassell,tastant,testate,coestate,colessee,colocolo,cosiness,costless,electant,lossless,sceletal,siletane,statelet,tactless,tallness,telltale,telocoel,coelostat,sissiness,stateless,tasteless,tattletale} ``` So "tattletale" seems to be the longest by one character. [Answer] # [Wonder](https://github.com/wonderlang/wonder), 41 bytes ``` !.(mstr"^(s|t|co?|(l|ta|si)n?|log?|e)+$") ``` Usage: ``` (!.(mstr"^(s|t|co?|(l|ta|si)n?|log?|e)+$")) "tasteless" ``` Totally misunderstood the question before, but now it's all fixed. Outputs `F` for match and `T` for no match. ## Noncompeting, 35 bytes ``` !.`^(s|t|co?|(l|ta|si)n?|log?|e)+$` ``` Usage: ``` (!.`^(s|t|co?|(l|ta|si)n?|log?|e)+$`) "tasteless" ``` This makes use of applicable regexes, which was implemented after this challenge. [Answer] # Processing, 223 bytes ``` int d(String b){for(String p:"tan0log0sin0cos0ln0e".split("0"))if(p.startsWith(b))return 1;return 0;} int l(String p){String b="";int t=1;for(char c:p.toCharArray()){b+=c;if(d(b)<1){b=c+"";t=d(b);}if(t<1)return t;}return t;} ``` Finally decided to do an answer without regex. To call the function, use `l("tasteless");`. Returns `0` for false and `1` for true. ### Expanded code with explanation ``` int d(String b){ for(String p:"tan0log0sin0cos0ln0e".split("0")) if(p.startsWith(b)) return 1; return 0; } //main function int l(String p){ String b=""; int t=1; for(char c:p.toCharArray()){ b+=c; if(d(b)<1){ b=c+""; t=d(b); } if(t<1)return t; } return t; } ``` Basically, we iterate over the given string, building up `b` char by char. We check using `d()` if any of the `tan`,`log`,... start with `b`. If it does, then it is valid. Else, we check if the char at that position is valid and we reset `b`. Now if it is invalid, `0` will be returned, or else it will still be valid. At the end, if the program hasn't already returned something, then return `1`. [Answer] # Scala, 49 bytes ``` s=>s.matches("(s(in?)?|co?|t(an?)?|ln?|log?|e)+") ``` Returns true if the given string matches the regex, false otherwise. [Answer] # [Python 3](https://docs.python.org/3/), 154 bytes ``` r=1;i=input() while r: r=0 for s in'sin,cos,tan,log,ln,co,lo,si,ta,s,c,t,l,e'.split(','): if i.startswith(s):r=i=i.replace(s,'',1);break print(i=='') ``` [Try it online!](https://tio.run/nexus/python3#FY1BDsMgDATvvIKbQbKi5pqIx9CINFYtQLarPJ/Q284cZoekdadEtf8sRHdfxMXL5rykl/NnE6@eKihVPJqi5YrcPsh/nAuVpkPFAw0ZCyzamSwAQpwRT6enRS2L6U12BY2bpHm3SOmcjxIUAXCN@1tK/rouVC1QSgDRjWHMzVRsjAc "Python 3 – TIO Nexus") [Answer] # [Python 3](https://docs.python.org/3/), ~~149~~ 130 bytes ``` i=input() for a in 'tan,sin,cos,log,si,co,ta,lo,lo,ln,s,c,t,l,e'.split(','): if a in i: i=i.replace(a,"") print(not i) ``` edit #1: shaved 19 bytes using @Henke solution [Answer] ## Python 2, 124 bytes ``` f=lambda w:any(f(w[len(s):])if w[:len(s)]==s else 0for s in'sin,cos,tan,log,ln,co,lo,si,ta,s,c,t,l,e'.split(','))if w else 1 ``` [Answer] # PHP, 60 bytes ``` <?=preg_match("#^((si|ta|l)n?|co?|log?|s|e|t)+$#",$argv[1]); ``` regex stolen from [ETHproductions](https://codegolf.stackexchange.com/a/102128#102128): takes input from command line argument; prints `1` for typable, `0` for not typeable. **older versions, ~~75~~ ~~73~~ 69 bytes** ``` <?=!preg_replace("#co|log|ln|lo|sin|si|tan|ta|[celst]#","",$argv[1]); ``` replaces all possible words with empty string, returns the result, negates. ``` <?=!preg_split("#co|log|ln|lo|sin|si|tan|ta|[celst]#",$argv[1],-1,1); ``` splits input by regex matches. Flag `1` stands for `PREG_SPLIT_NO_EMPTY` and tells `preg_split` to only return non-empty results. If input is typable, `preg_split` will only have empty results, so it will return an empty array, which is falsy. `!` negates the result. Both versions take input from command line argument and print `1` if result is empty (input is typable), else nothing. Notes: Packing the regex using `?` does not work here; it renders the expressions ungreedy; probably due to backtracking. And the order of the alternatives is important: `ta` has to stand before `t` or the engine will stop matching when it finds `t`. I found a [quantifier cheat sheet](http://www.rexegg.com/regex-quantifiers.html#cheat_sheet), thought `??` or `?+` might help; but they did not work for me. [Answer] # Java 8, 55 bytes ``` s->return s.matches("^((si|ta|l)n?|co?|log?|[ste])+$"); ``` Disclamer: *I used [ETHproductions'](https://codegolf.stackexchange.com/a/102128/60199) regex because it was many bytes shorter than mine.* Full credit on the Regex to him. What I did was add 24 bytes to make it a Java function. Returns `false` if the word did not fit into the Regex, else `true`. ]
[Question] [ ## Introductions A 2×n Boolean matrix can be represented as a string of the four characters `. ':`. The string has an "upper row" and a "lower row", with dots representing 1s and empty spaces representing 0s. For example, the 2×6 matrix ``` 1 0 1 0 0 1 0 0 0 1 0 1 ``` can be represented as `' '. :`. Your task is to take a matrix in this "compressed form", and rotate its entries one step clockwise, like a conveyor belt. ## Input Your input is a single string over the characters `. ':`. Its length is guaranteed to be at least 2. ## Output Your output shall be the input string, but with every dot rotated one step in the clockwise direction. More explicitly, the dots on the upper row more one place to the right, except the rightmost one, which moves down. The dots on the lower row move one step to the left, except the leftmost one, which moves up. In particular, the output string must have the same length as the original, and whitespace is significant. ## Example Consider the input string `:..:'.`, which corresponds to the 2×6 matrix ``` 1 0 0 1 1 0 1 1 1 1 0 1 ``` The rotated version of this matrix is ``` 1 1 0 0 1 1 1 1 1 0 1 0 ``` which corresponds to the string `::. :'`. ## Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. You can decide whether the input and output are enclosed in quotes, and one trailing newline is also acceptable in both. ## Test cases These test cases are enclosed in double quotes. ``` " " -> " " " ." -> ". " ". " -> "' " "' " -> " '" " '" -> " ." ": " -> "''" "''" -> " :" ":." -> ":'" ":.'" -> ":'." "..." -> ":. " ": :" -> "':." "':." -> ".:'" ".:'" -> ": :" " " -> " " "::::" -> "::::" ":..:'." -> "::. :'" " : .:'" -> ". '.. :" ": ''. :" -> "'' :'.." "........" -> ":...... " ":::: " -> ":::'' " " ::::" -> " ..:::" " : : : : " -> ". : : : '" ".'.'.'.'.'" -> "'.'.'.'.'." ".. :: '.' :." -> ": ..'' .' :.'" ".' '.:: :.'. . ::.' '. . .::' :.'." -> "' ' .:.''..'.'. ..:' ' .'. ...'''..'.'" ``` [Answer] # JavaScript (ES6), ~~100~~ ~~97~~ 93 bytes *Saved 4 bytes thanks to @edc65* ``` s=>s.replace(/./g,(c,i)=>" '.:"[(i?q>' '&q!=".":c>"'")+(q=c,s[++i]?s[i]>"'":c>' '&c!=".")*2]) ``` ### How it works This decides on the character we need to insert by performing some calculations on the chars before and after the current one. We sum: * If it's the first char, and it has a dot on the bottom, 2; * Otherwise, if the one before it has a dot on top, 2. * If it's the last char, and it has a dot on top, 1; * Otherwise, if the one after it has a dot on the bottom, 1. This sums nicely to 0 for a space, 1 for `'`, 2 for `.`, and 3 for `:`. ## Test snippet ``` f=s=>s.replace(/./g,(c,i)=>" '.:"[(i?q>' '&q!=".":c>"'")+(q=c,s[++i]?s[i]>"'":c>' '&c!=".")*2]) ``` ``` Try it out: <input id=A type="text" value=".' '.:: :.'. . ::.' '. . .::' :.'."> <button onclick="B.innerHTML=f(A.value)">Run</button> <pre id=B></pre> ``` [Answer] # Perl, ~~70~~ ~~69~~ ~~64~~ ~~63~~ ~~61~~ 60 bytes Includes +2 for `-lp` Run with the input string on STDIN, e.g. ``` perl -lp rotatedots.pl <<< ":..:'." ``` `rotatedots.pl`: ``` y/'.:/02/r=~/./;y/.':/01/;$_=$'.2*chop|$&/2 .$_;y;0-3; '.: ``` ## Explanation ``` y/'.:/02/r Construct bottom row but with 2's instead of 1's Return constructed value (for now assume space becomes 0 too) =~/./ Match first digit on bottom row into $&. $' contains the rest of the bottom row y/.':/01/ Convert $_ to top row (again assume space becomes 0 too) $'.2*chop Remove last digit from the top row, multiply by 2 and append to bottom row $&/2 .$_ Divide removed digit by 2 and prepend it to the top row $_= | "or" the top and bottom row together. The ASCII values of 0,1,2,3 have 00,01,10,11 as their last two bits. y;0-3; '.: Convert the smashed together top and bottom rows to the corresponding representation characters. Drop the final ; since it is provided by -p (after a newline which doesn't matter here) ``` Space is not converted in the above code. For the calculations `/2` and `*2` it will behave like and become `0`. In the other positions it will be part of the "or", but the 1 bits of space are a subset of the one bits of `0` and will have the same effect as `0` if or-ed with any of the digits. Only if the character it is or-ed with is a space will it remain a space instead of becoming a `0`. But that's ok since `0` would have been converted back to space anyways. [Answer] # Jelly, ~~32~~ ~~30~~ 29 bytes ``` ,Ṛe€"“':“.:”µṪ€;"ṚU1¦ZḄị“'.: ``` Note the trailing space. [Try it online!](http://jelly.tryitonline.net/#code=LOG5mmXigqwi4oCcJzrigJwuOuKAncK14bmq4oKsOyLhuZpVMcKmWuG4hOKAmOG7i-KAnCAnLjo&input=&args=IjouLjonLiI) or [verify all test cases](http://jelly.tryitonline.net/#code=LOG5mmXigqwi4oCcJzrigJwuOuKAncK14bmq4oKsOyLhuZpVMcKmWuG4hOKAmOG7i-KAnCAnLjrigJ0Kw4figqzhub7igqxq4oG3&input=&args=IiAgIiwiIC4iLCIuICIsIicgIiwiICciLCI6ICIsIicnIiwiOi4iLCI6LiciLCIuLi4iLCI6IDoiLCInOi4iLCIuOiciLCIgICAgIiwiOjo6OiIsIjouLjonLiIsIiA6ICAuOiciLCI6ICcnLiA6IiwiLi4uLi4uLi4iLCI6Ojo6ICAgICIsIiAgICA6Ojo6IiwiIDogOiA6IDogIiwiLicuJy4nLicuJyIsIi4uIDo6ICAnLicgOi4iLCIuJyAgJy46OiAgOi4nLiAuIDo6LicgICcuIC4gLjo6JyAgOi4nLiI). ### Background We begin by considering the input string (e.g., `:..:'.`) and its reverse. ``` :..:'. .':..: ``` For each character in the top row, we check if it belongs to `':`, and for each character of the bottom row if it belongs to `.:`. This gives the 2D array of Booleans ``` 100110 101111 ``` which is the matrix from the question, with reversed bottom row. We remove the last Boolean of each row, reverse the order of the rows, prepend the Booleans in their original order, and finally reverse the top row. ``` 100110 10011 10111 010111 111010 101111 10111 10011 110011 110011 ``` This yields the rotated matrix from the question. Finally, we consider each column of Booleans a binary number and index into `'.:` to obtain the appropriate characters. ``` 332031 ::. :' ``` ### How it works ``` ,Ṛe€"“':“.:”µṪ€;"ṚU1¦ZḄ‘ị“'.: Main link. Argument: S (string) Ṛ Reverse S. , Form a pair of S and S reversed. “':“.:” Yield ["':" ".:"]. e€" For each character in S / S reversed, check if it is an element of "':" / ".:". Yield the corresponding 2D array of Booleans. µ Begin a new, monadic chain. Argument: A (2D array of Booleans) Ṫ€ Pop the last Boolean of each list. Ṛ Yield the reversed array of popped list. ;" Prepend the popped items to the popped lists. U1¦ Reverse the first list. Z Zip to turn top and bottom rows into pairs. Ḅ Convert each pair from base 2 to integer. “'.: Yield "'.: ". ị Retrieve the characters at the corr. indices. ``` [Answer] # [Retina](https://github.com/mbuettner/retina), 66 * 2 bytes saved thanks to @daavko * 4 bytes saved thanks to @randomra ``` : 1e \. 1f ' 0e 0f T`h`Rh`^.|.$ (.)(\d) $2$1 e1 : e0 ' f0 f1 . ``` ### Explanation Starting with input: ``` : ''. : ``` The first 4 stages construct the matrix, using `1`/`e` for true and `0`/`f` for false for the top/bottom rows, respectively. Top and bottom rows are interlaced together. This would yield a string like: ``` e1f0e0e0f1f0e1 ``` However, these 4 stages also effectively move the lower row 1 to the left, simply by reversing the order of the letters and digits: ``` 1e0f0e0e1f0f1e ``` The `T`ransliteration stage reverses hex digits for the first and last characters only, i.e. replaces `0-9a-f` with `f-a9-0`. This has the effect of moving the bottom-left character up to the top row and the top-right character down to the bottom row: ``` ee0f0e0e1f0f11 ``` The next stage then swaps every letter-digit pair, thereby moving the upper row 1 to the right. Previously this was `(\D)(\d)`, but it turns out that `(.)(\d)` is sufficient because the substitutions always happen left-to-right and so the final two digits won't be erroneously matched by this, because penultimate character will have been already substituted. The matrix has now been fully rotated as required: ``` e0e0f0e1e0f1f1 ``` The final 4 stages then translate back to the original format: ``` '' :'.. ``` [Try it online.](http://retina.tryitonline.net/#code=OgoxZQpcLgoxZgonCjBlCiAKMGYKVGBoYFJoYF4ufC4kCiguKShcZCkKJDIkMQplMQo6CmUwCicKZjAKIApmMQou&input=OiAnJy4gOg) [All testcases, one per line](http://retina.tryitonline.net/#code=OgoxZQpcLgoxZgonCjBlCiAKMGYKVG1gaGBSaGBeLnwuJAooLikoXGQpCiQyJDEKZTEKOgplMAonCmYwCiAKZjEKLg&input=ICAKIC4KLiAKJyAKICcKOiAKJycKOi4KOi4nCi4uLgo6IDoKJzouCi46JwogICAgCjo6OjoKOi4uOicuCiA6ICAuOicKOiAnJy4gOgouLi4uLi4uLgo6Ojo6ICAgIAogICAgOjo6OgogOiA6IDogOiAKLicuJy4nLicuJwouLiA6OiAgJy4nIDouCi4nICAnLjo6ICA6LicuIC4gOjouJyAgJy4gLiAuOjonICA6Licu), `m` added to `T` line to allow separate treatment of each input line. [Answer] # Python 3, ~~145~~ ~~141~~ 130 bytes ``` def f(s):a=[i in"':"for i in s]+[i in".:"for i in s][::-1];return''.join(" '.:"[i+2*j]for i,j in zip([a[-1]]+a,a[-2:len(s)-2:-1])) ``` ## Explanation The golfed solution use the following property of zip : `zip('ABCD', 'xy') --> Ax By` so `zip(a[:l],a[l:])` can be replace by `zip(a,a[l:])` and that allow to remove the definition of `l` ``` def f(s): l=len(s)-1 # ┌───── unfold input string : 123 -> 123456 # │ 654 # ──────────────┴────────────────────────────── a=[i in"':"for i in s]+[i in".:"for i in s][::-1] # ─────────┬───────── ────────────┬─────────── # │ └──── generate the second row and reverse it # └─────────── generate the first row return''.join(" '.:"[i+2*j]for i,j in zip([a[-1]]+a[:l],a[l:-1][::-1])) # ──────┬────── ─┬ ────────────┬─────────── # │ │ └──── rotate and create first/second new row : 123456 -> 612345 -> 612 # │ │ 543 # │ └ group pair of the first and second row : 612 -> (6,5),(1,4),(2,3) # │ 543 # └─────────── replace pair by symbol ``` ## Results ``` >>> f(".' '.:: :.'. . ::.' '. . .::' :.'.") "' ' .:.''..'.'. ..:' ' .'. ...'''..'.'" >>> f(".....''''''") ":... '''':" ``` [Answer] # Pyth, ~~38~~ 36 ``` L,hb_ebsXCyc2.>syCXzJ" .':"K.DR2T1KJ ``` 2 bytes thanks to Jakube! [Try it here](http://pyth.herokuapp.com/?code=L%2Chb_ebsXCyc2.%3EsyCXzJ%22+.%27%3A%22K.DR2T1KJ&input=..+%3A%3A++%27.%27+%3A.&debug=0) or run the [Test Suite](http://pyth.herokuapp.com/?code=L%2Chb_ebsXCyc2.%3EsyCXzJ%22+.%27%3A%22K.DR2T1KJ&test_suite=1&test_suite_input=++%0A+.%0A.+%0A%27+%0A+%27%0A%3A+%0A%27%27%0A%3A.%0A%3A.%27%0A...%0A%3A+%3A%0A%27%3A.%0A.%3A%27%0A++++%0A%3A%3A%3A%3A%0A%3A..%3A%27.%0A+%3A++.%3A%27%0A%3A+%27%27.+%3A%0A........%0A%3A%3A%3A%3A++++%0A++++%3A%3A%3A%3A%0A+%3A+%3A+%3A+%3A+%0A.%27.%27.%27.%27.%27%0A..+%3A%3A++%27.%27+%3A.%0A.%27++%27.%3A%3A++%3A.%27.+.+%3A%3A.%27++%27.+.+.%3A%3A%27++%3A.%27.&debug=0). ### Explanation: ``` L,hb_eb ## Redefine the function y to take two lists ## and return them but with the second one reversed ## Uses W to apply a function only if it's first argument is truthy XzJ" .':"K.DR2T ## Does a translation from the string " .':" to ## .DR2T which is [0,1,2,3...,9] mapped to divmod by 2 ## (which is [0,0],[0,1],[1,0],[1,1], then some extra, unused values) ## we also store the string and the list for later use in J and K .>syC ... 1 ## zip the lists to get the bits on top and below as two separate lists ## apply the function y from before, flatten and rotate right by 1 Cyc2 ## split the list into 2 equal parts again, then apply y and zip again sX ... KJ ## apply the list to string transformation from above but in reverse ## then flatten into a string ``` [Answer] # Pyth, 66 bytes ``` KlQJ.nCm@[,1Z,Z1,ZZ,1 1)%Cd5Qjkm@" .':"id2Ccs[:JKhK<JtK>JhK:JtKK)K ``` [Try it here!](http://pyth.herokuapp.com/?code=KlQJ.nCm%40%5B%2C1Z%2CZ1%2CZZ%2C1%201%29%25Cd5Qjkm%40%22%20.%27%3A%22id2Ccs%5B%3AJKhK%3CJtK%3EJhK%3AJtKK%29K&input=%22%20.%22&test_suite=1&test_suite_input=%22%20%20%22%0A%22%20.%22%0A%22.%20%22%0A%22%27%20%22%0A%22%20%27%22%0A%22%3A%20%22%0A%22%27%27%22%0A%22%3A.%22%0A%22%3A.%27%22%0A%22...%22%0A%22%3A%20%3A%22%0A%22%27%3A.%22%0A%22.%3A%27%22%0A%22%20%20%20%20%22%0A%22%3A%3A%3A%3A%22%0A%22%3A..%3A%27.%22%0A%22%20%3A%20%20.%3A%27%22%0A%22%3A%20%27%27.%20%3A%22%0A%22........%22%0A%22%3A%3A%3A%3A%20%20%20%20%22%0A%22%20%20%20%20%3A%3A%3A%3A%22%0A%22%20%3A%20%3A%20%3A%20%3A%20%22%0A%22.%27.%27.%27.%27.%27%22%0A%22..%20%3A%3A%20%20%27.%27%20%3A.%22%0A%22.%27%20%20%27.%3A%3A%20%20%3A.%27.%20.%20%3A%3A.%27%20%20%27.%20.%20.%3A%3A%27%20%20%3A.%27.%22&debug=0) ## Explanation This can be broken down in 3 parts: * Convert the input into a flat array of ones and zeros. * Do the rotation. * Convert it back into ASCII. ### Convert input This is fairly trivial. Each character is mapped in the following way: ``` -> (0,0) . -> (0,1) ' -> (1,0) : -> (1,0) ``` *First one is a whitespace.* We get a list of 2-tuples which we transpose to get the 2 rows of the matrix which then gets flattened. **Code** ``` KlQJ.nCm@[,1Z,Z1,ZZ,1 1)%Cd5Q # Q = input KlQ # save the width of the matrix in K (gets used later) m Q # map each character d %Cd5 # ASCII-code of d modulo 5 @[,1Z,Z1,ZZ,1 1) # use this as index into a lookup list J.nC # transpose, flatten and assign to J ``` ### Rotate We have the matrix as flat array in `J` and the width of the matrix in `K`. The rotation can be described as: ``` J[K] + J[:K-1] + J[K+1:] + J[K-1] ``` **Code** ``` s[:JKhKJhK:JtKK) # J = flat array, K = width of matrix s[ ) # Concat all results in this list :JKhK # J[K] JhK # J[K+1:] :JtKK # J[K-1] ``` ## Convert it back ``` jkm@" .':"id2Cc[)K # [) = resulting list of the step above c[)K # chop into 2 rows C # transpose to get the 2-tuples back m # map each 2-tuple d id2 # interpret d as binary and convert to decimal @" .':" # use that as index into a lookup string to get the correct char jk # join into one string ``` [Answer] # Python 3, ~~166~~ ~~154~~ ~~153~~ ~~150~~ ~~146~~ ~~138~~ ~~137~~ ~~135~~ ~~132~~ 127 bytes **Edit:** I've borrowed the use of `zip` from [Erwan's Python answer](https://codegolf.stackexchange.com/a/75353/47581) at the end of the function. ~~and their idea to use `[::-1]` reversals, though I put in my own twist.~~ As it turns out, reversals were not a good idea for my function. I have changed my use of `format` for further golfing. Moved `a` and `b` directly into `zip` for further golfing (ungolfing remains unchanged because the separation of `a` and `b` there is useful for in avoiding clutter in my explanation) **Edit:** Borrowed `(some number)>>(n)&(2**something-1)` from [this answer by xnor on the Music Interval Solver challenge](https://codegolf.stackexchange.com/a/76296/47581). The clutter that is `zip(*[divmod(et cetera, 2) for i in input()])` can probably be golfed better, though I do like the expediency it grants from using two tuples `t` and `v`. ``` t,v=zip(*[divmod(708>>2*(ord(i)%5)&3,2)for i in input()]) print("".join(" '.:"[i+j*2]for i,j in zip((v[0],*t),(*v[1:],t[-1])))) ``` **Ungolfed:** ``` def rotate_dots(s): # dots to 2 by len(s) matrix of 0s and 1s (but transposed) t = [] v = [] for i in s: m = divmod(708 >> 2*(ord(i)%5) & 3, 2) # ord(i)%5 of each char in . :' is in range(1,5) # so 708>>2 * ord & 3 puts all length-2 01-strings as a number in range(0,4) # e.g. ord(":") % 5 == 58 % 5 == 3 # 708 >> 2*3 & 3 == 0b1011000100 >> 6 & 3 == 0b1011 == 11 # divmod(11 & 3, 2) == divmod(3, 2) == (1, 1) # so, ":" -> (1, 1) t.append(m[0]) v.append(m[1]) # transposing the matrix and doing the rotations a = (v[0], *t) # a tuple of the first char of the second row # and every char of the first row except the last char b = (v[1:], t[-1]) # and a tuple of every char of the second row except the first # and the last char of the first row # matrix to dots z = "" for i, j in zip(a, b): z += " '.:"[i + j*2] # since the dots are binary # we take " '.:"[their binary value] return z ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~40~~ 39 bytes ``` ' ''.:'tjw4#mqBGnXKq:QKEh1Kq:K+hv!)XBQ) ``` [**Try it online!**](https://tio.run/##y00syfn/X11BXV3PSr0kq9xEObfQyT0vwrvQKtDbNcMQSHtrZ6iVKWpGOAVq/v@vp66gAFRqpaBgpaeup6CnYGUFEQIygcLqEHEA) *The linked version has `v` repaced by `&v`, because of changes in the language after this answer was posted*. ``` ' ''.:' % pattern string. Will indexed into, twice: first for reading % the input and then for generating the ouput t % duplicate this string j % input string w % swap 4#m % index of ocurrences of input chars in the pattern string qB % subtract 1 and convert to binay. Gives 2-row logical array GnXKq:QKEh1Kq:K+hv! % (painfully) build two-column index for rotation ) % index into logical array to perform the rotation XBQ % transform each row into 1, 2, 3 or 4 ) % index into patter string. Implicitly display ``` [Answer] ## Ruby, ~~166~~ 163 bytes ``` ->s{a=s.tr(f=" .':",t='0-3').chars.map{|x|sprintf('%02b',x).chars}.transpose;a[1]+=[a[0].pop];a[0]=[a[1].shift]+a[0];a.transpose.map{|x|x.join.to_i 2}.join.tr t,f} ``` Yuck... `transpose` is too long. Tricks used here: * `sprintf('%02b',x)` to convert `"0"`, `"1"`, `"2"`, `"3"` into `"00"`, `"01"`, `"10"`, and `"11"` respectively. Surprisingly, the second argument does *not* have to be converted into an integer first. * The rotation is done via `a[1].push a[0].pop;a[0].unshift a[1].shift;`, which I thought was at least a little clever (if not excessively verbose in Ruby). The symmetry is aesthetically nice, anyway :P [Answer] # Javascript ES6 125 bytes ``` q=>(n=[...q].map(a=>(S=` .':`).indexOf(a))).map((a,i)=>(i?n[i-1]&2:n[0]&1&&2)|((I=n[i+1])>-1?I&1:n[i]&2&&1)).map(a=>S[a]).join`` ``` --- I map each character to a two digit binary equivalent ``` : becomes 3 11 ' becomes 2 10 . becomes 1 01 becomes 0 00 ``` and I'm thinking of them as being one on top of the other ``` 3212021 becomes 1101010 1010001 ``` I save that to n For each character (0-3) of n, I check it's neighbors, adding the highest order bit of the left neighbor to the lowest order bit of the right neighbor. if i==0 (first character) I use it's own lower order bit instead of the left neighbor's higher order bit. if n[i+1]>-1 it means we got 0,1,2,3 so when that's false we hit the last element. When that happens I use the character's own highest order bit instead of the right neighbor's lower bit map that back to `.':` land and join that array back together [Answer] # [Common Lisp](http://www.clisp.org/), ~~253~~ 247 bytes ``` (defun R(i &aux(n(length i))(u #1=(make-list n))(b #1#))(dotimes(k n)(setf(elt u k)(find #2=(elt i k)"':")(elt b k)(find #2#".:")))(map'string(lambda(u b)(cond((and u b)#\:)(u #\')(b #\.)(t #\ )))`(,(car b),@(butlast u))`(,@(cdr b),(nth(1- n)u)))) ``` [Try it online!](https://tio.run/##dVTBattAED3XXzHIpDsy8UIMvagEUkIKgZ5seqoLXUvrRFiSVWlV0ot@3X2zsqWNoWuwZt68ffNmrXVa5G19OnFm911Fa87po@neuOLCVi/ulfI45o7md/dcmoNdgu2oArYDNsczO7q8tC0fgHJr3Z5t4aijQ8z7vMpovrr3SA4kUkkU@2wX1OeRBgyp0tSqdU1evXBhyl1m0HgXc3qsMmYDrqTzbeINbZX3sNUxOzwIAr/4llPTgHT7wLvOFQZeO48/cJr5Alfule@WMItCHJ9mMnhtGlNaZxtaONu6ZWpa2y5mRIo5IopIvmLkRMg1cj3lWupqypXnqzFPfH3KEQJJprroJQFfKw/oqYP2lKBngv0QTSaO8jI60JGYPHN0TudZgmkSLKHJY3Kgpb2gmgJFSogGVU1K63AGUkoPnhR26Hfe/fID@PW@99kTIuwMTxnr7A0RDAX@4GP4eCdDGMytLh@xM2aBI5K2wGg4eqijt09DFaEIEagm2TNACAGrAY88W35@CADA5MrTcUwC@RDwgMtLPpudb9r4ohGPoTTHvXMLYs6runOEO9LgJZ4Y8ewDsX2rbepsRrhwcjuu641tO1wyXpNXkbZ@qv2xKQ3UKHoWPOlXn1zf9jdPF7213zjiV2mf/Pj65flb/3nz/fHxabPpf/armwgNsQa7o7GLA/u7M0V9jV/8/K8qp1Tjf0AE/tjmL83VdFzhFQXz9A8 "Common Lisp – Try It Online") Tests included in TIO. ``` (defun R (i &aux (n (length i)) ; take the length of input (u #1=(make-list n)) ; create the top (up) list (b #1#)) ; create the bottom list (dotimes (k.. n) (setf (elt u k) (find #2=(elt i k) "':") ; set the k'th element of the top list to a non-falsey value if k'th element of input is #\' or #\: (elt b k) (find #2# ".:") ; set the k'th element of the bottom list to a non-falsey value if k'th element of input is #\. or #\: (map 'string ; collect the results into a string (lambda (u b) ; for each element of the rotated up and bottom lists (cond ((and u b) #\:) ; if both top and bottom are non-falsey add #\: (u #\') ; if only top is non-falsey add #\' (b #\.) ; if only bottom is non-falsey add #\. (t #\ ))) ; if both are falsey add '#\ ' (#\Space) `(,(car b),@(butlast u)) ; first element of the bottom and the all but last element of the top `(,(cdr b),(nth(1- n)u)))) ; all but first element of the bottom and the last element of the top ``` *Saved 6 bytes using* `#=` *notation for* `(make-list n)` *and* `(elt i k)` [Answer] # JavaScript, 311 bytes Can probably be improved alot: ``` a=(s=prompt()).length-1;o=s[0]==":"||s[0]=="."?s[1]==":"||s[1]=="."?":":"'":s[1]==":"||s[1]=="."?".":" ";for(i=1;i<a;i++)o+=s[i-1]=="'"||s[i-1]==":"?s[i+1]=="."||s[i+1]==":"?":":"'":s[i+1]=="."||s[i+1]==":"?".":" ";alert(o+=s[a]==":"||s[a]=="'"?s[a-1]==":"||s[a-1]=="'"?":":"'":s[a-1]==":"||s[a-1]=="'"?".":" ") ``` [Answer] ## JavaScript (ES6), 237 210 204 188 182 178 bytes *Credit to [@Downgoat](https://codegolf.stackexchange.com/users/40695/downgoat) for saving 16 bytes in the 188-byte revision* *Update: I had a brainwave and reduced the first operation on `s` to a single `map` call instead of two separate ones* ``` s=>(r=" .':",a=[],s=[...s].map(c=>(t=('00'+r.indexOf(c).toString(2)).slice(-2),a.push(t[0]),t[1])),a.splice(0,0,s.shift()),s.push(a.pop()),a.map((v,i)=>r[+('0b'+v+s[i])]).join``) ``` ### Pretty Print & Explanation ``` s => ( r = " .':", // Map of characters to their (numerical) binary representations (e.g. r[0b10] = "'") a = [], // extra array needed // Spread `s` into an array s = [...s].map(c => ( // Map each character to a `0`-padded string representation of a binary number, storing in `t` t = ('00' + r.indexOf(c).toString(2)).slice(-2)), // Put the first character of `t` into `a` a.push(t[0]), // Keep the second character for `s` t[1] )), // Put the first character of `s` in the first index of `a` a.splice(0,0,s.shift()), // Append the last character of `a` to `s` s.push(a.pop(), // Rejoin the characters, alternating from `a` to `s`, representing the rotated matrix, and map them back to their string representation // Use implicit conversion of a binary number string using +'0b<num>' a.map((v,i) => r[+('0b' + v + s[i])]).join`` ) ``` [Answer] ## Perl, ~~144~~ ~~142~~ ~~137~~ 131 bytes ``` y/.':/1-3/;s/./sprintf'%02b ',$&/ge;@a=/\b\d/g;@b=(/\d\b/g,pop@a);@a=(shift@b,@a);say map{substr" .':",oct"0b$a[$_]$b[$_]",1}0..@a ``` Byte added for the `-n` flag. Pretty much the same algorithm as [my Ruby answer](https://codegolf.stackexchange.com/a/75303/3808), just shorter, because... Perl. ``` y/.':/1-3/; # transliterate [ .':] to [0123] s/./sprintf'%02b ',$&/ge; # convert each digit to 2-digit binary @a=/\b\d/g; # grab the 1st digit of each pair @b=(/\d\b/g, # 2nd digit of each pair pop@a); # push the last element of a to b @a=(shift@b,@a); # unshift the first element of b to a say # output... map{ # map over indices of a/b substr" .':",oct"0b$a[$_]$b[$_]",1 # convert back from binary, find right char }0..@a # @a is length of a ``` Obnoxiously, `@a=(shift@b,@a)` is shorter than `unshift@a,shift@b`. Alas, these are the same length: ``` y/ .':/0-3/;s/./sprintf'%02b ',$&/ge; s/./sprintf'%02b ',index" .':",$&/ge; ``` Thanks to [Ton Hospel](https://codegolf.stackexchange.com/users/51507/ton-hospel) for 5 bytes and [msh210](https://codegolf.stackexchange.com/users/1976/msh210) for a byte! [Answer] # [Vyxal](https://github.com/Lyxal/Vyxal), 44 bytes ``` f`:'. `f⁺↑b2ẇĿ2ẇÞT÷ḣ„ṫ$„p‟JWÞT⁺↑b2ẇ`:'. `fĿ∑ ``` [Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=f%60%3A%27.%20%60f%E2%81%BA%E2%86%91b2%E1%BA%87%C4%BF2%E1%BA%87%C3%9ET%C3%B7%E1%B8%A3%E2%80%9E%E1%B9%AB%24%E2%80%9Ep%E2%80%9FJW%C3%9ET%E2%81%BA%E2%86%91b2%E1%BA%87%60%3A%27.%20%60f%C4%BF%E2%88%91&inputs=%27%3A..%3A%5C%27.%27&header=&footer=) Yuck. [Answer] # [Python 3](https://docs.python.org/3/), 124 bytes ``` def f(a,s=" .':",j="".join):q=j(bin(4+s.find(i))for i in a);return j(s[int(j(x),2)]for x in zip(q[4]+q[3::5],q[9::5]+q[-2])) ``` [Try it online!](https://tio.run/##TVK7bsMwDJybryC0UEJUDkk6RIW/xPCQIjYqD05sq0Dan3dJUUorAyHv@Lizo/t3@rxNx2279gMM9uLXxgBhMH5sjKHxFicX5ma0H3Gyp/1KQ5yuNjo33BaIECe4uPelT1/LBKNd2zglO9qH8wfXSctDWn7i3c7tqdvP7TGEt87P7Vki49dD59yW@jWtAE27a1ndeDAEpvOMODLCgjAjQEUcBZGioJ2lhloLpZZ3BqwIFZZJIi1XzcBjsiqUOuo41XlJpL9uBz5ZTaJu4JNbJBZNEr3MEdRNEADKNgIkevoFRCoukLvpz2k@ajeff4rVB6c8Vb0IW/1wyj6qJ1bXR/U1r@@I9ckmnrD6AJFjAsqn5b2smfFzgzRIG1MEMqEUp0yj8vrv8iQDfk3MrfxJhMop08qbrtvJjUq@lzuVr0zYvdwXuXKDTc6D/ELTQO@2Xw "Python 3 – Try It Online") ## How it works : * `q="".join(bin(4+s.find(i))for i in a)` store an unpacked version of our starting string `a` by using binary conversion If `a` is equal to ``` ABCD EFGH ``` then `q` is equal to `---ae---bf---cg---dh` with a to h equal to `"1"` if there is a dot in the corresponding emplacement and `"0"` otherwise (and `---` equal to `0b1`) * `zip(q[4]+q[3::5],q[9::5]+q[-2])` reshapes `q` to have : `(eabcd),(fghd)` (the last `d` in the first part is ignored since the second part is shorter) * `s[int("".join(x),2)]` reverse the process converting back the binary number into their dot version. Result : ``` EABC FGHD ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 41 bytes ``` Â)εS„':„.:‚Nès夈¨}R¯øí˜2äćR¸ìζJC" '.:"sè ``` [Try it online!](https://tio.run/##yy9OTMpM/f//cJPmua3BjxrmqVsBCT0gMcvv8Iriw0sPLTnddmhFbdCh9Yd3HF57eo7R4SVH2oMO7Ti85tw2L2clBXU9K6Xiwyv@e/3XU1cA8awUFKz01PUU9BSsrCBCQCZQWB0iDgA "05AB1E – Try It Online") Outputs as a list of characters. Link includes a footer to format the output. ``` Â)εS„':„.:‚Nès夈¨}R¯øí˜2äćR¸ìζJC"..."sè # trimmed program è # push character... # (implicit) s... è # in... "..."s # literal... è # at... s # (implicit) indices in... ζ # list of elements with same indices in each element of... ¸ # list of... ć # first element of... ) # list of...  # implicit input... ) # and... # implicit input...  # reversed... ε # with each element replaced by... å¤ # is... s # (implicit) each element of... S # list of characters of... # (implicit) current element in map... å # in... ès # element in... ‚ # list of... „': # literal... ‚ # and... „.: # literal... è # at index... N # current index in map... ¨ # excluding the last element... ˆ # and append... ¤ # last element of... å¤ # is... s # (implicit) each element of... S # list of characters of... # (implicit) current element in map... å # in... ès # element in... ‚ # list of... „': # literal... ‚ # and... „.: # literal... è # at index... N # current index in map... ˆ # to global array... R # reversed... í # with... ¯ # global array... ø # with each element paired with corresponding element in... ¯ # global array... í # prepended... ˜ # flattened... ä # split into... 2 # literal... ä # equal pieces... R # reversed... ì # with... ) # list of...  # implicit input... ) # and... # implicit input...  # reversed... ε # with each element replaced by... å¤ # is... s # (implicit) each element of... S # list of characters of... # (implicit) current element in map... å # in... ès # element in... ‚ # list of... „': # literal... ‚ # and... „.: # literal... è # at index... N # current index in map... ¨ # excluding the last element... ˆ # and append... ¤ # last element of... å¤ # is... s # (implicit) each element of... S # list of characters of... # (implicit) current element in map... å # in... ès # element in... ‚ # list of... „': # literal... ‚ # and... „.: # literal... è # at index... N # current index in map... ˆ # to global array... R # reversed... í # with... ¯ # global array... ø # with each element paired with corresponding element in... ¯ # global array... í # prepended... ˜ # flattened... ä # split into... 2 # literal... ä # equal pieces... ć # excluding the first element... ì # prepended... # (implicit) with each element... J # joined... # (implicit) with each element... C # converted from binary to decimal ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~105~~ 104 bytes ``` s=" .':" a=[*map(s.find,input())] b=a[0]*2,*a,a[-1]//2 print(*map(lambda x,y:s[x&2|y&1],b,b[2:]),sep='') ``` [Try it online!](https://tio.run/##HctLCsMgEADQvaeQLOKHqWnsbsCTiIuRtFRorEQLEXp3C337V3p7vvNtjOombgROjJzXOxVZzSPlDVIunyaVCiw68tegLWgC8pc1LItl5Ui5yX940R434id0rP6c7bfPa4AI0VsMCuq9OCHUGByNQWG44QLHDw "Python 3 – Try It Online") [Answer] # Python 3, ~~294~~ ~~287~~ 283 bytes Waaayyyyyy too long, but I will try to golf of some bytes: ``` z=input() x=len(z) M=[0,1,2,3] for Q in M:z=z.replace(":'. "[Q],"11100100"[Q*2:Q*2+2]) a=[] b=[] for X in range(x):a+=[z[X*2]];b+=[z[X*2+1]] b=b[1:]+[a.pop()] c=[b[0]]+a z="" for X in range(len(c)): y=c[X]+b[X] for Q in M:y=y.replace("11100100"[Q*2:Q*2+2],":'. "[Q]) z+=y print(z) ``` [Answer] ## Lua, 139 bytes ``` print(((...):gsub(".",{[" "]="NN@",["."]="YN@",["'"]="NY@",[":"]="YY@"}):gsub("(.)@(.?)","%2%1"):gsub("..",{NN=" ",NY=".",YN="'",YY=":"}))) ``` Usage: ``` $ lua conveyor.lua ".' '.:: :.'. . ::.' '. . .::' :.'." ' ' .:.''..'.'. ..:' ' .'. ...'''..'.' ``` [Answer] # Excel, 139 bytes ``` =LET(e,LEN(A1),q,SEQUENCE(e),x,CODE(MID(A1,q,1))-32,l,x>7,u,x>l*14,CONCAT(MID(" '.:",IF(q=1,l,INDEX(u,q-1))+IF(q=e,u,INDEX(l,q+1))*2+1,1))) ``` [Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnD_4qim2waVo0S2j?e=ghmLxp) ## How it works ``` =LET( *Assignments* e,LEN(A1), 'e = length of A1 q,SEQUENCE(e), 'q = (1 .. e) x,CODE(MID(A1,q,1))-32, 'x = list of ASCII codes of each character - 32 l,x>7, 'l = array of lower numbers = 1 if x>7 (.:) u,x>l*14, 'u = array of upper numbers = 1 if x>l*14 (':) *Result* IF(q=1,l,INDEX(u,q-1)) + 'String indices = if q = 1 then l[1] else u[q-1] IF(q=e,u,INDEX(l,q+1))*2+1 ' + (if q=e then u[e] else l[q+1]) * 2 + 1 CONCAT(MID(" '.:",~,1))) 'Concatenate all the results ``` [Answer] # [J](http://jsoftware.com/), 55 bytes ``` ' .'':'&([{~([:g@($$_1|.,)g=.|.@{:1}_2{.])&.(|:@#:)@i.) ``` [Try it online!](https://tio.run/##VVJBasMwELz7FUsbIguSoelxIWAI9JRTriHkEJq0vfQBdvt1Z3dtadeyDNJoNDs79s/4gnSnPVOiDb0Ry7sFHU7HjzERUuK0bs/9f3vmR9euVtfdgE1@7DGg63n3d33vcclrtAN3r5y7b@QxN83n7etXFGVume62mjE4hoKlVEFUosETqOcFRb0ucL3vXHYq@33ncqAigAiok90tEOyys6VK6Yyj4yDuRoxSw4nxeEAso6rruuKghXmYa49VLHol@ZAUq1lCeiE4VwzuXxR1xI5tBGOm4rbVXrQuS3Hl9vUstiDF7PEuZsA/mrYUZ/GyxD1awDxBu4PrahRizcjEix9NyMbUKEyOLEmaVHSH6YeZz4MFE1RdnphSo6CygeYzn6VmfAI "J – Try It Online") ]
[Question] [ The gravitational force is a force that attracts any two objects with mass. In this challenge our objects will be Numbers and their mass will be their value. To do so, we don't care about the strength of the force but the direction of it. Imagine this set of numbers ``` [1 6 9 4 6 9 7 6 4 4 9 8 7] ``` Each of them creates a force between itself and it's adjacent numbers. Under some conditions, this will cause another number to be attracted (moved) toward a number. When the number is bigger than the adjacent, it attracts it. Lets take a look at our previous example: ``` [1 → 6 → 9 ← 4 6 → 9 ← 7 ← 6 ← 4 4 → 9 ← 8 ← 7] ``` The number `1` is not big enough to move `6`, but the number `6` is, etc... Basically, numbers are moved to the biggest adjacent number (also bigger than the number itself). If both of the adjacent numbers are equal it is not attracted then. It also happens when the number and it adjacent are equal. This is only to show the attraction, but what happens after? Numbers that collide due to attraction are summed up: ``` [20 32 28] ``` So basically the challenge is, Given a set of numbers, output the result of the attracted set of numbers. --- **Example 1** ``` Input => [10 15 20 10 20 10 10] [10 → 15 → 20 10 20 ← 10 10] Output => [45 10 30 10] ``` **Example 2** ``` Input => [9 9 9 9 8 1 8] [9 9 9 9 ← 8 1 8] Output => [9 9 9 17 1 8] ``` **Example 3** ``` Input => [1 6 9 4 6 9 7 6 4 4 9 8 7] [1 → 6 → 9 ← 4 6 → 9 ← 7 ← 6 ← 4 4 → 9 ← 8 ← 7] Output => [20 32 28] ``` **Example 4** ``` Input => [1 2 3 2 1] [1 → 2 → 3 ← 2 ← 1] Output => [9] ``` **Example 5** ``` Input => [1] Output => [1] ``` **Example 6** ``` Input => [1 1] Output => [1 1] ``` **Example 7** ``` Input => [2 1 4] Output => [2 5] ``` --- ## Notes * Attraction only happens once * Numbers are not attracted to non-adjacent Numbers * The set of numbers will only contain positive integers [Answer] # JavaScript (ES6), ~~106 104~~ 100 bytes *Saved 2 bytes thanks to @Shaggy* ``` a=>a.filter(n=>n,[...a].map((v,i)=>a[a[p>v&(n=~~a[i+1])<p?k:i+(k=i,n>v&p<n)]+=x=a[i],p=v,i]-=x,p=0)) ``` [Try it online!](https://tio.run/##fY9Rb4MgFIXf9yt4WiDeUq7VaZfifgjhgXS6sDokbWP61L/urm7plurGCSckh@8eeHe9O@2PPp5XoXuth0YPTldONr4910cedBXASCmdlR8uct6DF5QbZ2LVP1J@vTrjE7RiF18Ozz7hB@0hUBZ3QdhEXzTlFqIm0q70hU5KiGHfhVPX1rLt3njDDSrAHFJy9e2orBBsWus1M1nOULGNIrcPd/AWvlQCQnmj2A@8ZaOwYMjKGY3wRGw2eUGekcZZxThppFPqTVm6RKawoY33nbfeObJ09TeCCy3/QBPC5hA9CrK/sOlTLLfDJw "JavaScript (Node.js) – Try It Online") ### Commented We first update the original input array `a[]` by iterating on a copy of it. During this step, all values 'attracted' by other ones are set to \$0\$. Because the array is parsed from left to right, we can just add \$a\_i\$ to \$a\_{i+1}\$ whenever a value is attracted by its right neighbor. Example: \$4\rightarrow5\rightarrow6\$ is turned into \$[0,\color{red}9,6]\$ and then \$[0,0,\color{red}{15}]\$. But when several values in a row are attracted by their left neighbor, we need to add \$a\_i\$ to the first attractor \$a\_k\$ of this sequence (with \$k<i\$) rather than simply \$a\_{i-1}\$. Example: \$6\leftarrow5\leftarrow4\$ is turned into \$[\color{red}{11},0,4]\$ and then \$[\color{red}{15},0,0]\$. ``` [...a] // create a copy of a[] .map((v, i) => // for each value v in a[] at position i: a[ // this statement updates a[i]: a[ // this statement updates either a[i] or an adjacent value: p > v & // if the previous value p is greater than v (n = ~~a[i + 1]) // and the next value n < p ? // is less than p (attraction to the left): k // use k (k is initially undefined, but this code cannot // be triggered during the first iteration) : // else: i + ( // use either i or i + 1: k = i, // set k to i n > v & // use i + 1 if n is greater than v p < n // and p is less than n (attraction to the right) ) // ] += x = a[i], // add x = a[i] to the entry defined above p = v, // update the previous value to v i // actual index to update a[i] ] -= x, // subtract x from a[i] p = 0 // start with p = 0 ) // end of map() ``` We then filter out all entries equal to \$0\$. ``` a.filter(n => n) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~27~~ ~~25~~ ~~23~~ 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` «╥╦.ê§┘h!@ÆEÿ☺╜╫♥B ``` [Run and debug it](https://staxlang.xyz/#p=aed2cb2e8815d968214092459801bdd70342&i=[1+6+9+4+6+9+7+6+4+4+9+8+7]%0A[10+15+20+10+20+10+10]%0A[9+9+9+9+8+1+8]%0A[1+6+9+4+6+9+7+6+4+4+9+8+7]%0A[1+2+3+2+1]%0A[1]%0A[1+1]%0A[2+1+4]&a=1&m=2) Output is separated by newlines. This program operates on adjacent pairs in the array, and determines whether there should be a split between them using this procedure. Consider some arbitrary input `[... w x y z ...]`. Here is how to determine if there should be a split between `x` and `y`. * If `x == y`, then yes. * If `x > y`, then iff `z >= x`. * If `y > x`, then iff `w >= y`. The summing is left as an exercise. [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 64 bytes ``` \d+ $* (?<=(1+)) ((?=(1+\1))(?<!\3 \1 )|(?!\1)(?!1+ \1)) 1+ $.& ``` [Try it online!](https://tio.run/##fYuxCgIxEET7/Yo5UNk1IJm700tASelPpFDQwsZCLP33uKfW8tjHMMs8rs/b/dyWejy1egmyWIuW/UEZzKBa5lRp5mVXB1TCXlo6r9wMmH8i9OFm1RqxQ8b48eQenYyESRjBLXp3/JlRMr4kEEn@jNFj8KM44Bs "Retina 0.8.2 – Try It Online") Link includes test suite. Explanation: ``` \d+ $* ``` Convert to unary. ``` (?<=(1+)) ((?=(1+\1))(?<!\3 \1 )|(?!\1)(?!1+ \1)) ``` Remove the separators between attracted numbers. `(?<=(1+))` sets `\1` to the number before the separator. After the separator, there are then two cases: * The number after the separator is greater than both of the numbers before the separator * The number before the the separator is greater than both of the numbers after the separator In these cases there is an attraction between the two numbers and deleting the separator causes the numbers to collide, adding them together. ``` 1+ $.& ``` Convert to decimal. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 23 bytes ``` Ø0jMÆmær0Ʋ3Ƥ×=4$o<ʋƝk⁸§ ``` [Try it online!](https://tio.run/##y0rNyan8///wDIMs38NtuYeXFRkc22R8bMnh6bYmKvk2p7qPzc1@1Ljj0PL/1o8a5ijo2ik8aphr/XDHprDD7d7HNnE93L3lcPujpjWR//8bGigYmioYAUkDKGlowGWpAIEWCoYKFlyGCmZAtgmYNAeSJkAIkjMHyhgpGAOxIZAFxAA "Jelly – Try It Online") A monadic link which takes a list of integers as its argument and returns a list of integers. ### Explanation ``` Ø0j | Join [0, 0] with input list Ʋ3Ƥ | For each length 3 infix, do the following as a monad: M | - Indices of maximum Æm | - Mean ær0 | - Round to even (so the means of [1, 2, 3], [1, 2], [2, 3] and [1, 3] will all round to 2 ʋƝ | For each neighbouring pair, do the following as a dyad: × | - Multiply =4$ | - Check if equal to 4 o | - Or < | - First number less than second k⁸ | Split input after truthy values of the above § | Sum, vectorised ``` Some inspiration taken from [@recursive’s Stax answer](https://codegolf.stackexchange.com/a/185858/42248). [Answer] # [C (gcc)](https://gcc.gnu.org/), 111 bytes ``` a,b,c,s;P(){s=!printf("%d ",s);}f(int*v){for(b=s=0,c=*v;a=b,b=c;a<b|b<a&c<a||P(),s+=b,b<c&c<=a|!c&&P())c=*++v;} ``` [Try it online!](https://tio.run/##dU1LTsMwEF3TU0wjEdnNICUlUJDjO7AHFva0QVmQojryJvHZw9hVVAkRaX5@P9PDF9E8G7RI6NSbkKPT259L1w@tyO6PkKGTKrSCgZ2XY3u@CKudLpH0ziujLVpNyjR2so3JqTHTxCHoisg0xIg205bynFHJnqLwKsz@3B1hOLkh5gIHwwit8FLB8vVHn/ErbJLy23S9YM3mLnmi6f1TjlCVCNUTwj7u8rZjlxCk@mt4xVu9sC7Nf5VMPSdZvRyHdNSprvbDuneP8Jhmta5Zw9eoa1q9sGH@BQ "C (gcc) – Try It Online") Takes a zero-terminated array of integers. ### Explanation ``` a,b,c, // Three consecutive elements of input array s; // Accumulator for sum P(){s=!printf("%d ",s);} // Print and clear s f(int*v){ for( // Init b=s=0, c=*v; // Loop test a=b, // Shift b into a b=c; // Shift c into b, exit if zero // Post loop a<b|b<a&c<a||P(), // Print if a==b || (b<a && a<=c) s+=b, // Accumulate b<c&c<=a|!c&&P() // Print if c==0 || (b<c && c<=a) ) // Loop body c=*++v; // Read next number into c } ``` [Answer] # [Python 2](https://docs.python.org/2/), 162 bytes ``` l=input() a=[(L<R>C)-(R<L>C)for L,C,R in zip([0]+l,l,l[1:]+[0])] while any(a): i=0 while a[i]==0:i+=1 m=a.pop(i);x,y=[i,i+m][::m];l[x:y+1]=l[i]+l[i+m], print l ``` [Try it online!](https://tio.run/##NYu9DoMwDIT3PIXHRHErqFB/Au7CysQaZWBohaUQIkRV6MvTCLXyyffdWY7r3I/htG2eOMTXLJXoyMqmau@1Osi2apI/xwkarLEFDvDhKG3mtMc0NjdOp6ScePfsH9CFVXbKCGDKBPw6y44oM6wpFzBQd4xjlKzKBVeyjKwHZ40ZXOntYladO/LpRaeVLijixGEGv202Rzgj3BCKP1x2KHaleE2N@wI "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), 45 bytes ``` +//.~0,[:+/\2(<+.1=*)/\3(>./1:/@I.@E.])\0,,&0 ``` [Try it online!](https://tio.run/##NYzBDoIwEETvfsXEg4CUttuCQCOGxGhi4smreDIS48U/8NfrlkImO5tO387Hr2UyonNIIKDheAqJ4@169rlS8qfF3eVqMOk@l9RtMzXY9CAVOdVfZH@Sj2zQQmy0z1av5/uLsgJpWB28cBjDpgpmCqKTjmg7iWoQmsi2s5oQRYhPrIGZAcKOv8vJa/aSFfB6aewmyMDyUAwphsuDlqY5Mahiwgfc5v8 "J – Try It Online") Inspired by recursive's original Stax answer [Answer] # [R](https://www.r-project.org/), ~~222~~ ~~196~~ 173 bytes Here is a solution with some help from [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder) ``` n=length(d<-diff(y<-x<-scan()));l=c(1,sign(d[-n]+d[-1]),-1);m=!!l*n&c(d[1]>0,d[-1]>0|d[-n]<0,d[n]<0);for(t in 1:n){for(i in which(m))y[a]=y[a<-i+l[i]]+x[i];y=x=y-x*m};x[!m] ``` [Try it online!](https://tio.run/##LYvLCsMgEEX3/QqzKWMSQQtdqfkRcRHMSzAWkkKVtt9uJ6Gbc5l77mylRB3GOD8XGBQb/DRBViwptrs@AqVUBu1AtLufIwyGRdsghaUtE1SuuqpCHa8OlbAdb0/X8c@5VMd9BJWvxYcR1j5BqldK39NjA098JCjcAlhl01uNUMw3wXhrm4SUWSedGT59ZTKp47YITsSd3JD8T8HL5Qc "R – Try It Online") A short set of comments ``` n=length(d<-diff(y<-x<-scan())); #read input and compute pairwise differences #d[-n]+d[-1]: compare left and right differences l=c(1,sign(d[-n]+d[-1]),-1) #direction of attraction m=!!l*n& #indices of attracted numbers c(d[1]>0,d[-1]>0|d[-n]<0,d[n]<0) #!!l*n eliminates zeroes in l & the case n==0 for(t in 1:n){ #excessive loop on transfers for(i in which(m)) y[a]=y[a<-i+l[i]]+x[i] #transfer right vs. left y=x=y-m*x} #complete transfer x[!m] #output ``` [Answer] ## Python, ~~114~~ 112 bytes ``` lambda a:eval('['+'+'.join(str(c)+',0'*((e<c>d)==(c<d>b))for b,c,d,e in zip([0]+a,a,a[1:]+[0],a[2:]+[0,0]))+']') ``` This uses the fact that the direction of the arrow doesn't actually matter, and that the presence of an arrow between a[i] and a[i+1] can be determined by looking at the range of four elements a[i-1:i+3]. Edit: Thank you to Jo King for the rule clarification [Answer] # [Perl 5](https://www.perl.org/), ~~156~~ 147 bytes ``` $q='$F[$i';map{eval"\$i++while$q]$\_"}"<$q+1]",">$q+1]&&$q]>$q+2]&&\$i<\@F"if eval"$q-1]-$q+1]||$q]>$q+1]";$\.=$".sum@F[$p..$i];($p=++$i)<@F&&redo}{ ``` [Try it online!](https://tio.run/##LY3LDoIwEEV/hTSToqltWhM2PAwrVrp0JcSQWOMkIOWhLoBft1bC5s5J5twZo7sqsBbaxIfsAuhHdWlG/S4rkgMy9nlgpaEt4EpmEkPLVEF25LAApW7xx71DZ8d5mhG8e0sbWq4KvnjTtHquG0EuEiCif9Wp@2eEACyiDZiEMcBtnGaUdvrWzKO1Snoq8PYu5ZpKfhszYPPsLT8FQirp5hH7IQzPA1aJu2p5aX4 "Perl 5 – Try It Online") [Answer] # [Clojure](https://clojure.org/), ~~299~~ 252 bytes ``` (fn[l](loop[o[0]m(vec(map-indexed(fn[i v](def f #(max(nth l(+ % i)0)v))(-(f -1)(f 1)))l))i 0](defn f[x](update o(-(count o)x)#(+(l i)%)))(cond(<=(count m)i)(pop o)(>(m i)0)(recur(f 2)m(inc i))(<(m i)0)(recur(f 1)m(inc i))1(recur(conj(f 1)0)m(inc i))))) ``` [Try it online!](https://tio.run/##5ZBBasMwEEX3OcVACMxQApLjNClNe4kujRfBlomCLAljBd/eHcuBQOT0ApXwLOb/efqeyrhr6NQ4YmMLU6JxzheuEGWLN1Vhe/ZbbWs1qHoyaLiVWKsGGlizNqDtL2DwDTagSdCNCLfYwFYSV0lEhkiDiDMWmmIoMfj63CtwbKxcsD04GmiNb2gYseERbtsaT193uSVN6J1nH35jG9/BTlWh4ycyalHbipuEp2dRPkR5bzL6GhXx0PiM8z8FC/95C7RardB32vZmWgRvo5AC5B4yruJepSiJYD6f8HNxwdTgQu9DD0W@nyy76HpGfcB8jyDh@GC8Qs1meYjuJBa8s5jHeuCa853Ih8hNWJx8l0G2xMlgx59M8ixnSgGLgy8BciHBX4gUACmC40P@EpIuA/bl@As "Clojure – Try It Online") --- ### Explanation: ``` (fn [l] (loop [o [0] m (vec(map-indexed (fn [i v] ; This maps each element l[i] of l to max(l[i-1], l[i]) - max(l[i+1], l[i]) (def f #(max (nth l (+ % i) 0) v)) (- (f -1) (f 1))) l)) ; l[x] is zero when l[x] is out of bounds of the input vector l i 0] (defn f [x] (update o (- (count o) x) #(+ (l i) %))) ; Defines a function f(x) that returns the result of mapping the (x-1)th to last element of o over the function g(y) = l[i] + y (cond (<= (count m) i) (pop o) ; If the length of m is less than or equal to i, there are no more elements in m, so return all but the last element of o (> (m i) 0) (recur (f 2) m (inc i)) ; If m[i] is positive, l[i] is pulled toward to the previous element, so add l[i] to the 2nd to last element of o (< (m i) 0) (recur (f 1) m (inc i)) ; If m[i] is negative, l[i] is pulled toward the next element, so add l[i] to the last element of o 1 (recur (conj (f 1) 0) m (inc i))))) ; 1 is truthy ; If the length of l is less than or equal to i, and m[i] is not positive or negative, we have m[i] = 0, so l[i] is not pulled toward any other element ``` [Answer] # [K (ngn/k)](https://codeberg.org/ngn/k), 47 bytes ``` {+/'x@.={x x}/(!#x)+{-/2=+/x<\:x 2 0}'3':0,x,0} ``` [Try it online!](https://ngn.bitbucket.io/k#eJwtjN0KgkAQhe/3KSYKTNzaX1N3E3oPW7AbIQoC8WJEtmdvVmM4h+8wZ2ZwSyEyvJ3bBQGjOO72mBfLSei2EHi9OwQNMmYmc5Ijl5GxyS2Hbv6ObgD0/eflj/3weL49+tmPeYhs6pQEVYIml39XMtgygUlMlQa2qUFBHTZWVQrpHi4U7eoVuaVJ1SrQN6NBbyUNhqQ8bwJlTqDCulCBRERLsEFDyX5mtzXC) `0,x,0` surround the argument with 0s `3':` triplets of consecutive items `{` `}'` for each do `x 2 0` get last and first of the current triplet - `x[2]` and `x[0]`. they are the neighbours of `x[1]`, on which the triplet is centred `x<\:` compare using less-than against each of the current triplet `+/` sum. the result is a pair corresponding to `x[2]` and `x[0]` `2=` check if either neighbour is greater than the other 2 elements from `x`, return a pair of 0-or-1 booleans `-/` subtract them. a result of -1 means `x[1]` is attracted to the left, 1 to the right, and 0 means it stays in place `(!#x)+` add 0 to the first item, 1 to the second, etc. this computes the indices towards which items are attracted `{x x}/` index with itself until convergence. the result are the effective indices to which each item is ultimately attracted `x@.=` group `x` (the original argument) by those. the result is a list of lists `+/'` sum each [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~52~~ 51 bytes ``` {+/(⊃∘⍵¨⊢)⌸{⍵[⍵]}⍣≡(⍳≢⍵)+{-/2=+⌿⍵∘.<1↓1⌽⍵}¨3,/∊0⍵0} ``` [Try it online!](https://tio.run/##LU1NS4VAFN3Pr5idipozjmYv6pdECzEsSTDUTYirQt4zfRQRtO21ebsWEUQQgT/l/hE7U48798w9536c@Cp3z67jvDh3kzyuqiyZaf2UFdTdi7mxPZP6G1o@0/gxbanfWDR8NiAnyNOWxldavZg0vtNqA8WyG9fzj20afsCwtnckqXuUNHyDt9NWOR4tewEi2jmFB41rGExviroH@FZlAqwvsmqu0dVOuFyiTGn8OjTSOMsNVNBLurs1ikujZVJwGXIfKHaIV/Mg1L/SjC34fxxwiax3TEaaMsn3QYI/jIABQo9GGMQ95XNfD/lcISVEZ8FMR1ooJHStAJnuBXqFh8z9BQ "APL (Dyalog Classic) – Try It Online") translation of [my k answer](https://codegolf.stackexchange.com/a/185980/24908) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 21 bytes ``` 0.øŒ3ùεZQXsÂU‚ÆZ≠}Å¡O ``` [Try it online!](https://tio.run/##yy9OTMpM/f/fQO/wjqOTjA/vPLc1KjCi@HBT6KOGWYfboh51Lqg93Hpoof///9GGBjqGpjpGQNIAShoaxP7X1c3L181JrKoEAA "05AB1E – Try It Online") ]
[Question] [ I love programming and know every language, but I suck at math. Unfortunately, my school requires that computers students must take a year of calculus. There's a test next week, and I don't know any of the formulas for derivatives! Please help me find the formulas. I need a cheat sheet - a program (as short as possible so my teacher won't notice it) that takes an expression (like `4*x^3-2`) as input and outputs the derivative. (I don't care if the input and output uses command line arguments, STDIN, STDOUT, or whatever, since I'm doing all of the calculation in my head anyway.) The test covers the following types of functions: * Constants, like `-3` or `8.5` * Power functions, like `x^0.5` or `x^-7` * Exponential functions, like `0.5^x` or `7^x` (the base is always positive) * A constant multiplied by a function, like `3*x^5` or `-0.1*0.3^x` * The sum and difference of multiple functions, like `-5*x^2+10-3^x` My teacher always formats his questions in the exact same way, as shown above. He also doesn't use any fractions, numbers like pi or *e*, or really big numbers (bigger than 1,000). He never uses parentheses, and always shows multiplication using an asterisk (`*`). The only variable used is always *x*. On the other hand, my teacher is pretty lenient about answers. They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying. While I can use any language, remember that I can't figure out derivatives by myself. So if the program uses built-in functions to deal with equations or calculate derivatives, I won't be able to use it. During the test, I won't have access to the Internet or any files other than the program on the cheat sheet. *Note: This scenario is entirely fictional. In real life, cheating and helping others cheat is wrong and should never be done.* [Answer] # Perl - 121 ~~122~~ (+2 for `-p`) ``` s/(?<![-\d.*^])-?[\d.]+(?![*^\d.])/0/g;s/(?<!\^)x(?!\^)/1/g;s/x\^(-?[\d.]+)/"$1*x^".($1-1)/ge;s/([\d.]+)\^x/ln($1)*$&/g ``` Test: ``` $ perl -p diff.pl << EOF > -3 > 8.5 > x^0.5 > x^-7 > 0.5^x > 7^x > 3*x^5 > -0.1*0.3^x > -5*x^2+10-3^x > EOF 0 0 0.5*x^-0.5 -7*x^-8 ln(0.5)*0.5^x ln(7)*7^x 3*5*x^4 -0.1*ln(0.3)*0.3^x -5*2*x^1+0-ln(3)*3^x ``` [Answer] ## Wolfram 136 134 109[Thanks to Calle for his comment below] Limited support for product and chain rules. ``` n=n_?NumberQ;d[v_Plus]:=d/@v;d[v_]:=v/.{x_^n:>x^(n-1)d[x]n,n^x_:>Log[n]d[x]n^x,x_*y__:>d[x]y+d[y]x,n:>0,x:>1} ``` Example: ``` d[3^(x^2)*(x^3+2*x)^2] >> 2*3^x^2*(2+3*x^2)*(2*x+x^3) + 2*3^x^2*x*(2*x+x^3)^2*Log[3] ``` Note that this does not use any "built-in functions to deal with equations or calculate derivatives": only pattern-matching is involved\*. [\*Well... technically the interpreter also parses and builds a sort of AST from the input too] --- Ungolfed: ``` d[expr_Plus] := d /@ expr; d[expr_] := expr /. { Power[x_, n_?NumberQ] :> n Power[x, n - 1] d[x], Power[n_?NumberQ, x_] :> Log[n] Power[n, x] d[x], Times[x_, y__] :> d[x] y + d[y] x, n_?NumberQ :> 0, x :> 1 } ``` [Answer] ## Haskell 38 Chars The function `d` takes a function and returns a function. It is inputted in the form of a [power series](http://en.wikipedia.org/wiki/Power_series), and is outputted the same way (which is a type of whatever.) ``` d=zipWith(*)[1..].tail ``` For example, if we input `x->x^2`, we get `x->2*x`. ``` λ <Prelude>: d [0,0,1] [0,2] ``` And for the exponential function. ``` λ <Prelude>: take 10 exp --exp redefined above to be in power series notation [1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6] λ <Prelude>: let d=zipWith(*)[1..].tail in take 10 $ d exp [1.0,1.0,0.5,0.16666666666666666,4.1666666666666664e-2,8.333333333333333e-3,1.388888888888889e-3,1.984126984126984e-4,2.48015873015873e-5,2.7557319223985893e-6] ``` [Answer] ## Prolog 176 ``` d(N,0):-number(N). d(x,1). d(-L,-E):-d(L,E). d(L+R,E+F):-d(L,E),d(R,F). d(L-R,E-F):-d(L,E),d(R,F). d(L*R,E*R+L*F):-d(L,E),d(R,F). d(L^R,E*R*L^(R-1)+ln(L)*F*L^R):-d(L,E),d(R,F). ``` Supported operators: binary `+`, binary `-`, binary `*`, binary `^`, unary `-`. Note that unary `+` is not supported. Sample run: ``` 49 ?- d(-3,O). O = 0. 50 ?- d(8.5,O). O = 0. 51 ?- d(x^0.5,O). O = 1*0.5*x^ (0.5-1)+ln(x)*0*x^0.5. 52 ?- d(x^-7,O). ERROR: Syntax error: Operator expected ERROR: d(x ERROR: ** here ** ERROR: ^-7,O) . 52 ?- d(x^ -7,O). O = 1* -7*x^ (-7-1)+ln(x)*0*x^ -7. 53 ?- d(x,O). O = 1. 54 ?- d(0.5^x,O). O = 0*x*0.5^ (x-1)+ln(0.5)*1*0.5^x. 55 ?- d(7^x,O). O = 0*x*7^ (x-1)+ln(7)*1*7^x. 56 ?- d(3*x^5,O). O = 0*x^5+3* (1*5*x^ (5-1)+ln(x)*0*x^5). 57 ?- d(-0.1*0.3^x,O). O = 0*0.3^x+ -0.1* (0*x*0.3^ (x-1)+ln(0.3)*1*0.3^x). 58 ?- d(-5*x^2+10-3^x,O). O = 0*x^2+ -5* (1*2*x^ (2-1)+ln(x)*0*x^2)+0- (0*x*3^ (x-1)+ln(3)*1*3^x). ``` Prolog is confused when it runs into `^-` sequence. A space must be inserted between `^` and `-` for it to parse the expression correctly. Hope your teacher doesn't mind the mess of equation. Crazy time: ``` 59 ?- d(x^x,O). O = 1*x*x^ (x-1)+ln(x)*1*x^x. 60 ?- d((x^2-x+1)*4^ -x,O). O = (1*2*x^ (2-1)+ln(x)*0*x^2-1+0)*4^ -x+ (x^2-x+1)* (0* -x*4^ (-x-1)+ln(4)* - 1*4^ -x). ``` [Answer] # C, 260 248 bytes −12 bytes thanks to **ceilingcat** Hey, I think I know your teacher! Isn't it that one who has the supernatural ability to detect students executing library pattern-matching functions in their head? So, using `sscanf` is out of question... But don't worry: ``` #define P,s--||printf( q=94,s,c,t;main(a){char*p,i[999],*e=p=i;for(gets(i);q=c=*p++,t=q^94|c^45?c%26-16?c/46:c%16/3:1,s=(a="30PCqspP#!C@ #cS` #!cpp#q"[s*5+t])/16-3,p[-1]*=~a&1,!t?0 P"*0")P"/x")P"/x*%s",e)P"*ln(%s)",e),s=0:0,e=a&2?p:e,printf(&c););} ``` Running examples (input on `stdin`; output goes to `stdout`): > > 4\*x^3-2 > > > ``` 4*x^3/x*3-2*0 ``` This format is much better than just `12*x^2`, because this way your teacher can be sure that you calculated the answer yourself and didn't cheat by copying it from someone else! > > x+2^x > > > ``` x/x+2^x*ln(2) ``` The output has a slight domain problem at `x=0`, but it's correct *almost everywhere*! For reference, here is an ungolfed, readable (by mere mortals) version. It uses a state machine with 5 states and 5 categories of input characters. ``` void deriv(char* input) { char* p = input; // current position char* exp = p; // base or exponent char q = '^'; // previous character // State machine has 5 states; here are examples of input: // state 0: 123 // state 1: 123* // state 2: 123*x // state 3: 123*x^456 // state 4: 123^x int state = 0; // Control bits for state machine: // bit 0: special action: stop recording base or exponent // bit 1: special action: start recording base or exponent // bits 4-7: if first column, specify how to calculate the derivative: // 3 - multiply the constant term by 0 // 4 - divide x by x // 5 - divide x^n by x and multiply by n // 6 - multiply n^x by ln(n) // bits 4-7: if not first column, specify the next state // (plus 3, to make the character printable) const char* control = "\x33\x30\x50\x43\x71" "\x73\x70\x50\x23\x21" "\x43\x40\x20\x23\x63" "\x53\x60\x20\x23\x21" "\x63\x70\x70\x23\x71"; for (;;) { int c = *p++; // Convert a char to a category: // category 0: // - + // category 3: // * // category 2: // x // category 4: // ^ // category 1: // numbers: 0...9 and decimal point int category; int action; if (q == '^' && c == '-') category = 1; // unary minus is a part of a number else category = c%26==16?c%16/3:c/46; // just does it // Load new state and action to do action = control[state * 5 + category]; if (action & 1) p[-1] = 0; state = (action >> 4) - 3; if (category == 0) { if (state == 0) printf("*0"); if (state == 1) printf("/x"); if (state == 2) printf("/x*%s", exp); if (state == 3) printf("*ln(%s)", exp); state = 0; } if (action & 2) exp = p; if (c == 0 || c == '\n') // either of these can mark end of input break; putchar(c); q = c; } } ``` P.S. Watch out for that `gets` function: it has a security vulnerability that can let your teacher execute a rootkit in your mind by providing too long input... [Answer] # Lua ~~296~~ ~~268~~ 263 ``` function d(a)l=""i=a:find"x" if i then if a:sub(i-1,i-1)=="^"then l="log("..a:sub(1,i-2)..")*"..a elseif a:sub(i+1,i+1)=="^"then l=a:sub(i+2).."*"..a:sub(1,i)p=a:sub(i+2)-1 if p~=1 then l= l..a:sub(i+1,i+1)..p end else l=a:sub(1,i-2)end else l="0"end return l end ``` Not very golfed and cannot currently handle multiple terms (you can just run it a few times, right?), but it can handle `n^x`, `x^n` and `n` as input. --- Ungolfed... ``` function d(a) l="" i=a:find"x" if i then if a:sub(i-1,i-1)=="^" then l="log("..a:sub(1,i-2)..")*"..a elseif a:sub(i+1,i+1)=="^" then l=a:sub(i+2).."*"..a:sub(1,i) p=a:sub(i+2)-1 -- this actually does math here if p~=1 then l= l..a:sub(i+1,i+1)..p end else l=a:sub(1,i-2) end else l="0" end return l end ``` [Answer] ## ECMAScript 6, 127 bytes Here is my regex attempt (using a single regex and some logic in the replacement callback): ``` i.replace(/(^|[*+-])(\d+|(?:([\d.]+)\^)?(x)(?:\^(-?[\d.]+))?)(?![.*^])/g,(m,s,a,b,x,e)=>s+(b?'ln'+b+'*'+a:e?e--+'*x^'+e:x?1:0)) ``` This expects the input string to be stored in `i` and simply returns the result. Try it out in an ECMAScript 6 compliant console (like Firefox's). [Answer] ## sed, 110 Taking very literally "They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying": ``` s/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g ``` The byte count includes 1 for the `r` flag. Ungolfed, with comments: ``` # Add underscores before and after the string, to help with solo-constant recognition s/.*/__&_/ # Power rule: replace x^c with c*x^(c-1) where c is a number s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g # Exponentials: replace c^ with lnc*c^ where c is a number # (This assumes that there will be an x after the ^) s/([0-9.]+)\^/ln\1*\1^/g # Constants: replace ?c? with ?0? where c is a number and ? is +, -, or _ # Except if it's prededed by a parenthesis then don't, because this matches c*x^(c-1)! s/([^(][-+_])[0-9.]+([-+_])/\10\2/g # Get rid of the underscores s/_//g ``` Sample run: ``` $ cat derivatives.txt -3 8.5 x^0.5 x^-7 0.5^x 7^x 3*x^5 -0.1*0.3^x -5*x^2+10-3^x $ sed -re 's/.*/__&_/;s/x\^(-?[0-9.]+)/\1*x^(\1-1)/g;s/([0-9.]+)\^/ln\1*\1^/g;s/([^(][-+_])[0-9.]+([-+_])/\10\2/g;s/_//g' derivatives.txt -0 0 0.5*x^(0.5-1) -7*x^(-7-1) ln0.5*0.5^x ln7*7^x 3*5*x^(5-1) -0.1*ln0.3*0.3^x -5*2*x^(2-1)+0-ln3*3^x ``` I bet this could be golfed further; it's my first try at `sed`. Fun! [Answer] ## Ruby, 152 ...or 150 if you don't need to print... or 147 if you also are ok with an array that you need to join yourself. run with `ruby -nal` ``` p gsub(/(?<!\^)([-+])/,'#\1').split(?#).map{|s|s[/x\^/]?$`+$'+"x^(#{$'}-1)":s[/-?(.*)\^(.*)x/]?s+"*ln(#{$1}*#{$2[0]?$2:1})":s[/\*?x/]?($`[0]?$`:1):p}*'' ``` ungolfed: ``` p gsub(/(?<!\^)([-+])/,'#\1').split(?#). # insert a # between each additive piece, and then split. map{ |s| if s[/x\^/] # if it's c*x^a $` + $' + "x^(#{$'}-1)" # return c*ax^(a-1) elsif s[/-?(.*)\^(.*)x/] # if it's c*b^(a*x) ln = $1 + ?* + ($2[0] ? $2 : 1) # return c*b^(a*x)*ln(b*a) s+"*ln(#{ln})" elsif s[/\*?x/] # if it's c*x ($`[0] ? $` : 1) # return c else # else (constant) nil # return nil end }*'' ``` My main problem with this one is the number of characters proper splitting takes. The only other way I could think of was `split(/(?<!\^)([-+])/)` which gives `+` and `-` as their own results. Any hints for a better solution? Also, is there a shorter way to return `s` if it's not empty, but otherwise return `y`? I've used `s[0]?y:s`? In JS I'd just do `s||y`, but `""` is truthy in Ruby. ]
[Question] [ You're given the map of a cinema theatre as a boolean matrix: 0 represents a free seat, 1 - occupied. Each [Finn](https://finnishnightmares.blogspot.fi/) who walks in chooses the seat farthest away ([Euclidean distance](https://en.wikipedia.org/wiki/Euclidean_distance)) from the nearest occupied one, or if several such exist - the first among them in [row-major order](https://en.wikipedia.org/wiki/Row-major_order). Output a matrix showing the order seats will eventually be occupied in; that is, replace the 0s with 2, 3, 4, etc ``` // in 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 // out 2 8 3 9 1 10 5 11 6 12 4 13 14 15 7 16 17 1 1 18 // in 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 // out 5 43 17 44 45 46 18 47 8 48 49 6 50 19 51 2 52 24 53 54 1 55 56 25 57 26 58 59 27 60 28 61 20 62 63 29 64 65 1 66 30 67 68 21 69 9 70 71 72 73 1 74 31 75 76 77 78 1 79 80 32 81 82 11 12 83 84 1 85 86 87 13 88 89 90 14 91 92 33 93 94 34 95 96 97 15 98 99 35 100 36 101 102 1 103 22 104 105 37 106 38 107 39 108 109 16 110 40 111 112 41 113 4 114 115 7 116 23 117 3 118 119 42 120 1 121 122 10 // in 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 // out 2 38 39 26 40 6 41 42 12 43 44 7 45 46 27 47 3 48 49 15 50 28 51 52 29 53 30 54 55 56 16 57 31 58 32 59 60 33 61 62 17 63 64 65 18 66 67 68 34 69 35 70 10 71 72 13 73 74 75 1 76 77 78 11 79 80 14 81 82 83 36 84 85 86 21 87 88 89 22 90 91 37 92 93 94 19 95 96 97 23 98 99 100 24 101 102 103 25 104 105 106 20 107 108 4 109 110 111 8 112 113 114 9 115 116 117 5 118 119 ``` I/O format is flexible within the established code golfing norms for your language. You can assume the input is correct, of size at least 3x3, and doesn't consist entirely of the same boolean value. Write a function or a complete program. The shortest solution per language is considered the winner; no answer will be accepted. Standard loopholes are forbidden. [Answer] # [MATL](https://github.com/lmendo/MATL), 37 bytes ``` !t~z:Q"@yX:gG&n:!J*w:+X:&-|w/X<&X>(]! ``` [Try it online!](https://tio.run/##y00syfn/X7GkrsoqUMmhMsIq3V0tz0rRS6vcSjvCSk23plw/wkYtwk4jVvH//2gDBQLQWoE2SgzpZREGjAUA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmfEOH9X7GkrsoqUMmhMsIq3Vstz0rRS6vcSjvCSk23plw/wkYtwk4jVvG/QXKES8j/aAMFCDS0VoAxDTCYhkBoEMsFV4wDIvQZElKAQ5E1FglDbCYYEnYDJjQkpICACVBLCQcEEbaQqcSQXhZhwFgA). You may also want to [see the cinema being filled up](https://matl.suever.net/?code=%21t%7Ez%3AQ%22%40yX%3AgG%26n%3A%21J%2aw%3A%2BX%3A%26-%7Cw%2FX%3C%26X%3E%28t%21.5%26XxZcD%5Dx&inputs=%5B0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+1+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%3B+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0+0%5D&version=20.8.1) in ASCII art. ### Explanation ``` !t % Implicit input: M×N matrix of zeros and ones. Transpose and duplicate. % The transpose is needed because MATL uses column-major (not row-major) % order. It will be undone at the end ~z % Number of zeros, say Z :Q % Range, add 1 element-wise: gives the array [2, 3, ..., Z+1]. These are % the new values that will be written into the matrix " % For each k in that array @ % Push k. Will be written in a position to be determined y % Duplicate from below: pushes a copy of the current matrix, that has % values up to k-1 already written in X: % Linearize into an (R*C)×1 vector, in column-major order g % Convert to logical: this replaces non-zero values by 1 G&n % Push input size as two separate numbers: M, N :! % Range, transpose: gives the column vector [1; 2; ...; N] J* % Multiply by imaginary unit, 1j, element-wise w: % Swap, range: gives the row vector [1, 2, ..., M] + % Add, with broadcast. Gives an N×M complex matrix defining a grid of % coordinates: [1+1j, ..., M+1j; 2+1j, ... 2+1j; ...; N+1j, ..., N+Mj] X: % Linearize into an (M*N)×1 vector, in column-major order &-| % (M*N)×(M*N) matrix of absolute differences. This gives all distances % between seats. Rows of this matrix represent currently used seats, % and columns correspond to potential new positions w/ % Swap, divide with broadcast. This divides the rows representing % occupied seats by 1, and those with unocuppied seats by 0. So the % latter rows are set to infinity, which effectively removes them for % the subsequent minimization X< % Mimimum of each column: this gives the minimum distance to currently % occupied seats for each potential new seat &X> % Argument maximum: gives the index of the first maximizing value ( % Write value k at that position, using linear indexing ] % End ! % Transpose. Implicit display ``` [Answer] # JavaScript (ES6), ~~156~~ 137 bytes *Saved 18 bytes thanks to @l4m2* That's quite a lot of `map()` ... ``` f=(a,n=1)=>a.map(B=(r,y)=>r.map((_,x)=>a.map(b=q=>q.map(v=>b=b<(d=X*X--+Y*Y)|!v?b:d,X=x)&Y--,Y=y)|v|b<=B||(R=r,C=x,B=b)))|B?f(a,R[C]=++n):a ``` [Try it online!](https://tio.run/##xZBRi4JAFIXf51fUS8zNO@G8RlfB/kFPikjMaMYupmWLGMx/d61dFpcwBgrivMxhPs453E/VqHNafxy/RFllu67LiSssSQJ5anFQRx4Qr/HS2/pm@Rbbvz9NJ/JOt2dDnia94hmF81AIJ5pHYKaNr5cZhtTCLBICI7qA0SsKjOEbqnFNLQakAcAEft4Xb@J1Qo5TwlJ1aVWeq2K3KKo9z3nMJpPYxR/JBIfWHbWyl5uwBIAN44CxB@kj@l8ibaARcLhvFB0mSbtN95I2kEXS74AXXdJy0pOYfEfpPXY9WfcN "JavaScript (Node.js) – Try It Online") ### Commented ``` f = (a, n = 1) => // a = input array; n = seat counter a.map(B = // initialize B to a non-numeric value (r, y) => // for each row r at position y in a[]: r.map((_, x) => // for each target seat at position x in r[]: a.map(b = // initialize b to a non-numeric value q => // for each row q in a[]: q.map(v => // for each reference seat v in q[]: b = b < ( // if b is less than d, defined as d = X * X-- + Y * Y // the square of the Euclidean distance ) | !v ? // or the reference seat is empty b // let b unchanged : // else: d, // update b to d X = x // start with X = x ) & Y--, // end of q.map(); decrement Y Y = y // start with Y = y ) | // end of inner a.map() b <= B || // unless b is less than or equal to B, (R = r, C = x, B = b) // update B to b and save this position in (R, C) ) // end of r.map() ) | B ? // end of outer a.map(); if B was updated: f(a, R[C] = ++n) // update the best target seat and do a recursive call : // else: a // stop recursion and return a[] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~216~~ ~~213~~ ~~185~~ 184 bytes ``` import Data.Array m a=[snd$maximum a|a/=[]] f k=k//m[(r,((a,b),maximum(elems k)+1::Int))|s<-[assocs k],((a,b),0)<-s,r<-[minimum[(x-a)^2+(y-b)^2|((x,y),i)<-s,i>0]]] (until=<<((==)=<<))f ``` Takes the input as an array. Input and output are in reverse order. Credit for fixed point magic to [Laikoni](https://codegolf.stackexchange.com/questions/144393/prime-factoral-roots/144402#144402). [Try it online!](https://tio.run/##jZJhS8MwEIa/91ccY8KFpduqiDBaQRFBmCDot1JZtmUzrElLksoG@@/z2nXqkMkI7SW9p7nLm/dDuJXM853SZWE9vMm1779YZfwCsGwiC9rcg/Ci/1iZmVeFASzMcWasnAdc2qIq7zds9zt1Z63YBBpEkjoz72qxVrqi5VYMkjTLggWsktVgoFO0HFHwKeMtgzKX2sGK9aLR6Ml4xrYuDlPhXDGjz9kBH7I4dNxSSitT/5jiOhTs/bKHm3BKcYu45hvGVQOq22FGdZcJVsarPIljxCRhFBlb7LykkySQ04GazgFxSBU43vDomjHogpWf0jpJs1lhZsJDAGlKzH8j4wHANxSdA50Af6DjZHRqp@i8nv6O6BzojJ3aBkjyoDEVyUoCl5V/9XZsoA@VyZWRjmZalIB7VZ9F2XoQOhdXc@iQ9i1Qv8hK9bp1HDQ3CJPCTAAXzvfpafi9V4JAC2Xqoof6XVhCfdO7Lw "Haskell – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~200~~ 187 bytes ``` a=input() z=len(a[0]);P=[divmod(i,z)for i in range(len(a)*z)];i=2 while 0in sum(a,[]):t,y,x=max((min((u-U)**2+(v-V)**2for V,U in P if a[V][U]),-v,-u)for v,u in P);a[-y][-x]=i;i+=1 print a ``` [Try it online!](https://tio.run/##zVHPa4MwFD43f0VuJjaC8VjJsbuuF72EHIKma6BGidGp/7xTBxsO1s7CoPAdHu@978fjVb27lCYaszJXzPO8UTJtqsYhDAZ2VQZJHgocnxjPdVuUOdJkwOfSQg21gVaaN4WWNewPWMSaReD9oq8KhtO4bgokCRf44EhPOlbIDqFCG4SaIMG@H@1RG6RzMSumJJk1T1CfoeSp4InAJGhJ0CyGLWmWMY4lD3rBg04wHes9o6Cy2jgoxyk/cLY/gN1nBjpVO9WpDM7nTfWyCFSXqcrB4@vL0drSTkuVrGsARs5DAr9ABYGrRnijQReEQoC1yH38FKWbGfd5q5x/oq486CN33ADdzNjo8R34gYc8lOw/SPS54/1OEuAD "Python 2 – Try It Online") -13 bytes thx to a tip from [Not that Charles](https://codegolf.stackexchange.com/users/13950/not-that-charles) by removing unneeded check for cells being 0. [Answer] # [J](http://jsoftware.com/), ~~74~~ ~~70~~ 60 bytes ``` (+(1+>./@,)*i.@$(=]i.>./)*<./@(#|@-/])&,j./&i./@$)^:(1#.0=,) ``` [Try it online!](https://tio.run/##xVDBCoJAEL3vVwwpuqPb6igVWIYfknWIllZYOnitb9/WhJA6WBjEY2Dem3kzwzRWtVAWkIILy2NO8VYmlcBIy8rnZa2l4xhtnMi9azVPagxEI5NAO8XHfcHJk2kp0CKbSQhVNy0EAbcCVMuYoU44LKDeuSU96Jm9groaM9nDQ8uhaQw0oYdGu@jjO6Z53tzM5P0zVt8847eg/@xl7HQ8X4CvFYKhIcmGJLd3) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 39 bytes Thanks Cows quack for saving one byte, and ngn for saving another ``` 1⌈2-≢∘⍸-⍴⍴∘⍋⍸∘~{⍵∪⍺[⊃⍒⌊/+.×⍨¨⍺∘.-⍵]}⍣≡⍸ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkG/w0f9XQY6T7qXPSoY8aj3h26j3q3gBCI0w3kAxl11Y96tz7qWPWod1f0o67mR72THvV06WvrHZ7@qHfFoRVAYaAiPaDGrbG1j3oXP@pcCNT3Pw1o@qPePiOQjr6pxUXJQLIkI7P4fy5YovNR7yoDBQg05MoF8oDCCjARAwIihkBowJWmkMulrs6FaSAOiGGoIZHqcKhFcxJO1WjmGRLtPkxoSKQ64syDuoTkgCTeCVRRaTigtmOqBAYXAA "APL (Dyalog) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 43 bytes ``` ,¬J;Ѐ"T€Ẏ©Ʋ€ạ²Sɗþ/Ṃ€MḢị®⁸⁸ẎṀ‘¤ṛ¦€Ḣ}¦µẎċ0Ɗ¡ ``` [Try it online!](https://tio.run/##y0rNyan8/1/n0Bov68MTHjWtUQoBEg939R1aeWwTmLXw0Kbgk9MP79N/uLMJKOD7cMeih7u7D6171LgDiIAqH@5seNQw49CShztnH1oG0rJjUe2hZYe2AqWOdBsc6zq08P/h9qOTHu6c8f9/dLSBjgIcGcbqKKAIGOARMAQjg9hYAA "Jelly – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 44 bytes ``` {×⍵:⍵⋄≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣≡ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/rw9Ee9W62A@FF3y6PORY86Vj3q6HrUu6vWwdChutD2UU@Hvk7ho7YJj3q6HvXs19YDqV9xaIXGo94dYK2ajzpm6Ok@6t38qHcLkFsLlH3Uu/hR58L/aSBdvX1Gj7qaH/VNLS5KBpIlGZnF/9MUTBRMgcoNFCDQUMEABzQEyQEA "APL (Dyalog Unicode) – Try It Online") Alternate solution at 44 bytes ``` {≢∪∊⍺}@1@{q=⌈/,q←⌊⌿+.×⍨¨(⍸×⍵)∘.-⍳⍴⍵}⍨⍣(~0∊⊣) ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 121 bytes ``` Nest[p=Position;ReplacePart[#,#&@@Pick[a=#~p~0,m=Min/@DistanceMatrix[a,N@p[#,x_/;x>0]],Max@m]->Max@#+1]&,#,Total[1-#,2]]& ``` [Try it online!](https://tio.run/##zZFLq4MwEIX/ytCAm46YdFuULO7WIpfuQiiDpNzQ@kCzEMT@dVu7aLHQh8KFwoGBw3xzTkhG7s9k5GxK/R5C6DemdqoMk6K2zhb5@teUR0pNQpVTDJknZWLTg6KQncoTxyyMbR7IH1s7ylMTk6tsowg3srysN7tg3URca4ypkZn2o2GypdAeMtwWjo5K@AxXWnt9Utl8yIAF@BEsEPaKaQ0eBBLatuUIN4kOYWTwF4a4ineDM955q8erYjLxnhsV/QgdZYg573ghMZmYmHEvPOdHZlX7D0h8d73nUNf1Zw "Wolfram Language (Mathematica) – Try It Online") [Answer] ## Clojure, 247 bytes ``` #(let[R(range(count %))C(range(count(% 0)))](loop[M % s 2](if-let[c(ffirst(sort-by last(for[x R y C :when(=((M x)y)0)][[x y](-(nth(sort(for[i R j C :when(>((M i)j)0)](+(*(- i x)(- i x))(*(- j y)(- j y)))))0))])))](recur(assoc-in M c s)(inc s))M))) ``` Input is a vec-of-vecs `M`, which is modified in a `loop` by `assoc-in`. When no free spot is found (`if-let`) then the result is returned. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~35~~ ~~33~~ ~~30~~ 29 bytes ``` ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL ``` [Try it online!](https://tio.run/##y0rNyan8/z/K6/Cyh7u7D@/zcnu4a@HhfRWHlrodWq3v@3DHooc71xye7vZwZ8OjhhnHuvIdgMzGQ1sPT/D5/3D3loc7Nj1qWhN2uN39/38DBQg05IKxDNBYhkBoAAA) Replaced the `×ı+` with `æị` (complex combine), a new dyad based on `j.` from J, saving a byte. Here is a more efficient version for TIO. [Try it online!](https://tio.run/##y0rNyan8/z/K6/Cyh7u7D@/zcnu4a@HhfRWHlro93LlA5dBqfd@HOxY93Lnm8HSgQMOjhhnHuvIdgMzGQ1sPT/D5/3D3loc7Nj1qWhN2uN39/38DBbyQC8YyJCCPQw0XprghFv2GBO3HhIYE5PHrh9oIAA) ## Explanation ``` ZJæịþJFạþx¥F«/MḢṬ×FṀ‘Ɗo@FṁµÐL Input: matrix M Z Transpose J Enumerate indices - Get [1 .. # columns] J Enumerate indices - Get [1 .. # rows] æịþ Outer product using complex combine (multiply RHS by 1j and add to LHS) F Flatten F Flatten input ¥ Dyadic chain x Times - Repeat each of LHS by each of RHS ạþ Outer product using absolute difference «/ Reduce by minimum M Indices of maximal values Ḣ Head Ṭ Untruth - Return a Boolean array with 1's at the indices × Times Ɗ Monadic chain F Flatten input Ṁ Maximum ‘ Increment o@ Logical OR F Flatten input ṁ Mold - Reshape to match the input µÐL Repeat until result converges ``` [Answer] # [K (ngn/k)](https://gitlab.com/n9n/k), ~~81~~ ~~75~~ ~~73~~ ~~72~~ 70 bytes ``` {(~&/,/){a[*>A*&/+/''b*b:i[&~A:~a]-/:\:i:+!n:(#x;#*x)]:#?a:,/x;n#a}/x} ``` [Try it online!](https://tio.run/##vdTdahpBGAbg81zFWyzGNQk7/z@70JLrsELMgUVSLIQcbBC9dft@M6YGUlEIlNWJs843M77zZJ/u1j/X@/2y20x24/a2bTaL2fTb/XTc3rTX14/Tx241G@/uu91iftd2P7pVd/Nl3U1GQz@aDs28G31fdLft0K9Hi207bPcv3ebr7HX33C0x9A@/n/rJw3Kx@tUP/Wv/3My3Vy@ziUK99BWAt476Z0fzUg17E4MEi1yLtIKH1gjQRvoO2kKz9Yjle34RS7FOzfz9mieu94vr80NODDvu@uTA4yz6kr18vPT5IWdnOSxdcmWQzkpazsHxM5NLcJFpO74yI/YsyPAaJWp4A@PgLTzzhvfwAYZthOHYBJ9hIoKCSQjltGAUgkGwMJzPIfDsEAIsb3NkgmE382yjQqwV0SByV4gOli2PNSBGxCT3MpKCJQiNZMigVGj2LZLsKXmkgBQFRUpInFqJjqyRDSwV2VKSOTnveuSAHAVPTsgZlvtTXIFRKApSRhwp7t5Ue1xDeVhWKP4IbklFWMpU8jEXfATquCaJam7MyZ@6JmvFqUBly@T4Kxm@tKxmzo6rmQLfyJs9dZHgi1B8YpD@v8t9uCpWI3kza1JjvkGSLYGJYQKOB8IESMKHxAtjBu4LSToWwVkEEyARV8I8CxImNp9KGX1RMhnTS9Dil8dEwge/SQBXvTQUBE2Fq@ThFLUIJj8iJuEo4I@C3wgTQqp4U8FLcPRb9fLwCbjqJQICpl6SI@BMwK6az0e9hFT1Cl3jjnQFrv@rVsgaVR3HQtZVtLpyTQWslsep/McUqbqIjuWRW5A28/0f "K (ngn/k) – Try It Online") ]
[Question] [ What general tips do you have for golfing in Windows PowerShell? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to PowerShell (e.g. "remove comments" is not an answer). Please post one tip per answer. —taken nearly verbatim from [marcog's question](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python). [Answer] Powers of 10 literals with scientific notation: ``` 4e6 = 4000000 ``` Powers of 2 literals: ``` 4KB = 4096 4MB = 4194304 4GB = 4294967296 # TB and PB suffixes also exist, but less useful for golf. ``` Could come in handy. [Answer] If you need to run a loop, and you know *exactly* how many times it needs to run every time, consider piping an array of contiguous integers into `ForEach-Object` via the `%` alias instead of using `for`. `for($x=1;$x-le10;$x++){`...`}` vs `1..10|%{`...`}` [Answer] You can skip spaces *a lot* in PowerShell. If it feels like it might not be needed, it quite possibly isn't. This is particularly useful in comparisons. Example: ``` $x-eq$i-and$x-ne9 ``` vs. ``` $x -eq $i -and $x -ne 9 ``` --- If you need to branch your script based on the result of a single test which may have multiple outcomes, `switch` can sometimes match or beat an if statement. Example (switch vs. if/else - tie): ``` if($x%2-eq0){'even'}else{'odd'} ``` vs. ``` switch($x%2){0{'even'}1{'odd'}} ``` Or (switch vs. if/elseif/else - switch wins by 15): ``` if($x%2-eq0){'even'}elseif($x%2-eq1){'odd'}else{'error'} ``` vs. ``` switch($x%2){0{'even'}1{'odd'}2{'error'}} ``` If the switch is *actually* based on certain math results, like the modulo operation above, you can replace the switch entirely with an array. Here, it saves another 13 characters and is even shorter than the original two-option if/else statement. (Thanks to [Danko Durbic](https://codegolf.stackexchange.com/questions/12177/collatz-conjecture/15220?noredirect=1#comment29076_15220) for this bit.) ``` ('even','odd','error')[$x%2] ``` If you will be using a particular command a lot, especially one without a pre-existing short-hand alias, set up a single-character alias early on. Example: ``` nal g Get-Random;g 10;g 10;g 10 ``` vs. ``` Get-Random 10;Get-Random 10;Get-Random 10 ``` [Answer] Encapsulating the command that defines a variable in parenthesis allows you to feed the variable's definition directly to other commands. For example, you can set $x and then set $y based on the value of $x in one shot with this: ``` $y=($x=1)+1 ``` Instead of this: ``` $x=1;$y=$x+1 ``` You can set $h and output it with this: ``` ($h='Hello World!') ``` Instead of this: ``` $h='Hello World!';$h ``` [Answer] A switch can act like a loop, when given an array. For example: ``` $FooBarMeh='a','b','c' switch ($FooBarMeh) { 'a'{'FOO'} 'b'{'BAR'} default{'MEH'} } ``` Will output: > > FOO > > BAR > > MEH > > > I'm not totally sure where this will be useful, but I expect it will be handy for someone some time. [Answer] Want to find the maximum or minimum of a collection of values? Tried ``` (...|measure -ma).Maximum ``` or ``` (...|measure -mi).Minimum ``` already? Just sort and use the last or first item: ``` (...|sort)[-1] # maximum (...|sort)[0] # minimum ``` [Answer] Replace `[math]::pow` with multiplication. Instead of ``` [math]::pow($a,$b) ``` you can write ``` "$a*"*$b+1|iex ``` This works for integer exponents >= 0. [Answer] # Shortening Property Names Sadly, unlike parameters, properties/methods (anything accessed with a dot `.`) cannot usually be shortened down to its unambiguous form. But certain cmdlets can operate on property names and take wildcards, and there are little-known parameter sets of `%` and `?` that can be useful. Usually we pass in a scriptblock and refer to the item with `$_`, but there's another form of these that takes a property name, and it accepts a wildcard. ``` $o|select Le* $o|%{$_.Length} ``` With a property like `.Length` we can't use the v3 magic that would normally work on an array because `Length` is a property of the array itself, so the above two could be used to get the lengths of the individual members. The `select` comes in a little bit shorter. But `%` can take a property name directly and return that value: ``` $a|% Length ``` Which can be shortened with wildcards. The wildcard must resolve to a single property (or method, more on that later), so it will throw a helpful error if it doesn't, indicating exactly which members it could resolve to. In the case of `Length`, `Le*` is typically the shortest. Even on a single string, this method is 1 byte shorter than just using the property. ``` $a.Length # 9 #(doesn't work on array) $a|%{$_.Length} # 15 $a|% Le* # 8 ``` But depending on what you're doing with this, this can be worse. You can do `$a.Length*5` but to do it with the pipeline expression you'd have to wrap it `($a|% Le*)*5`; might still be worth it if it's against an array, but the point is it's not always appropriate as a straight substitution. It works with methods too, and you can leave off the `()` which makes a full name the same length, but same restriction as above about sometimes having to wrap it. ~~The method must have an overload that takes no parameters~~ (you can pass arguments by placing them after the method name, which is really nice): ``` $a.ToUpper() # 12 $a|% *per # 9 ``` With arguments: ``` 'gaga'-replace'g','r' # 21 'gaga'|% *ce g r # 16 ``` These aren't strictly the same in that the `-replace` operator does a regex replace, but if you're just doing a string replace, it can (now) be shorter to use the method; it helps that the strings are cmdlet arguments instead of method arguments so they don't need to be quoted. ## Where-Object Properties `?` can take (partial) property names as well, and apply an "operator" to it (in the form of switch parameters). Again this can be shorter than using the standard `Where-Object` scriptblock approach if the property name is sufficiently long and unique. ``` $a|?{$_.Length-gt5} # 19 $a|? Le* -GT 5 # 14 ($a|% Le*)-gt5 # 14 - Lengths, not objs ``` [Answer] Comparison operators work on collections of values by returning matching values: ``` 1..5 -gt 2 ``` will yield `3`, `4` and `5`. In some cases this can help to save an otherwise longer `|?{$_...}`. `-match` is a comparison operator too. [Answer] Use aliases whenever possible. There are a bunch of useful ones: ``` ? Where-Object % ForEach-Object gu Get-Unique sort Sort-Object iex Invoke-Expression ``` [Answer] Finding a sum the long way: ``` (...|measure -s).Sum ``` A shorter way: ``` ...|%{$s+=$_};$s ``` And even shorter: ``` ...-join'+'|iex ``` [Answer] `for` loops can have anything between 0 and three statements in their header: Endless loop: ``` for(){} ``` Loop with initialization: ``` for($n=0){} ``` Loop with initialization and end condition: ``` for($n=0;$n-lt7){} ``` In such cases the additional semicolons at the end may be omitted (it's explicitly stated in the [language specification](http://www.microsoft.com/download/en/details.aspx?id=9706), so it's not an implementation detail) in contrast to C-like languages which always require exactly three statements. This also makes `while` a bit shorter. Compare ``` while(...){} ``` and ``` for(;...){} ``` With the added bonus that you can stick in a previous line (if there is one) into the `for` as well without extra cost (and even saving a character). [Answer] Semicolons and line breaks are interchangeable. Golfed code is often more readable if not jammed into a single line. And the length is still the same (provided you use U+000A as line break which PowerShell handles without problems). [Answer] The `Get` verb is implied. This can shorten any `Get-Frob` to just `Frob`. Frequent contenders are `date` or `random`. Note that this *won't* work properly in some cases because you might have GNU utilities in your path (or other native programs that clash). Order of command lookup in that case seems to prefer the native program before it considers cmdlets with the `Get-` removed: ``` PS Home:\> date Freitag, 15. November 2013 07:13:45 PS Home:\> $Env:Path += ';D:\Users\Joey\Apps\GnuWin32\bin' PS Home:\> date Fr Nov 15 07:14:13 W. Europe Standard Time 2013 ``` [Answer] If you are assigning an array that you know will only have two values, don't use indexing. Something like this: ``` $a="apple","orange" $a[0] # apple $a[1] # orange ``` Can easily be turned into this: ``` $a,$o="apple","orange" $a # apple $o # orange ``` This can also be useful for if you just need to the first element of an array: ``` $a,$b=1..10 $a # 1 $b # 2..10 ``` [Answer] Casting to string: ``` [string]$x ``` vs. ``` "$x" ``` Casting to string like this can also be used to flatten an array of strings, instead of joining it: ``` $a = @('a','b','c') $a -join ' ' ``` vs. ``` $a = @('a','b','c') "$a" ``` Casting a string to a numeric type: ``` [int]$x [float]$x ``` vs. ``` +$x ``` Also very useful to know that PowerShell *always* takes the type of the left operand to determine the final type of an expression and conversions to apply: ``` '1'+2 -> '12' 1+'2' -> 3 ``` which can help determining where needless casts are. [Answer] Don't forget that you don't always need to provide the full name of a parameter, and some parameters are positional. ``` Get-Random -InputObject (0..10) ``` ...can be trimmed to... ``` Get-Random -I (0..10) ``` ...because "I", in this case, is enough to uniquely identify `InputObject` from the other valid parameters for this command. You could trim it further to... ``` Get-Random (0..10) ``` ...because `InputObject` is a positional parameter. Piping is usually shorter than feeding objects as a parameter, especially when it can remove the need for parenthesis. Let's trim our random number generator further... ``` 0..10|Get-Random ``` Also be on the lookout for other ways to accomplish the same thing, even if you can't change the command. For the above case, you could do this: ``` Get-Random 11 ``` Or, incorporating [another suggestion](https://codegolf.stackexchange.com/a/778/9387)\*: ``` Random 11 ``` \*\*Note: Omitting `Get-` from a command name can bloat the run time by about 50,000%. Not bad if you only need the command once, but be careful using it in long loops.\* And that's how can knock a simple command down to a third of its size. [Answer] Automatic variables have booleans for True and False as `$true` and `$false` but you can get similar results using the logical not operator `!` and the integers 0 and 1( or any non-zero integer.) ``` PS C:\Users\matt> !1 False PS C:\Users\matt> !0 True ``` Near all PowerShell expressions can be evaluated as booleans. So as long as you are aware of how certain data is evaluated you can get booleans and never need to explicitly cast them. Be aware of the LHS value when doing these. * Integer 0 is false and non-zero integers are evaluated to true. * non-zero length strings are true and empty or null (and nulls themselves) strings are false. There are other examples but you can easily test by doing a cast ``` PS C:\Users\matt> [bool]@(0) False ``` [Answer] When using a number as an argument to an operator that would otherwise require a string, you can use the number directly. Compare ``` ...-join'0' ``` vs. ``` ...-join0 ``` Works with `-split` as well. The argument is always converted to a string first. [Answer] Fake ternary operator. You can assign straight from an `if` statement: ``` $z=if($x-eq$y){"truth"}else{"false"} ``` But you can use a 2-element array and use the test to index into it. $falsey results get element 0, $truthy results take element 1: ``` $z=("false","true")[$x-eq$y] ``` NB. that this is really doing array indexing, and if the test results in a value which *can* be cast to an integer, you'll ask for an item outside the bounds of the array and get $null back, and will need to do `!(test)` to force cast the result to a bool, with the options reversed. [ Edit: There's a genuine ternary operator in PowerShell 7+ in the C-language-style `cond ? 1 : 0` ] [Answer] Absolute value With ``` $n=-123 ``` Instead of ``` [math]::abs($n) ``` use ``` $n-replace'-' ``` Of course, the savings are cancelled if parentheses are needed. [Answer] If you need to silence errors, the obvious variant would be ``` try{ <# something that throws errors #> }catch{} ``` However, this is way too long. A shorter variant is to run the `try` block as a script block and just redirect the errors into an unset variable (`$null` would be the usual one, but that's still too long): ``` .{ <# something that throws errors #> }2>$x ``` This saves five valuable bytes (if not the world). [Answer] Use the `$ofs` [special variable](https://technet.microsoft.com/en-us/library/hh847768.aspx) to change the **O**utput **F**ield **S**eparator used when stringifying an array. Useful if you're needing to transform arrays to strings multiple times. For example: ``` $a=1,2,3,4 $a-join',';$a-join',' $ofs=',';"$a";"$a" ``` Saves 2+*n* characters on the 2nd `-join`, where *n* is the length of the separator, and saves an additional 5+*n* for the 3rd `-join` and each thereafter. [Answer] ## **Use `[bigint]` instead of `[Math]::floor`** The `bigint` datatype is a numeric type that can store arbitrarily large numbers and holds no decimal values. It always floors when using `[bigint]::new()`. A suffix for it was added in PowerShell core but using the `n` prefix rounds normally instead of floor which doesn't work for this. Example: ``` [bigint](.9) # 0 [bigint]3/4 # 0 [bigint](.1) # 0 [bigint]1/4 # 0 [bigint]10.5 # 10 [bigint]100/3 # 33 (.9)n # 1 3/4n # 1 (.1)n # 0 1/4n # 0 10.5n # 11 100/3n # 33 ``` [Answer] `Invoke-Expression` and `Get-Random` can also get pipeline input instead of arguments. For `iex` this allows to save parentheses on some expressions: ``` iex 1..5-join'+' # won't work iex(1..5-join'+') # does work, but has extra parentheses 1..5-join'+'|iex # doesn't need the parentheses ``` In case of `random` this allows a common case to be optimized a bit: ``` random -mi 10 31 # gets a random integer between 10 and 30 10..30|random # much better :-) (random 21)+10 # if needed in another expression that doesn't require extra # parentheses ``` The latter way of using it simply selects an item from a list. The `-c` argument can be given to allow more than a single selection. [Answer] Consider storing repeated script blocks in variables, instead of using functions. I was going to use this to save some characters in [my Rock, Paper, Scissors implementation](https://codegolf.stackexchange.com/a/15386/9387) before I realized that re-writing the function as a variable made even the variable unnecessary. This could still be useful for other scripts though, where you're actually running the same code multiple times. ``` function Hi{echo 'Hello, World!'};Hi ``` vs. ``` $Hi={echo 'Hello, World!'};&$Hi ``` [Answer] Converting floating-point numbers to integers in PowerShell is a bit of a minefield. By default the conversion does [Bankers Rounding](http://c2.com/cgi/wiki?BankersRounding) which doesn't always trim off the decimal and leave the smaller whole number, or always round .5 up to the next number like people do casually, it rounds evens one way and odds another way - this can be surprising, e.g. ``` PS C:\> [int]1.5 2 PS C:\> [int]2.5 2 ``` and break codegolf calculations. Many other common languages do truncation-rounding, therefore golf questions often require truncation. You might reach for `[Math]::Floor()` as the next best thing, but beware this only behaves the same as truncation for positive numbers, but it takes negative numbers lower - further away from zero. `[Math]::Truncate()` is what you need to bring PS behaviour in line with other language's default rounding, but it's a lot of characters. Regex replacing digits after the decimal point can help save a couple of characters: ``` [Math]::Truncate(1.5) [Math]::Floor(1.5) 1.5-replace'\..*' [Math]::Truncate($a) [Math]::Floor($a) $a-replace'\..*' $a.split('.')[0] # literal character split, not regex pattern split ``` [Answer] ### Use variables to store .NET names As outlined by cogumel0 in [this answer](https://codegolf.stackexchange.com/a/148058/42963), you can use variables to store .NET type names. For example, changing ``` param($a)$a-[math]::pow(2,[math]::floor([math]::log($a,2))) ``` into ``` param($a)$a-($m=[math])::pow(2,$m::floor($m::log($a,2))) ``` saved 3 bytes in this example. [Answer] You can use `$s|% t*y` instead `[char[]]$s` to split a string to char array. Given from [TessellatingHeckler's answer](https://codegolf.stackexchange.com/a/158441/80745): `% t*y` expands to `| ForEach-Object -Method ToCharArray` equiv. of `"$args".ToCharArray()` For example, compare ``` $s|% t*y ``` and ``` [char[]]$s ``` and ``` $s.ToCharArray() ``` It's useful with `$args` especially: `$args|% t*y` [Answer] You can access static methods via instance: ``` $x=4,2,3 $x::Sort($x) # [Array]::Sort($x) "$x" # 2 3 4 $x::Reverse($x) # [Array]::Reverse($x) "$x" # 4 3 2 ``` BigInteger suffix (`n`) introduced in PowerShell 7: ``` (0n)::Pow(4,5) # [bigint]::Pow(4,5) (0n)::Abs(-3) # [bigint]::Abs(-3) 2*0n::Abs(-3) # some cases don't require parentheses ``` ]
[Question] [ What general tips do you have for golfing in Mathematica? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Mathematica (e.g. "remove comments" is not an answer). [Answer] Some built-in functions with long names can be replaced with shorter expressions. For example: * `Total` => `Tr` for 1d arrays * `Transpose` => `Thread` or `` (`\[Transpose]`) * `True` => `1<2` * `False` => `1>2` * `Times` => `1##&` * `Alternatives` => `$|##&` * `IntegerQ` => `⌊#⌋==#&` or `1∣#&` (Thanks to [@Misha Lavrov](https://codegolf.stackexchange.com/users/74672/misha-lavrov)) * `a[[1]]` => `#&@@a` * `a[[All,1]]` => `#&@@@a` * `ConstantArray[a,n]` => `Array[a&,n]` or `Table[a,n]` * `Union@a` => `{}⋃a` or `a⋃a` * `ToExpression@n` => `FromDigits@n` if `n` is a number * `Divisible[n,m]` => `m∣n` * `FromDigits[n,2]` => `Fold[#+##&,n]` if `n` is a list of `0`s and `1`s * `Complex@z` => `{1,I}.z` where `z` is a list of the form `{x,y}` * `Rest@FoldList[f[#,#2]&,x,l]` => `t=x;(t=f[t,#])&/@l` * `Table[f[i,l],{i,Length@l}]` => `i=1;f[i++,l]&/@l` * `CoefficientList[f,x]` => `(f+O@x^n)[[3]]` if you know that the degree of the polynomial `f` is `n` and the constant term is not zero * `FractionalPart[x]` => `Mod[x,1]` if x is nonnegative [Answer] Tips below vary from the most economical to the most often used: 1. Use Mathematica's high-level commands where possible, even bulky ones: * `MorphologicalComponents`: [Code-Golf: Count Islands](https://codegolf.stackexchange.com/questions/6979/code-golf-count-islands/6980#6980) * Image manipulation capabilities: e.g. [Today (September 24) is HONDA birthday](https://codegolf.stackexchange.com/questions/12627/today-september-24-is-honda-birthday/12639#12639) * `Subsets` * `IntegerPartitions` * [Distance and Similarity measures:](http://reference.wolfram.com/mathematica/guide/DistanceAndSimilarityMeasures.html) e.g. `EuclideanDistance` can be a byte saver. Note however, that it's usually shorter to write `Total@Abs[a-b]` instead of `a~ManhattanDistance~b` and `Max@Abs[a-b]` instead of `a~ChessboardDistance~b`. 2. Use `Graphics and` `Text` for Ascii art: e.g [Star programming!](https://codegolf.stackexchange.com/questions/7107/star-programming/7109#7109) and [Build an analog clock](https://codegolf.stackexchange.com/questions/10759/build-an-analog-clock/10761#10761) 3. Dedicated symbols: * logic and set operations symbols instead of their long form names: ⋂, ⋃, ∧, ∨ * `Map` and `Apply`: `/@`, `//@`. `@@`, `@@@` 4. Prefix and infix notation: * `Print@"hello"` in place of `Print["hello"]` * `a~f~b` in place of `f[a,b]` 5. When a function is used only once, a pure function may economize a character or two. 6. Joining strings in a list. `""<>{"a","b","c"}` instead of `StringJoin@{"a","b","c"}` 7. Exploit listable functions. The longer the lists the better. `{a, b, c} + {x, y, z}= {a+x, b+y, c+z}` `{2, 3, 4} {5, 6, 7}= {10, 18, 28}` `{{a, b}, {c, d}}^{2, 3} = {{a^2, b^2}, {c^3, d^3}}` [Answer] ## Lists with repeated values This is quite a common vector to work with: ``` {0,0} ``` It turns out this can be shortened by a byte: ``` 0{,} ``` Even more bytes are saved if the vector is longer than two zeros. This can also be used to initialise zero matrices, e.g. the following gives a 2x2 matrix of zeros: ``` 0{{,},{,}} ``` This can also be used for non-zero values if they're sufficiently large or sufficiently many or negative. Compare the following pairs: ``` {100,100} 0{,}+100 ``` ``` {-1,-1} 0{,}-1 ``` ``` {3,3,3,3} 0{,,,}+3 ``` But remember that starting at 6 values, you're better off with `1~Table~6` in this case (potentially earlier, depending on precedence requirements). The reason this works is that `,` introduces two arguments to the list, but omitted arguments (anywhere in Mathematica) are implicit `Null`s. Furthermore, multiplication is `Listable`, and `0*x` is `0` for almost any `x` (except for things like `Infinity` and `Indeterminate`), so here is what's happening: ``` 0{,} = 0*{,} = 0*{Null,Null} = {0*Null,0*Null} = {0,0} ``` For lists of `1`s, you can use a similar trick by making use of exponentiation rules. There are two different ways to save bytes if you have at least three `1`s in the list: ``` {1,1,1} 1^{,,} {,,}^0 ``` [Answer] # Know your pure function arguments When golfing code, you'll often employ a functional approach, where you use anonymous (pure) functions with the `&` shorthand syntax. There are a lot of different ways to access the arguments of such a function, and you can often shave off a couple of bytes by having a good grasp on the possibilities. ## Accessing single arguments You probably know this if you've used pure functions before. The **n**th argument is referred to as `#n`, and `#` acts as an alias for `#1`. So if, say, you want to write a function that takes as parameters another function and its argument (to pass the argument to that function), use ``` #@#2& ``` This does *not* work with negative numbers (such as you might use when accessing lists). ## Accessing named arguments (new in V10) One of the major new language features in Mathematica 10 is `Association`s, which are basically key-value maps with arbitrary key types, written like ``` <| x -> 1, "abc" -> 2, 5 -> 3 |> ``` If such an association is passed in as the *first* argument to a pure function, you can access some if its arguments as named parameters: ``` {#, #2, #3, #abc, #xyz} & [<| "abc" -> "1st", "xyz" -> "2nd", abc -> "3rd" |>, "4th", "5th"] (* {<| "abc" -> "1st", "xyz" -> "2nd", abc -> "3rd" |>, "4th", "5th", "1st", "2nd"} *) ``` Note that `#` still refers to the entire association as expected. For the named parameters to work, the keys have to be *strings* (it won't work if you use undefined variables for instance), and those strings must begin with a letter and only contain letters and digits. ## The "self" argument `#0` A lesser known feature is that `#0` also exists, and gives you the function object itself. This can be really useful in quines and generalised quines. In fact, the shortest Mathematica quine (I know of) is ``` ToString[#0][] & [] ``` What's slightly annoying is that it won't give you the exact characters you entered. E.g. if use `@` for function application, it will still render as `[...]` and spaces will be inserted in some places. This will usually make the quine a bit longer than you'd like it to be, but it will always work, by golfing the quine first, and then just copying its output - which should now be a real quine. Apart from quines, this also means that you can write recursive code without having to name your function. Compare these three (naive but golfed) Fibonacci implementations: ``` f@0=0;f@1=1;f@n_:=f[n-1]+f[n-2] f@n_:=If[n<2,n,f[n-1]+f[n-2]] If[#<2,#,#0[#-1]+#0[#-2]]& ``` ## Sequences of arguments Now this is where the real magic starts. Sequences aren't used often in golfing, because `Sequence` it's just too long a name to be worth it most of the time. But in pure functions is where they shine. If you're not familiar with sequences, they are basically like splats in some other languages, if you use a sequence in a `List` or the argument list of a function, it's elements will automatically be expanded into separate slots. So ``` {1, Sequence[2, 3, 4], 5} == {1, 2, 3, 4, 5} f["a", Sequence[0, {}], "b"] == f["a", 0, {}, "b"] ``` Now, in pure functions `##` or `##1` is a sequence of all the arguments. Likewise, `##2` is a sequence of all arguments starting from the second, `##3` all arguments starting from the third etc. So for a start, we can just reimplement `Sequence` as `##&`, saving 5 bytes. As an example usage, this provides us with an alternative to `Join@@list` (see [this tip](https://codegolf.stackexchange.com/a/12930/8478)), which doesn't save any bytes, but is good to know about anyway: ``` ##&@@@list ``` This effectively flattens the first level of a nested list. What else can we do with this? Here is a 1-byte saving for `RotateLeft`: ``` RotateLeft@list {##2,#}&@@list ``` For these things alone it's worth keeping this feature in mind. However, we can do better! Sequences get really interesting when consider that operators are actually implemented as functions under the hood. E.g. `a+b` actually evaluates to `Plus[a,b]`. So if we give that a sequence... ``` 1+##&[1,2,3] => Plus[1,##] => Plus[1,1,2,3] => 7 ``` This trick has been use [in this tip](https://codegolf.stackexchange.com/a/12922/8478) to save a byte on `Times`, because juxtaposition is technically also just an operator: ``` 1##&[1,2,3] => Times[1,##] => Times[1,1,2,3] => 6 ``` You can also use it to save a byte on `Unequal` if you have a single-character value or variable you know is not in your arguments (`N` will probably work in 99% of the cases): ``` Unequal[a,b,c] N!=##&[a,b,c] ``` This gets even more interesting with unary operators and `-` and `/` - the latter two are actually implemented in terms of multiplication and exponentiation. Here is a list of things you can do, where the last column assumes that the function was passed the arguments `a, b, c`: ``` Operator Function Expanded Equivalent to +## Plus[##] Plus[a,b,c] a+b+c 1## Times[1,##] Times[1,a,b,c] a*b*c -## Times[-1,##] Times[-1,a,b,c] -a*b*c x+## Plus[x,##] Plus[x,a,b,c] x+a+b+c x-## Plus[x,Times[-1,##]] Plus[x,Times[-1,a,b,c]] x-a*b*c x## Times[x,##] Times[x,a,b,c] x*a*b*c x/## Times[x,Power[##,-1]] Times[x,Power[a,b,c,-1]] x*a^b^c^-1 ##/x Times[##,Power[x,-1]] Times[a,b,c,Power[x,-1]] a*b*c/x x^## Power[x,##] Power[x,a,b,c] x^a^b^c ##^x Power[##,x] Power[a,b,c,#] a^b^c^x x.## Dot[x,##] Dot[x,a,b,c] x.a.b.c ``` Other common operators are `!=`, `==`, `&&`, `||`. Less common ones to keep in mind are `|`, `@*`, `/*`. To conclude, here is a little bonus trick: ``` #### Times[##,##] Times[a,b,c,a,b,c] (a*b*c)^2 ``` Keep experimenting with these, and let me know if you find any other useful or particularly interesting applications! [Answer] `Sqrt@2` or `2^.5` => `√2` `a[[1]]`=>`a〚1〛` `#+#2&`=>`+##&` `Flatten@a`=>`Join@@a` (sometimes) `Function[x,x^2]`=>`xx^2` or `#^2&` `a〚1;;-1;;2〛`=>`a〚;;;;2〛` `a〚2;;-1 ;;2〛`=>`a〚2;;;;2〛` `a〚All,1〛`=>`a〚;;,1〛` `{{1}}〚1,1〛`=>`Tr@{{1}}` `0&~Array~10`=>`0Range@10` `Range[10^3]`=>`Range@1*^3` [Answer] ## Operators as Functions [Inspired by Dennis's recent discovery for Julia](https://codegolf.stackexchange.com/a/81028/8478) I thought I'd look into this for Mathematica. I was aware that Mathematica defines a large number of unused operators, but never paid much attention to it. For reference, [the list of all operators can be found here](https://reference.wolfram.com/language/tutorial/OperatorInputForms.html) in the form of a precedence table. The triangle in the last column indicates whether that operator has a built-in meaning or not. While not all of those that don't can be defined easily, most of them can. Conveniently, there are two unused operators with a codepoint less than 256, such that they can be used as single bytes in an ISO 8859-1 encoded source file: * `±` (0xB1) can be used either as a unary prefix operator or a binary infix operator. * `·` (0xB7) can be used as a variadic or n-ary infix operator, for n > 2. There's one more catch though: for some weird reason when *defining* these operators you need one space in front of them, or else Mathematica tries to parse a multiplication. When using them you don't need any spaces though: ``` ±x_:=2x x_ ±y_:=x+y x_ ·y_ ·z_:=x*y+z Print[±5] (* 10 *) Print[3±4] (* 7 *) Print[3·4·5] (* 17 *) ``` Compare this with: ``` f@x_:=2x x_~g~y_:=x+y h[x_,y_,z_]:=x*y+z Print[f@5] (* 10 *) Print[3~g~4] (* 7 *) Print[h[x,y,z]] (* 17 *) ``` So this saves one byte when defining the function and two bytes when using it. Note that the definition of `·` will not save bytes for four operands and will start costing bytes for more operands, but the usage may still save bytes, depending the precedence of operators used in the arguments. It's also good to note that you can cheaply define a variadic function that can then be called much more efficiently: ``` x_ ·y__:={y} Print[1·2·3·4·5] (* {2, 3, 4, 5} *) ``` But note that it's not easily possible to call these variadic functions with a single argument. (You could do `CenterDot[x]` or `##&[]·x` but if you actually need that there's a good chance you're better off with a different solution.) Of course, this isn't saving anything for solutions where an unnamed function suffices, but sometimes you need to define helper functions for use later on, and sometimes it's shorter to define named functions e.g. to set up different definitions for different parameters. In those cases, using an operator instead can save a decent amount of bytes. Note that using these ISO 8859-1 encoded files requires `$CharacterEncoding` to be set to a compatible value, like the Windows default `WindowsANSI`. On some systems this defaults to `UTF-8` which won't be able to read these code points from single bytes. [Answer] 1. **Explore recursive solutions** - Mathematica is multi-paradigm, but the functional approach is often the most economical. `NestWhile` can be a very compact solution to searching problems, and `NestWhileList` and `FoldList` are powerful when you need to return or process the results of intermediate iterations. `Map (/@)`, `Apply (@@, @@@)`, `MapThread`, and really everything on Wolfram's [Functional Programming](http://reference.wolfram.com/mathematica/guide/FunctionalProgramming.html) documentation page is potent stuff. 2. **Shortened form for increment/decrement** - For example, instead of `While[i<1,*code*;i++]` you can do `While[i++<1,*code*]` 3. **Don't forget you can pre-increment/decrement** - For example, `--i` instead of `i--`. This can sometimes save you a few bytes in the surrounding code by eliminating a preparatory operation. 4. Corollary to David Carraher's #5: **When the same function is used many times, assigning a symbol to it can save bytes.** For example, if you are using `ToExpression` 4 times in a solution, `t=ToExpression` enables you to use `t@*expression*` thereafter. However, before you do this consider whether the repeated application of the same function indicates an opportunity for a more economical recursive approach. [Answer] # Choosing values based on integer The naive approach to choose between `y` and `z`, depending on whether `x` is `0` or `1` is ``` If[x<1,y,z] ``` However, there's a shorter way: ``` y[z][[x]] ``` This works because `[[0]]` gives the `Head` of an expression, in this case `y`, whereas `[[1]]` just gives the first element - in this case the first argument, `z`. You can even use this to choose between more than two values: ``` u[v,w][[x]] ``` Note that this won't work if `u` is a function that actually evaluates to something. It's important that Mathematica keeps `u[v,w]` as it is. However, this works in most cases, including if `u` is a is a number, a string or a list. Credits for this trick go to alephalpha - I discovered this in one of his answer. If `x` is 1-based instead of zero-based, just use ``` {y,z}[[x]] ``` or ``` {u,v,w}[[x]] ``` In some rare cases, you can even make use of the fact that multiplication is not evaluated for some values: ``` {"abc","def"}[[x]] ("abc""def")[[x]] ``` Note though that Mathematica will actually reorder the arguments, of a multiplication if it remains unevaluated, so the above is *identical* to ``` ("def""abc")[[x]] ``` [Answer] # Don't use `{}` if you are using `@@@`. In some cases, you may encounter an expression like: ``` f@@@{{a,b},{c,d}} ``` It is possible to reduce bytes by writing: ``` f@@@{a|b,c|d} ``` `Alternatives` has a very low precedence, so it's generally okay to write expressions (a notable exception is pure functions; you can use it only in the leftmost element of `Alternatives`). ``` f@@@{f@a|b~g~1,#^2&@c|d@2} ``` Note that `f@@a|b|c` (instead of `f@@{a,b,c}`) does not work because `Apply` has a higher precedence than `Alternative`. In this case, you should simply use `f@@{a,b,c}`. [Answer] ## Alternatives to `Length` *This has been entirely rewritten with some suggestions from LegionMammal978 and Misha Lavrov. Many thanks to both of them.* In many cases, `Length` can be shortened a bit by making use of `Tr`. The basic idea is to turn the input into a list of `1`s, so that `Tr` sums them up which will then equal the length of the list. The most common way to do this is to use `1^x` (for a list `x`). This works because `Power` is `Listable` and `1^n` for most atomic values `n` is just `1` (including all numbers, strings and symbols). So we can already save one byte with this: ``` Length@x Tr[1^x] ``` Of course, this assumes that `x` is an expression with higher precedence than `^`. If `x` contains only `0`s and `1`s, we can save another byte using `Factorial` (assuming `x` has higher precedence than `!`): ``` Length@x Tr[x!] ``` In some rare cases, `x` might have lower precedence than `^` but still higher precedence than multiplication. In that case it will also have lower precedence than `@`, so we really need to compare with `Length[x]`. An example of such an operator is `.`. In those cases, you can still save a byte with this form: ``` Length[x.y] Tr[0x.y+1] ``` Finally, some remarks about what kind of lists this works on: As mentioned at the top, this works on flat lists containing only numbers, strings and symbols. However, it will also work on some deeper lists, although it actually computes something slightly different. For an **n**-D rectangular array, using `Tr` gives you the *shortest* dimension (as opposed to the first). If you know that the outermost dimension is the shortest, or you know they're all the same, than the `Tr`-expressions are still equivalent to `Length`. [Answer] # Don't write 0-argument functions There is no need for code like this: ``` f[]:=DoSomething[1,2] (*...*) f[] (*...*) f[] ``` You can simply use a variable with `:=` to force re-evaluation of the right-hand side: ``` f:=DoSomething[1,2] (*...*) f (*...*) f ``` This also means that you can alias any action that you perform often (even if it's just something like `n++`) to a single character at the cost of 5 bytes. So in the case of `n++` it pays back after the fourth use: ``` n++;n++;n++;n++ f:=n++;f;f;f;f ``` [Answer] ## Mathematica 10 only **Operator forms** Mathematica 10 supports so-called "operator forms", which basically means some functions can be curried. Currying a function is to create a new function by fixing one of its operators. Say, you're using `SortBy[list, somereallylongfunction&]` a lot of different `list`s. Before, you probably would have assigned `SortBy` to `s` and the pure function to `f` so ``` s=SortBy; f=somereallylongfunction&; list1~s~f; list2~s~f; list3~s~f; ``` Now you can curry `SortBy`, which means you can now do ``` s=SortBy[somereallylongfunction&]; s@list1; s@list2; s@list3; ``` The same works for a lot of other functions, which take a list or function argument, including (but not limited to) `Select`, `Map`, `Nearest`, etc. ybeltukov over on Mathematica.SE was able [to produce a complete list of these](https://mathematica.stackexchange.com/q/60045/2305): ``` {"AllTrue", "AnyTrue", "Append", "Apply", "AssociationMap", "Cases", "Count", "CountDistinctBy", "CountsBy", "Delete", "DeleteCases", "DeleteDuplicatesBy", "Extract", "FirstCase", "FirstPosition", "FreeQ", "GroupBy", "Insert", "KeyDrop", "KeyExistsQ", "KeyMap", "KeySelect", "KeySortBy", "KeyTake", "Map", "MapAt", "MapIndexed", "MatchQ", "MaximalBy", "MemberQ", "Merge", "MinimalBy", "NoneTrue", "Position", "Prepend", "Replace", "ReplacePart", "Scan", "Select", "SelectFirst", "SortBy", "StringCases"} ``` **Composition and RightComposition** There are new shorthands for `Composition` (`@*`) and `RightComposition` (`/*`). An obviously contrived example where these can save characters is seen in the following three equivalent lines ``` Last@Range@# & /@ Range[5] Last@*Range /@ Range[5] Range /* Last /@ Range[5] ``` [Answer] If you need a list of numbers sorted in reverse, don't use ``` Reverse@Sort@x ``` but ``` -Sort@-x ``` to save six bytes. Sorting by a negative value is also useful for `SortBy` scenarios: ``` Reverse@SortBy[x,Last] SortBy[x,-Last@#&] ``` [Answer] # Use `Null` as an iteration variable As has been mentioned [elsewhere](https://codegolf.stackexchange.com/a/100629/81203), missing arguments are interpreted as `Null`. Since iterators such as those used in `Sum` or `Table` localize the iteration variable, symbols such as `Null` can be used as the iteration variable, potentially saving bytes. For example, ``` Sum[,{,10}] ``` is interpreted as `Sum[Null,{Null,10}]`, which evaluates to the expected `55`. [Answer] # Use `%` to get a free variable **This tip is only applicable if Mathematica's REPL environment can be assumed.** `%` is not defined when code is run as a script. When you *can* make use of the REPL features, don't do this: ``` a=someLongExpression;some[other*a,expression@a,using^a] ``` Instead, remember that Mathematica stores the last evaluated (newline-terminated) expression in `%`: ``` someLongExpression; some[other*%,expression@%,using^%] ``` The added newline costs a byte, but you are saving two by removing `a=`, so overall this saves one byte. In some cases (e.g. when you want to print the value of `a` anyway), you can even leave off the `;`, saving two bytes: ``` someLongExpression some[other*%,expression@%,using^%] ``` One or two bytes may seem fairly minor, but this is an important case, because it makes extraction of repeated expressions (which is a very common technique) much more useful when golfing: The normal technique of extracting repeated expressions costs four bytes of overhead, which need to be saved by further uses of the expression. Here is a short table of the minimum number of uses of an expression (by length of the expression) for extraction into a named variable to save anything: ``` Length Min. Uses 2 6 3 4 4 3 5 3 6 2 ... 2 ``` By using the unnamed variable, it will be possible to save a couple of bytes much more often: ``` When ; is required When ; can be omitted Length Min. Uses Length Min. Uses 2 5 2 4 3 3 3 3 4 3 4 2 5 2 ... 2 ... 2 ``` --- I don't think `%%` or `%n` can be used for golfing, because if you don't use them at least twice, you can just put the expression right where it's needed. And if you use it twice, the additional character in the variable name cancels out the savings from omitting some `x=`. [Answer] # Mathematica 10.2: `BlockMap` is `Partition`+`Map` This tip could also be titled, "Read the release notes, all of them". (For reference, [here are the release notes for 10.2](http://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn102.html) and [here of today's 10.3 release](http://reference.wolfram.com/language/guide/SummaryOfNewFeaturesIn103.html).) Anyway, even minor releases contain a wealth of new features, and one of the more useful ones (for golfing) from 10.2 is the new `BlockMap` function. It essentially combines `Partition` and `Map`, which is great for is golfers, because `Partition` is used quite often, and it's a really annoyingly long function name. The new function won't shorten `Partition` by itself, but whenever you want to map a function onto the partitions (which probably happens more often than not), you can now save a byte or two: ``` #&/@l~Partition~2 BlockMap[#&,l,2] ``` ``` #&/@Partition[l,3,1] BlockMap[#&,l,3,1] ``` The savings get even bigger when the new position of the unnamed function allows you to save yourself some parentheses: ``` #&@@(#&/@Partition[l,3,1]) #&@@BlockMap[#&,l,3,1] ``` Unfortunately, I have no idea why didn't also add `BlockApply` while they were at it... Also note that `BlockMap` does not support the 4th parameter you can use with `Partition` to get a cyclic list: ``` Partition[Range@5, 2, 1, 1] (* Gives {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 1}} *) BlockMap[f, Range@5, 2, 1, 1] (* Nope... *) ``` [Answer] # Checking if a list is sorted This is essentially a corollary of [this tip](https://codegolf.stackexchange.com/a/45188/8478) but this is a sufficiently common task that I think it warrants its own answer. The naive way to check if a list is in order is to use ``` OrderedQ@a ``` We can do one byte better with ``` Sort@a==a ``` However, this doesn't work if we don't have the thing we want to check in a variable already. (We'd need something like `Sort[a=...]==a` which is unnecessarily long.) However, there's another option: ``` #<=##&@@a ``` The best thing is that this can be used to check whether the input is reverse sorted for the same byte count: ``` #>=##&@@a ``` One more byte can be saved if a) we know that the list elements are distinct and b) we know a lower bound between 0 and 9 (inclusive; or upper bound for reverse sorted order): ``` 0<##&@@a 5>##&@@a ``` To see why this works, check out "Sequences of arguments" in the tip linked at the top. [Answer] ### Repeating a string Instead of `StringRepeat[str,n]` use `(0Range[n]+str)<>""`. Or if `str` doesn't depend on any slot arguments, even better is `Array[str&,n]<>""` as per [this](https://codegolf.stackexchange.com/a/60086/30688) tip. [Answer] You can stick an expression in `Break` which can save one or two characters. Example (*other details not golfed for clarity*): ``` result = False; Break[] ``` can be turned into ``` Break[result = False] ``` to save one character. If the expression in question does not have lower precedence than function application you can even save another character: ``` Print@x; Break[] ``` can be turned into ``` Break@Print@x ``` Although undocumented, the argument to `Break` seems to be returned by the surrounding loop, which can potentially lead to even more savings. [Answer] [Here is a list with loads of operator input forms](http://reference.wolfram.com/language/tutorial/OperatorInputForms.html) which can shorten a lot of things. Some of these have been mentioned in other posts, but the list is *long* and I'm always surprised to find a few new things on there: [Answer] To remove all whitespace from a string `s`, use ``` StringSplit@s<>"" ``` That is, use `StringSplit`'s default (split into non-whitespace components) and simply join them back together. The same is probably still the shortest if you want to get rid of any other character or substring: ``` s~StringSplit~"x"<>"" ``` [Answer] ## Alternatives to `Range` A very common task is to apply some sort of function to all numbers from 1 to a `n` (usually given as input). There are essentially 3 ways to do this (using an unnamed identity function as an example): ``` #&/@Range@n Array[#&,n] Table[i,{i,n}] ``` I tend to go for the first one (for whatever reason), but this is rarely the best choice. ### Using `Array` instead The above example shows that using `Array` has the same byte count. However, it has the advantage that it is a single expression. In particular, if you want to further process the result with a function `f` you can use prefix notation, which saves a byte over `Range`: ``` f[#&/@Range@n] f@Array[#&,n] ``` Furthermore, you may be able omit parentheses around your unnamed function which you might have needed with `Range`, e.g. ``` 15/(#&)/@Range@n 15/Array[#&,n] ``` If you *don't* want to use it further (or with an operator which has lesser precedence), you can instead write `Array` itself in infix notation and also save a byte: ``` #&/@Range@n #&~Array~n ``` Hence, `Array` is almost certainly better than `Range`. ### Using `Table` instead Now table has to make up for 3 bytes, or at least 2 when infix notation is an option: ``` #&/@Range@n i~Table~{i,n} ``` When *not* using infix notation, `Table` might allow you to omit parentheses if your function consists of several statements: ``` (#;#)&/@Range@n Table[i;i,{i,n}] ``` This is still longer, but gives extra savings with in the case mentioned below. The real savings stem from the fact that `Table` gives the running variable a name should not be dismissed. Often, you'll have nested unnamed functions where you want to use the outer variable inside one of the inner functions. When that happens, `Table` is shorter than `Range`: ``` (i=#;i&[])&/@Range@n Table[i&[],{i,n}] i&[]~Table~{i,n} ``` Not only do you save the characters for assigning `i`, you might also be able to reduce the function to a single statement in the process, which allows you to use infix notation on top of it. For reference, `Array` is also longer in this case, but still shorter than `Range`: ``` (i=#;i&[])&~Array~n ``` ### When would you actually use `Range`? Whenever you don't need a function call to process the values, e.g. when the mapping can be performed via a vectorised operation. For instance: ``` 5#&~Array~n 5Range@n ``` ``` #^2&~Array~n Range@n^2 ``` Of course, it's also shorter if you don't want to map any function at all, e.g. ``` Mean@Array[#&,n] Mean@Range@n ``` [Answer] # Finding the smallest number that satisfies a condition Some construct like `i=1;While[cond[i],i++]` is fine as is, but there is an alternative that is two bytes shorter: ``` 1//.i_/;cond[i]:>i+1 ``` The above code repeatedly replaces a number `i` with `i+1` while it meets the condition `cond[i]`. In this case, `i` starts at `1`. Note that the default maximum number of iterations is 2^16 (= 65536). If you need more iterations than that, `While` would be better. (`MaxIterations->∞` is too long) [Answer] # Storing functions and expressions in a variable If your answer ends up using the same functions or expressions multiple times, you may want to consider storing them in variables. If your expression is length `l` and you use it `n` times, it would normally use up `l * n` bytes. However, if you store it in a length-1 variable, it would take only `3 + l + n` bytes (or `2 + l + n` bytes, if you assign the variable where you won't need `CompoundExpression (;)` or parentheses). --- For example, let's consider a simple problem, finding [twin primes](https://en.wikipedia.org/wiki/Twin_prime) less than N. One could write this 54 byte solution: ``` Select[Range@#,PrimeQ@#&&(PrimeQ[#+2]||PrimeQ[#-2])&]& ``` In this example, the function `PrimeQ` is used three times. By assigning `PrimeQ` a variable name, the byte count can be reduced. Both of the following are 48 bytes (54 - 6 bytes): ``` Select[p=PrimeQ;Range@#,p@#&&(p[#+2]||p[#-2])&]& Select[Range@#,(p=PrimeQ)@#&&(p[#+2]||p[#-2])&]& ``` [Answer] # Abuse [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation) You can sometimes replace `If` with a logical operator. For instance, let's say you want to make a function that checks whether a number is prime, and print `2*(number) - 1` is if it's true: ``` If[PrimeQ@#,Print[2#-1]]& ``` It's shorter if you use `&&` instead: ``` PrimeQ@#&&Print[2#-1]& ``` Even when you have multiple expressions, you still save byte(s): ``` If[PrimeQ@#,a++;Print[2#-1]]& PrimeQ@#&&a++&&Print[2#-1]& (* or *) PrimeQ@#&&(a++;Print[2#-1])& ``` You can use `||` for cases when you want the condition to be `False`: ``` If[!PrimeQ@#,Print[2#-1]]& (* or *) If[PrimeQ@#,,Print[2#-1]]& (* can become *) PrimeQ@#||Print[2#-1]& ``` These tricks work because logical operators can be [short-circuited](https://en.wikipedia.org/wiki/Short-circuit_evaluation); the second argument and thereafter don't even need to be valid boolean expressions. Of course, this does not work if you need the return value of `If` or when you need both truthy and falsy arguments of `If`. [Answer] # Special characters **This post is community wiki. Feel free to edit and add more characters that you find useful.** Mathematica has many special [named characters](https://reference.wolfram.com/language/tutorial/InputAndOutputInNotebooks.html#4718). Some of them are helpful for golfing. But these characters are hard to type outside Mathematica. Some are even in the [Private Use Areas](https://en.wikipedia.org/wiki/Private_Use_Areas). The following is a list of commonly used named characters, so that you can copy and paste. Other than the 2-byte `°` (`\[Degree]`), all of these characters are 3 bytes long. * ``: `\[Conjugate]`, conjugate of a complex number * ``: `\[ConjugateTranspose]`, conjugate transpose of a matrix * ``: `\[Cross]`, cross product * `°`: `\[Degree]`, degree, symbol that equals `Pi/180` * ``: `\[DirectedEdge]`, directed edges in a graph; `->` often works instead * `∣`: `\[Divides]`, `a∣b` means `b` is divisible by `a` * `∈`: `\[Element]`, tests membership in a domain or region (e.g. `Primes`, `Ball[]`) * `⧦`: `\[Equivalent]`, logical equivalence * ``: `\[Function]`, anonymous functions; in Mathematica 12.3 or newer versions you can write `|->` * ``: `\[HermitianConjugate]`, the same as `` (`\[ConjugateTranspose]`) * ``: `\[Implies]`, logical implication * `∞`: `\[Infinity]`, infinity * `⋂`: `\[Intersection]`, set intersection * `⌈`: `\[LeftCeiling]`, `⌈x⌉` is the ceiling of `x` * `⌊`: `\[LeftFloor]`, `⌊x⌋` is the floor of `x` * `⊼`: `\[Nand]`, logical nand * `⊽`: `\[Nor]`, logical nor * ``: `\[Piecewise]`, `{{a,b}...}` is mostly equivalent to `Which[b,a,...,True,0]` * `⌉`: `\[RightCeiling]`, `⌈x⌉` is the ceiling of `x` * `⌋`: `\[RightFloor]`, `⌊x⌋` is the floor of `x` * `√`: `\[Sqrt]`, square root * ``: `\[Transpose]`, transpose of a matrix * ``: `\[UndirectedEdge]`, undirected edges in a graph; `<->` often works instead * `⋃`: `\[Union]`, set union * ``: `\[VectorLess]`, `xy` means `x[[i]]<y[[i]]` for every `i` * ``: `\[VectorLessEqual]`, `xy` means `x[[i]]<=y[[i]]` for every `i` * ``: `\[VectorGreater]`, `xy` means `x[[i]]>y[[i]]` for every `i` * ``: `\[VectorGreaterEqual]`, `xy` means `x[[i]]>=y[[i]]` for every `i` * ``: `\[Xnor]`, logical xnor * `⊻`: `\[Xor]`, logical xor More can be found in this link: <https://reference.wolfram.com/language/guide/ListingOfNamedCharacters.html> [Answer] # Using `Optional (:)` [`Optional (:)`](https://reference.wolfram.com/language/ref/Optional.html) can be used to expand lists in replacements, without having to define a separate rule for the expansion. [This answer by me](https://codegolf.stackexchange.com/a/106533/60043) and [this answer by @ngenisis](https://codegolf.stackexchange.com/a/106649/60043) are examples. **Usage** ``` ... /. {p___, a_: 0, b_, q___} /; cond[b] :> ... ``` The above replacement first uses the pattern `{p___, a_, b_, q___}` and finds a match such that `b` meets a certain condition. When no such match is find, it omits `a_` and instead searches for `{p___, b_, q___}`. `a` is not included in the search and is assumed to have the value `0`. Note that the second pattern search would only work for `b` that occurs at the beginning of the list; if a `b` value satisfying a condition is in the middle, then `{p___, a_, b_, q___}` (which has a higher precedence) would match it instead. The replacement is equivalent to prepending a `0` when a `b` satisfying a condition occurs at the beginning of the list. (i.e. there is no need to define a separate rule, `{b_, q___} /; cond[b] :> ...`) [Answer] ## Know when (and when not) to use named pure function arguments For code golf, pure `Function` arguments are most commonly referenced using `Slot`s; e.g. `#` for the first argument, `#2` for the second, etc. (see [this answer](https://codegolf.stackexchange.com/a/45188/61980) for more details). In many cases, you will want to nest `Function`s. For example, `1##&@@#&` is a `Function` which takes a list as its first argument and outputs the product of its elements. Here is that function in `TreeForm`: [![enter image description here](https://i.stack.imgur.com/6qUVF.png)](https://i.stack.imgur.com/6qUVF.png) Arguments passed to the top level `Function` can only fill `Slot`s and `SlotSequence`s present at the top level, which in this case means that the `SlotSequence` in the inner `Function` will not have any way of accessing arguments to the top level `Function`. In some cases, though, you may want a `Function` nested within another `Function` to be able to reference arguments to the outer `Function`. For example, you may want something like `Array[fun,...]&`, where the function `fun` depends on an argument to the top level `Function`. For concreteness, let's say that `fun` should give the remainder of the square of its input modulo the input to the top level `Function`. One way to accomplish this is to assign the top level argument to a variable: ``` (x=#;Array[Mod[#^2,x]&,...])& ``` Wherever `x` appears in the inner `Function` `Mod[#^2,x]&`, it will refer to the first argument to the outer `Function`, whereas `#` will refer to the first argument to the inner `Function`. A better approach is to use the fact that `Function` has a two argument form where the first argument is a symbol or list of symbols that will represent named arguments to the `Function` (as opposed to unnamed `Slot`s). This ends up saving us three bytes in this case: ``` xArray[Mod[#^2,x]&,...] ``` `` is the three byte private use character `U+F4A1` representing the binary infix operator `\[Function]`. You may also use the binary form of `Function` within another `Function`: ``` Array[xMod[x^2,#],...]& ``` This is equivalent to the above. The reason is that, if you are using named arguments, then `Slot`s and `SlotSequences` are assumed to belong to next `Function` above which does not use named arguments. Now just because we can nest `Function`s in this way, doesn't mean we always should. For example, if we wanted to pick out those elements of a list that are less than the input, we might be tempted to do something like the following: ``` Select[...,xx<#]& ``` It would actually be shorter to use `Cases` and avoid the need for a nested `Function` entirely: ``` Cases[...,x_/;x<#]& ``` [Answer] You can save a byte by working around `Prepend` or `PrependTo`: ``` l~Prepend~x {x}~Join~l {x,##}&@@l ``` or ``` l~PrependTo~x l={x}~Join~l l={x,##}&@@l ``` Unfortunately, this doesn't help for the more common `Append`, which seems to be the shortest equivalent of an `Array.push()` in other languages. [Answer] # To achieve an ascending key-value list, use `Sort` instead of `SortBy` For lists such as `list = {{1, "world"}, {0, "universe"}, {2, "country"}}`, the following three statements are almost equivalent. ``` SortBy[list,#[[1]]&] list~SortBy~First Sort@list ``` # Combine `Select` and `SortBy` Sometimes we need to pick entries out of a larger set and sort them to find a minimum / maximum. **Under some circumstances**, two operations could be combined into one. For example, for a minimum, the following two statements are almost equivalent. ``` SortBy[Select[l,SomeFormula==SomeConstant&],SortValue&] SortBy[l,SortValue+99!(SomeFormula-SomeConstant)^2&] ``` and ``` SortBy[Select[l,SomeFormula!=SomeConstant&],SortValue&] SortBy[l,SortValue+1/(SomeFormula-SomeConstant)&] ``` `1/0` is `ComplexInfinity`, which is "larger" than all real numbers. For a key-value list, for example: ``` {SortValue,#}&/@SortBy[Select[l,SomeFormula==SomeConstant],SortValue&] Sort[{SortValue+99!(SomeFormula-SomeConstant)^2,#})&/@l] ``` ]
[Question] [ You are to print this exact text: ``` A ABA ABCBA ABCDCBA ABCDEDCBA ABCDEFEDCBA ABCDEFGFEDCBA ABCDEFGHGFEDCBA ABCDEFGHIHGFEDCBA ABCDEFGHIJIHGFEDCBA ABCDEFGHIJKJIHGFEDCBA ABCDEFGHIJKLKJIHGFEDCBA ABCDEFGHIJKLMLKJIHGFEDCBA ABCDEFGHIJKLMNMLKJIHGFEDCBA ABCDEFGHIJKLMNONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA ABCDEFGHIJKLMNONMLKJIHGFEDCBA ABCDEFGHIJKLMNMLKJIHGFEDCBA ABCDEFGHIJKLMLKJIHGFEDCBA ABCDEFGHIJKLKJIHGFEDCBA ABCDEFGHIJKJIHGFEDCBA ABCDEFGHIJIHGFEDCBA ABCDEFGHIHGFEDCBA ABCDEFGHGFEDCBA ABCDEFGFEDCBA ABCDEFEDCBA ABCDEDCBA ABCDCBA ABCBA ABA A ``` # Specs * Extra trailing newlines are allowed at the end of the output. * Extra trailing spaces (U+0020) are allowed at the end of each line, including the extra trailing newlines. * You can use all lowercase instead of all uppercase, but you cannot print partially lowercase partially uppercase. * You can return the text as a function output instead of printing it in a full program. # Scoring Since this is a triangle, and a triangle has 3 sides, and 3 is a small number, your code should be small in terms of byte-count. [Answer] # Vim, 37 bytes ``` :h<_↵↵↵YZZPP$xqqxYpGP√2G$A♥-€k$q24@qJ ``` [![enter image description here](https://i.stack.imgur.com/pM4Ku.gif)](https://i.stack.imgur.com/pM4Ku.gif) ## Legend ``` ↵ = Return √ = Ctrl+V ♥ = Ctrl+R € = Escape ``` [Answer] # Logo, ~~232 207 196~~ 190 bytes ## Did somebody say triangles? Get out your compass and protractor, and let's do this the graphical way. The geometry uses an equilateral triangle to align the results. I previously had an isosceles triangle, but it involved too many decimal places. This change also compacted the output, reducing the amount of screen prep and font changing I had to do. I used the [Calormen online interpreter](http://www.calormen.com/jslogo/#) to flesh this one out. If you don't have enough screen real estate, it's going to wrap, but you can also fiddle with some numbers to take care of that. I used the "F11" full-screen mode on my browser. ``` ht pu to r:n:b:l repeat:n[rt:b label char 90-:n lt:b fd:l] end to t:s fd 12 rt 120 bk 6 repeat 2[r:s 90 12] repeat 2[rt 120 r:s 90-heading 24] end rt 90 label "Z lt 210 repeat 25[t repcount] ``` The `r` procedure draws a line of `n` characters. The character is determined automatically depending on how many segments it is told to use. The `b` parameter tells it how much to temporarily rotate so that the letters are pointing in the right direction. The `l` parameter determines the linear distance between letters. The `t` procedure steps to the next position and calls the `r` function a four times to create a triangle, rotating when appropriate. I called it twice for the vertical side because that took fewer bytes than calling it once with special handling. The end of the procedure positions the turtle for start of the next triangle, one step above. `Z` is a special case, so we just print it directly and rotate as if we had just finished a triangle. Finally, `t` is called 25 times. [![In progress annotated picture](https://i.stack.imgur.com/xvU9F.png)](https://i.stack.imgur.com/xvU9F.png)[![Finished result](https://i.stack.imgur.com/gBWWD.png)](https://i.stack.imgur.com/gBWWD.png) [Answer] ## Haskell, 58 bytes ``` f x=init x++reverse x t=unlines$f[f['A'..c]|c<-['A'..'Z']] ``` Defines a function `t` that returns the output as a string. ``` f x= define a helper function init x take the argument minus its last element ++ and concatenate it with reverse x the argument reversed, producing ex. [a,b,c,b,a] from [a,b,c] t= define the main function [ |c<-['A'..'Z']] for every char c from 'A' to 'Z'... ['A'..c] generate the range from 'A' to c f call the helper function to "reflect" it f call the helper function on the entire list unlines$ join on newlines ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` Ṗ;Ṛ ØAḣJÇ€Çj⁷ ``` *Thanks to @LeakyNun for golfing off 3 bytes!* [Try it online!](http://jelly.tryitonline.net/#code=4bmWO-G5mgrDmEHhuKNKw4figqzDh2rigbc&input=) ### How it works ``` Ṗ;Ṛ Helper link. Argument: A (array) Ṗ Pop; yield A without its last element. Ṛ Reversed; yield A with inverted order. ; Concatenate the results to both sides. ØAḣJÇ€Çj⁷ Main link. No arguments. ØA Alphabet; set link argument and return value to "A...Z". J Indices; yield [1, ..., 26]. ḣ Head; take the first, the first two, etc. elements of the alphabet. This yields ["A", AB", ..., "A...Z"]. Ç€ Apply the helper link to each string. Ç Apply the helper link to the array itself. j⁷ Join, separating by linefeeds. ``` [Answer] ## Python, 74 bytes ``` def f(x=66,s='A'): t=s+s[-2::-1];print t if x<91:f(x+1,s+chr(x));print t ``` A Python 2 function that prints and takes no arguments. The key idea is to generate the triangular there-and-back pattern with recursion. First consider this simpler function that prints the letters 'A' up to 'Z' and down back to 'A': ``` def f(x=65): t=chr(x);print t if x<90:f(x+1);print t ``` The function first prints "A" (char-code 65), then recurses to print "B" (66) and so on to "Z" (90). From there, it stops recursing. On the way popping back down the recursive stack, it prints whatever character `t` it printed at the same layer, from "Y" back to "A". The main code does the same, except it accumulates into `s` the string of letters so far, and prints the up-and-down string `s+s[-2::-1]`. Thanks to xsot for 2 bytes. In Python 3, the same thing is a byte shorter (73 bytes) by putting everything on one line. ``` def f(x=66,s='A'):t=s+s[-2::-1];print(t);x>90or[f(x+1,s+chr(x)),print(t)] ``` [Answer] # brainfuck, ~~1733~~ ~~121~~ 119 bytes ``` ----[---->+<]>++.<++++++++++.<+++++[<+++++>-]<+>>>.<[>>[>.]<[>+>+<<-]>+.>[<<+> >-]<[<.]<-]>>[>[>]<[-]<[<]>>[.>]<<[.<]>] ``` Slightly more readable version: ``` ----[---->+<]>++.< ++++++++++.< +++++[<+++++>-]<+ >> >.< [ >>[>.]< [>+>+<<-] >+.> [<<+>>-] <[<.]< - ] >> [ >[>]< [-] <[<]> >[.>]<<[.<]> ] ``` Explanation possibly to come. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~20 13 12~~ 6 bytes Saved 2 bytes thanks to Adnan. Saved 6 bytes thanks to *Magic Octopus Urn* and some new language functionality. ``` Aη€ûû» ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f8dz2R01rDu8@vPvQ7v//AQ "05AB1E – Try It Online") **Explanation** ``` Aη # push prefixes of alphabet €û # palendromize each prefix û # palendromize the whole list » # join on newlines ``` [Answer] # Python 3, 97 bytes ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ" a=[s[:x]+s[x::-1]for x in range(26)] print('\n'.join(a+a[24::-1])) ``` [Ideone it!](http://ideone.com/D2L9xU) [Answer] # J, ~~26~~ ~~23~~ 22 bytes ``` f(f=:,1}.|.)\u:65+i.26 ``` ## Explanation ``` ,1}.|. Monad f: Input: A |. Reverse the items in A 1}. Drop the first item in the reversed A , Join A and the previous f(f=:,1}.|.)\u:65+i.26 i.26 Create the range [0, 1, ..., 25] 65+ Add 65 to each u: Convert to characters to get 'A..Z' f=:,1}.|. Define a verb f ( )\ Call f monadically on each prefix of 'A..Z' f Call f again on that result ``` [Answer] # Ruby, 71 bytes [Try it on repl.it](https://repl.it/Civw) ``` s=*?A..?Y s+=[?Z]+s.reverse puts s.map{|e|k=[*?A...e]*'';k+e+k.reverse} ``` [Answer] # [><>](https://esolangs.org/wiki/Fish), 60 bytes ``` 1"AA"1[v ?v:1-:}>:5d*= o>l ?!v {$-}:1[\ao]{:}+::"@Z"@=?;=2* ``` [Try it online!](http://fish.tryitonline.net/#code=MSJBQSIxW3YKP3Y6MS06fT46NWQqPQpvPmwgID8hdgp7JC19OjFbXGFvXXs6fSs6OiJAWiJAPT87PTIq&input=) [Answer] # C, ~~272~~ ~~247~~ ~~234~~ ~~230~~ ~~144~~ 137 bytes: (*Saved many bytes (`272 -> 230`) in my previous method thanks to great golfing tips & tricks from [sigalor](https://codegolf.stackexchange.com/users/41463/sigalor)!*) (*Saved nearly 100 bytes (`230 -> 144`) by switching to a better method.*) ``` main(q,i,e,x){for(q=0;q<51;q++){i=q>25 ? 25-(q-25):q;for(e=65;e<66+i;e++)printf("%c",e);for(x=64+i;x>64;x--)printf("%c",x);printf("\n");}} ``` My first answer ever in `C`. I just started self-learning it recently, so let's see how it goes. [C it in Action! (Ideone)](https://ideone.com/9mlbQk) [Answer] # JavaScript (ES6), 81 bytes ``` [...'ZYXWVUTSRQPONMLKJIHGFEDCBA'].reduce((p,c)=>c+` `+p.replace(/^|$/gm,c)+` `+c) ``` [Answer] # Mathematica 59 bytes ``` Column@FromCharacterCode[#@#@26+64]&[#-Abs@Range[1-#,#-1]&] ``` [Answer] ## Dyalog APL, 18 bytes ``` ↑(⊣,⌽)(⊣,1↓⌽)¨,\⎕a ``` [Answer] # R, ~~63 61~~ 59 bytes ``` for(i in c(1:26,25:1))cat(LETTERS[c(1:i,i:1-1)]," ",sep="") ``` Helpfully `LETTTERS[0]` doesn't return any characters. Edit: lost one thanks to @leakynun Edit: two more thanks to @plannapus [Answer] # (plain) TeX, 209 bytes ``` \newcount~~65\newcount\j\j64\tt\def\a#1{{\loop\advance\j1\char\j\ifnum\j<#1\repeat\loop\advance\j-1\char\j\ifnum\j>65\repeat}\par}\def\c#1#2#3.{\loop\advance~#11\a~\ifnum~#2#3\repeat}A\par\c{}<90.\c->66.A\bye ``` Output: [![](https://i.stack.imgur.com/il32X.png)](https://i.stack.imgur.com/il32X.png) [Answer] # TSQL, 159 bytes ``` DECLARE @ varchar(52)='ABCDEFGHIJKLMNOPQRSTUVWXY',@o varchar(max)SELECT @+='Z'+REVERSE(@)+' ',@o=@ WHILE''<@ SELECT @=STUFF(@,LEN(@)/2,2,''),@o=@+@o+@ PRINT @o ``` **[Fiddle](https://data.stackexchange.com/stackoverflow/query/520605/alphabet-triangle)** [Answer] # Javascript(using external library-Enumerable), 135 bytes ``` _.Range(1,51).WriteLine(x=>(g=_.Range(65,x>25?52-x:x)).Write("",y=>(w=String.fromCharCode)(y))+(g.Reverse().Skip(1).Write("",y=>w(y)))) ``` Link to the library: <https://github.com/mvegh1/Enumerable> Code explanation: Create a range of ints starting at 1, for a count of 51. For each, write a line according to complex pred. Do some JS wizardry with global variables and caching...and voila. For each int in WriteLine, we are creating the left hand range of ints and storing into global "g", and String Joining (Write) with `""` delimiter and mapping each int to the String mapping to the int char code. Then, we concat the right hand side by taking the reversal of that sequence (and skipping the first element because that will match the last element of the original order...), writing with the same logic. EDIT: Updated the internals of Write in the library. An empty sequence will write an empty string instead of null now. This also shaved 15 bytes off the answer [![enter image description here](https://i.stack.imgur.com/YTF0i.png)](https://i.stack.imgur.com/YTF0i.png) [Answer] # Powershell, 61 52 bytes Thanks to TimmyD for saving 9 bytes! ``` 65..90+89..65|%{-join[char[]]((65..$_-ne$_)+$_..65)} ``` Loops through ASCII values for capital letters forwards, then backwards. For each number, this creates an array of the first X numbers, removes the X-1st number, then adds the reverse of the first X numbers, which is all then cast to chars and joined into a string. [Answer] # Python 2, 117 111 105 100 bytes ``` s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"*2 for i in range(51):print(s[:-i-1]+s[-i-3::-1],s[:i]+s[i::-1])[26>i] ``` [Run it](https://ideone.com/QiWRUJ) Thanks to @**LeakyNun** and @**manatwork** for pointing out a few byte saves. **Non-Golfed:** ``` import string def print_alphatriangle(n): offset = 1 tail_offset = 3 alpha = string.ascii_uppercase * n for i in range(len(alpha) - offset): if len(alpha) / 2 > i: print alpha[:i] + alpha[i::-offset] continue print alpha[:-i-offset] + alpha[-i-tail_offset::-offset] ``` This method works simply by string splicing an *alphabet* string that is concatenated together. Depending on whether `i` has reached a mid-way point of the string, it then starts to print out decreasing strings. [Answer] # [Cheddar](https://github.com/cheddar-lang/Cheddar), ~~102~~ ~~96~~ ~~79~~ ~~69~~ 67 bytes **17 bytes thanks to Downgoat, and inspiration for 10 more.** ``` "A"+(2@"27+@"(25|>1)).bytes.map(i->65@"(64+i)+@"((64+i)|>65)).vfuse ``` The fact that strings can concatenate but not arrays means that I would have to convert the two ranges to strings, concatenate, and then convert back to arrays. Also, the fact that `vfuse` produces a leading newliens means that I would need to generate the first line manually and then concat to the rest. `@"` as a dyad (two-argument function) can convert to string directly, but does not work for reversed range (if first argument is bigger than the second). Range was half-inclusive. After the bug-fix it became inclusive. ## Usage ``` cheddar> "A"+(2@"27+@"(25|>1)).bytes.map(i->(65@"(64+i)+@"((64+i)|>65))).vfuse "A ABA ABCBA ABCDCBA ABCDEDCBA ABCDEFEDCBA ABCDEFGFEDCBA ABCDEFGHGFEDCBA ABCDEFGHIHGFEDCBA ABCDEFGHIJIHGFEDCBA ABCDEFGHIJKJIHGFEDCBA ABCDEFGHIJKLKJIHGFEDCBA ABCDEFGHIJKLMLKJIHGFEDCBA ABCDEFGHIJKLMNMLKJIHGFEDCBA ABCDEFGHIJKLMNONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYZYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXYXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWXWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVWVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUVUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTUTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSTSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRSRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQRQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPQPONMLKJIHGFEDCBA ABCDEFGHIJKLMNOPONMLKJIHGFEDCBA ABCDEFGHIJKLMNONMLKJIHGFEDCBA ABCDEFGHIJKLMNMLKJIHGFEDCBA ABCDEFGHIJKLMLKJIHGFEDCBA ABCDEFGHIJKLKJIHGFEDCBA ABCDEFGHIJKJIHGFEDCBA ABCDEFGHIJIHGFEDCBA ABCDEFGHIHGFEDCBA ABCDEFGHGFEDCBA ABCDEFGFEDCBA ABCDEFEDCBA ABCDEDCBA ABCDCBA ABCBA ABA A" ``` ### Cheddar, 55 bytes (non-competing) In [the latest version](https://github.com/cheddar-lang/Cheddar/releases/tag/v1.0.0-beta.29) with all the fixes, the answer is: ``` (|>25+24|>0).map(i->65@"(65+i)+(i?(64+i)@"65:"")).vfuse ``` but it was made after the challenge. [Answer] # C, 93 bytes Call `f()` without arguments. ``` g(l,n){putchar(l);n?g(l+1,--n),putchar(l):0;}f(n){for(n=-26;++n<26;puts(""))g(65,25-abs(n));} ``` [Try it on ideone](http://ideone.com/xGbRYw). [Answer] # Mathematica ~~98 96~~ 92 bytes There has to be a shorter way, even in Mathematica. 6 bytes saved thanks to Martin Ender. ``` r=Reverse@*Most; Print/@FromCharacterCode@Join[t=Join[s=Range[65,64+k],r@s]~Table~{k,26},r@t] ``` [Answer] ## VBA, 94 bytes ``` Function T:For j=-25To 25:k=25-Abs(j):For i=-k To k:T=T &Chr(65+k-Abs(i)):Next:T=T &vbLf:Next ``` Call in Immediate window with ?T Just to explain what's going on: I use Abs function twice, to reflect both the alphabet traverse and the line length. It's well suited to the task because of the single extreme value in both cases, which corresponds to the zero crossing of the pre-Abs variable. As a simple set of commands in VBA Immediate window, rather than a program or function, the following would need 72 bytes: ``` For j=-25To 25:k=25-Abs(j):For i=-k To k:?Chr(65+k-Abs(i));:Next:?:Next ``` *(with thanks to @GuitarPicker)* [Answer] ## Python, ~~73~~ 71 bytes *Thanks to @xnor for the recursion* ``` f=lambda x=66,s='A',t='':x/92*t or t+f(x+1,s+chr(x),s+s[-2::-1]+"\n")+t ``` --- ### Explanation * **Parameters**: + `x` is the ascii value of the next letter in the alphabet + `s` is an accumulator for the alphabet + `t` is a line in the triangle (ie `s` + `s backwards`) * **Return**: `t` if the alphabet is done (ie we're at the center) * **Else**: `t+f(...)+t` with: + `x` incremented + `s` appended with the next letter + `t` reset to `s` + `s backwards` + `\n` --- **Update** * **-2** [16-08-05] Remove leading `\n` (+1) and shortened conditional (-3) all thanks to *@xnor* [Answer] # HTML + CSS, 884 characters (763 characters HTML + 121 characters CSS) Just expanding [Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)'s [comment](https://codegolf.stackexchange.com/questions/87496/alphabet-triangle/88834?noredirect=1#comment216336_88735) on [MonkeyZeus](https://codegolf.stackexchange.com/users/32018/monkeyzeus)'s [answer](https://codegolf.stackexchange.com/a/88735). (Though I might misread the comment…) ``` p{margin:0}p:before{content:"ABCDEFGH"}p:after{content:"HGFEDCBA"}a:before{content:"IJKLMNOP"}a:after{content:"PONMLKJI"} ``` ``` <pre>A ABA ABCBA ABCDCBA ABCDEDCBA ABCDEFEDCBA ABCDEFGFEDCBA ABCDEFGHGFEDCBA <p>I</p><p>IJI</p><p>IJKJI</p><p>IJKLKJI</p><p>IJKLMLKJI</p><p>IJKLMNMLKJI</p><p>IJKLMNONMLKJI</p><p>IJKLMNOPONMLKJI</p><p><a>Q</p><p><a>QRQ</p><p><a>QRSRQ</p><p><a>QRSTSRQ</p><p><a>QRSTUTSRQ</p><p><a>QRSTUVUTSRQ</p><p><a>QRSTUVWVUTSRQ</p><p><a>QRSTUVWXWVUTSRQ</p><p><a>QRSTUVWXYXWVUTSRQ</p><p><a>QRSTUVWXYZYXWVUTSRQ</p><p><a>QRSTUVWXYXWVUTSRQ</p><p><a>QRSTUVWXWVUTSRQ</p><p><a>QRSTUVWVUTSRQ</p><p><a>QRSTUVUTSRQ</p><p><a>QRSTUTSRQ</p><p><a>QRSTSRQ</p><p><a>QRSRQ</p><p><a>QRQ</p><p><a>Q</a></p><p>IJKLMNOPONMLKJI</p><p>IJKLMNONMLKJI</p><p>IJKLMNMLKJI</p><p>IJKLMLKJI</p><p>IJKLKJI</p><p>IJKJI</p><p>IJI</p><p>I</p>ABCDEFGHGFEDCBA ABCDEFGFEDCBA ABCDEFEDCBA ABCDEDCBA ABCDCBA ABCBA ABA A ``` [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~37~~ 29 bytes **Credits to Fatalize for his assistance throughout.** **4 bytes thanks to Fatalize, and inspiration for another 4 bytes.** ``` @A:1&e:"a"yr:1&cw@Nw\ :Lc.r.! ``` [Try it online!](http://brachylog.tryitonline.net/#code=QEE6MSZlOiJhInlyOjEmY3dATndcCjpMYy5yLiE&input=) ### Predicate 0 (Main predicate) ``` @A:1&e:"a"yr:1&cw@Nw\ @A:1& Apply predicate 1 to @A, which is basically "abcdefghijklmnopqrstuvwxyz" e Choose one element from the result (choice point) :"a"yr generate substring from element to "a" :1& apply predicate 1 c concatenate w write to STDOUT @Nw write "\n" to STDOUT \ Backtrack to last choice point to choose another element until there is no more choice left, then halt. ``` ### Predicate 1 (Auxiliary predicate) This basically builds a palindrome from the given string. ``` :Lc.r.! :Lc. output is [input:L] .r. output reversed is still output ! stop searching after the first output ``` [Answer] # R, ~~127~~ 125 bytes ``` k=cat;L=LETTERS;for(i in 1:26)k(c(L[1:i],L[(i-1):0],"\n"));for(i in 1:26)k(c(L[0:(26-i)],L[ifelse((25-i)>=0,25-i,0):0],"\n")) ``` Not completely satisfied with this solution, especially the two `for` loops, but couldn't come with something better ! `LETTERS` contains the uppercase letters. **Ungolfed :** ``` for(i in 1:26){ cat(c(LETTERS[1:i],LETTERS[(i-1):0],"\n")) } for(i in 1:26){ cat(c(LETTERS[0:(26-i)],LETTERS[ifelse((25-i)>=0,25-i,0):0],"\n")) } ``` `ifelse` is a shorter way for unsing `if... else...` and works this way : `ifelse(condition,action if TRUE, action if FALSE)` An other 125 bytes' solution : ``` for(i in 1:26)(k=cat)(c((L=LETTERS)[1:i],L[(i-1):0],"\n"));for(i in 1:26)k(c(L[0:(26-i)],L[ifelse((25-i)>=0,25-i,0):0],"\n")) ``` [Answer] ## Java 131 bytes **Without using String (131 bytes)** ``` public static void main(String[] args) { for(int i = 0 ,k=1; i>-1; i+=k){ for(int c= 65, d = 1; c>64;){ d = d>-1 & c < 65+i?1:-1; System.out.print((char)c+((c+=d)<65?"\n":"")); } k = k>-1 & i < 25?1:-1; } } ``` **Codegolfed** ``` for(int i=0,k=1;i>-1;k=k>-1&i<25?1:-1,i+=k)for(int c=65,d=1;c>64;d=d>-1&c<65+i?1:-1,System.out.print((char)c+((c+=d)<65?"\n":""))); ``` --- **With String(173 bytes)** ``` String a="abcdefghijklmnopqrstuvwxyz"; for(int i = 1 ,k=1; i>0; i+=k==1?1:-1){ System.out.println(a.substring(0,i)+new StringBuilder(a).reverse().substring(27-i)); k = k>-1 & i < 26?1:-1; } ``` **Codegolfed** ``` String a="abcdefghijklmnopqrstuvwxyz";for(int i=1,k=1;i>0;k=k>-1&i<26?1:-1,System.out.println(a.substring(0,i)+new StringBuilder(a).reverse().substring(27-i)),i+=k==1?1:-1); ``` --- **Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) and [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)** ]
[Question] [ # Definition A dollar word is a word where when each of its letters is given a cent value, from a = 1 to z = 26, and the letters are summed, the result is 100. [Here](https://codereview.stackexchange.com/questions/58446/program-to-find-dollar-words) is an example on CodeReview, and [here](http://mathlair.allfunandgames.ca/onedollarwords.php) is a list of dollar words I found online. # Input Input will be alphabetical from a-z, in your one language's text datatypes (arrays are allowed). You do not need to account for any other input - there will be no spaces, apostrophes, or hyphens. You can take as lowercase, uppercase, or a combination. Trailing newlines are allowed. # Output Output a truthy value if the input is a dollar word, and a falsey value if it is not. # Test Cases Truthy: ``` buzzy boycott identifies adiabatically ttttt ``` Falsey: ``` zzz zzzzzzz abcdefghiljjjzz tttt basic ``` This is code-golf, so the shortest answer in bytes wins! Standard loopholes and rules apply. Tie goes to first poster. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes Code: ``` Ç96-O4bQ ``` Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@3@43dJM198kKfD//6TSqqpKAA "05AB1E – TIO Nexus") Explanation: ``` Ç # Convert the string into a list of character codes 96- # Subtract 96 of each element O # Take the sum 4b # Push 100 (4 in binary) Q # Check if equal ``` [Answer] # Python, ~~39~~ 38 bytes ``` lambda s:sum(ord(i)-96for i in s)==100 ``` [Try it online!](https://tio.run/nexus/python2#JYxBCoMwEEX3nmKYVUK12E2hQnqRtouJMTQQtSSThYpnt5H81YP/eFa9D0@jNgSxi2kUczDCyeZxt3MAB26CKJW6te3BIfF3AQUv1GldF6yxT55TGDKRcaSJXU/eL/ipLPk4FJl0jzXgmnceOctntuQuRewq@AU3MeC2Q/OEbcdrNkdiwTVYwVIefw "Python 2 – TIO Nexus") --- -1 byte thanks to @JonathanAllan [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` 96-s100= ``` Uses lowercase input. [Try it online!](https://tio.run/nexus/matl#@29ppltsaGBg@/@/elJpVVWlOgA "MATL – TIO Nexus") ### Explanation The code is as readable as it gets: ``` 96- % Implicitly input string. Subtract 96 from each char interpreted as ASCII code s % Sum of array 100= % Does it equal 100? Implicitly display ``` [Answer] # [Raku](https://perl6.org), 21 bytes ``` {100==[+] .ords X%32} ``` [Try it](https://tio.run/nexus/perl6#VVDBTsMwDL3nK3wYaNXaaQOJS1W0E1/QQyXEwU1SSBWaqknYmmlfxCfsth8rSVMh8MHPdp6f7VjN4etpS3PyOcK90BlTUuKQHdXAoJjO@92uKF43b7D1BQ3V3ePDZfLUQzlYDgXcvglAbZ0bA6qRKmN8JBjvjGgE1z5BJrBGIyhKGWgmmMcyGLld59mHF5T6V9E5F72LEdaU8eb9Q8i2befKolGjFnTWsL675NrkpJfYLQtuFt2cNGqARqKBdXypIECS@jxOrmDGBLJnWImutyaFFT/1nBrO4ByO0vD/g9aRl/whpktvTi7TDw "Perl 6 – TIO Nexus") Alternate: ``` {Ⅽ==[+] .ords X%32} ``` [Try it](https://tio.run/nexus/perl6#VVDBTsMwDL3nK3wY06q1O4DEpSraiS/oodK0g5ukkCo0VZPAmmlHvgbxBdz2KfxISZoKgQ9@tvP8bMdqDq/3O5qTlxHWQmdMSYlD9qYGBsV0/n7/LIrD9gg7X9BQ3dzdXiZP3ZeD5VDA9YMA1Na5MaAaqTLGR4LxzohGcO0TZAJrNIKilIFmgnksg5Hr1zx7/4hS/yo656J3McKaMt48PQvZtu1cWTRq1ILOGtZ3l1ybnPQSu2XB7aKbk0YN0Eg0sIkvFQRIUp/HyRXMmED2ACvR9daksOKnnlPDGZzDURr@f9Am8pI/xHTpzcll@gE "Perl 6 – TIO Nexus") Note that the `Ⅽ` is `ROMAN NUMERAL ONE HUNDRED` U+216D with a unival of … 100 Which takes 3 bytes to encode. ## Expanded: ``` { # bare block lambda with implicit parameter $_ 100 # is 100 == # equal to [+] # the sum of the following .ords # the ordinals of the input (implicit method call on $_) X[%] # crossed using the modulus operator 32 # with 32 to get 65..90 or 97..122 to become 1..26 } ``` [Answer] # [GS2](https://github.com/nooodl/gs2), 6 bytes ``` ▲1Θd←q ``` Input must be in uppercase. [Try it online!](https://tio.run/nexus/gs2#@/9o2ibDczNSHrVNKPz/38k1yM8xyMXTzx8A "GS2 – TIO Nexus") ### How it works ``` Θ Combine the previous two tokens into a block and map it over the input. ▲ Push 64. 1 Subtract 64 from the character on the stack. d Take the sum of the resulting character array. ← Push 100. q Compare the two items on the stack for equality. ``` [Answer] ## JavaScript (ES6), 46 bytes Returns `0` or `1`. ``` let f = w=>[...w].map(c=>p-=parseInt(c,36)-9,p=100)|!p console.log(f('buzzy')) console.log(f('qwerty')) ``` [Answer] # Mathematica, 23 bytes ``` 100==Tr@LetterNumber@#& ``` Pure function taking a string (or an array of letters) as input, case-insensitive, and returning `True` or `False`. Here `Tr` just adds the letter-numbers together; everything else is self-explanatory. [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f s=sum[1|c<-s,_<-['a'..c]]==100 ``` [Try it online!](https://tio.run/nexus/haskell#HYpbCoMwFAW3cpCCP1X036xEpNy82hsSFRMRQ/duTQcOw4G5LKKIexj7rxqa@HwNzVhT3bZqmoTou@4KxDME1o3nhAcCrbC3j2XTEZXccz4hl1MtKYG1mRNbNhGkmSQlVuT9iVRAzrmsAJJKG/v@sHfO3f8fSIqsqusH "Haskell – TIO Nexus") The idea is to make a list of characters from `a` to the given character for each character in the list, and check that the total length is 100. Other attempts: ``` f s=sum[1|c<-s,_<-['a'..c]]==100 f s=sum[fromEnum c-96|c<-s]==100 f s=100==length((\c->['a'..c])=<<s) (==100).length.(>>= \c->['a'..c]) (==100).length.(=<<)(\c->['a'..c]) (==100).length.(enumFromTo 'a'=<<) f s=100==length(do c<-s;['a'..c]) ``` Too bad `enumFromTo` is so long. [Answer] # C, ~~45~~ 43 bytes *Thanks to @Neil for saving two bytes and making the solution case-insensitive!* ``` n;f(char*s){for(n=100;*s;)n-=*s++&31;n=!n;} ``` [Try it online!](https://tio.run/nexus/c-gcc#HcjRCkAwFIDh@z3FrGhnKHJ52o08hptFi@LQxgXy7LP8V19/ILRymIxTHh67OUm6ripUHoFKrXyeZ02NpBPCN8x08NXMJIE9jMd2F5eVIh17SkdR8Oj2vO9LwO9uWxbjBACyN3w) [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` f w=sum[fromEnum c-96|c<-w]==100 ``` This works for lowercase input. For uppercase, `s/96/64/`. Mixed-case support would add a bunch of bytes. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7?\* 8 [bytes](https://github.com/DennisMitchell/jelly) ``` ɠO%32S⁼³ ``` Full program, outputting 1 if the input is a dollar word, or 0 if not. **[Try it online!](https://tio.run/nexus/jelly#@39ygb@qsVHwo8Y9hzb//5@ZkppXkpmWmVrMBQA)** ### How? ``` ɠO%32S⁼³ - Main link ɠ - read a line of input from STDIN O - cast to ordinals %32 - mod 32 (vectorises) (-3*32=96 from lowercase; -2*32=64 from uppercase) S - sum ³ - literal: 100 ⁼ - equal? ``` --- \* Could it be 7 bytes? The only reason this took input with `ɠ` was to keep `³` as the literal 100 rather than the 3rd command line input (1st program input). A way to avoid that would be, as pointed out by Dennis, to create 100 using the raw literal form `ȷ2` which is 102. This leads to another 8 byte `O%32S=ȷ2`, but this is now an unnamed monadic function (as well as operating as a full program with a 3rd argument). Since, in golf, one may create variables or helper functions which restrict the program in which they may reside (one cannot reuse the name in-scope without stopping the function from being reusable), maybe restricting the program to only taking input from STDIN may also be acceptable, in which case the 7 byte `O%32S=³` would be acceptable here as an unnamed function. [Answer] ## [Alice](https://github.com/m-ender/alice), 23 bytes ``` /o! \i@/e)q&w[?'`-+k3-n ``` [Try it online!](https://tio.run/nexus/alice#@6@fr8gVk@mgn6pZqFYeba@eoKudbayb9/9/YkpmYlJiSWZyYk5OJQA "Alice – TIO Nexus") Input should be lower case. Prints `1` for dollar words and `0` otherwise. ### Explanation Time to show off Alice's tape and some advanced control flow. Despite being fairly good at working with integers and strings individually, Alice has no built-ins to a) determine a string's length, b) convert between characters and their code points. The reason for this is that all of Alice's commands either map integers to integers or strings to strings. But both of those would require mapping strings to integers or vice versa, so they don't fit into either of Alice's modes. However, in addition to it's stack, Alice also has a tape and Cardinal and Ordinal mode interpret the data on the tape in different ways * In Cardinal mode, it's a regular tape familiar from other languages like Brainfuck. You can store one integer in each cell and you can move a tape head around. The tape is infinitely long and initially holds a **-1** in every cell. The cells are also indexed and the tape head starts at index **0**. * Ordinal mode has its own tape head (also starting at index **0**) and it interprets the tape as a list of strings. Strings are terminated by non-character cells (i.e. any values which are not a valid Unicode code point), in particular **-1**. So for Ordinal mode, the tape is initially filled with empty strings. This tape can be used for both of the above operations: to get a string length, we write it to the tape in Ordinal mode, seek the terminating **-1** in Cardinal mode and retrieve the position of the tape head. To convert characters to their code points, we simply read them off the tape in Cardinal mode. The other two important features used in this solution are the return stack and an iterator. Alice has a return stack which is usually filled when using the jump command `j`, and which you can pop an address from to jump back with `k`. However, it's also possible to push the current address to the return stack without jumping anywhere with `w`. If we combine `w` with the *repeat* command `&`, we can push the current address to the return stack **n** times. Now each time we reach `k`, one copy is popped off the return stack and we perform another iteration from `w` (starting at the cell after it, because the IP moves before executing another command). When the return stack becomes empty, `k` does nothing at all and the IP simply passes through. Hence `&w...k` pops an integer **n** and then executes `...` **n+1** times, which gives us a very concise way to express a simple `for` loop. On to the code itself... ``` / Reflect to SE. Switch to Ordinal. i Read the input word as a string. Bounce off bottom boundary, move NE. ! Store the input word on the tape. Bounce off top boundary, move SE. / Reflect to E. Switch to Cardinal. e Push -1. ) Seek right on the tape for a -1, which finds the -1 terminating the input word. q Push the tape head's position, which gives us the string length N. &w Repeat this loop n+1 times (see above for an explanation)... [ Move the tape head left by one cell. ? Retrieve the code point of the character in that cell. '` Push 96. - Subtract it from the code point to convert the letters to 1...26. + Add the result to a running total. This total is initialised to zero, because in Cardinal mode, the stack is implicitly filled with an infinite amount of zeros at the bottom. k End of loop. Note that the above loop ran once more than we have characters in the string. This is actually really convenient, because it means that we've added a "-1 character" to the running total. After subtracting 96 to convert it to its "letter value" this gives 97. So dollar words will actually result in 100 - 97 = 3, which we can check against for one byte less than for equality with 100. 3- Subtract 3 to give 0 for dollar words. n Logical NOT. Turns 0 (dollar words) into 1 and everything else into 0. The IP wraps around to the beginning of the first line. \ Reflect to NE. Switch to Ordinal. o Implicitly convert the result to a string and print it. Bounce off top boundary, move SE. @ Terminate the program. ``` [Answer] # R, ~~55~~ 54 bytes ``` function(x)sum(match(el(strsplit(x,"")),letters))==100 ``` -1 byte thanks to BLT * returns a function that does the required computation, which returns `TRUE` and `FALSE` as one would expect. * takes input in as lowercase; would only be a switch from `letters` to `LETTERS` for all uppercase [Answer] # Ruby, 25 bytes ``` ->s{s.sum-s.size*64==100} ``` Works for uppercase. I see a couple of more complex Ruby entries, but it really is this simple. `s.sum` adds the ASCII codes of the input string, and from this we subtract 64 times the length of the string. **Example of use** ``` f=->s{s.sum-s.size*64==100} puts f["ADIABATICALLY"] puts f["ZZZ"] ``` [Answer] # Java 8, 36 bytes ``` s->s.chars().map(c->c%32).sum()==100 ``` [Try it online!](https://tio.run/nexus/java-openjdk#ZY6xTgMxDIb3ewovSIlErQLjcTcwMMF0I2Iwaa6kSpwocQoV6rMfhxpY@Bdb9qfPXlxIMQsc6EhYxXmcKxtxkfGxNX33j5kMMdvcd12qb94ZMJ5KgWdyDF8drGnzIiRrOUa3g7Bu1STZ8f7lFSjvi27wT36v3V@Ia3iI0VviEWYYoGzGguadclEaAyVlNqO5urvVWGpQehhuttv@zzWditiAsQqmVSae1YyUkj8pth/QvlcNc6yR7ac8ObZKa33xnLvzslQmLzbb3Tc "Java (OpenJDK 8) – TIO Nexus") Note: case independent. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes ``` 5bIvAyk>- ``` [Try it online!](https://tio.run/nexus/05ab1e#@2@a5FnmWJltp/v/f1JpVVUlAA "05AB1E – TIO Nexus") **Explanation** As **1** is the only truthy value in 05AB1E we can save a byte using subtraction over comparing to *100*. ``` 5b # convert 5 to binary (results in 101) Iv # for each letter in input word Ayk # get the index of the letter in the alphabet > # increment - # subtract from total ``` [Answer] # [Perl 5](https://www.perl.org/), 30 bytes *-1 byte thanks to @Neil (`31&` instead of `-96+`).* 29 bytes of code + `-p` flag. ``` $@+=31&ord for/./g;$_=$@==100 ``` [Try it online!](https://tio.run/nexus/perl5#U1YsSC3KUdAt@K/ioG1rbKiWX5SikJZfpK@nn26tEm@r4mBra2hg8P9/elF@aUkxAA "Perl 5 – TIO Nexus") [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 36 30 bytes ``` $args|%{$s+=$_[0]-96};$s-eq100 ``` [Try it online!](https://tio.run/nexus/powershell#@6@SWJReXKNarVKsbasSH20Qq2tpVmutUqybWmhoYPD//3/1JPX/6qVAXAXFlepf8/J1kxOTM1IB "PowerShell – TIO Nexus") Inputs as an array, but I'm wondering if there is a better way to handle characters. **EDIT** Missed an easy space but @AdmBorkBork kindly let me know :P also, there was in fact a better way to handle the characters! [Answer] # [Alice](https://github.com/m-ender/alice), ~~28~~ 18 bytes *Thanks to @MartinEnder for golfing 10 bytes* ``` =I.!'`-+?hn >3-nO@ ``` [Try it online!](https://tio.run/nexus/alice#@2/rqaeonqCrbZ@Rx2VnrJvn7/D/f2JKZmJSYklmcmJOTiUA "Alice – TIO Nexus") This submission uses a different method than @MartinEnder's answer. This submission outputs `0x00` for falsy and `0x01` for truthy. So here is a version that outputs `0` or `1` instead: [Try it!](https://tio.run/nexus/alice#@2/rqaeonK@eoKttn5HHZWesm6ev4PD/f2JKZmJSYklmcmJOTiUA) ### Explanation The explanation below is for the "visible" version. Both are very similar, except in the first program, the last `o` doesn't convert the `0` or `1` into a string (because we are in cardinal mode), but instead takes the number and output the character at that code point. ``` = Does nothing, but will be useful later on I Read a character and push its code point onto the stack If there is no more input, -1 is pushed instead . Duplicate it ! Store it on the tape # Skip the next command o Gets skipped '` Push 96 - Subtract it from the character + And add it to the total ? Load the number on the tape h Increment it n And negate it For all characters that are read, ?hn results in 0, but if -1 is pushed, then the result becomes 1 ``` After this the IP wraps around to the left edge at the `=`. If the top value of the stack is `0`, the IP continues on with its path, increasing the total sum of all the characters, once it is done with the input (the top of the stack will be `1`), then the IP turns right (90 degrees clockwise). One thing is important to note, the loop on the first line will iterate once after the input has ended. This will subtract `97` (`96` from the `'`` and `-1` from the lack of input) from the total. ``` > Set the direction of the IP to East 3- Subtract 3 from it (yields 0 if sum is 100, something else otherwise) n Negate it; Zero becomes 1, non-zero numbers become 0 / Mirror; the IP gets redirected South-East The IP reflects off the bottom and goes North-East Now the program is in Ordinal mode, where numbers are automatically converted into strings when being used o Output the top of the stack as a string IP reflects off the top and heads South-East @ End the program ``` [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 1259 bytes ``` Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to Auctioneer School.Go to Auctioneer School:s 1 r 1 l 1 l.Pickup a passenger going to Chop Suey.0 is waiting at Starchild Numerology.Go to Starchild Numerology:s 1 l.Pickup a passenger going to Addition Alley.Go to Chop Suey:e 1 l 2 r 3 r 3 r.[a]Switch to plan "b" if no one is waiting.Pickup a passenger going to Charboil Grill.Go to Charboil Grill:n 1 l 3 l 3 l.Pickup a passenger going to What's The Difference.Go to Go More:e.64 is waiting at Starchild Numerology.Go to Starchild Numerology:e 2 r.Pickup a passenger going to What's The Difference.Go to What's The Difference:e 1 l 2 r 1 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:e 2 r.Pickup a passenger going to Addition Alley.Go to Chop Suey:n 1 r 2 r.Switch to plan "a".[b]Go to Addition Alley:n 1 l 2 l.Pickup a passenger going to Equal's Corner.100 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 1 l 3 l 2 r.Pickup a passenger going to Equal's Corner.Go to Equal's Corner:w 1 l.Switch to plan "c" if no one is waiting."TRUE" is waiting at Writer's Depot.[c]"FALSE" is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:n 1 r 2 r 1 l. ``` With line breaks, it looks like this: ``` Go to Post Office:w 1 l 1 r 1 l. Pickup a passenger going to Auctioneer School. Go to Auctioneer School:s 1 r 1 l 1 l. Pickup a passenger going to Chop Suey. 0 is waiting at Starchild Numerology. Go to Starchild Numerology:s 1 l. Pickup a passenger going to Addition Alley. Go to Chop Suey:e 1 l 2 r 3 r 3 r. [a] Switch to plan "b" if no one is waiting. Pickup a passenger going to Charboil Grill. Go to Charboil Grill:n 1 l 3 l 3 l. Pickup a passenger going to What's The Difference. Go to Go More:e. 64 is waiting at Starchild Numerology. Go to Starchild Numerology:e 2 r. Pickup a passenger going to What's The Difference. Go to What's The Difference:e 1 l 2 r 1 l. Pickup a passenger going to Addition Alley. Go to Addition Alley:e 2 r. Pickup a passenger going to Addition Alley. Go to Chop Suey:n 1 r 2 r. Switch to plan "a". [b] Go to Addition Alley:n 1 l 2 l. Pickup a passenger going to Equal's Corner. 100 is waiting at Starchild Numerology. Go to Starchild Numerology:n 1 l 1 l 3 l 2 r. Pickup a passenger going to Equal's Corner. Go to Equal's Corner:w 1 l. Switch to plan "c" if no one is waiting. TRUE is waiting at Writer's Depot. [c] FALSE is waiting at Writer's Depot. Go to Writer's Depot:n 1 l 1 r. Pickup a passenger going to Post Office. Go to Post Office:n 1 r 2 r 1 l. ``` It accepts upper or lowercase because the `Auctioneer School` converts it all to uppercase. `Chop Suey` breaks it into individual characters. `Charboil Grill` converts characters to their ASCII code. We pickup one character a time, convert it to ASCII, subtract 65, and add it to the running total. Once there aren't any more characters, compare the total to 100. Returns `TRUE` for dollar words and `FALSE` for everything else. [Answer] # IA-32 machine code, 21 bytes Hexdump: ``` 33 c0 6a 64 5a 8a 01 41 24 1f 75 05 83 ea 01 d6 c3 2b d0 eb f0 ``` Assembly code: ``` xor eax, eax; initialize eax to 0 push 100; initialize edx pop edx; to 100 myloop: mov al, [ecx]; load a byte inc ecx; go to next byte and al, 31; convert from letter to number jnz cont; not done? continue ; done: sub edx, 1; check whether edx got to 0; result is in CF __emit(0xd6); aka SALC - set al to CF ret cont: sub edx, eax jmp myloop ``` Counts from 100 to 0. If arrived to 0, returns true (0xff); otherwise false (0x00). [Answer] # Dyalog APL, ~~17~~ 15 bytes ``` 100=+/17-⍨⎕AV⍳⍞ ``` Uses the Dyalog Classic character set. ``` ⍞ ⍝ string input ⎕AV⍳ ⍝ index in the character map 17-⍨ ⍝ subtract 17 from each ('a' = 18) +/ ⍝ sum 100= ⍝ equal to 100? ``` [Answer] # [Python](https://docs.python.org/2/), 38 bytes ``` lambda s:sum(map(ord,s))==4-96*~len(s) ``` [Try it online!](https://tio.run/nexus/python2#JczBCoMwEATQu1@x7ClpY0@lUCH9kbaHTVQaSFSSzUHF/rpNcU4D85hev3ZPwbQEqUk5iECTGGOrkpRaX@v77fT13SCS3Dlm/syg4YkmL8uMCm32nGNXGrWODLGz5P2M76onn7oDk7GoAJeS/zBGYHADHHfnAzYVTNENDLhuUD9g3fBSZCAWrKAXLOX@Aw "Python 2 – TIO Nexus") Same length as [ovs's solution](https://codegolf.stackexchange.com/a/116937/20260). Rather than subtracting 96 from each `ord` value, this checks if the `ord` total equals `100+96*len(s)`. This is expressed one byte shorter as `4-96*~len(s)`, which equals `4-96*(-len(s)-1)`. [Answer] # [Ruby](https://www.ruby-lang.org/), ~~35~~ 30 bytes ``` ->w{196==eval(w.bytes*'-96+')} ``` [Try it online!](https://tio.run/nexus/ruby#S7P9r2tXXm1oaWZrm1qWmKNRrpdUWZJarKWua2mmra5Z@7@gtKRYIS1aKS0ns6CgUimWCyaQVFpVBeT/BwA "Ruby – TIO Nexus") [Answer] # [Retina](https://github.com/m-ender/retina), ~~47~~ 23 bytes ``` \w !$& }T`l`_l ^!{100}$ ``` [Try it online!](https://tio.run/nexus/retina#C0nwScjhCk6IjkvUrYrV5lLV0HBP@B9TzqWoosZVG5KQkxCfwxWnWG1oYFCr8v@/U2pRXmJRSmZevkJmSmpeSWZaZmqxQmleYk5JalFqikJKfk5OYpFCeX5RSjEA "Retina – TIO Nexus") Note: Header lowercases input and splits it into words; results appear on separate lines. Edit: Saved far too many bytes thanks to @MartinEnder. [Answer] # Octave, 18 bytes ``` @(x)sum(x-96)==100 ``` Subtracts `96` from the input string `x` (lower case), to get the numeric values of the letters. Takes the `sum` and compares it to `100`. Returns a logical `1` for truthy cases, and a logical `0` for false cases. I could save one byte if it was OK to give false for "dollar words" and true for "non-dollar words". [Answer] # [///](https://esolangs.org/wiki////), ~~564~~ ~~210~~ ~~189~~ 185 bytes ``` /~/1\/\///4/11~3/41//6/33//2/66//5/22~a/~b/1~c/4~d/3~e/31~f/34~g/6~h/16~i/46~j/36~k/316~l/346~m/2~n/12~o/42~p/32~q/312~r/342~s/62~t/162~u/462~v/362~w/3162~x/3462~y/22~z/122~5555/0///1/0 ``` [Try it online!](https://tio.run/nexus/slashes#FY43EsNADMSeBJE88zVqnHPOLvbrMrUtZjEYENbTAw0zBc0giQAnEya4a4pmmOY0LQgtCdOKaFqT2mCpLS21I1L7gqlD0dQR1wlznWmuC@G6FnbdCrvupOtRd9ez/q5XCVzv0eD6jArXdwz4lcQ1qdFVq9ENwx8 "/// – TIO Nexus") Prints a 1 if it is a "dollar word", otherwise prints a "0" Input is the following: (Scroll all the way to the right) ``` /~/1\/\///4/11~3/41//6/33//2/66//5/22~a/~b/1~c/4~d/3~e/31~f/34~g/6~h/16~i/46~j/36~k/316~l/346~m/2~n/12~o/42~p/32~q/312~r/342~s/62~t/162~u/462~v/362~w/3162~x/3462~y/22~z/122~5555/0//INPUT WORD HERE/1/0 ``` Works by replacing each letter with its value in unary, then replacing a unary 100 with a 0. It then substitutes whatever the word's value is with a 1. If the word's value is 0, then it will print a 1 because at the end of the code, it is replacing a 0. If the word's value is anything else, it will just print that 0. The golf works by using common occurrences in the code as replacements. [Answer] # [Japt](https://github.com/ETHproductions/japt), 13 12 10 bytes ``` L¥U¬x_c %H ``` ### Explanation: ``` L¥ U¬x _c %H L¥(U¬x(_c %H)) L¥( ) // 100== U¬ // Input split into a char array x( ) // The sum of: _ // At each char: c // Get the char-code and %H // Mod 32 ``` [Test it online!](https://tio.run/nexus/japt#@@9zaGnooTUV8ckKqh7//yslpmQmJiWWZCYn5uRUKgEA) 12-bytes: ``` L¥U¬mc m%H x ``` [Try it online!](https://tio.run/nexus/japt#@@9zaGnooTW5yQq5qh4KFf//K2WmpOaVZKZlphYrAQA) Another 12-byte solution using a different technique ``` L¥U¬x@;CaX Ä ``` [Try it online!](https://tio.run/nexus/japt#@@9zaGnooTUVDtbOiREKh1v@/1fKTEnNK8lMy0wtVgIA) [Answer] # Ruby (2.4+), 38 bytes Takes input in lowercase. Requires Ruby 2.4's `Array#sum` so it won't run on TIO. ``` ->a{a.chars.map{|c|c.ord-96}.sum==100} ``` [Answer] # Bash + GNU utils, 47 ``` od -An -td1 -vw1|sed 's/^/a+=-96+/;$a!a-100'|bc ``` [Try it online](https://tio.run/nexus/bash#Pc3NCsIwEATgu08xQiWHEtpeBCkefBFh86dbSiLNqjT03av14AdzGBiYkCaIz2Ipe3CEeZYyw6TZJhGw81E4sM8gx2RI2NI4zpANSilbNiBjnQ@3O4/DMHz7b2Aos@3h0g5fj4mjBKhDVqj@p8uaHPQlQovroF/vbsneQeXm2lB91qdj3fQV7Ul3basWY1eXol8/). ]
[Question] [ # Challenge So, um, it seems that, while we have plenty of challenges that work with square numbers or numbers of other shapes, we don't have one that simply asks: Given an integer `n` (where `n>=0`) as input return a truthy value if `n` is a perfect square or a falsey value if not. --- ## Rules * You may take input by any reasonable, convenient means as long as it's permitted by [standard I/O rules](https://codegolf.meta.stackexchange.com/q/2447/58974). * You need not handle inputs greater than what your chosen language can natively handle nor which would lead to floating point inaccuracies. * Output should be one of two consistent truthy/falsey values (e.g., `true` or `false`, `1` or `0`) - truthy if the input is a perfect square, falsey if it's not. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so lowest byte count wins. --- ## Test Cases ``` Input: 0 Output: true Input: 1 Output: true Input: 64 Output: true Input: 88 Output: false Input: 2147483647 Output: false ``` [Answer] # [Neim](https://github.com/okx-code/Neim), 2 bytes ``` q𝕚 ``` Explanation: ``` q Push an infinite list of squares 𝕚 Is the input in that list? ``` When I say 'infinite' I mean up until we hit the maximum value of longs (2^63-1). However, Neim is (slowly) transitioning to theoretically infinitely large BigIntegers. [Try it!](http://178.62.56.56:80/neim?code=q%F0%9D%95%9A&input=64) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes ``` Ʋ ``` [Try it online!](https://tio.run/##y0rNyan8//9w26FN////NzMBAA "Jelly – Try It Online") [Answer] # dc, 9 ``` 0?dvd*-^p ``` Outputs 1 for truthy and 0 for falsey. [Try it online](https://tio.run/##RYtBCsIwEADvfcVQlIIQaDW0AUF/ItTslvaSlCb05N@jCOIcZ5jnmOYyxY2sKfsxKUugpaO3OMe5s4N1l94OVyRWfFi3JeSJ@pgwN2oOv/Nb1c/xr3ghHqM0pb3LLifzWEtTSQxa3g). ``` 0 # Push zero. Stack: [ 0 ] ? # Push input. Stack: [ n, 0 ] dv # duplicate and take integer square root. Stack: [ ⌊√n⌋, n, 0 ] d # duplicate. Stack: [ ⌊√n⌋, ⌊√n⌋, n, 0 ] * # multiply. Stack: [ ⌊√n⌋², n, 0 ] - # take difference. Stack: [ n-⌊√n⌋², 0 ] ^ # 0 to power of the result. Stack: [ 0^(n-⌊√n⌋²) ] p # print. ``` Note `dc`'s `^` exponentiation command gives 00=1 and 0n=0, where n>0. [Answer] # TI-Basic, 4 bytes ``` not(fPart(√(Ans ``` Simply checks if the square root is an integer by looking for a nonzero fractional/decimal part. [Answer] # C#, 27 bytes ``` n=>System.Math.Sqrt(n)%1==0 ``` --- A more [correct/accurate way](https://stackoverflow.com/questions/2751593/how-to-determine-if-a-decimal-double-is-an-integer) to do this would be: ``` n=>System.Math.Sqrt(n)%1<=double.Epsilon*100 ``` [Answer] # JavaScript (ES6), 13 bytes ``` n=>!(n**.5%1) ``` Returns true if the square root of n is a whole number. **Snippet:** ``` f= n=>!(n**.5%1) console.log(f(0)); console.log(f(1)); console.log(f(2)); console.log(f(4)); console.log(f(8)); console.log(f(16)); console.log(f(88)); console.log(f(2147483647)); ``` [Answer] # [Perl 5](https://www.perl.org/), 14 bytes 13 bytes of code + `-p` flag. ``` $_=sqrt!~/\./ ``` [Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@q8TbFhcWlSjW6cfo6f@3VlCJV9CzVVCKyVP6b8hlZsJlYQEA "Perl 5 – Try It Online") Computes the square root, and looks if it's an integer (more precisely, if it doesn't contain a dot (`/\./`). [Answer] # [Python 3](https://docs.python.org/3/), 19 bytes ``` lambda n:n**.5%1==0 ``` [Try it online!](https://tio.run/##Pcs9C4MwFIXhuf6KW0FIRETpByI4dOncoZt1iHqDoTFKbqT461MpbbfDy3nm1Q2TOXhZPbwWY9sLMKWJ4/QU5VWV@UBOFhQoA4zlyd0uyBN2Pv5WUSRXoQk5L4OdkiCZqrOGw74CVefNFnezVcax8GanVuMIPTrsHPbwUm4Ah@Q6QQgRhdGHbqK1KJ7B1120/r8IZkG0WVq6DonkovWahty/AQ "Python 3 – Try It Online") [Answer] # [Retina](https://github.com/m-ender/retina), 18 bytes ``` .+ $* (^1?|11\1)+$ ``` [Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLSyPO0L7G0DDGUFNb5f9/Ay5DLjMTLgsLAA "Retina – Try It Online") Shamelessly adapted from @MartinEnder's answer to [Is this number triangular?](https://codegolf.stackexchange.com/questions/122087) but with the base conversion included at a cost of 6 bytes. Note that Is this number triangular? wasn't for some inexplicable reason required to support zero as a triangular number, so part of the adaption was to add a `?` to make the leading 1 optional, allowing the group to match the empty string, and therefore a zero input. However, having now matched the empty string, the `+` operator stops repeating, to avoid the infinite loop that would happen if it kept greedily matching the empty string (after all, `^1?` would certainly keep matching). This means that it doesn't even try to match the other alternative in the group, thus avoiding the match of 2, 6, 12 etc. As @MartinEnder points out, a simpler way to avoid that while still matching the empty string is to anchor the match at the start while making the group optional for the same byte count: `^(^1|11\1)*$`. [Answer] # C (gcc), 30 bytes ``` f(n){n=sqrt(n)==(int)sqrt(n);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zOs@2uLCoBMiytdXIzCvRhPKsa/8DeQq5iZl5Gppc1VwKQFBQBBRK01BSTYnJw8RKOgppGgaaINIQTJqZQDhm5ubmRoZmYI6FBZgyMjQxN7EwNjMx19S05qr9/y85LScxvfi/bk4uAA) # C, 34 bytes ``` f(n){return(int)sqrt(n)==sqrt(n);} ``` [Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zuii1pLQoTyMzr0SzuLCoBChkawtlWNf@Bwor5CZm5mloclVzKQBBQRFQKE1DSTUlJg8TK@kopGkYaIJIQzBpZgLhmJmbmxsZmoE5FhZgysjQxNzEwtjMxFxT05qr9v@/5LScxPTi/7o5uQA) # C, 33 bytes ``` #define f(n)(int)sqrt(n)==sqrt(n) ``` [Try it online!](https://tio.run/##S9ZNT07@/185JTUtMy9VIU0jT1MjM69Es7iwqATItrWFMv4DBRVyEzPzNDS5qrkUgKCgCCiUpqGkmhKTh4mVdIBmGWiCSEMwaWYC4ZiZm5sbGZqBORYWYMrI0MTcxMLYzMRcU9Oaq/b/v@S0nMT04v@6ObkA) [Answer] # [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes Thanks to Luis for reducing my one byte longer code by two bytes, making it the shortest one. ``` t:Um ``` [Try it online](https://tio.run/##y00syfn/v8QqNPf/f0MTEwA) **Explanation:** ``` % Implicit input t % Duplicate it : % Range from 1 to input value U % Square the range, to get 1 4 9 ... m % ismember, Checks if the input is a member of the range of perfect squares ``` --- Old answer: ``` X^1\~ ``` [Try it online!](https://tio.run/##y00syfn/PyLOMKbu/38zEwA "MATL – Try It Online") ``` % Implicit input X^ % Square root of input 1\ % Modulus 1. All perfect squares will have 0, the rest will have decimal value ~ % Negate, so the 0 becomes 1, and the decimal values become 0 ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~40~~ 38 bytes *Thanks to squid for saving 2 bytes!* ``` lambda n:n in(i*i for i in range(n+1)) ``` [Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKk8hM08jUytTIS2/SCETyFEoSsxLT9XI0zbU1PxfUJSZV6KRmJOjkaaRrQlWkw1SE22gY6hjZhKrqckFUZKXX6KQmFeJrsxIx8ICqOg/AA "Python 3 – Try It Online") Too slow to return an answer for `2147483647` in a reasonable amount of time. (But written using a generator to save memory, since it doesn't cost any bytes.) Works in Python 2 also, though an `OverflowError` is a possibility due to `range` if you try it with huge inputs. (A `MemoryError` would also be likely in Python 2, also due to `range`.) [Answer] # Regex (ECMAScript / Python or better), 50 bytes ``` ^((?=(xx+?)\2+$)((?=\2+$)(?=(x+)(\4+$))\5){2})*x?$ ``` [Try it online!](https://tio.run/##TY9BT8JAFIT/CjYE3qO2FEQPrEtPHrhw0KNosoFH@3TZbnYXqCC/vbYxJt5m5ptkMh/qqPzGsQ2Jt7wlt6/MJ301Tho69Z6peKotwFkuxqPmHSCXUNdxjutp3MfO/ooujhHWs9bg@h4v0yuO6rzfjMZnTEP1EhybAjD1mjcED7fJDFF4mYlTyZoAtHSktpoNAeKNNAet8VJInXqrOcAwGaLgHYCRRarJFKHExfT7m/1KrYClVc7T0gQoXrM3xD9A/4FZTPLJvMMYSledoqU5Ks3bnlOmoHkvirXYVQ4EP0oSHMfYDkZ1lDqypAIwpnsVNiU4xIsfDGx7KUD3YiLsIfjg2oq4XpssuZtl2Q8 "JavaScript (SpiderMonkey) – Try It Online") This regex is explained in [Match strings whose length is a fourth power](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/21951#21951). teukon and I arrived at it independently, starting on 2014-02-22, though golfing it down to this point took him 2 days and took me 4 days. It works by dividing away squared prime factors one at a time, thus keeping the number's property of being a square at every step iff it started out being a square. This regex represents a local minimum in length; it's the shortest form that this particular algorithm can be golfed into. It can be modified to match Nth powers by changing the `2` in `{2}` to N. # Regex (ECMAScript), 28 bytes ``` ^(x(x*)|)(?=(\1*)\2+$)\1*$\3 ``` [Try it online!](https://tio.run/##TY@xbsIwFEV/JY0QeS9pQkIrBlzD1IGFoR2BShY8EreOY9kGUqBrP6Cf2B9JYUDqdqUz3HPexV64tZXGp87IDdm60R/02Vmu6RC8UPncGoAjnwzi7g1aaGM8I0w5LIsYl8Okh5fRWz508eCImW9evZW6BMyckmuC0X36iMgcz9mhkooAFLckNkpqAsQ7rndK4ankKnNGSQ9RGiGTWwDNy0yRLn2Fk@H5LN1czEFyI6yjmfZQLvIV4g3Qf6AnxbQYXzH6yjaHcKb3QslNYIUuaRyEiWLbxgKTT5yYTBK8HNY8bMPMkiHhQWJWC7@uwCKeXL9vLlEerh0FMzvvvAWZRMHv908QJfWiWN1U2ddXl6fFKM//AA "JavaScript (SpiderMonkey) – Try It Online") ``` ^ # tail = C = input number (x(x*)|) # \1 = A = conjectured square root of C; \2 = A-1, or unset if A==0, # allowing us to match C==0 using ECMAScript NPCG behavior; tail -= A (?= (\1*)\2+$ # iff A*A==C, the first match here must result in \3==0 ) \1*$\3 # assert A divides tail, and \3==0 ``` This ultimate form of this was arrived upon from 2014-03-02 to 2014-03-04 through several rounds of golfing between teukon and me, after we had already independently come up with the coprime moduli method of generalized multiplication (which took him 3 hours and took me almost 2 days). I came up with the idea to do one of the tests as `(\1*)\2+$` followed by testing if `\3`==0 although it didn't improve my regex's overall length at the time, and he came up with the idea to combine the `\3`==0 test and `\1*$` test into one, as `\1*$\3`, thus doing the `\1*$` test at the end instead of the beginning (which sacrifices speed in the name of golf, assuming the regex engine doesn't optimize it). (That is with the group numbering of the fully golfed form mapped onto the snippets.) I've explained the generalized multiplication algorithm [in this post](https://codegolf.stackexchange.com/questions/179239/find-a-rocco-number/179420#179420), but since its application to squares is simpler, I'm including an explanation for that here. To explain why this works, let's rearrange the order of the assertions: ``` (?= \1*$ # assert that A divides C-A ) (?= (\1*)\2+$ # iff A*A==C, the first match here must result in \3==0 ) .*$\3 # assert that \3==0 ``` We have \$A^2 \stackrel{?}{=} C\$. If this assertion were true, we would have: \$\begin{aligned}C &= A^2 \\ C-A &= A^2-A \\ &= (A-1)A\end{aligned}\$ This shows that the assertions made by the regex will hold true if \$C=A^2\$: \$\begin{aligned}C-A &\equiv 0 \pmod A \\ C-A &\equiv 0 \pmod {A-1}\end{aligned}\$ Note that in regex, \$0 \equiv 0 \pmod 0\$, so the algorithm works for \$C=1^2\$ and \$A=1\$ without any need for a special case. It also works for \$C=0\$, matching it using ECMAScript NPCG (unset/non-participating capture group) behavior – every assertion becomes \$0 \equiv 0 \pmod 0\$ and passes. Assuming \$A>1\$, these can be simplified into: \$\begin{aligned}C &\equiv 0 \pmod A \\ C &\equiv 1 \pmod {A-1}\end{aligned}\$ We now have two coprime moduli, \$A\$ and \$A-1\$. By the [Chinese remainder theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem), there is one and only one integer \$E\$ such that \$0 \le E < A(A-1)\$ and the above moduli are satisfied. That applies to any window of the same length, so we can change it to \$A < E \le A^2\$. \$A^2-A=(A-1)A\$ shows there is at least one \$E\$ satisfying the moduli: \$E=A^2\$. The Chinese remainder theorem shows that there is exactly one \$E\$ satisfying the moduli within a certain range. Thus, if we restrict our search to the range \$A < E \le A^2\$, the only value matching both moduli will be \$E=A^2\$. The first thing the regex does is `(x(x*)|)` which subtracts \$A\$ from \$C\$, so instead of directly searching for a matching \$E\$, it is searching for a matching \$E-A\$. `(\1*)\2+$` will first attempt a match using the largest possible number of repetitions of `\1`. Since we already asserted `\1*$`, this will bring us exactly to `$`. But then there will be no room for `\2+`, which is required to have a positive repetition count due to the `+`. So then it starts trying smaller repetition counts for `\1`, giving `\2+` more space in incremental steps of `\1`, thus resulting in incrementally larger repetition counts for `\2`. Note that `\1`\$=A\$ and `\2`\$=A-1\$. So a successful match of `\2+$` represents a value of \$E-A\$ such that \$E-A \equiv 0 \pmod A\$ and \$E-A \equiv 0 \pmod {A-1}\$. The regex essentially searches for the smallest \$A-1 \le E-A \le C-A\$ satisfying the moduli, or alternatively stated, the smallest \$2A-1 \le E \le C\$ satisfying the moduli. Thus, even if \$C > A^2\$, the first matching \$E\$ it finds will be \$E=A^2\$. Note that the range only had to be restricted to \$A < E\$ via the Chinese remainder theorem, and the regex restricts it to \$2A-1 \le E\$ which is a subset of that range. If no match is found, then \$C < A^2\$ and we get a non-match. If a match is found, and if \$E-A=C-A\$, then the `\1` in `(\1*)` will have a repetition count of zero, and `\3` will capture a value of zero. The regex asserts that \$E=C\$ by asserting that `\3` has a value of zero; if this matches, then \$C=A^2\$ and is indeed a perfect square. Note that in no point in this reasoning did it matter what the value of \$A\$ is. It will only match if \$A^2=C\$. Thus, it doesn't matter whether we search for a matching \$A\$ from smallest to largest or largest to smallest. The regex does the latter, starting at \$A=C\$ and going downward from there in decrements of \$1\$. # Regex (ECMAScript / Python or better), 30 bytes ``` ^(x(x*))(?=(\1*)\2+$)\1*$\3|^$ ``` [Try it online!](https://tio.run/##TY@9bsIwFEZfhUYI7k2akFDUAdcwdWBhaMdSJAsuyW2NY9kGUn6ePQ1DpW6fdD7p6Hypo/Ibxzak3vKW3L423/TTOmno1Huj8rWxAGc5G8XtGhpoYkSYS1gVMa7GSR@70V89Xdf9Nh6dMQv1e3BsSsDMa94QPD@mE0ThZS5OFWsC0NKR2mo2BIgP0hy0xkspdeat5gDDdIiCdwBGlpkmU4YKZ@Prlf1SLYGlVc7TwgQoP/JPxD9A/4GZFfNiescYKlefooU5Ks3bnlOmpGkvSrTY1Q4Ev0gSnCTYCaMmyhxZUgEYs70Kmwoc4sUPBrZLCnCvKIQ9BB9cdxG3W5unRT6e/AI "JavaScript (SpiderMonkey) – Try It Online") - ECMAScript (SpiderMonkey) [Try it online!](https://tio.run/##TY69bsIwFIVfBUVIvpcQK6GdkhqmDiwM7dgUYSWXcCvXSW0DkYBnT0OlSmxH@s7flz5pXznuQmLbmgav0sKpN2pe@w7eg2PbSKfPu2ELPfQzRFgpKLMZlot4iqOYlk/X7XTYSW@4IsjmSYZYOPo5siMQjnRt2JJAWY060NoGcns9Wi9su2PIO9dW5L30oWZ7Q9laEH@JuVHLS6OM9J3hACIRWPAewKpGGrJNOOBycb2y3@gNsOq08/d2aD7ST8R/QI/ALrNVlt8xhoNrz9HanrTheuK0bSifRLEp9q2Dgl8UFRzHOA5GfSQddeN5YJTfOlQHcIiXh@PtMciz40AAfiVKK3IhMGYsvMqK2w2HNMnSxfMv "JavaScript (Node.js) – Try It Online") - ECMAScript (Node.js - fast) [Try it online!](https://tio.run/##RU5BasMwEPzKEpZYG9vYcttLZCUOpNeeeqsTkYYYBGriSi64qO7XXcUN5LLMzM7uTHuy5mn8@Aa0Ary5HA8GMBOBynK7ed2sBmgulqGTuShXgjzoJjDyrdXnDmb1eSYGqIx0rdEdi9IocV/vrgsnKkl5wun0eTWt72oedFqiInH95ULiwVamLMhX5o3vZJj5Ttxy9Y2iLuW0DiiOyesGGIv6CHoIJiKQv5Chzcijm8@nclO3UJyL/66oxTAMSj2/bJUa96xn/YKIrSWr@YLqIkYKAOuHnz2OY57yvHj8Aw "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##bVJdb9swDHzvr@CMDpGSVE26PU01im3YgAHrNrSPSQootpyolWlPkhsnXX97RjneR4H4hSJ5PupOvFeP6uw@f9ibsq5cgHvKhanEUML/lSYYe7Tm9Eq31Dmpm6U1GWRWeQ/XyiA8QV/zQQUKj5XJoaQOuw3O4AqUW/nZgkNYu2rj4VOb6TqYiv48AfhsrIYiRb3pjiwRWZVrQf2Eyw9NUWin8xutcu1g2cFeFtmfP/u04Fz2c/04yM068jPm0yVpUPlXg5px/irFxlpuCuaF/tko61lyPhwOE86fXkIPDIyFowRPxBD@MhDBOTEsCfcg/SgdzHEQY5DPh9rzDxWCdggu7U@ktqzjAM8lubGsKqsVwi4tiFFLuM0UIkk3WDcBUohq@xq73fqgS2GQS@h1djCxVv6bbgNds7MYoDfE0t2J4wBCQvQS@/5sAZbaESV8bU1gyRk9AuED4IQ6XzDQGjhRK@c1JczOJgs@BpwebQqrcRXWlxdwBREJ7yhMF8SYrZWbLdpeT5fhdCHhvXNq60VhrGXteNAOOlMAispFbXSNFCcS8DLFKYXRiAReq5CtyaGS2JwoDxnrNhdpwT8S@WFjxMapmvUjsqrefi9uFK40TZqMkfOotABW0njMybv4tjvem1yRYxtngmbxUbncpcE18X3@tWvyMBQsee0TsoTL5/idxK3a37GWtUPO2VXK5tMhn1@MTjkdTudvft2d7uPe7Cdn08nF298 "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##dVPbjtowEH3nK6YULTZJdglUfUjIrlSpP1D1oRWwUdaYxCo4luOIS7u/Xjp2ljSl4IfEnsuZOWdsplSQM3Z6LyTb1CsOs5eyrMyD5jnf3xdKPfYuXXzPuDKilA8rkeUSTYKlQq5Lvc2sucliRaYhVfMlJPCl/2m3@/Eyrb8fDt@@Fh93BTk9kz3ZjyglTwlZhCO6mHgDipvBYvrreXCilxl9H0YqSZUXxp2OBFbXPNs@9oQ0sM2EJBR@9gCXmqNrwyVRNAiXyTiGGmOmk9RAaU82IbebyqyiCGOFzNGoahO7fFbKyoCjHEVODtAcweKzrUK6rIBdkb1loAJALOwxGftw5C14zs1GSE7cgQnpN3VofO7VLpsox6hWZkpBXMA9S7EvQqkPMvRBlRW6G89ayBUZBkMatwAyRK@NeZd0OUWRtManK7jguXgPQgoRFv@L5aY3suUk3zWnuQy9cBnDlm8rbkjlw3A/tI2hIhU6rcRtfiuFSKTVepbIMAbPE13Gdhl9uLA4LdZAusqnFc80Kwjp8KJ3tmoglr4bgY/TofQK1hnvSAGpWypkuJAoHI4pjK@GN3MqawOzGYj/Y157t0/MXQryz@1pXwzcca3pDcLXG7xoxn76EXzWutT9@DoOp7C2SA7GtwC2amxvZIuHli5e3/7fur3@qonDuEG82TVfzU2tJeBleD2Ng3A8@fCbrTdZXp2CjauQupH@AQ "C++ (gcc) – Try It Online") - Boost [Try it online!](https://tio.run/##NY5BboMwEEX3nGJksZghgDDpCmrlIECkqHUaV@6Axo5KpN6d4lTdfc3772uWR7zNfNzc1zJLhPAIpdjyM8zcgxhRSm1nXHEtiPBkcNQFje0hpz3k4/HnnG97ZdBdpacenGmy6yzgwXGaqkN8d9xl4I2vw@JdRFUpysBdwVtGT69tB37Qk/FDM2WQZE6yXPjDouOICVD5l/REB037XhoQWwd7kbcbSglqVQU/SUKug0WSQs@D0f3/N/M91t/iosUQBZloayrdtC@/ "Python 3 – Try It Online") - Python [Try it online!](https://tio.run/##PY5RS8MwEMff9ylupbCk2pBUnxaDFFfElwnTt3YLyrIuELKSZqyC@NVrMuce7rj73/93d@74@TU6ELBSrRo6YtUJFuV7SZz62N7@ifP5y/PydVU9lW8VBy0oh9NeGwVGtMr3EwC9A1PnbC1E0tiEh4GpKSF5seag7DY4gkL6zmiPZvkMXxBilG39HuGHIjB14AN2RXYHBxa0hSgSf5AaMYoJicZrG3znXSgZksxiED/geBT0NP7ZHX1/3hf/ZqF32nqw/ydijiFltVxIOW7QgIYMY/QoUMMy3BQ3KQ5F2tx9b9JxpDmjxf0v "Ruby – Try It Online") - Ruby [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaK622nZuQ2LxZRsIYw/b3qyG2qW2LKYhjSA4f3t3K3vaQy7nfpxzbq6tbb9c2doS5khG6IySKbFOHaRTVhel4sFsOl5JWRfay7I92kYrl/McRP4@64KQBPgqLMqDGgaMV8Z3XMqX9euzlBCSBFAShcWoMY3slOfUlk5N90X57R0GqZtj42lI6DxdzBcPj@ninoIYVa3jrMliwXRWoXrHPz6f1m8g4EKaijO96bzTyiCCKNlmGc0NBRzuTnvsYDmMwyiBga/OVrdfitOIhjgukF@2J@MH7jJF0gYFMMZbMSLk5mz@cmaW2a2PaDIBtCb8dqFj4cuaMxei2XAuVXgenIOQGQAgl2HFBlRZt8NeguBXEkGGnDAjrmhz/XdWDqLf8TM/jwH4KuN5MoY8nTBAwPK7nx3r@zhK4nT@Cw "PHP – Try It Online") - PCRE (fastest) [Try it online!](https://tio.run/##RY/RaoQwFER/ReSCiW4WtX3aEHahz/0CdUHs3TWQ3kjMoqzNt1ttKX2bMwzDzGAndGOPxqzgVOXwjnNzOhFO7JKsVzazOeWcnRWri5TXZQZ8E1C/fF1hTS6H@M1@DtrgR8wlPFUub9Zh2/UMTKQpAk3Dw/MFWgVGjIPRPhax1DcG7bGzD/LC@KjcA5mCtsqbsBUwIFVp8s2PI4GEwT8uds4yvuwd7vje@q7HkSVzkgLxX/vJl8lpj6K3ow/brEL@cyTIbveMJoyAQghrLoq8fP0G "PowerShell – Try It Online") - .NET This is a port of the 28 byte version, dropping the dependence on ECMAScript NPCG behavior. Matching \$0^2\$ is done as a special case, the `^$` alternative at the end. # Regex (Perl / Java / PCRE / .NET), 12 bytes ``` ^(\1xx|^x)*$ ``` [Try it online!](https://tio.run/##RY5fa8IwFMW/ykWCzdWWJoI@mMZVcK972tvU4IaFQNQuqRDJsq/exU7w5XLPuX/Orz1aM@9PNyBWQDCXr4MBUookZbVZv69XEZqLpcRJJqqVwAC6SQpDa/W5g9H2PBIRaiNda3RHsyLL3fXTdelE5QXPOR6/70svT5clH5dEobj/cinxYGtTzTDU5oPvZKpsJx65@iGJruQwTt10ikE3QGnmM/CQlhBB/kJJbImBuPF4gBvYEjgX/6xEixijUq9vG6X6Pd1y73/2Hiek71kxmy8Y@wM "Perl 5 – Try It Online") - Perl (fastest) [Try it online!](https://tio.run/##bVLLbtswELznK7ZCC5N@MFaPZYSiLVqgQJMWydFxAFqibDrUSiWpWHaab3eXsvoIEF7I3R3Ocoa7VQ9qti3uj6ZqahdgS7EwtRhL@D/TBmNfzDm91h1Vzpp2ZU0OuVXew6UyCI8w5HxQgbaH2hRQUYXdBGdwDcqt/WLJIWxcvfPwuct1E0xNN88AvhirocxQ7/ojS0ReF1pQPeHyY1uW2uniWqtCO1j1sOdJ9ufmEJacy6Gvnwa520R@xny2Ig2q@GZQM85fZdhay03JvNA/W2U9S87H43HC@eNz6ImBsfAiwSMxhL8MRHBODCvC3Us/yUa3OIp7kE@n3NMPFYJ2CC4bTqS2amIDzyW5saprqxXCISuJUUu4yRUiSTfYtAEyiGqHHLvZ@6ArYZBLGHT2MLFR/kp3gZ7ZWwwwGGLp7cRxAiEhBolDfbEES@WIEr6xJrBkRp9A@AA4p8pXDDQGTjTKeU0Bs4v5kk8B0xeLwmpch83FW3gPEQnvaEuXxJhvlFssu0FPH2G6lPDBObX3ojTWsm466ka9KQBl7aI2ekaGcwl4kWFK22RCAi9VyDfkUEVsTlSniPWTizTgn4j8NDFi51TDhhZ53ey/l9cK15o6zafIeVRaAquoPRbkXfzbAx9MrsmxnTNBs/ipXB6y4Nr4P//KDXkYSpa88QlZwuVTXGdxqo537Dbtul93HR@/PsYpOc5n6ZzWbw "Java (JDK) – Try It Online") - Java [Try it online!](https://tio.run/##XVBda8IwFH33V4QQaKKptqIOicWXbSCMPWx7sxpql9qwmIY0QsHtt3e3sqc95HK/zjk3x9Wu32xd7RDxKEN4htEUOa/O0itnilLRaDYdb6WsCxNk2VycNsrnNGcif5u1EUcRvAqa8qyGBRuUDS2V8nn38iQl4yhlQAnEYqStlq0KFLvSq@mpKL@ChyCNvuiAOcKL@XqxXj3M10vMxKhqPCU6SwQxWQXsLX3/eNy9MsFuSFeUmH0bvFEWMhanhyzDucUMltvrCSbQ5gmPUzbgVedM86kojjGHdQH4srnaMGA3cwDtgQBichAjhO7K9q8mdpPd55BNJgykEb07dClCWVPiOYgNdqki0KiLOLGMMXQbTtRMlXUz3CUQfCUVaKgRseIHZH7@2UqZ6I80T7vu@9ixMen7JJ4vV0nyCw "PHP – Try It Online") - PCRE (fast) [Try it online!](https://tio.run/##RY/BasMwEER/RZgFS3EV7B4jBIGe@wWOA8Ld1AJ1ZWQFizj6dtduKZ3bG4ZhZvQzhmlA51YIug34iak7nQhnfi7XK780KT2vSRxgLc8vxZv/Gq3Dj0IoeOha3XxA0w8cHLPEwNJ4j2IBo8HJaXQ2FrJQ9sbBHHt/pyhdZK97oNJg2rrLWwEH0q2l2P04Ckg6/ONm56oSy94Rju8m9gNOvEzlAUj82g@xzMFGlIOfYt5mNeqfmSS/nXGWkAHlnNdaNvWmbw "PowerShell – Try It Online") - .NET This works by exploiting the fact that \$(N+1)^2-N^2=2N+1\$, i.e. the differences between consecutive squares are consecutive odd numbers. The loop is initialized by subtracting \$1\$ from tail, which then captures `\1`=\$1\$. Every subsequent iteration sets `\1`\$=\$`\1`\$+2\$ and subtracts `\1` from tail. As a result, the cumulative subtraction from tail is at every step a perfect square, and the `$` will only match at the end if the subtraction culminates in tail equaling zero, meaning the initial value of tail before the loop started was a perfect square. As such, this regex relies on being able to read the last captured value of group 1 from inside group 1 – a nested backreference, which is a feature not supported by the ECMAScript, Python, or Ruby regex engines. In [this post by primo](https://codegolf.stackexchange.com/questions/19262/match-strings-whose-length-is-a-fourth-power/22084#22084), it is explained how to extend this method to higher powers and polynomials. An alternative 12 byte form is `(\1xx|^x?)+$`, but this breaks some nice properties of the form shown above. Most notably, it breaks letting the loop iteration count equal the square root of the number being matched. One of the beauties of keeping that property is that we can return the square root, for example using .NET's balanced groups feature (**25 bytes**): ``` ^(?=(\1xx|^x)*$)(?<-1>x)* ``` [Try it online!](https://tio.run/##RY9RboMwDIavEiFLJGVBsL2VZa20552AUQl1LkRKHRSCQGW87gA74i7CwqZpb/78W5/tzo7o@haNWcGp0mGDU7XfE478GK8nflD8NZ@m99MkdiD44VHmT6Fc4@Nd9GyvnTb4FokCbiorLtZhfW45GKaJgaZu8GKGWoGRfWe0j2RU6AuHOj3bgbw0nt1vA4mCusyqJQg4kCo1@eqnUwBJg3@cb5wkYt4cVwUufan9ucWex1O8AxK/yU3Mo9MeZWt7v4TL8uKfmSQbnjOakEVA7Ovjk0GwpY2zQ9eHnalBanwromVZ1kzmD1n2DQ "PowerShell – Try It Online") - .NET Or using group-building with a branch reset group (**19 bytes**): ``` ^(?|\1(\1x)|^(x))*$ ``` [Try it online!](https://tio.run/##RU5BTsMwELz3FVZl1V6aNDYSlzpuUqlcOXEjrVVQCpZMGuwgBbnmyAN4Ih9J3YDEHlY7o5mdaWtrbobXD4StQN4cn/YG4UxEKPPN@n69CpPD0VLsJBP5SoBH@hAR@NbqpkPTqpmKgEojXWt0R0lKEvf@6LpoUUnKEw7120VU/LMs8rDECsTll4uJe1ua/Bp8aR74VsbNtiJMEBqT9R@BdS5HQbzmc/DRS0lPeqxBfmbYZuCxm83GXmOt2JmL35pYLwj6@fpGZEExL0zdPHcvmC8ZiBCCUrd3G6WGHS1OFacV7@G0oz3AFR4GlnIW5ww "Perl 5 – Try It Online") - Perl [Try it online!](https://tio.run/##XVHNatwwEL7vUwxC4JlE67WXNGGrNXtpAoGQQ9tbnAjH1camtixkBTYke80D5BHzItvx0l4q0DB/3/fNSL7xh/XGNx5kgALEQkAKPtgnE6zvqtpiskhPNsY0VRdNPfS@7WwosSRdfl@MiYKE75aT5slODS5aF0c05ur65tIYUpATUzKxnrWuNaONKHwdbPpY1b9jYGO6tm@jUCDOlquz1fnFcvVFkJ5th4CyLTItu2LL7CP@@Pnt@pY0vUK7RdndjTF01rFH8/y@KETpBHHz@PzIFU6rTM1zmvB257vhl0UxF4rbNePr4dnFCbteMuiOCdhm93oGcFR2f2Pp1sWxzt7pKbE04PGF@irWDcqgWGx6LltFTHaJko6U7IngdZqyJVs3wzSaBt4m1zDFIF0q4PP9A0SKtvfxBWXPGrTJvv7b6hiT3vNA@/8@AEkfHnDzVuZY5jt6e8Ad0Yk8HLJ5nvH5Aw "PHP – Try It Online") - PCRE # Regex (Python[`regex`](https://bitbucket.org/mrabarnett/mrab-regex/src/hg/) / Ruby or better), 22 bytes ``` ^((?=(\3xx|^x))(\2))*$ ``` [Try it online!](https://tio.run/##NY5BasMwEEX3PsUgsphJbWMlO7siB3EcCK2SqKgjM1KpAr27a7l0Vp95vM@fn@kR@Li4zzlIgviMtdi7zfVHDDyAGFFKLRfEk8HzMeefSybC84Fov1tWNOq@0dMAznTVLQh4cFxa2pjeHfcVeOPbOHuXUDWKKnA38JbR0@uhBz/qyfixmyooMhdZrny36DhhAVT/JT3Ri6a1rxRsC9tor/L2QKlBZbXnDRbqepilWLQ9jB7@B4Wv1H6LSxZjEmSipWt0t94v "Python 3 – Try It Online") - Python `import regex` [Try it online!](https://tio.run/##PY7RS8MwEMbf/SvOIiwZNqQV9rAYpLgivkyYvrVbUJZ1gXAracYiiP96Tabu4Q7uu@/33bnjx@foQMJKdzr0DPUJFtVbxZx@397@ivP589PyZVU/Vq@1ACO5gNPeWA1WdtoPVwBmB7bJi7WUWYuZiAvbcMbyci1A4zY6osKG3hpPJvmE/iHMauz8ntD7MjJN5CN2QXYHBwgGIYnMH5QhBaeMJeNljL5zFslCNkUK8hucSIK5Tn/2Rz@c89LfRZydQQ/4fyL1VErVy4VS44aQB0nauxC@NoFS0paUTm/GkeezGec/ "Ruby – Try It Online") - Ruby In regex flavors with no support for nested backreferences, that feature must be emulated via forward-declared backreferences (which aren't supported either by ECMAScript or Python's built-in `re` module). This is done here by copying back and forth between `\2` and `\3`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` Ln¹å ``` [Try it online!](https://tio.run/##MzBNTDJM/f/fJ@/QzsNL//83MwEA "05AB1E – Try It Online") [Answer] ## [SageMath](https://sagemath.org), 9 bytes ``` is_square ``` [Try it online](http://sagecell.sagemath.org/?z=eJzLLI4vLixNLErVMNLSMjEyNdY11AQASNYF0A==&lang=sage) The built-in function does exactly what it says on the tin. Since Sage uses symbolic computation, it's free of computational accuracy errors that plague IEEE-754 floats. [Answer] # [Japt](https://github.com/ETHproductions/japt), 3 bytes ``` ¬v1 ``` [Try it online!](https://tio.run/##y0osKPn//9CaMsP//81MAA "Japt – Try It Online") Seems to work fine for `2**54-2` in the [Japt Interpreter](http://ethproductions.github.io/japt/?v=1.4.5&code=rHYx&input=MTgwMTQzOTg1MDk0ODE5ODI=) but fails on TIO for some reason... [Answer] ## Haskell, ~~26~~ 24 bytes ``` f n=elem n$map(^2)[0..n] ``` [Try it online!](https://tio.run/##DclBCoAgEADAr@zBQ8Eiq1mefIkoeFCSdJHq/9Zc50zPlVubswC73HIHFj2NJerVk5QcZk@VwcG4K78g4E8o4AkVHgaVMVHjjhYVkcLNhvkB "Haskell – Try It Online") Checks if n is in the list of all squares from `0` to `n`. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 27 bytes ``` +N:-between(0,N,I),N=:=I*I. ``` [Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/X9vPSjcptaQ8NTVPw0DHT8dTU8fP1srWU8tTDyipYaipx8UFAA "Prolog (SWI) – Try It Online") ## Explanation Searches through all numbers greater or equal to `0` and less than or equal to `N` and tests whether that number squared is equal to `N`. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 1 byte ``` ° ``` [Try it online!](https://tio.run/##y00syUjPz0n7///Qhv//DbgMucxMuCwsuIwMTcxNLIzNTMy5jM24jM25zEwB "MathGolf – Try It Online") I don't think an explanation is needed. I saw the need for an "is perfect square" operator before I saw this challenge, as the language is designed to handle math related golf challenges. Returns 0 or 1, as MathGolf uses integers to represent booleans. [Answer] # APL, 5 bytes ``` ⊢∊⍳×⍳ ``` Explanation: ``` ⊢ N ∊ in ⍳ numbers up to N × times ⍳ numbers up to N ``` Test: ``` ((⊢∊⍳×⍳) ¨ X) ,[÷2] X←⍳25 1 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 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 ``` [Answer] # PHP, 21 bytes ``` <?=(-1)**$argn**.5<2; ``` If the square root is not an integer number, `(-1)**$argn**.5` is `NAN`. [Answer] # R, 15 ``` scan()^.5%%1==0 ``` ^.5 is less bytes than sqrt(). %%1, the modulus, will result in 0 if answer is an interger. scan() takes user input. <http://www.tutorialspoint.com/execute_r_online.php?PID=0Bw_CjBb95KQMSm1qVktIOUdSSDg> [Answer] # Ruby, 25 bytes ``` Math.sqrt(gets.to_i)%1==0 ``` There probably is a shorter way but that's all I found. [Try it online!](https://tio.run/##KypNqvz/P0fBVkHXTkGjQlOhWsE3sSRDr7iwqATIVTW0tTVQqOUqKC0pVsjRS07MydFITy0p1ivJj8/UpKXw//8GXIZcZiZcFhZcRoYm5iYWxmYm5gA "Ruby – Try It Online") [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, ~~20~~ 17 bytes Saved 3 bytes thanks to @chunes! ``` [ √ dup ⌊ = ] ``` [Try it online!](https://tio.run/##LcwxCsIwGIbh3VN8JyimhiQqzuLiIk7iUNK/GNQkpn8GEXcRT@DxepEo4vjCw9s1lkMq281qvZzh3PABMRHzNSbnGUdKnk7o6ZLJW@p/ouqyt@yC/2f2zoaWMB/dMIZADYkphILQUBLGoBZSSzNRUuOOssPweKPNEcPriQX25fuJqMoH "Factor – Try It Online") [Answer] # [PHP](https://php.net/), 26 bytes ``` <?=(0^$q=sqrt($argn))==$q; ``` [Try it online!](https://tio.run/##K8go@G9jX5BRwKWSWJSeZ6tkYqlkzWVvBxS01TCIUym0LS4sKtEAS2pq2tqqFFr///81L183OTE5IxUA "PHP – Try It Online") [Answer] # [CJam](https://sourceforge.net/projects/cjam/), 8 bytes ``` ri_mQ2#= ``` [Try it online!](https://tio.run/##S85KzP3/vygzPjfQSNn2/38zIwA) ### Explanation Integer square root, square, compare with original number. [Answer] # Mathematica, 13 bytes ``` AtomQ@Sqrt@#& ``` [Try it online!](https://tio.run/##y00sychMLv6fZvvfsSQ/N9AhuLCoxEFZ7X9AUWZeiYJDmoOF4X8A "Mathics – Try It Online") [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 8 bytes ``` 0=1|*∘.5 ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/hR2wQDW8MarUcdM/RMgXwFAwVDBTMTBQsLBSNDE3MTC2MzE3MA "APL (Dyalog Unicode) – Try It Online") `0=` [is] zero equal to `1|` the modulus-1 (i.e. the fractional part) of `*∘.5` the argument raised to the power of a half [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 27+2 bytes ``` {x=int($0^0.5);$0=x*x==$1}1 ``` [Try it online!](https://tio.run/##jcwxCgJRDATQfk9hsYUKSuYnmeQjewSvIFiKYCW4IJ79m97GcoY3c33dx3ivy@3x3M5ykaPvTrMs635dlhkfjCETJtqUOTVYaHdKVSEwINUoxt7YHUJ0kAwV84S37n86/jhFKJhFNOCZBvFosfmB7s2V8EIh0qmVeh2qScumLCJd01gD1ahVWJ0zG2DOcTh/AQ "AWK – Try It Online") Add `+2` bytes for using the `-M` flag for arbitrary precision. I originally used string comparison because large number compared equal, even though they weren't, but the `sqrt` was also returning imprecise values. `2^127-2` should not be a perfect square. [Answer] # T-SQL, 38 bytes ``` SELECT IIF(SQRT(a)LIKE'%.%',0,1)FROM t ``` Looks for a decimal point in the square root. `IIF` is specific to MS SQL, tested and works in MS SQL Server 2012. Input is in column **a** of pre-existing table **t**, per [our input rules](https://codegolf.meta.stackexchange.com/a/5341/70172). ]
[Question] [ I think we've all done this as a kid: some websites require a minimum age of 18, so we just subtract a few years from the year of birth and voilà, we 'are' 18+. In addition, for most rides at amusement parks the minimum height to enter is 1.40 meters (here in The Netherlands it as at least). Of course this can be cheated less easily than age, but you could wear shoes with thick heels, put your hair up, wear a hat, stand on your toes, etc. ## Input: Your program/function accepts a positive integer or decimal. ## Output: * Is the input an integer `>= 18`? Simply print the input. * Is the input an integer `0-17`? Print `18`. * Is the input a decimal `>= 1.4`? Simply print the input. * Is the input a decimal `0.0-1.4`? Print `1.4`. # Challenge rules: * Assume the input will always be in the range of `0-122` (oldest woman ever was 122) or `0.0-2.72` (tallest man ever was 2.72). * You are allowed to take the input as a String, object, or anything else you prefer. * The decimal inputs will never have more than three decimal places after the decimal point. * `2` or `2.` both aren't valid outputs for `2.0`. You are free to output `2.00` or `2.000` instead of `2.0` however. Just like the input the output will never have more than three decimal places after the point. ## 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](http://meta.codegolf.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call. * [Default Loopholes](http://meta.codegolf.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. ## Test cases: ``` 0 -> 18 1 -> 18 2 -> 18 12 -> 18 18 -> 18 43 -> 43 115 -> 115 122 -> 122 0.0 -> 1.4 1.04 -> 1.4 1.225 -> 1.4 1.399 -> 1.4 1.4 -> 1.4 1.74 -> 1.74 2.0 -> 2.0 2.72 -> 2.72 ``` [Answer] # Python 2.7, 34 bytes ``` lambda x:max(x,[18,1.4]['.'in`x`]) ``` [Answer] # JavaScript (ES6), 27 ~~31~~ Input taken as a string. To check if the input value has decimals, it's appended to itself: if there is no decimal point the result is still a valid number, else it's not. To recognize a valid number (including 0), I use division as in javascript `1/n` is numeric and not 0 for any numeric `n` (eventually the value is `Infinity` for `n==0`), else it's `NaN` ``` x=>x<(y=1/(x+x)?18:1.4)?y:x ``` **Test** ``` f= x=>x<(y=1/(x+x)?18:1.4)?y:x ;[ ['0', '18' ],['1', '18' ],['2', '18' ],['12', '18' ],['18', '18' ],['43', '43' ],['115', '115'], ['122', '122' ] ,['0.0', '1.4'],['1.0', '1.4'],['1.04', '1.4'],['1.225', '1.4'],['1.399', '1.4'],['1.4', '1.4'],['1.74', '1.74'],['2.0', '2.0'],['2.72', '2.72'] ].forEach(t=>{ var i=t[0],k=t[1],r=f(i) console.log(i,k,r,k==r?'OK':'KO') }) ``` *My prev (wrong) solution:* Taking input as a number, you can use remainder operator `%` to check if the number is integer. ``` x=>x<(y=x%1?1.4:18)?y:x ``` or ``` x=>Math.max(x,x%1?1.4:18) ``` But this does not work as the challenge request to discriminate between, say, `2` and `2.0` and that's the same number. So it's not possibile to get the input as a number [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), ~~13~~ 11 bytes Uses [CP-1252](http://www.cp1252.com/) encoding. ``` ÐîQ18*14T/M ``` **Explanation** ``` Ð # triplicate input î # round up Q # check for equality 18* # multiply 18 by this (18 if input is int, else 0) 14T/ # push 14 / 10 M # take max of stack (input and 1.4 or 18) ``` [Try it online](http://05ab1e.tryitonline.net/#code=w5DDrlExOCoxNFQvTQ&input=MS4z) [Answer] # Java 8, ~~90~~ ~~61~~ 57 bytes ``` i->(i+"").contains(".")?(float)i<1.4?1.4:i:(int)i<18?18:i ``` -4 bytes returning `Object` instead of `String`; and some additional bytes converting Java 7 to 8. -4 byte taking the input as `Object` instead of `String` as well. **Explanation:** [Try it here.](https://tio.run/##jY9BTsMwEEX3OcUoK1uoVuIGNU1bcgLKokvEwnUdNCG1o9qthFDOHhzIlg4LW575b/4ft@qmFq43tj19jLpT3sOzQvuVAKAN5tIobWA/lQAvx9boAJrND@Sb2B@SePmgAmrYg4UdjLh4YviQplxoZ0O08ywVKa9Z0zkVOG5zUdTxVFixmDI1yjovKxw3k1l/PXbRbPa8OTzBOZqwQ7igfX99A8V/Fzp8@mDOwl2D6KMUOsus0CzjP4v9qeeELql5EigJoFiSEfcy7s9mImsoe5EVNCPlIw0t12sa@kfYimQk/S8pVnJmhmQYvwE) ``` i-> // Method with Object as both parameter and return-type (i+"").contains(".")? // If the input as String contains a dot: (float)i<1.4? // If the input is a float below 1.4: 1.4 // Return double 1.4 : // Else: i // Return the input-float as is :(int)i<18? // Else if the input is an integer below 18: 18 // Return integer 18 : // Else: i // Return the input-integer as is ``` [Answer] # Pyth, 14 bytes ``` eS,@,18h.4}\.` ``` [Try it online.](http://pyth.herokuapp.com/?code=eS%2C%40%2C18h.4%7D%5C.%60&input=17&test_suite_input=12%0A18%0A36%0A1.5%0A2.0%0A1.0&debug=0) [Answer] # PHP, 40 Bytes modified by @user59178 Thank You ``` <?=max(is_int(0+$i=$argv[1])?18:1.4,$i); ``` PHP, 42 Bytes first Version ``` <?=max(strpos($i=$argv[1],".")?1.4:18,$i); ``` [Answer] # Perl, ~~29~~ 27 bytes Includes +2 for `-lp` Give input on STDIN ``` adult.pl <<< 1.24 ``` `adult.pl`: ``` #!/usr/bin/perl -lp $_>($a=/\./?1.4:18)or*_=a ``` If you don't mind an extra newline if you really were a full adult then leaving out the `l` option for 26 bytes works too [Answer] ## EXCEL: ~~26~~ ~~31~~ 29 Bytes ``` =MAX(A1;IF(MOD(A1;1);1,4;18)) ``` Formula can go anywhere except A1, the input cell. Fixed errors, and replaced with Emigna's suggestion. Thanks to Alexandru for saving me some bytes using truths [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 14 bytes ``` #$:18ot|:1.4ot ``` [Try it online!](http://brachylog.tryitonline.net/#code=IyQ6MThvdHw6MS40b3Q&input=MS4zOTk&args=Wg) ### Explanation ``` #$ Input is an integer :18o Sort the list [Input, 18] t Take the last element | Or :1.4o Sort the list [Input, 1.4] t Take the last element ``` [Answer] # GNU sed, 40 + 1 = 41 bytes (score +1 for use of `-r` flag to interpreter) ``` s/^.$|^1[^9]$/18/ /^0|1\.[0-3]/s/.*/1.4/ ``` ### Annotated: ``` #!/bin/sed -rf # First, anything that's a single digit or is '1' followed by a # digit other than '9' is replaced with '18'. s/^.$|^1[^9]$/18/ # Now, any line beginning with '0' or containing '1.0' to '1.3' is # replaced with '1.4'. /^0|1\.[0-3]/s/.*/1.4/ ``` We take advantage of the constraints on input, so don't have to test the start of string when we see '1.' - we know there's only one digit before the decimal point. ### Test result: ``` $ ./94832.sed <<END > 0 > 1 > 2 > 12 > 18 > 43 > 122 > > 0.0 > 1.04 > 1.225 > 1.399 > 1.4 > 1.74 > 2.0 > 2.72 > END 18 18 18 18 18 43 122 1.4 1.4 1.4 1.4 1.4 1.74 2.0 2.72 ``` [Answer] ## Haskell, 50 bytes ``` x#y=show$max x$read y f s|elem '.'s=1.4#s|1<2=18#s ``` Usage example: `f "1.0"` -> `"1.6"`. Haskell's strict type requires usage of strings as input and output. Howevers, `read`, `max` and `show` are polymorphic and handle all numeric types. [Answer] # Java, ~~79~~ 70 bytes ``` int f(int x){return x<18?18:x;} float f(float x){return x<1.4?1.4f:x;} ``` Defines two methods with overloading, which use the conditional operator. Call it like `f(5)` or `f(1.4f)`. [Answer] # [Convex](http://github.com/GamrCorps/Convex), 9 bytes ``` _1ÛI1.4?» ``` [Try it online!](http://convex.tryitonline.net/#code=XzHDm0kxLjQ_wrs&input=&args=NS4w) [Answer] # CJam, ~~18~~ 14 bytes Saved 4 bytes thanks to Martin Ender. ``` q~_`'.&1.4I?e> ``` [Online interpreter](http://cjam.aditsu.net/#code=q%7E_%60%27.%261.4I%3Fe%3E&input=1.2) [Answer] # IBM/Lotus Notes Formula Language, ~~58~~ 49 bytes ``` @If(@Like(@Text(a);"%.%");@If(a<1.4;1.4;a);@If(a<18;18;a)) ``` Computed field formula where a is an editable numeric field. **EDIT** ``` @If(@Like(@Text(a);"%.%");@Max(1.4;a);@Max(18;a)) ``` Alternative inspired by @Mego [Answer] # AWK - 29 bytes ``` ($0<c=$0~/\./?1.4:18){$0=c}1 ``` Usage: ``` awk '{c=$0~/\./?1.4:18}($0<c){$0=c}1' <<< number ``` Testing was performed with `gawk` on RHEL 6. I tried with all the test cases, unfortunately I don't have `AWK` on the machine that has internet access, so copy-paste is not possible. Is there a more compact way to do this in `AWK`? [Answer] # C#, 58 bytes ``` x=>x is int?(int)x>17?x:18:(float)x<1.4?"1.4":$"{x:.0##}"; ``` No crazy string parsing needed for C#. Input is expected to be an `int` or `float` (unfortunately C# can't cast a `double` to `float` if the `double` is in an `object`). Output will be either `int` or `string` in an `object`. (almost missed the at least 1 decimal requirement, added that now) Ungolfed: ``` /*Func<object, object> Lambda = */ x => x is int // if parameter is an int ? (int)x > 17 // check if x is at least 18 ? x // at least 18 so return x : 18 // less than 18 so return 18 : (float)x < 1.4 // x is float, check if at least 1.4 ? "1.4" // less than 1.4 so return 1.4 : $"{x:.0##"} // at least 1.4 so return x and ensure at least 1 decimal place ; ``` Alternate implementation which is also 58 bytes. ``` x=>x is int?(int)x>17?x:18:$"{((float)x<1.4?1.4:x):.0##}"; ``` [Answer] ## Actually, 16 bytes ``` ;:.7τ9τ($'.íuIkM ``` [Try it online!](http://actually.tryitonline.net/#code=OzouN8-EOc-EKCQnLsOtdUlrTQ&input=LjI) Explanation: ``` ;:.7τ9τ($'.íuIkM ; dupe input :.7τ 1.4 (.7*2) - note that :1.4 is the same length, but an additional delimiter would be needed to separate it from the following 1 9τ 18 (9*2) ($'.íu 1-based index of "." in string representation of input, 0 if not found I 1.4 if input contains a "." else 18 kM maximum of remaining values on stack ``` [Answer] ## Emacs Lisp, 37 bytes ``` (lambda(x)(max(if(floatp x)1.4 18)x)) ``` Guesses from the "datatype" whether the integer or float version should be used. (`floatp` returns `t` for `1.0`, but not for `1.`) The parameter is a number as integer or float, i.e. it should satisfy `numberp`. [Answer] # Haskell, 49 bytes ``` x#y=show.max x.fst<$>reads y;f s=head$18#s++1.4#s ``` Basically, this first attempts to read the input as an integer and then as a double if that fails. Then proceeds to compare it to the respective comparison baseline. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~16 15 13~~ 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to caird coinheringaahing (take input as a string). ``` ċ”.ị1.4,18»V ``` **[TryItOnline](https://tio.run/##y0rNyan8//9I96OGuXoPd3cb6pnoGFoc2h32//9/JSM9AyUA "Jelly - Try it online!")** Or see all test cases, also at **[TryItOnline](https://tio.run/##y0rNyan8//9I96OGuXoPd3cb6pnoGFoc2h3GdXTP4fZHTWu8gTjy////0UoGSjpKhkBsBKLBhAWQMDEGsQxNwYIgUQM9sEI9AxMwZWQEltIzNrYE0xBRcxBlBFZppGdupBQLAA "Jelly - Try it online!")** How? ``` ċ”.ị1.4,18»V - Main link: string, S ”. - '.' character ċ - count (occurrences of '.' in S) 1.4,18 - pair literals 1.4 and 18: [1.4, 18] ị - index into (1-indexed) V - evaluate (S) as Jelly code » - maximum ``` [Answer] # C#, 69 bytes ``` s=>s.Contains(".")?float.Parse(s)<1.4?"1.4":s:int.Parse(s)<18?"18":s; ``` [**Try it online!**](http://ideone.com/53iScL) Full program with test cases: ``` using System; namespace YesImAnAdult { class Program { static void Main(string[] args) { Func<string,string>f= s=>s.Contains(".")?float.Parse(s)<1.4?"1.4":s:int.Parse(s)<18?"18":s; Console.WriteLine(f("0")); //18 Console.WriteLine(f("1")); //18 Console.WriteLine(f("2")); //18 Console.WriteLine(f("12")); //18 Console.WriteLine(f("18")); //18 Console.WriteLine(f("43")); //43 Console.WriteLine(f("122")); //122 Console.WriteLine(f("0.0")); //1.4 Console.WriteLine(f("1.04")); //1.4 Console.WriteLine(f("1.225")); //1.4 Console.WriteLine(f("1.399")); //1.4 Console.WriteLine(f("1.4")); //1.4 Console.WriteLine(f("1.74")); //1.74 Console.WriteLine(f("2.0")); //2.0 Console.WriteLine(f("2.72")); //2.72 } } } ``` A pretty straightforward solution. Note that on some systems float.Parse() might return incorrect results. Pass *CultureInfo.InvariantCulture* as the second argument according to [this answer](https://stackoverflow.com/questions/16657090/why-does-float-parse-return-wrong-value). [Answer] # ~~[Dyalog APL](http://goo.gl/9KrKoM), 14 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)~~ Rendered invalid by further specifications `⎕IO←0` which is default on many systems. Takes string as argument. ``` ⍎⌈18 1.4⊃⍨'.'∘∊ ``` `⍎⌈` max of the evaluated argument and `18 1.4⊃⍨` {18,1.4} selected by `'.'∘∊` whether the argument contains a period [Answer] # C++, 68 bytes ``` int A(int a){return a<18?18:a;}float A(float h){return h<1.4?1.4:h;} ``` This answer is actually 2 functions with the same name, and the compiler works out for me which to call, so it acts as one function without me having to take in one input and decide which it is. Since input on the floating point is guaranteed to be of the same precision as the output, I can return it safely without having to truncate it either. ***Ungolfed + tests*** ``` #include <iostream> int A(int a) { return a < 18 ? 18 : a; } float A(float h) { return h < 1.4 ? 1.4 : h; } int main() { std::cout << 0 << " " << A(0) << "\n"; std::cout << 19 << " " << A(19) << "\n"; std::cout << 1.1 << " " << A(1.1f) << "\n"; std::cout << 2.2 << " " << A(2.2f) << "\n"; } ``` [Answer] ## C, 50 bytes: ``` #define A(x)(x/2+(x+1)/2-x?x<1.4?1.4:x:x<18?18:x) ``` The byte count includes the newline at the end of the macro definition. [Test](http://melpon.org/wandbox/permlink/2d0kLPfsteRO9zzN): ``` #define A(x)(x/2+(x+1)/2-x?x<1.4?1.4:x:x<18?18:x) #include <assert.h> int main() { assert(A(0) == 18); assert(A(1) == 18); assert(A(2) == 18); assert(A(12) == 18); assert(A(18) == 18); assert(A(43) == 43); assert(A(115) == 115); assert(A(122) == 122); assert(A(0.0) == 1.4); assert(A(1.04) == 1.4); assert(A(1.225) == 1.4); assert(A(1.399) == 1.4); assert(A(1.4) == 1.4); assert(A(1.74) == 1.74); assert(A(2.0) == 2.0); assert(A(2.72) == 2.72); } ``` [Answer] # C#, 71 bytes ``` object A(object i){return i is int?(int)i>18?i:18:(double)i>1.4?i:1.4;} ``` try it [here](https://dotnetfiddle.net/6DFkdX) [Answer] # C, ~~119~~ ~~111~~ ~~105~~ 100 ``` m;f(char*s){float atof(),l=atof(s);for(m=s;*s&&*s++!=46;);puts(*s?l<1.4?"1.4":m:atoi(m)>18?m:"18");} ``` Tested with ``` main(c,v)char**v;{ f("0"); f("1"); f("2"); f("12"); f("18"); f("44"); f("115"); f("122"); f("0.0"); f("1.04"); f("1.225"); f("1.339"); f("1.4"); f("1.74"); f("2.0"); f("2.72"); } ``` Output ``` 18 18 18 12 18 44 115 122 1.4 1.4 1.4 1.4 1.4 1.74 2.0 2.72 ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, ~~13~~ 12 bytes ``` ₌⌊±[18|1.4]∴ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJB4biLIiwiIiwi4oKM4oyKwrFbMTh8MS40XeKItCIsIiIsIlwiMFwiXG5cIjFcIlxuXCIyXCJcblwiMTJcIlxuXCIxOFwiXG5cIjQzXCJcblwiMTE1XCJcblwiMTIyXCJcblwiMC4wXCJcblwiMS4wNFwiXG5cIjEuMjI1XCJcblwiMS4zOTlcIlxuXCIxLjRcIlxuXCIxLjc0XCJcblwiMi4wXCJcblwiMi43MlwiIl0=) Takes input as string. [Answer] ## Batch, 102 bytes ``` @set/ps= @if %s:.=%==%s% (if %s% lss 18 set s=18)else if %s:~0,1%%s:~2,1% lss 14 set s=1.4 @echo %s% ``` First determines whether the input is an integer by checking whether deleting all `.`s has any effect on the string. If it is then the value is readily compared against 18, otherwise the first and third characters are combined into a number which is compared against 14. [Answer] # C#, 95 Bytes Golfed: ``` string y(string p){int a;return int.TryParse(p,out a)?a>17?p:"18":double.Parse(p)<1.4?"1.4":p;} ``` Ungolfed: ``` class YesOfCourseImAnAdult { public string y(string p) { int a; return int.TryParse(p, out a) ? a > 17 ? p : "18" : double.Parse(p) < 1.4 ? "1.4" : p; } } ``` Test cases: ``` var codeGolf = new YesOfCourseImAnAdult(); Console.WriteLine(codeGolf.y("0")); Console.WriteLine(codeGolf.y("1")); Console.WriteLine(codeGolf.y("2")); Console.WriteLine(codeGolf.y("12")); Console.WriteLine(codeGolf.y("18")); Console.WriteLine(codeGolf.y("43")); Console.WriteLine(codeGolf.y("122")); Console.WriteLine(codeGolf.y("0.0")); Console.WriteLine(codeGolf.y("1.04")); Console.WriteLine(codeGolf.y("1.225")); Console.WriteLine(codeGolf.y("1.399")); Console.WriteLine(codeGolf.y("1.4")); Console.WriteLine(codeGolf.y("1.74")); Console.WriteLine(codeGolf.y("2.0")); Console.WriteLine(codeGolf.y("2.72")); ``` Output: ``` 18 18 18 18 18 43 122 1.4 1.4 1.4 1.4 1.4 1.74 2.0 2.72 ``` ]
[Question] [ My friend and I were working on a lab in our AP Computer Science class and decided to code golf one one the problems since we still had half the class free after we finished. Here is the question: > > Given a number n, is n divisible by each of its digits? > > > For example, 128 will pass this test- it is divisible by 1,2, and 8. Any numbers with a zero automatically disqualify the number. While you may use other languages and post solutions with them if you like, we are most interested in seeing how compact people can make the program in Java, as that is the language we use in the class. So far, we both have 51. Here is my current code: ``` public boolean dividesSelf(int n){for(int p=n;n%10>0;)n/=p%(n%10)>0?.1:10;return n<1;} // 51 characters // Breakdown: // for(int p=n; Saves one semicolon to put declaration into for loop // n%10>0;) Basic check-for-zero // n/= Pretty simple, discarding one number off of n at a time // p%(n%10)>0? If p (the given value) is not divisible by n%10 (the current digit)... // .1:10; Divide by .1 (multiply by 10) so it fails the check next iteration. If it is divisible, divide by 10 to truncate the last digit // return n<1 If the number was fully divisible, every digit would be truncated, and n would be 0. Else, there would still be non-zero digits. ``` ## Requirements The method signature can be whatever you want. Just count the function body. Make sure, though, that the method returns a boolean value and only passes in *one numeric* parameter (not a string). The code must be able to pass all of these cases (in order to stay true to the directions of the original question, *only* boolean true and false values count if the language supports booleans. If and only if your language does not have boolean variables you may represent false with 0 and true with any nonzero integer (preferably 1 or -1): ``` 128 -> true 12 -> true 120 -> false 122 -> true 13 -> false 32 -> false 22 -> true 42 -> false 212 -> true 213 -> false 162 -> true 204 -> false ``` Also, we didn't count whitespace, so feel free to do the same, unless the whitespace is essential to the working of the program (so newlines in Java don't count, but a single space between `int` and `x=1` does count.) Good luck! [Answer] # Perl 6, 13 ``` sub golf($_) { $_%%.comb.all } ``` Uses the implicit variable `$_` — `$_ %% .comb.all` is equivalent to `$_ %% all($_.comb)`. `%%` is the "is divisible" operator, and `comb` with no additional argument returns a list of the characters in a string. As an example, if the argument is 123, then the function evaluates ``` 123 %% all(123.comb) ``` which is ``` 123 %% all(1, 2, 3) ``` junction autothreading makes it ``` all(123 %% 1, 123 %% 2, 123 %% 3) ``` which is ``` all(True, False, True) ``` which is false in boolean context because it's an "all" junction and clearly not all of its elements are true. It should be possible to coerce the return value to `Bool` and hide the junction-ness from callers by making the function signature `sub golf($_ --> Bool())`, but coercions in function signatures don't work yet in Rakudo. The return value is still correctly true or false, it's just not `True` or `False`. [Answer] # C# and System.Linq - 26 / 40 Per the rules, not counting the method declaration itself. ``` bool dividesSelf(int i) { return(i+"").All(d=>i%(d-48d)<1); } ``` Showing that once again, C# is the superior choice when Java is under consideration... I kid, I kid! Unfortunately, this function (and many in other answers) will not produce correct results for negative input. We can fix this, but the solution loses a lot of its charm (and grows to 46 characters in length): ``` return(i+"").All(d=>d>48&&i%(d-48)==0||d==45); ``` **Edit**: shaved off one character with Tim's suggestion. **Edit**: with the introduction of [expression-bodied members](https://docs.microsoft.com/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members) in C# 6, we can pare this down further by cutting out the `return`: ``` bool dividesSelf(int i) => (i+"").All(d=>i%(d-48d)<1); ``` for a total of 26 characters (in my opinion, the `=>` should not be included any more than braces would be). The version handling negative numbers can be similarly shortened. [Answer] ## APL (~~13~~ 11) (apparently the brackets don't count) ``` {0∧.=⍵|⍨⍎¨⍕⍵} ``` Explanation: * `⍎¨⍕⍵`: evaluate each character in the string representation of `⍵` * `⍵|⍨`: for each of those, find the modulo of it and `⍵` * `0∧.=`: see whether all of those are equal to `0` Testcases: ``` N,[.5] {0∧.=⍵|⍨⍎¨⍕⍵} ¨ N←128 12 120 122 13 32 22 42 212 213 162 204 128 12 120 122 13 32 22 42 212 213 162 204 1 1 0 1 0 0 1 0 1 0 1 0 ``` [Answer] ## Python 2: 43 chars ``` f=lambda n:any(n%(int(d)or.3)for d in`n`)<1 ``` Checks whether the number has any nonzero remainders modulo its digits, and outputs the negation of that. Zero digits are handled strangely: since computing `%0` causes an error, digits of `0` are replaced with `.3`, which seems to always give a nonzero result due to floating point inaccuracies. The function body is 32 chars. [Answer] ## Perl - 27 bytes ``` sub dividesSelf{ $_=pop;s/./!$&||$_%$&/ger<1 } ``` Not counting the function signature, as instructed. **Sample Usage:** ``` use Data::Dump qw(dump); for $i (128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204) { printf "%3d -> %s\n", $i, dump(dividesSelf $i); } ``` **Sample Output:** ``` 128 -> 1 12 -> 1 120 -> "" 122 -> 1 13 -> "" 32 -> "" 22 -> 1 42 -> "" 212 -> 1 213 -> "" 162 -> 1 204 -> "" ``` --- Addressing the problem specification: "Only boolean true and false values count. Truthy/falsey values do *not* count." ``` use Data::Dump qw(dump); dump(1 == 1); dump(0 == 1); ``` Outputs: ``` 1 "" ``` 'True' and 'False' are defined as `1` and `""`. **Erratum:** As Brad Gilbert [rightly points out](https://codegolf.stackexchange.com/q/41902#comment97962_41906), perl defines *true* as a scalar which is both the integer `1` and the string `"1"` simultaneously, and *false* as a scalar which is both the integer `0` and the string `""` simultaneously. [Answer] # CJam, ~~11~~ 10 bytes ``` { _Ab:df%:+! }:F; ``` This defines a function named `F` and discards the block from the stack. [Try it online.](http://cjam.aditsu.net/#code=%7B_Ab%3Adf%25%3A%2B!%7D%3AF%3B%20e%23%20Define%20function.%0A%5Bq~%5D%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Read%20input.%0A%7BF%7D%25%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Execute%20F%20for%20each%20integer.%0Ap%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Print.&input=128%2012%20120%20122%2013%2032%2022%2042%20212%20213%20162%20204) ### Test cases ``` $ cjam <(echo '{_Ab:df%:+!}:F;[128 12 120 122 13 32 22 42 212 213 162 204]{F}%p') [1 1 0 1 0 0 1 0 1 0 1 0] ``` ### How it works ``` _ " Copy the integer on the stack. "; Ab " Push the array of its digits in base 10. "; :d " Cast each digit to Double. "; f% " Take the integer on the stack modulus each of its digits. "; :+ " Add the results. "; ! " Push the logical NOT of the sum. "; ``` [Answer] # JavaScript ES6, ~~39~~ ~~32~~ 28 bytes ``` v=>[...""+v].every(x=>v%x<1) ``` Thanks core1024 for the suggestion to replace `(""+v).split("")` with `[...""+v]`, and openorclose for suggesting the use of `every` function. The answer currently doesn't contain one bit of my code :O ### Previous solution ``` v=>[...""+v].filter(x=>v%x|!+x)=="" ``` `==""` is not a valid way to check if an array is empty, since `[""]==""` returns `true`, but the array is guarantee to contain non-empty string, so it works here. The rest are quite standard shorthand type conversion in JavaScript. [Answer] ## Java 8, 46 Bytes (method body) Using [Jeroen Mostert](https://codegolf.stackexchange.com/a/41918/21777)'s converting to double trick. ``` public static boolean dividesSelf(int n) { return(""+n).chars().allMatch(x->n%(x-48d)<1); } ``` [Answer] # Pyth, 12 bytes ``` !f|!vT%vzvTz ``` This filters the characters in the string for being either zero (`!vT`) or not dividing the input (`%vzvT`), then takes the logical not of the resulting list. [Try it here.](http://isaacg.scripts.mit.edu/pyth/index.py) [Answer] # Ruby, 44 bytes (function body: 37) Probably has potential to be golfed further. ``` f=->n{n.to_s.chars.all?{|x|x>?0&&n%x.hex<1}} ``` Input taken through function `f`. Example usage: ``` f[128] # => true f[12] # => true f[120] # => false ... ``` [Answer] # Python - ~~59~~ ~~50~~ ~~49~~ 47 bytes ``` f=lambda n:all(c>'0'and 0==n%int(c)for c in`n`) ``` I'm sure there's a faster way... oh well. *Edit* - Thanks to FryAmTheEggman for the golfing tips. *Edit 2* - FryAmTheEggman may as well have written this at this point, oops *Edit 3* - Hands up if you didn't even know genexps were a thing. ...Just me? [Answer] ## [Pyth](https://github.com/isaacg1/pyth) 11 ``` !f%Q|vT.3`Q ``` This combines [@isaacg's](https://codegolf.stackexchange.com/a/41905/31625) and [@xnor's](https://codegolf.stackexchange.com/a/41915/31625) answers. It filters out digits from the input by checking the value of `input % (eval(current_digit) or .3)`. Then it checks if the resulting string is empty or not. Came across another couple same-length variants: ``` !f%Q|T.3jQT !f|!T%QTjQT ``` [Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py) [Answer] # Bash + coreutils, 44 bytes The full function definition is: ``` f()((`tr 0-9 \10<<<$1``sed "s/./||$1%&/g"<<<$1`)) ``` I'm not sure how to score this as normally shell functions use a single set of `{}` or `()` to contain the function body. I found here I could also use double `(())` to contain the function body which causes an arithmetic expansion which is what I need here. So for now I am counting just one pair of those brackets - further discussion of this is welcome. ### Output: ``` $ for i in 128 12 120 122 13 32 22 42 212 213 162 204; do f $i; printf "%d " $?; done 1 1 0 1 0 0 1 0 1 0 1 0 $ $ ``` [Answer] # J - 14 char The function body is the portion after the `=:`. If we want to minimize the character count for the whole function, that's the 15 char `*/@(0=,.&.":|])`. ``` f=:0*/@:=,.&.":|] ``` `,.&.":` is the shortest way in J to expand as number into a list of its decimal digits: convert to string, separate the digits, and convert each digit back into a number. `,.&.":|]` takes the input number (`]`) modulo (`|`) those digits. `0*/@:=` returns true if all the results were 0, else gives a false. ``` f 162 1 f every 204 212 213 0 1 0 ``` [Answer] # Java - ~~121~~ ~~102~~ ~~97~~ ~~79~~ 78 bytes I just *know* this will get clobbered later. Oh well. ``` boolean b(int a){int m=10,j,t=1;for(;m<a*10;m*=10){j=10*(a%m)/m;if(j==0||a%j>0)t=0;}return t>0;} ``` I'll be back. [Answer] ## Julia 32 25 23 ### Improved using digits Also fixes problem with negative numbers ``` selfDivides(x)=sum(x%digits(x).^1.)==0 ``` ### Old method All digits divide if the sum of all the remainders is 0. Like others, has a problem with negative numbers. ``` selfDivides(x)=sum(x.%(Float64["$x"...]-48))==0 ``` ## Output ``` [selfDivides(x) for x in [128,12,120,122,13,32,22,42,212,213,162,204]] 12-element Array{Any,1}: true true false true false false true false true false true false ``` ### Improved method also handles BigInt ``` selfDivides(BigInt(11111111111111111111111111111111111111112)) true ``` however ``` selfDivides(BigInt(11111111111111111111111111111111111111113)) false ``` because ``` BigInt(11111111111111111111111111111111111111113) %3 1 ``` [Answer] # Haskell - 100 54 38 ``` f x=all(\y->y>'0'&&x`mod`read[y]<1)$show x ``` Still learning, critiques appreciated [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` SÖP ``` Only `1` is [truthy](https://codegolf.meta.stackexchange.com/a/2194/52210) in 05AB1E, so this will output `1` if the input-integer is divisible by each of its digits. For falsey test cases it either outputs `0`, or a multiple of the input if it contains `0`s (due to division by zero errors). If you want a distinct falsey output of `0`, you can add a trailing `Θ` (`== 1` builtin). [Try it online](https://tio.run/##MzBNTDJM/f8/@PC0gP//DY0sAA) or [verify all test cases](https://tio.run/##MzBNTDJM/V9Waa@k8KhtkoKSfaXL/@DD0wL@6/yPNjTSMTLSMQRjCx1DMyAXKGRqbm6qY2isY2ykYwKSMdAxMjAByhjrGBoYGMYCAA). **Explanation:** ``` S # Convert the (implicit) input-integer to a list of digits Ö # Check for each digit if it evenly divides the (implicit) input-integer # (results in 1 for truthy; 0 for falsey; and itself for division by zero errors) P # Take the product of this list to check if all are truthy # (after which it is output implicitly as result) ``` [Answer] # CJam, 15 bytes ``` {_Abf{_g{%}*}:|!} ``` This is a block, the closest thing to a function in CJam. I'm only counting the body (i.e. omitting the braces). You can use it as follows: ``` 128{_Abf{_g{%}*}:|!}~ ``` Or if you want to test a series of inputs, you can do ``` [128 12 120 122 13 32 22 42 212 213 162 204]{{_Abf{_g{%}*}:|!}~}% ``` The block leaves `0` (falsy) or `1` (truthy) on the stack to indicate the result. (CJam doesn't have a Boolean type.) [Test it here.](http://cjam.aditsu.net/) Explanation: ``` _ "Duplicate input."; Ab "Get base-10 digits."; f{ } "This maps the block onto the list of digits, supplying the input each time."; _g "Duplicate digit, get signum S (0 or 1)."; { }* "Repeat this block S times."; % "Take input modulo digit."; "This leaves an array of zeroes for divisible digits, non-zeroes for non-divisible digits, and non-zero junk for zeroes."; :| "Fold OR onto this list. One could also sum the list with :+"; ! "Logical NOT. Turns 0 into 1, and non-zero values into 0."; ``` # Alternative, also 15 bytes ``` {:XAb{X\_X)?%},!} ``` Explanation ``` :X "Store input in X."; Ab "Get base-10 digits."; { }, "Filter this list by the result of the block."; X\ "Push another copy of X, swap with digit."; _ "Duplicate digit."; X) "Push X+1."; ? "Select digit itself or X+1, depending on whether digit is 0 or not."; % "Take modulo. X%(X+1) will always be nonzero for positive integers."; ! "Logical NOT. Turns an empty list into 1 and a non-empty list into 0."; ``` [Answer] # CJam, 15 bytes ``` {_Abf{_{%}1?}1b!} ``` `{}` is the closest thing to a function in CJam. I am just counting the body of the function Use it like this: ``` 128{_Abf{_{%}1?}1b!}~ ``` To get either `1` (if the number is divisible) or `0` (if the number is not divisible by its digits). [Try it online here](http://cjam.aditsu.net/) **Explanation** ``` _Ab "Copy the number and split it to its digits"; f{ } "For each digit, run this code block on the number"; _{%}1? "If the digit is 0, put 1, otherwise perform number modulus digit"; 1b "We now have an array of modulus corresponding to each digit. Sum it up"; ! "Negate the sum. If all digits were divisible, sum of modules will be" "0, thus answer should be 1 and vice versa"; ``` [Answer] # C89, 43 bytes ``` unsigned char d(int n, int c) { int a=n%10;return!n||a&&!(c%a)&&d(n/10,c); } ``` C89 doesn't have a boolean type. Hope that works. Also I used a second parameter to pass a copy of the original number through the stack, but the definition can be anything. To get the correct result you just have to call the function with the same value for both parameters (`d(128, 128)`). **EDIT:** Applied suggested edits by an anonymous user [Answer] # C11 - 44 Bytes in function body Another C version, non recursive and without a floating point exception. ``` bool digit_multiple(int i) { for(int n=i;i%10&&n%(i%10)<1;i/=10);return!i; } ``` This will also work in C++, Java, and most other C-like languages. Edited to include the improvement of primo's comment. [Answer] # C / C++, 58 bytes (44 in body) **Invokes Undefined Behaviour** (see comments) ``` int d(int i){int j=i;while(i&&!(j%(i%10)))i/=10;return!i;} ``` `true` and `false` **are** 1 and 0, but feel free to add one character to the signature to return a `bool`. And for fun, a recursive version which is smaller if you allow calls of the form `r(128,128)` **Edit**: Now disallowed by the rules: ## C / C++, 53 bytes (33 in body) ``` int r(int i,int j){return!i||!(j%(i%10))&&r(i/10,j);} ``` [Answer] # PHP: 45 Characters The character count is for the body of the function. It is necessary to only pass the first parameter. ``` function t($n, $k=true, $s='str_split'){foreach($s($n)as$b)$k=$k&&$n%$b===0;return$k;} ``` [Answer] ## R: ~~72~~ ~~67~~ 65 The function ``` f<-function(a)!(anyNA(a%%(d=as.double(strsplit(paste0(a),"")[[1]])))|sum(a%%d)) ``` Thanks to @AlexA and @plannapus for the savings Test run ``` i=c(128,12,120,122,13,32,22,42,212,213,162,204) for(a in i){print(f(a))} [1] TRUE [1] TRUE [1] FALSE [1] TRUE [1] FALSE [1] FALSE [1] TRUE [1] FALSE [1] TRUE [1] FALSE [1] TRUE [1] FALSE ``` [Answer] # GNU Awk: 53 characters The counted part: ``` for(;++i<=split($1,a,//);)r=r||!a[i]||v%a[i];return!r ``` The entire function: ``` function self_divisible(v, i, r) { for (; ++i <= split($1, a, //); ) r = r || ! a[i] || v % a[i] return ! r } ``` As Awk has no boolean values, returns 1 tor true and 0 for false. [Answer] # JavaScript (ES6) 30 Function with one numeric parameter. Using % and subtraction, no need to special case '0' because 0%0 is NaN in JavaScript. *Edit* Saved 1 char thx DocMax ``` F=n=>[for(d of t=n+'')t-=n%d]&&t==n ``` Just for fun, abusing the rule about not counting function signature, 4 ``` Check=(n,t=n+'',q=[for(d of t)n-=t%d])=>t==n ``` **Test** In FireFox/FireBug console ``` console.log([128, 12, 120, 122, 13, 32, 22, 42, 212, 213, 162, 204] .map(x=>+x + ' -> ' + F(x)).join('\n')) ``` *Output* ``` 128 -> true 12 -> true 120 -> false 122 -> true 13 -> false 32 -> false 22 -> true 42 -> false 212 -> true 213 -> false 162 -> true 204 -> false ``` [Answer] # PHP: 85 bytes (64 bytes on the body) For this function to work, simply pass a string or a number. `0` will correctly return false. The code: ``` function f($n,$i=0){for($n.='';$n[$i]&&$t=!($n%$n[$i++]););return$t&&$i==strlen($n);} ``` Please, DO NOT SET THE 2ND PARAMETER! # Javascript: 76 bytes (61 bytes on the body) This is a rewrite of the previous function. Not much changed between both versions. Here is the code: ``` function f(n){for(i=0,n+='';n[i]/1&&(t=!(n%n[i++])););return t&&i==n.length} ``` --- # Polyglot: Javascript+PHP 187 ~~217~~ bytes (~~76~~ 84 bytes without boilerplate): Why I made it? Because of reason and maybe because I can! ~~Just ignore the error on PHP: it works anyway!~~ No longer needed, this was fixed by removing 3 bytes. Here is the masterpiece: ``` if('\0'=="\0"){function strlen($s){return $s['length'];}} function toString(){return'';} function f($n){for($i=0,$n=$n.toString();$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);} ``` You can run this code both on your console and on a PHP interpreter! --- Old version: ``` if('\0'=="\0"){function strlen($s){return $s['length'];}} function s($s){return('\0'=="\0")?$s+'':str_replace('','',$s);} function f($n,$i){for($i=0,$n=s($n);$n[$i]/1&&($t=!($n%$n[$i++])););return $t&&$i==strlen($n);} ``` [Answer] # Octave, 33 (39 including function setup) Using numeric-to-matrix conversion: ``` f=@(a)sum(mod(a./(num2str(a)-48),1))==0 ``` Divide number elementwise by matrix X, where X is made by converting number to string and subtracting 48 to go from ASCII values to numbers again. Take modulo 1 to get decimal part of each division, confirm that all of these are zero (if any are NaN because of /0, the sum will be NaN and hence not zero). Sample input using www.octave-online.net: ``` f=@(a)sum(mod(a./(num2str(a)-48),1))==0 for j=[128,12,120,122,13,32,22,42,212,213,162,204] f(j) end ``` Output: ``` ans = 1 ans = 1 ans = 0 ans = 1 ans = 0 ans = 0 ans = 1 ans = 0 ans = 1 ans = 0 ans = 1 ans = 0 ``` [Answer] # MATLAB - 39 characters ``` function [b] = dividesSelf(i) b=all(~mod(i,sscanf(num2str(i),'%1d'))) end ``` ]
[Question] [ Steve Ballmer is the ex-CEO of Microsoft, and in a [recent article](https://mspoweruser.com/steve-ballmer-still-not-know-wrong-mobile/), claimed that he "still does not know what he did wrong with mobile". As [CodeProject](https://www.codeproject.com/)'s newsletter pointed out, "That article's title could be ended at so many spots and still be accurate". Given no input, output the following: ``` Steve Ballmer still does not know. Steve Ballmer still does not know what he did. Steve Ballmer still does not know what he did wrong. Steve Ballmer still does not know what he did wrong with mobile. ``` This must be outputted exactly as shown, and must be the only output of your program. You may include a single trailing newline. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so fewest bytes **in each language** wins [Answer] # [Python 3](https://docs.python.org/3/), ~~100~~ ~~99~~ ~~99~~ 97 bytes -1 byte thanks to ovs -1 byte thanks to Jonathan Allan -1 byte thanks to Dennis ``` for i in b'!-3?':print('Steve Ballmer still does not know what he did wrong with mobile'[:i]+'.') ``` [Try it online!](https://tio.run/##BcFBDoJADAXQq3xWlRjdsGND4hVcGheQqU5DacnQMPH043v7L7Lb0NrHCwRiWKi7DRONexGLCz2DT8ZjVt244AhRRXI@YB5YzStqngOZkSShFrcvqkTG5oso02uU95Xu1Lf2Bw "Python 3 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~50~~ ~~49~~ ~~45~~ 44 bytes 4 bytes saved with inspiration from [Kevin's Java answer](https://codegolf.stackexchange.com/a/123976/47066) ``` „€Ž†©'–Ñ…€À€½ƒ§“mer„â‚à€–ƒ€“”™¸ïß”[Žì'.«=¨ð« ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcO8R01rju591LDg0Er1Rw2TD0981LAMKHS4AUgc2nts0qHljxrm5KYWAVUeXvSoYdbhBUAJoMJjk8D0nEcNcx@1LDq04/D6w/OB7Oijew@vUdc7tNr20IrDGw6t/v8fAA "05AB1E – Try It Online") **Explanation** ``` „€Ž†© # push "with mobile" '–Ñ # push "wrong" …€À€½ƒ§ # push "what he did" “mer„â‚à€–ƒ€“ # push "mer still does not know" ”™¸ïß” # push "Steve Ball" [Ž # loop until stack is empty ì # prepend the top string to the 2nd top string '.« # append a dot = # print without popping ¨ # remove the dot ð« # append a space ``` [Answer] ## Haskell, 96 bytes ``` (++".\n")=<<scanl(++)"Steve Ballmer still does not know"[" what he did"," wrong"," with mobile"] ``` [Try it online!](https://tio.run/##HchBDsIgEEbhq/yZlU2NJygbr9ClukCZAOkwGBjt8bFx976XfN9YZIzoTvNMl7vS5Jalv7zKMSZajb@Mqxcp3NAtiyBU7tBq2LTudCPsyRsSI@RA54OtavxHtoRSn1mYHqP4rHB4f2y1hjh@ "Haskell – Try It Online") `scanl` is like `foldl` (or reduce as it is called in other languages) except it returns a list of all intermediate results instead of just the final one. Each intermediate result is appended with `".\n"` and all of them are concatenated into a single string. [Answer] ## [Retina](https://github.com/m-ender/retina), ~~82~~ 75 bytes *Thanks to Neil for saving 7 bytes.* Byte count assumes ISO 8859-1 encoding. ``` Steve Ballmer still does not know what he did wrong with mobile. w .¶$`$& ``` [Try it online!](https://tio.run/##BcHBDYAgDAXQO1P8g/HIEK7gAmJopLHQBBq7mQO4GL7XybilOcNu9BC2JFKpYxiLICsNNDXcTR1ekqEQMmd413bB2QqqniwUAzzE712OZZ3zBw "Retina – Try It Online") ### Explanation ``` Steve Ballmer still does not know what he did wrong with mobile. ``` Initialise the working string to the full headline. ``` w .¶$`$& ``` As pointed out by Neil, all three truncations are made before a word starting with `w`, and there are no other words starting with `w`. So we match a space followed by a `w` to find the truncation points. At these points, we insert the following: * `.¶`, a period and a linefeed to truncate the sentence and begin a new one. * `$``, the entire string in front of the match, so that the next sentence starts over from the beginning. * `$&`, the space and `w` again, so that they're also part of the next sentence. We don't need to match the `mobile` explicitly, because that will simply be what's left over on the third match. [Answer] # [///](https://esolangs.org/wiki////), 88 bytes *8 bytes saved by @MartinEnder!* ``` /1/Steve Ballmer still does not know//2/1 what he did//3/2 wrong/1. 2. 3. 3 with mobile. ``` [Try it online!](https://tio.run/##DcLRDcMgDAXA/0zxJuAJskFX6ARUWAXVwVJslfFpT@davYvvzcxnyFfwqKqX3PAYqmgmjmmBz7RFFmasXgNd0EYjTxas2@abOR0lHec/1oiOy15DJe39Aw "/// – Try It Online") [Answer] # PHP, 104 95 94 bytes ``` <?=$a="Steve Ballmer still does not know",$a=". $a what he did",$a.=" wrong",$a?> with mobile. ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 46 bytes ``` ”™¸ïßme”“r„â‚à€–ƒ€“«…€À€½ƒ§'–Ñ„€Ž†©).pvyðý'.«» ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcPcRy2LDu04vP7w/NxUEK9hTtGjhnmHFz1qmHV4waOmNY8aJh@bBKbnHFr9qGEZkHm4AUgc2nts0qHl6kDpwxOBGoAiR/c@alhwaKWmXkFZ5eENh/eq6x1afWj3//8A "05AB1E – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), 112 bytes ``` f(){printf("%.33s.\n%1$.45s.\n%1$s.\n%1$s with mobile.","Steve Ballmer still does not know what he did wrong");} ``` [Try it online!](https://tio.run/##Nc2xDsIgGEXhV7khNoFESUx16uYruLog0EKEnwaIDE2fHR10Ot929GnRuveZi23NnurM2SDHscgHDeeDvFx/@gfNV4eYnj5YyY7sXu3b4qZCiDajVB8CTLIFlCpelBqaUxXOwniDlhMtTEx7j8oTF9jwPU/Y@wc "C (gcc) – Try It Online") [Answer] # Java 8, ~~127~~ 126 bytes ``` ()->{String t="Steve Ballmer still does not know",d=".\n";return t+d+(t+=" what he did")+d+(t+=" wrong")+d+t+" with mobile.";} ``` -1 byte thanks to *@KonstantinCh*. [Try it here.](https://tio.run/##RY8xbsMwDEX3nOJDkww3uoDhDt2bJWObQbHYWIlMGRLtIAh8dldtDRQgh0/@4b2rne0@jsRXd1u7YHPGu/X83AGehdKX7QiHnwgcJXm@oNNVU/JStkwWK77DAYwWq672r8@tJ606Cs2ENxvCQKlUfQhwkTI4Cm4c7@rFtcp8smoSyZQYUrtaS90q3Hsr6AnOO1X9X1Pky2@WuiQvPYZ49oGMapa12RWicTqHQrSBzdE7DEVJ/2F9nGCrzeeRhQYTJzFjeUlgzabYbXrL@g0) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~52~~ 46 bytes ``` “ṬċḌ)⁹œḃṣ⁷Ṅḋ%W3Œƭ;ḷẓ“£Ṿ⁴'Þḣ~ẉ“¥Ị)“Ṡ8gÐ/»;\p”.Y ``` Credits for `ṬċḌ)⁹œḃṣ⁷Ṅḋ%W3Œƭ;ḷẓ` go to @EriktheOutgolfer, who used it in [his answer](https://codegolf.stackexchange.com/a/124000/12012). [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO9cc6X64o0fzUePOo5Mf7mh@uHPxo8btD3e2PNzRrRpufHTSsbXWD3dsf7hrMlD1ocUPd@571LhF/fC8hzsW1z3c1QkSXPpwd5cm2KwFFumHJ@gf2m0dU/CoYa5e5P//AA "Jelly – Try It Online") ### How it works The lion share of the work is done by Jelly's dictionary compression here. ``` ṬċḌ)⁹œḃṣ⁷Ṅḋ%W3Œƭ;ḷẓ ``` encodes ``` Steve| Ball|mer| still| do|es| no|t| know ``` there `|` indicates boundaries between words that where fetched from the dictionary and strings that were encoded character by character (`mer`, `es`, and `t`). Similarly, `£Ṿ⁴'Þḣ~ẉ` encodes `what| he| did` (surprisingly, `he` does *not* come from the dictionary), `¥Ị)` encodes `wrong`, and `Ṡ8gÐ/` encodes `with| mobile`. ``` “ṬċḌ)⁹œḃṣ⁷Ṅḋ%W3Œƭ;ḷẓ“£Ṿ⁴'Þḣ~ẉ“¥Ị)“Ṡ8gÐ/» ``` thus yields the string array ``` “Steve Ballmer still does not know“ what he did“ wrong“ with mobile” ``` `;\` cumulatively reduces by concatenation, building the phrases on each line. Finally, `p”.` computes the Cartesian product of these phrases and the dot character, and `Y` separates the resulting sentences by linefeeds. [Answer] # JavaScript (ES6), 102 bytes ``` _=>(s="Steve Ballmer still does not know")+`. ${s+=" what he did"}. ${s+=" wrong"}. ${s} with mobile.` ``` --- ## Try it ``` o.innerText=( _=>(s="Steve Ballmer still does not know")+`. ${s+=" what he did"}. ${s+=" wrong"}. ${s} with mobile.` )() ``` ``` <pre id=o> ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~95~~ 86 bytes ``` :` Steve Ballmer still does not know. :`.$ what he did. :`.$ wrong. .$ with mobile. ``` [Try it online!](https://tio.run/##PcgxDoAgDAXQnVP8wZkDMHoFLwCGRhoLTaCR42Pi4PbyOhm3tFaI7jB6CHsSqdQxjEWQlQaaGu6m07sQ/eYwSzIUQub8V9d2efeRraDqyUJ@rRc "Retina – Try It Online") Edit: Saved 9 bytes by switching from outputting parts of the whole string to building up the string in pieces. The `:`` is needed on the first three stages to make them output. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~124~~ 122 bytes ``` #define A"Steve Ballmer still does not know" #define B".\n"A" what he did" f(){puts(A B B" wrong"B" wrong with mobile.");} ``` [Try it online!](https://tio.run/##NYyxTsQwEER7f8XI1yQIIvogpOQXKIHC2HvxCmeN7M2lON23B4N0Uz3NPI1/Wrw/Tiw@bYHwUjVwHuLrcQp0ZiFMsG9KF8LsUlqpoCqnhJCpQrLiW/Juzd2eYYcPsZPFHp0iEgIHa85df/3ZtHZTM@Y2liyLvQN21og1f3Giwfbj7WBRrI6l@wNXFv8IH12Bz1IVD625vH/25mrQ0s7HfyikWxE8j@Zmjl8 "C (gcc) – Try It Online") [Answer] # C#, ~~158~~ ~~128~~ ~~120~~ 114 bytes ``` ()=>{var s="Steve Ballmer still does not know";return s+$@". {s+=" what he did"}. {s+=" wrong"}. with mobile.";}; ``` *Saved 30 bytes thanks to @KevinCruijssen.* *Saved 6 bytes thanks to @Shaggy.* --- Version using sub-stringing for 120 bytes: ``` s=n=>"Steve Ballmer still does not know what he did wrong with mobile".Substring(0,n)+".\n";()=>s(33)+s(45)+s(51)+s(63); ``` Version borrowed from @KevinCruijssen for 128 bytes: ``` ()=>{string t="Steve Ballmer still does not know",d=".\n";return t+d+(t+=" what he did")+d+(t+=" wrong")+d+t+" with mobile"+d;}; ``` Version using looping for 158 bytes: ``` ()=>{var r="";for(int i=0;++i<5;)r+=$"Steve Ballmer still does not know{(i>1?$" what he did{(i>2?$" wrong{(i>3?" with mobile":"")}":"")}":"")}.\n";return r;}; ``` Simple approach using ternary statements to in a loop to append the new parts onto the string each time. [Answer] # Bash, ~~111~~ ~~109~~ 107 bytes ``` a=(Steve Ballmer still does not know "what he did" wrong with\ mobile) for i in {6..9};{ echo ${a[@]::i}.;} ``` [Try it online!](https://tio.run/##BcGxCsIwEAbg3af4KR10ySjYIoiv4FgdruY0h2kOkmCGkGdPv2@l5Hqn6/GR@c@4k/cbR6Qs3sMqJwTN@AUtGIqjDMewYgeUqOGLItk9sekqnk@Hj0YIJKCejbm0uYLfTjFWWm6vaZJm5tb7Dg) [Answer] # Vim, 79 keystrokes ``` iSteve Ballmer still does not know.<CR><C-x><C-l><Backspace> what he did.<CR><C-x><C-l><Backspace> wrong.<CR><C-x><C-l><Left> with mobile ``` `<C-x><C-l>` auto-completes with the previous line. Alternatively you can replace every occurrence of `<CR><C-x><C-l>` with `<Esc>o<C-a>` [Answer] # [CJam](https://sourceforge.net/p/cjam), 79 bytes ``` 4{)"Steve Ballmer still does not know hat he did rong ith mobile"N/<" w"*'.+N}% ``` [Try it online!](https://tio.run/##S85KzP3/36RaUym4JLUsVcEpMScnN7VIobgkMydHISU/tVghL79EITsvv5wrI7FEISNVISUzhasoPy@dK7MkQyE3PykzJ1XJT99GSaFcSUtdT9uvVvX/fwA "CJam – Try It Online") [Answer] # Ruby, 94 bytes ``` "!-3Z".bytes{|i|puts"Steve Ballmer still does not know what he did wrong with mobile"[0,i]+?.} ``` Iterates through the 4 characters in the first string, converting each to its ascii value `n` and outputting the first `n` characters of the second string each time. It really does not matter what the last character of the first string is, so long as its ascii value is equal or greater than the length of the second string. [Answer] # Fission, ~~299~~ ~~291~~ 269 bytes ``` MN"." ] ] ] W$] W$$] W$$$] R"Steve Ballmer still does not know"%[" what he did"%[" wrong"%[" with mobile."; [W [W [W ``` [Try it online!](https://tio.run/##jc6hDsJAEIRh36eYbIqtwOLwIECcaCpKbuE2bG@T3qV9/KOiQZAAHfXnU3OXlMTivpTTmRrCv3U/pauwYW3tPuEtS9auutA188Q49qoDj0hZVOGNE6JlPKPNtENLmEOfERhe/AqjxceakgMGu4lyQ4dtz@C@wpKlvAA "Fission 2 – Try It Online") Finally a 2D language I understand! ### Explanation Program spawns an atom with 1 mass and 0 energy (a `1:0` atom)at the `R` on line 3, and begins moving to the right. `"Steve Ballmer still does not know"` prints each character. `%` moves the atom up if it has 0 energy, or decrements it's energy and moves it down. `]` moves the atom to the left, `$` increments the atom's energy, `W` moves the atom up. Once the atom is on the top row, it moves to the left, until it reaches `"."`, which prints a period, `N`, which prints a newline, and finally `M`, which moves the atom down to the `R` again, which subsequently moves the atom to the right. Each loop the atom's energy is one higher, meaning it will pass through one more `%`. After the 4th loop it reaches the `;` at the end of the third line, which destroys the atom. The program terminates once all atoms are destroyed. [Answer] # [Nim](https://nim-lang.org/), 100 bytes ``` for i in " ,2>":echo "Steve Ballmer still does not know what he did wrong with mobile"[0..i.int],"." ``` here the same in more readable code: ``` const str = "Steve Ballmer still does not know what he did wrong with mobile" for i in [32, 44, 50, 62]: echo(str[0..i], ".") ``` The language has string slicing and inclusive upper bounds. The rest should explain itself if you know programming. [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~70~~ ~~68~~ ~~65~~ ~~61~~ ~~60~~ 59 bytes Contains a few characters that won't display here; follow the link below to see the full code. ``` `Sve Ba¥´r Ð]l º not know Ø ¹d Ùg ØP ¶ßè`£'.iP±X}R ``` [Try it online](https://ethproductions.github.io/japt/?v=1.4.5&code=YFOSdmUgQmGltHIg0F1sILqDIG5vdCBrbm93CiDYiSCUILlkCiDZkWcKINhQILbf6GCjJy5pULFYfVI=&input=) * ~~3~~ 4 bytes saved thanks to [ETH](https://codegolf.stackexchange.com/users/42545/ethproductions), plus another 4 with some prompting. --- ## Explanation Everything between the 2 backticks is a compressed string of the following: ``` Steve Ballmer still does not know what he did wrong with mobile ``` ``` `...` :Decompress the string. £ }R :Map over the each line X in the string P±X : Append X to P (initially the empty string) '.i : Prepend that to the string "." ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 49 bytes ``` “ṬċḌ)⁹œḃṣ⁷Ṅḋ%W3Œƭ;ḷẓ“¡=~Ṃ©N|ȯ“¡ṭṂ“CṬṀWỌ»ḣJK;¥€”.Y ``` [Try it online!](https://tio.run/##y0rNyan8//9Rw5yHO9cc6X64o0fzUePOo5Mf7mh@uHPxo8btD3e2PNzRrRpufHTSsbXWD3dsf7hrMlD1oYW2dQ93Nh1a6VdzYj2Y/3DnWqAAkOkMNOnhzobwh7t7Du1@uGOxl7f1oaWPmtY8apirF/n/PwA "Jelly – Try It Online") [Answer] # PHP, 116 Bytes ``` for(;$i<4;)echo"Steve Ballmer still does not know",["",$t=" what he did",$t.=" wrong","$t with mobile"][+$i++],". ``` "; [Try it online!](https://tio.run/##FcixDsIgEADQ3a@4XBg0kE5u1Jj4C45NhyqnXKQcoRf5fLTLG16JpY/X8vcl9egNj2d/omcUvCt9CW5LSitV2JRTgiC0QRaFT5aGbkJ0Ri8ILS4KkSBw2GfYq0p@o0Oj0FgjrPLgRDhP1rC1s8PhgL73Hw "PHP – Try It Online") [Answer] # [SOGL](https://github.com/dzaima/SOGL/tree/8971b53470a627e82dc99741b7acbabf89ea7b28/P5Parser), 42 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) ``` ⁹⁴<>‘υG‘Γω/w¹‘O‛Æw▓½0H(æ█◄K∆2Ξgh‘4{Tļ.@+;+ ``` Explanation: ``` ..‘ push "with mobile" ..‘ push "wrong" ..‘ push "what he did" ..‘ push "Steve Ballmer still does not know" 4{ 4 times do T output, not popping the top of stack ļ. output "." @+ append a space to the top thing in stack ;+ reverse add (adding the next part to the top thing in stack) ``` [Answer] # Sed, 96 ``` s/^/Steve Ballmer still does not know./p s/\./ what he did./p s/\./ wrong./p s/\./ with mobile./ ``` [Try it online](https://tio.run/##TcjBDYAgDAXQu1P8CegOruDVmGBohFiooY2Mj1eP7xmnOY0O2pxfxhpFKneYFxEkZUNTx910BHoWoz0QRo6OzEgl/bJru34snlH1LMKB5vwA). Implicit newline input given, as per [this meta-question](https://codegolf.meta.stackexchange.com/questions/5476/are-languages-like-sed-exempt-from-no-input-rules). [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~92~~ 91 bytes ``` printf 'Steve Ballmer still does not %s. ' know{,' what he did'{,\ wrong{,\ with\ mobile}}} ``` [Try it online!](https://tio.run/##HcYxDsMgDAXQvaf4S8US5RC9QtcsIJxgxeAIrDBEnJ1KfdMLvqU5r8rFdriv0U34eJFMFc1YBFGpoajh3daXw1m0P4tDT96QCJGje5YNvWo5/mFLG7IGFhpjzPkD "Bash – Try It Online") [Answer] # [Go](https://golang.org/), ~~140~~ 127 bytes ``` import."fmt" func f(){for _,i:=range"!-3?"{Println("Steve Ballmer still does not know what he did wrong with mobile"[:i]+".")}} ``` [Try it online!](https://tio.run/##Hc5NDoIwEEDhPacYZwVR2bgjMSaewMSlMaZCWya0M6SMdkE4O/68C3zPyzqadjDeQjTEK8VRktboomLhXtyCK6vZSYLHjppjMuwtbvaHE86XRKyBS7yqfVs4mxCiTTAphQCd2AlYFAaWDLk3Cr2FjjrISdhDJu0hypOCxVtD9y3WWC3L@id/J2UFcwHfvn6xrB8 "Go – Try It Online") [Answer] JavaScript (ES6, no browser dependencies) 154 Bytes ``` (s='Steve Ballmer still does not know what he did wrong with mobile.')=>{ let l=s.slice.bind(s) return `${l(0,33).\n${l(0,45)}.\n${l(0,51)}.\n${s}` } ``` The other ES6 solution requires (and doesn't account for) the use of html and html element APIs. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 81 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") ``` ↑1⌽¨,\'.Steve Ballmer still does not know' ' what he did' ' wrong' ' with mobile' ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97f@jtomGj3r2HlqhE6OuF1ySWpaq4JSYk5ObWqRQXJKZk6OQkp9arJCXX6KQnZdfrq6grlCekViikJGqkJKZAuYW5eelgxmZJRkKuflJmTmp6iCz/6cBAA "APL (Dyalog Unicode) – Try It Online") One the very right, we have a list of strings. `,\` cumulative concatenation `1⌽¨` cyclically rotate each one step left (puts the periods at the ends) `↑` mix the list of strings into a character matrix [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~113~~ 112 bytes -1 bytes thanks to ceilingcat. ``` f(c){for(c=0;write(1,"Steve Ballmer still does not know what he did wrong with mobile","!-3?"[c++]);puts("."));} ``` [Try it online!](https://tio.run/##BcFLDsIgEADQtZxiZAVpazQuiTHxCi6NC4ShJfIxMMqi6dnxPTPNxvTuhJGry0WYy1G14gnFaeR3wh/CTYcQsUAlHwLYjBVSJnin3KAtmmBBsN5CKznN0DwtEPPLB@Qj30/nK3@YYXhK9flSFfzApVRbj9onIdnKdk5Ixbb@Bw "C (gcc) – Try It Online") ]
[Question] [ # Background The Royal Netherlands Meteorological Institute [defines a heat wave](https://www.knmi.nl/kennis-en-datacentrum/uitleg/hittegolf)\* as a series of **at least** 5 **consecutive** days of ≥25°C weather (“summery weather”), such that **at least** 3 of those days are ≥30°C (“tropical weather”). The tropical weather doesn't have to be measured consecutively: for example: `30, 25, 30, 26, 27, 28, 32, 30` is a 8-day long heat wave with 4 days of tropical weather. \*(Well, by Dutch standards.) # Challenge Given a non-empty list of positive integers representing Celsius temperature measurements from successive days, decide whether that list contains a heat wave (as per the above definition). The shortest answer in bytes wins. # Test cases Falsey: ``` [30] [25, 30, 25, 60, 25] [29, 29, 29, 47, 30] [31, 29, 29, 28, 24, 23, 29, 29, 26, 27, 33, 20, 26, 26, 20, 30] [23, 31, 29, 26, 30, 24, 29, 29, 25, 27, 24, 28, 22, 20, 34, 22, 32, 24, 33] [23, 24, 25, 20, 24, 34, 28, 32, 22, 20, 24] [24, 28, 21, 34, 34, 25, 24, 33, 23, 20, 32, 26, 29, 29, 25, 20, 30, 24, 23, 21, 27] [26, 34, 21, 32, 32, 30, 32, 21, 34, 21, 34, 31, 23, 27, 26, 32] [29, 24, 22, 27, 22, 25, 29, 26, 24, 24, 20, 25, 20, 20, 24, 20] [23, 33, 22, 32, 30] [28, 21, 22, 33, 22, 26, 30, 28, 26, 23, 31, 22, 31, 25, 27, 27, 25, 28] [27, 23, 42, 23, 22, 28] [25, 20, 30, 29, 32, 25, 22, 21, 31, 22, 23, 25, 22, 31, 23, 25, 33, 23] ``` Truthy: ``` [30, 29, 30, 29, 41] [1, 1, 25, 30, 25, 30, 25, 25, 25, 25, 25, 25, 25, 25, 40, 1, 1] [31, 34, 34, 20, 34, 28, 28, 23, 27, 31, 33, 34, 29, 24, 33, 32, 21, 34, 30, 21, 29, 22, 31, 23, 26, 32, 29, 32, 24, 27] [26, 29, 22, 22, 31, 31, 27, 28, 32, 23, 33, 25, 31, 33, 34, 30, 23, 26, 21, 28, 32, 22, 30, 34, 26, 33, 20, 27, 33] [20, 31, 20, 29, 29, 33, 34, 33, 20] [25, 26, 34, 34, 41, 28, 32, 30, 34, 23, 26, 33, 30, 22, 30, 33, 24, 20, 27, 23, 30, 23, 34, 20, 23, 20, 33, 20, 28] [34, 23, 31, 34, 34, 30, 29, 31, 29, 21, 25, 31, 30, 29, 29, 28, 21, 29, 33, 25, 24, 30] [22, 31, 23, 23, 26, 21, 22, 20, 20, 28, 24, 28, 25, 31, 31, 26, 33, 31, 27, 29, 30, 30] [26, 29, 25, 30, 32, 28, 26, 26, 33, 20, 21, 32, 28, 28, 20, 34, 34] [34, 33, 29, 26, 34, 32, 27, 26, 22] [30, 31, 23, 21, 30, 27, 32, 30, 34, 29, 21, 31, 31, 31, 32, 27, 30, 26, 21, 34, 29, 33, 24, 24, 32, 27, 32] [25, 33, 33, 25, 24, 27, 34, 31, 29, 31, 27, 23] ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~88~~ ~~75~~ 73 bytes * Saved two bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). ``` h,e,a;t(int*_){for(h=e=a=0;*_;h+=e>4&a>2)e=*_<25?a=0:++e,a+=*_++>29;e=h;} ``` [Try it online!](https://tio.run/##zVdRj9owDH4ev6J30qaWMilN2lLWlXvbL9jb3YQQK@OkjU2se5gQv52lqZ34SI8WWmAnRVcS2/ns2F@cxftvi8V@vxrlo3lauM/rYjjztsufG3eV5dk8Y@lwlq78LJ@G7@ZT7uXZcPaRRw9y5YPvSyVfTvj@lE/SPFulu/2P@fPa9baDXxtpa@neZ1nmfJp//53/deTn0/reSwdvcLFwt4KNHObc4G/nSUDO269O9uAsJa6Rc3dXuGUEHr94FayddwCWT0YOjlLiauCPg62FZYEXgZHiiRyhHILMxXKMpXY5x@B3XH13crQh0l1h2ackJbXVuJJSVtFiVFlUc@WOHKyF1bfg1Vq5I@vxlPqEVeu00owgTCFoJqDJzTy7YmqeAst2CkMRVFoCLUEYOOSEshQfhJKREIvKRhle1oNTl4BlOx@D5aCypAZaDchaCHklIH/iSuZC9doZVj2rQpIrSQ6hwuoPYTCSR8zMsQuyahdY9cQkTDX/L9dHHSwbPCS8kgJpTWMJhAQpjsN/pLQxfCdnONwAvi9YtsNj0OSQxPxMB3p2@DVYtgOUbiagEYFGYEKirEQkPPAbqazvE@sLlnIY/X1al53m582fYnWk08QOCf9fvfqK2k7TglXbvOmrhpk7VA1gWCUjYG1iriPKzGoXbEJoYIGd9YGE@lo6Cv52sGpuS9RGCwLuVt1sINFFL1Gp3WE3hYI0JwK9ikkLOibN4fEA3QSWHRwGuzLyUMBdRMdb9PzUbwWrntZik3eChEaHRZjQqDDimiB3NhIphBlzWHdvGNak3UnfApbNE6G57jQSZBYssIDkGjt4fQXmGHRL2yY7GnjiUrDs7KDsQYuHkw4tIa@siBQlHg0W6CnP/IbsuBSs14kwIn15Yt7NOn8CspYY@hbnPhBbEmEXWLXpLgR5U4egDQ8Ozm9CbK1g2c4wkiNYBOMDBpmYJkkPsCyYySuU1cxCEFiPw@YG5WqwatleiJeVr6RDwxy6MESPp93M9ifBUo7tBvt/ "C (gcc) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` :5_5Ṡ‘ẆP«LƊ€>4Ṁ ``` A monadic link accepting a list of numbers which returns `1` if a heatwave was detected else `0`. **[Try it online!](https://tio.run/##y0rNyan8/9/KNN704c4FjxpmPNzVFnBotc@xrkdNa@xMHu5s@P//f7SxoY6CkSUUWwCxCRAbI4mZAbG5joIxSMwAyjeDsI0NYgE "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##fVQ7TgNBDO05xR4gSLPjmf1Q5AQUtCiKqGiiXIAuogCJkioFSPRwgSAqULjH5iLLrOd57KRAijWbsf38e57V7Xp9N44X8SYOu7fDZjt8Plx9v1/@Ph3uP@Zh2G3G/dfPY/qzfx5223Sm32o6Ni/V@bw6bF6vx3GxILecnVUL388qEXKT8DXVeu27JCEJmbsmSZvMpzuH/03@FuSkKjBNRmcYgYgZgu@mEB7uIX@TzzqiAsemEREDTDuYernP5oJaZzMS14CkkTi7NidZOZMtZQzfZtgGUHV2ZRGY2ugCiicUOfl57ThqZJVHVGlrgDhTrGRjWkvaJuk46uVrqEvnO6DLVDxOmUKL7y5DtTD1qMGrynaoh0mESa3o7BZNJPzP3c8sc0q8fPJ1MkZm5I7P/2SymTwLf8vYnTKFBTNhG4KuV2rYWXJgIbEtpIFdr0Q1FBFzcWG31pBVBhiP0@BwgOewhtwkZTRm7VrdD4cwziy0wJJSJwIhGJJ2hsjBFEjISHRkmCkEQcbS6LJXkmEmjcDauZSpS39r0xB38v7UWlFZY1Rkx2J7583udOadiWYmUqXM5/gVLKOMZss7fe1KkbXRdco4CqV4IvMSBpjjYfC@bEMpRHrQnoym1yUrAihyWrzYlpGZkPIOYRdtS1kddCSlL7Rc/gE "Jelly – Try It Online"). ### How? The criteria is the existence of a run of more than four values greater than or equal to 25, of which more than two must be greater than or equal to 30. If we divide through by five the criteria becomes the existence of a run of more than four values greater than or equal to five, of which more than two must be greater than or equal to six. If we subtract five from these values the criteria becomes the existence of a run of more than four values greater than or equal to zero, of which more than two must be greater than or equal to one. If we take the sign of these values (getting -1, 0, or 1) the criteria becomes the existence of a run of more than four values not equal to -1, of which more than two must be equal to one. If we add one to these values (getting 0, 1, or 2) the criteria becomes the existence of a run of more than four values not equal to zero, of which more than two must be equal to two. The product of a list containing any zeros is zero and the product of a list containing more than two twos (and the rest being ones) is more than four. This means that the criteria on this adjusted list becomes that the minimum of the product and the length is greater than 4. ``` :5_5Ṡ‘ẆP«LƊ€>4Ṁ - Link: list of numbers :5 - integer divide by five (vectorises) _5 - subtract five (vectorises) Ṡ - sign {negatives:-1, zero:0, positives:1} (vectorises) ‘ - increment (vectorises) Ẇ - all sublists Ɗ€ - last three links as a monad for €ach: P - product L - length « - minimum >4 - greater than four? (vectorises) -- 1 if so, else 0 Ṁ - maximum -- 1 if any are 1, else 0 ``` [Answer] # [C (clang)](http://clang.llvm.org/), 64 bytes ``` h;o(*t){for(h=1;*t;++t)h=h&&*t<25?1:h*(*t<30?2:6)%864;return!h;} ``` The function o() returns 1 for a heatwave or 0 else. Thanks to the magic number 864 and to [Udo Borkowski](https://codegolf.stackexchange.com/users/81057) and Mathis for their ideas. How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number >= 25 is seen the reduce is multiplied by 2. If a number >= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0 and in a return value of true. [Try it online!](https://tio.run/##xVdNj9owEL3zK9KtdpWwtHI8SQgb6N76C3rr9oCAbZBoqNhwqBC/nQZnxp5lcfhIACSLxLGf34zHb8ajL6PZMPu9@TzNRrPleOL03/LxdP41/bZJk7nbzr3V63zhpgM/aefJ42PupYP04aGd92X47D@l7WJIH8SzfIq8@zgKksUkXy6yT2my3kyz3PkznGaut2r9XRRvr@7dYDBwvg9nb5N/TvH4kt15ScvBH42ZuysQHUc4N/itvYKXcz8umHWcuesWjH7@8ko@a28/WdnrONS2A69G3kJ2Lx8befDNYBkXLSgasL6oaN0CZNsn8D0qn2sZavN0XT7WXSomaPCoHKzACTgsgVXfdmGJoEH5DLL8tl1YNLFLTfKpMloBhOitAAFiBJCmX1wjNE/hYzWKPOKXk4EA0RsSQ0MBRjseFczTUGJsvSzqGHUJPlbjI1zALwFVI3CffQswvADDKCrHNH1ea/OpVFWMdTVBosdIBAJsgoWTMH3iEqpah0@lMIE51DdPH/v4WMlj3KvBOEmrWYyeIaWT@E/K1sXn@AyDbeSb4mM1uIsAEmNZnmlAUwbb@FgN4KrTw4khTvSNZxRYyLyE76Roje1YU3yUwWToS7atNH8slnl6uNKkQon@xY0rzQ98qoo3nXGESaWqodCqMYDfeiYrcYFWi1Etwv2LIq33JdDZyVq83YiPPVsSCAEBplhdc5Dehe/JKRK4qCLDahQg4yJWiXZZcViRLa/Ox@ocgYsLdl@gxaBmFj1HCY7hUylrkQk/YB7S3gHjIeVN@gYsdZOeorcplHURR96ND@z0LfhYdSIwWU8TIoGhc@azkBM7lzDf7IaubI@JDptOXIqPNTq4iPAzJFmhFrPLVsjOJu0QndNTrvm26LgUn4NCGLLyPDbXZx1GPvsWGxWHcy@Ih4SwDp@qcAdgV@sAQfDeIeV1he0oPlZjBAsVOgvdHSHpmVpJN1wAhAkvGqsFhhH5cDmsKFCuxqdK7QHeC4CaFBgB0ecDGtztCrU/iY8ybN3a/Ac "C (clang) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~73~~ ~~72~~ ~~71~~ ~~69~~ ~~67~~ 66 bytes ``` any(\a->sum[1|x<-a,x>29,take 4a<a]>2).scanl(\a t->[0|t>24]>>t:a)[] ``` Thanks to @flawr and @Laikoni for two bytes each and @xnor for a byte! [Try it online!](https://tio.run/##fVXNbtswDL7nKXTYoQWSQhblv6H1i7g@CFmzFnWyoHaBFuiz15MpUmQyYAciifjx4z/zHKbXp3FcDmGcPs2D2Zi@BztszLZ37dawgF0Fn6GQZ9dE8VFAvVVR6ghf3yz9rtJ3Zo6qTFMldqRhijJR4NvqwpG5T9/BJR1ApkNoSR49QRuCOn5PcGYtEgzY1FPQFDiaVldRWRUtJA5XJ9qKqIpkisI0hdJ5Sh4oydXOScUpR1Q58spl9SRWJcvR2IEKC1Ikrjdli8@kznVviJt74uiTe1DT9yZR1QR1lIETla5PS5CSIIWwo1mpPNHvVPtINWw289v7/CzzKEOYPtFfNKU4wV5@/k9WzGqZZzmPgJWpQaH@IAZI18qY6L6iYx5onVZFuFaGVo0Lw9kEzWo1uNzO8jIMdEf06FYNOnAalVrBWnbFkhurlptpES69rKQ4oLxkDyBeMCLWgZpSHheKmAudd4wjTCPEtLovuetc30IVxF7dokIyyitNGem26No5tUeNujml6glnyf25vIi5laXa@EYuX06yULpGJg58Th5AXUVPcDoSLh0JsCoRrkF91ZpWVi4LUYGV5BmbW6Zc8k2izdQlRbWXluS60PYeHh6XcPq8eQy7bno/9sXXx/0ubD@6CJ7D65Px4T4Mnbu9m/bhNEacmXddb7/mLt7orpt/htt@WI7h5RRPwK8/G2POby@n2fwwx3A2B4P/Vv@8pqOxfO8PY/g9Lbv9@fwX "Haskell – Try It Online") Equal length: ``` any(\a->take 4a<a&&sum a>2).scanl(\a t->[0|t>24]>>sum[1|t>29]:a)[] ``` [Try it online!](https://tio.run/##fVVLb9swDL77V@gwFCvQDLIov4rWf8T1QciatqiTBbV7KLDfPk@mSJHJgB0I23x8fNOvYX5/nqb1EKb5yzyawgwD2LEwd4Pr7gwT2I2QDaWwXRvJRwLFqyM1UX3jWfqu0zsjR1GGqRM6wjBElSCQt7lwZO7TO7gkA8hwqFqRR0@qLak65id1Ri2TGrCpp6ApcDStr6KyKlpIGK5JsDVBlckUiWFKJfOUPFCSm52TilOOKHLklcvqiaxKlqOxIxUWpEhcb8oW2STOdW8Jm3vi6Mk9aOi9TVANqTrKwIlI16cjlYpUSkFHs0p5ou9U@wg1FsXy8bm8yjzKEKYn@oumFCfYy@f/aNPZLPMs5xGwMjVI1B/UAZJ1Mia6r@iYB1qnVZNeJ0OrxoXV2QTNGjW43M7qMgx0R/DoVg06cBq1WsFGdsWSG6uWm2FRXXpZS3FAeckeQLxgRCwDNaU8LhQxFzrvGEeYRohhdV9y17m@pSqIvbpFpWSUV5oy0m3RtXNqj1p1cyrVE86S@3N5EXMrK7XxrVy@nGSpZK1MHPicPIC6ip7U6Ui4dCTAqkS4Bs1VazpZuUwEBVaSZ93cMuWSbxJtpi4pir20JNeFtvfw@LSG09f3p7Drl/D@bHx4CDc38@fRhN7d/pj34TRFqVl2/WB/L328zH0fxUO5fXTjfbgdxvUY3k7xBPz8VRhz/ng7LeabOYazORj8W/3DTUdj/bM/TOFlXnf78/kv "Haskell – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 79 bytes ``` lambda T:any(len(s)>4<sum(s+s)for s in bytes(t>29or(t<25)*9for t in T).split()) ``` [Try it online!](https://tio.run/##fVVNb9swDD3Xv0JHaSsGWZT8EXT9Fb1lPaRYgwVInSD2gObXZ5b0KLE57EDYFsnHr0f5fF3@nCa67dVP9et23H28/d6pl81uuurj@6Rn8@yf5r8fev4@m/3pomZ1mNTbdXmf9fLsxtNFL08umG9jVC5R@WJ@zOfjYdHG3MqhbtR2S/b1sVFq68ZHxUI2Sj6ntp67YRW/ComzbpV@tY9nFt9dfi/Yq67gdBk/4TBGyBjpLMZw8Pf5nVzWEVW8ZBsQ08N2gK3jc9gzbpvtiH098kbuybe7y8uKfCljuB64HbDa7JuEcVqh86ifUGf0c6LvqDPpHOJybz3Eino5H9lfqr0qfUfN6Rz60v8B@DwbhyfPosf7AKwetg51OKGTfRphE2DTVvzkF0QsfOcZvEawSMhKwvzMQVZ7pEf26/N/Em2iZyVzIYCtpEmC4SQbgm6sJJFDTZGZ0LKYDnZjJa0kC9uzT/LrBXF5kOFrHike8FNcQXTiOjqxhL1YFos4Viw445IgUQCGF4QdBKm9qJGQE@tIkJSJgpy512XJOEeQh3HlbMrsucet6Im9u5DaWlNZaq5Jzkb2z4lFGsTFE8RcuE6e0d3FWOYZxNIP9QIsdbZCN1Teka/1E4nL0cMeF4XDRUFW1MJ96O/mM9aFKwIssrV@ti1zEzHLxYTFlH1Nel/nUnqzLm9jNs1D/Ld8xn/LslHny2Fa9F5/GtM85A9z@wc "Python 3 – Try It Online") [Answer] # [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21~~ 20 bytes ``` 1∊8≤4↓⍉×\25 30⍸↑,⍨\⎕ ``` [Try it online!](https://tio.run/##bVNLalxBDNy/U/QBMtAt9fvdxZvBYYJhwAavfIGJHRiTEEIukEWOkL1v0hcZt6qk51kEmkc/fapLJWn/cNx9ftof77/sbo/7x8e720t7/XV3307fy9Cevx4upT1/W9rLn9pOP9v55e33jYxJczv/a6cfn9r5701PuPTQy2HQPBwGWRNPnRMMWtwgS5KaRON3StJD@m/GfbILITR50tQNSGLGaBn225EE4dUuKmZUZar5R4BW@Bf4hRYLYX4xpzK2ggaYWOx09V4OBmopMhvAhLxisXaYVMJYQV5BtUeKawKmZhPgsv6Kk4MwXwoJ1GujJqBsBphdmQUolEvwpUQzLovlzeavAkbitq2uFdRHeIqjWOAYcLhDnGFnvWQOvrV0Q0l4U/PH97@n5h5YOA2ue/bu2IFa5lIYV2/JpqshcyI2WhO8qzc/GsMQRlngHP2nnuPHIwYJGAOOGVGSmmIsZ5@qDLDsc@EA6q0aEyeinxpYDqSOZY/RqNFx9IUkqIbPHx@2NhFgE8y1pwwlaslXy1WcnI80yG16bbVKjNoSqzSGWuRK2dBmYky@DD7pi6@rUy1hXLynWkleNXa4IgT7IMIxclasYL6SbPVJ9IM8zU6eAS5ioHLFMKZb8WauLpYXpO8 "APL (Dyalog Classic) – Try It Online") uses `⎕io←1` `25 30⍸x` is 0 if x<25, 1 if 25≤x<30, or 2 otherwise we compute cumulative products of these starting from (or equivalently: ending at) all possible locations, discard the first 4 products, and detect the presence of products ≥8 (which is 23) [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~19~~ 18 bytes ``` ô<25 d_ʨ5©3§Zè¨30 ô // Partition the input at every item <25 // where the value is less than 25. d_ // Then, return whether any resulting subarray ʨ5 // is at least five items long © // and 3§ // has at least three items Zè¨30 // with a value of at least 30. ``` I hope I got all the discussions in the comments correctly. Shaved off one byte thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy). [Try it online!](https://tio.run/##y0osKPn///AWGyNThZT4w12HVpgeWml8aHnU4RWHVhgb/P8fbWSqo2BsDMEgtpEJEJsD@UDa2BDItoTSQDEj41gA) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 121 bytes ``` param($a)$b="";($a|%{if($_-ge25){$b+="$_ "}else{$b;$b=""}})+$b|?{(-split$_).count-ge5-and(-split$_|?{$_-ge30}).count-ge3} ``` [Try it online!](https://tio.run/##RYzfCsIgGMVfReQL/NgMme0ixqg3ES2rgW0yF104n91kUF2dP/zO8dPbzuFhncvZ61k/GWgE01PaFbfu4nBjoPjdNi1GMFVPQRGarAu2xG4jU8IKzHqKjAfvhgUU7i/Ta1zKrOV6vP76wmxnUqQ/IlPO@cykqElzrMlXDwI/ "PowerShell – Try It Online") or [Verify all test cases](https://tio.run/##fVTbbtswDH3vV7iGh9pIM8ii5AuKbv2PYQiczukyZE6QpNhD6m/3ZIqUmDz0gbAsHh7eddj/64@n3/1uN23eh9fzdj8km8t06I7d3zzrimz9nKZP7vTx5bLd5Nlq@dZrW1yy9eI5zVZJOva7U@9@nxA5jsUiW398v@TL02G3PWer4uvr/n04OzO77IZf4d5hkAzUGCEwTuNd1h3fTj/UT@dx9vdnvx0ekodikSbLb0m6uL/PN4njHafpJQdVPN695Lp9TFhAzYLXUMZr3TgxTkDcVU5qB5/vFP1X/szMThVoKs@ONExhPQXezS40mRt/Bu11AIEOoZY8GoI2BNV87@HMWnoYsKmhoClwNK1uolIiWvAcuva0FVGV3hSFaUqhM5Q8UJKznY4VpxxRpckrl9WQKJEsRyNKC7FMXHHKF69JHSrfEDt3RdOXu1DTufFUNUE15aCjSlaoJYglSBnZ0cwKT/Tvq49UftRUnD7/xWtnQeGBuv5@JjNmtgxDHHqv4rigUGMQA6Rr43zIhqJjnmSZTUW4Nk6rmBOGswma1WJiuYv2Ogx0R/ToVkw4cBqV2L06LokiN0psNdNCnB9LDEZMaiOm2YgEgSJiHYjx5CmhiLnQYbk4Qj85TCv7ErrO9S1FQdTNI1TGjMIuU0ayLbJ2WixQIx4bK3rCWXJ/rp/C0EorVr2JT15IshS6Jk4cmJA8gHgODcHpddA6bENIhGtQ37SmjZsWhKhAxeQZG1omXPJjRAspS4pqE1sS6gLFfw "PowerShell – Try It Online") PowerShell doesn't have the equivalent of a `.some` or `.every` or the like, so this is rolled by hand. We take input `$a` as an array of integers. Set helper variable `$b` to the empty string. Then, loop through every integer in `$a`. Inside the loop, if the integer is `-g`reaterthanor`e`qual to `25`, add it to our potential string `$b`, otherwise put `$b` on the pipeline and set it to the empty string. Once outside the loop, array-concatenate the pipeline results with `$b`, and put those through a `Where-Object` clause `|?{...}`. This pulls out those strings that have an element length of `-ge5` (based on splitting on whitespace) and a count of temps greater than `30` being `-ge3`. Those strings are left on the pipeline, so a truthy value is non-empty (see the "verify all test cases" link for truthy/falsey distinction). [Answer] # JavaScript (ES6), ~~63~~ 51 bytes Returns a boolean. ``` a=>a.some(n=>(n>24?y+=++x&&n>29:x=y=0)>2&x>4,x=y=0) ``` [Try it online!](https://tio.run/##fVTbTsMwDH3nK3gamwZTGqc3UMsbX8Ab4qGCjYvGijZA29ePNjlOzJTwYLVJ7OPLsf3e/XS7p@3b59fVpn9eHlfNsWvabrHrP5bTTdNON602t4d5M5/vJ5PhUF/vm0OjZq2e7Ftz6Q7Hp36z69fLxbp/mV483HXr3eHxYnZzJu9X0wdSj7PZ6aWuL89ZSI0SUaIsKOlqEDMIibtikHIwHu8UzoX7j3sdFD1o4TxbUAbMHaC9Gx1qgBn3T9q9ESXArWGOaAwMKxhqvo8Zs8fMGREDGaSHFC1QcRKxEpmQw9BlzEkB4MwBWWHQTLwZlIlQjtFOp1hEbayiRkRMjoEoURaONEkQhWLHWUSdrBKUPZsVPDPTGl9mtsR/FQMuYaiRu04pyqrXMMhhkAXPFiQXUeDsGB2Bz/4O0f32@@s1MUVhWNw3MTC@e1RoPysg0@oQ3urQYbIJrBOeExl7Ab06zEKy09iYASxIKeaBuc7/BmWdw5kNQswPcVKFmPoyNZAKTpXYNeyEUh2YA92IOajErBhRCkK0/Eai3bmXkA1T4geZo4/1FzuRfHrimZdMlE6dLMosZOu3SDRbSa6suRbDWomFmAsuuQLM63@r3DdELlZOFVa2L0cm3qrQxWQSZSIS69zAGDtLx3YWKZEy1648IbgOc@wFwKRCmVjXEy8CiC9MDL8kxiqbQKyv59jTx18 "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 16 bytes ``` :5_5Ṡṣ-ḤS«LƊ€Ṁ>4 ``` [Try it online!](https://tio.run/##fVQ7TgMxEO1zihwgSLbH3g8FLQ0d5SqiokG5AB2iQeIUSNDBAUgLEvdYLrL488Z@2QIpo3U8M29@b3x3ezjcL8t5uAnz8WU@vp7Nn2/XX@9XP8@/jx/z8eHCL99P8Rh/l8syTZOY/W6z3U5u3G1VxCQp92LbvRui@ChCd12UPtqnO4P/XTlX7KirOF3BzziKEQpGvksxHPx9OYsrOpGGl20DYnrYDrB1eg97xbXFTtTXI2/knn27VV6G8pWC4XrgdsCyxTeL4ljSedQvqDP5Oeo76sw6h7jaWw8xVK/mw/2V1qvad9Sc76Gv/R@Ar7Nx@OosepwHYPWwdajDkY77NMImwMY2/OwXKBb@lxnsE1giZCNh@ZYg0R7piTn9/ifJJnk2MlcCmEaaLBhOthHoxkYSHmqOrITmYjrYjY20TBa1V5/s1xNxdZDhNI8cD/g5LhFdtI6OlrCnZTGIY2jBFVeIRAEYngg7EKk91SjISXVCJFWiIGftdV0yzRHkUVyeTZ299thST8zqQbKtprrUWhPPhvvnaJEGengCzUXr1BmtHsY6z0BLP7QHsNZpSTc03olv9YvQ4@hhj4fC4aEQQ7VoH/rVfMa2cFWAJabVr7Z1bhSzPkxYTO5r1vs2l9qbuLyb/R8 "Jelly – Try It Online") ### How it works ``` :5_5Ṡṣ-ḤS«LƊ€Ṁ>4 Main link. Argument: T (array of temperatures) :5 Divide each item of T by 5 (integer division). _5 Subtract 5 from each quotient. Ṡ Take the signs. This maps (-oo,25) to -1, [25,30) to 0, and [30,+oo) to 1. ṣ- Split at occurrences of -1. Ḥ Double, replacing 1's with 2's. Ɗ€ Map the three links to the left over each chunk. S Take the sum. L Take the length. « Take the minimum of the results. Ṁ Take the maximum. >4 Test if it's larger than 4. Note that the sum is larger than 4 if and only if there are more than two 2's, which correspond to temperatures in [30,+oo). ``` [Answer] # [Python 2](https://docs.python.org/2/), 86 bytes ``` lambda l:any(2<s.count('2')*(len(s)>14)for s in`[(t>24)+(t>29)for t in l]`.split('0')) ``` [Try it online!](https://tio.run/##fVXJbtswEL37K3ST1AYBxaE2I8mxX9CbYyBuGiMGVNmwlIO/3hGHb8ixDz0MKM3yZidPl/nzONrr/vn1Ouz@/fm7y4b1brwU9ml6fD9@jXOR27z8UQwfYzGVL5Ur98dzNmWH8W1TzC/WlT/90TN7XtjZsH17nE7DYbE0eVle97thujxvNmS2D6uN7R8yITKePJeqxLXdQm4hUrxmoXbR9jyD/yZ8A3eRRJQmYDOKINQBgXneg4W1C99kg4xI0Fizhj8HzQ6aVvisLZhV0CKxdIgYUbNlcxeTUbFSwLAtozZAqoIlk6BUSuaQOSFDb2djrZEfSyx8SkUdyKhMJZZUVUoVQq2RK3MhjTXvgC39sDil/i2@O0ZqoWkRv40SXZseGjU0qoTNVrXyg/9Q9wVpu1rN56/5M4xgGrxweleLFQIkc3v@j7yOt5TxjY03aVSY0BbWIcj6NBy6nexXhlgn1ECvT4OahkS0xYKtWjWs0sT6Ngr2BnT2qoabJItGLV0b18PAi1HLLKgUh6eGvVND2qlBdio7QjwiIzWaMiSIV6oc10ri48ERVN2T2G@pbaWqYe6unirlE5c45KM7outm1ep06oqpVT8kR@nNzfUXu1irFe/SNRczrJSsS7NGTjInUleggzYuBcuXAhmVheTf3nWlT0sWCUhkUuaiG7ulPOIKwirqarLUpW7EmoR1PZ0P45zlv/yzsc5X/K58TPy08FOyDgr7wnNLUX8df/OW31mE1b81uX4D "Python 2 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 20 bytes ``` Œʒ24›DPsO4›*}29›O2›Z ``` [Try it online!](https://tio.run/##fVQ9TkMxDL5K1REVKbGTl7yFib3MVB1A4gRISB2QOEOP06VDxcIxuMgjcT4nbgcGN6@x/fnvc1x8efVvy8dh@T7@HCn8fp0en9639bz7pLkcWyo/z8thfTmv7h9Wl/N6s@x27PabHc2blQq7KuWS/bikXCQUYXM3FUnFuN45/J/ad0Mtig4yNWQBUYDYAOSuBiA4h/bN1HTMABPDiGgBhhmGpPfVWBF9M2J1DEgXKYvjdJORM5lyw6BUQScA@eYooiDe6ALKZpRX/Ui7jNpEQYiozQwQZ8rUTHpDeTSndRl1yiWUvdsZyDoJwqmdT/jOFSjBkJA7qcJ2ZYZBhIEfyOIUTRT8bx2vjHKDYu0sl8UQGbG7Pv@TalM9wdM@ZDdYIYIZiA1DNw8i2NlJWKWrLWGC3Two2QmhxuogTsnQUkcWr5OQYACXoIbGrEVMZrmS7oFDEGdWVkFZiRLhHQwds6FsMKUxslEdGxYqJZCttrjvj2ZXaaKgdh590tpXb1rhbt4XP6rpyyrV2GHYnpHZkWzekWhmoRXqXOwL1wcYzSbn8ZL18rzR5cEyDiib2bxyAcZYfSIwv5egtaebgcxjnboAiN0oW237oEzA9s5g52wjRRnGIHo/eL//Aw "05AB1E – Try It Online") **Explanation** ``` Œ # push sublists of input ʒ } # filter, keep the lists where: * # the product of: DP # the product and sO4› # the sum compared using greater-than to 4 24› # for the elements greater than 24 # is true # the result is: Z # the maximum from the remaining lists where O # the sum of 29› # the elements greater than 29 2› # is greater than 2 ``` [Answer] ## Batch, 119 bytes ``` @set h=0 @for %%t in (0 %*)do @if %%t lss 25 (set/as=5,t=3)else set/a"t+=!!t*(29-%%t)>>9,s-=!!s,h+=!(s+t+h) @echo %h% ``` Takes input as command-line arguments and outputs 1 for a heatwave otherwise 0. [Answer] # [Python](https://docs.python.org/3/), 67 bytes ``` f=lambda l:l>l[:4]and(min(l)>24<sorted(l)[~2]-5)|f(l[1:])|f(l[:-1]) ``` [Try it online!](https://tio.run/##fVXLbuMwDDzHX6GjDbSAJMpPdPsjhg9ZpEYDuE6R@tACxf561pKGEptDD4QlkRq@hvL71/Z6Wel2m/8sx7e/p6NahuV5GQc3HddT@XZey6V6tu7p43LdXk77Zvxnp8e6@p7LZTTDFBfDo5mq23y5qk2dV1UWahxJTw@FUqPtHxQLaS/xnEw@t90ubhcSZ80u7W7vzzT2TVwn7F2XcJqIH3AYo44Y4cz7sLjv4pps1BFlvGBbw6eDbQdby@ewZ1wT7YjvOsSN2MPd5i4uLeKliGFb4DbAMvFuEMYxQueQPyFPf8@KuiPPoLPwy7V1EC3y5XhkfSnXKtUdOYdz6FP9O@Bzbyy@3IsW6w5YLWwt8rBCJ@vUw6aGjcn44V4tfGEfezB5ME/ITML4jU52e4RH@uf3N/E2/mYmcyKAzqQJguYEG4KuzySRTQ2emdAymQZ2fSatJAvb851wrxXE5UbWP@MI/oAf/AqiE@fRiCFsxbBo@NFiwBmXBIlqYDhB2E6Q2okcCTGxjgRJmSiImWudhoxjBHkYV/Ym9Z5rbERN9N2DZHJOaag5J9kbWT8rBqkTD08t@sJ5co/uHsbUz1oMfZcfwJSnEbou845czp9IPI4O9ngoLB4K0iIXrkN7158@D1wSYJHO@bNt6pvwmR4mDKasa9C73JdUm314i2ooDv7f8un/LdugisPhPKvlZS0/qyfbDO/X87qV876rikPcVLf/ "Python 3 – Try It Online") Times out on the longer test cases due to exponential growth. Finds contiguous sublists by repeatedly chopping the first or last element. That 3 days are ≥30°C is checked by looking at the third-largest value `sorted(l)[~2]`. The base cases could perhaps be shorter by taking advantage of truthy/falsey or terminating with error. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 48 bytes ``` a=>a.some(x=>x>24?++A>4&(B+=x>29)>2:A=B=0,A=B=0) ``` [Try it online!](https://tio.run/##fVTJTsMwEL3zFZygUaFyPM4GShAc@AJuiEMEZVNpEAUEX18S@409rWwOk8WeebO8mXntv/vN/cfL@@fpenhYbh/bbd92/WIzvC1nP23302lzMZ9fduZodjVvx98m6/TZZXvVqhP7zLb3w3ozrJaL1fA0O7697leb37vj7PxAnj/ObkndZdn@oW5ODllITRJRojwo6XoUMwqJs3KUajSezhT@S/cd9zoqetDSebagDFg4QHs2OdQAM@6btLsjSoBbwwLRGBjWMNR8HjNmj7kzIgYySA8pWqByL2IlMiGHoauYkxLAuQOywqC5uDMoE6Eck51OsYjaWEWNiJgcA1GiLBxpkiAKxY6ziDpZJSh7Nmt4ZqY13sxshe86BlzBUCN3nVKUVW9gUMAgD54tSCGiwL9jdAI@2B2im4@vz@fEFIVhce/EwPjuUaH9rIBMq0O4a0KHySawTnhOZOwl9JowC8lOY2MGsCCVmAfmutgNyjqHMxuEmB/ipEox9VVqIBWcKrFr2AmlOrAAuhFzUItZMaIUhGj5jkS7cy8hG6bEDzJHH@svdiL59MQzL7kondpblHnI1m@RaLaSXFlzLYa1FguxEFxyBZjX/1a5b4hCrJw6rGxfjlzc1aGLySTKRCTWuYExdpaO7SxSImWuXbVHcBPm2AuASYUysa4nXgQQX5gYfkmMVTaBWF/Pqae3fw "JavaScript (Node.js) – Try It Online") quite bad one [Answer] # [Haskell](https://www.haskell.org/), 64 bytes ``` f l=or$drop 4l>>[sum[1|x<-l,x>29,all(>24)l]>2,f$tail l,f$init l] ``` [Try it online!](https://tio.run/##fVXbittADH33V8xDHlrwwng0vkHXP2L8YHbrbugkMYkXdmG/va6tkUZKCoUI27oc3ZW38fb7ZwjrNIbbp3k2mel7sENm8t61uWECuxOyoRC2azbyG4HiVRvVm/rOs/RdxXdG3kQJporoCMMQZYRA3u7CkbmP7@CiDCDBoWpJHj2pNqTqmB/VGbWIasCmnoKmwNG0eojKqmghYrg6wlYEVURTJIYplMxT8kBJ7nZOKk45osiRVy6rJ7IqWY7GDlRYkCJxvSlbZJM41b0hbO6Joyf3oKb3JkLVpOooAyciXZ@WVEpSKQQdzUrlib5j7XnG0s/mexJDli3X9@VNZlQGMz7RcIOj2MHeP/9Hu85umeY7jYWVSUKinqEOkKyV0dG9Rsc85DrVivRaGWQ1QqzOJmhWq2HmFpf3YaA7gke3aviB06jUWtayP5bcWLXwDIvq0t9KigPKS/IA4gUjYhmoyeURooi50GnvOMI4Vgyr@5K6zvUtVEHsw30qJKO05pSRbouunVO71ag7VKqecJbcn/srmVpZqivQyDVMSRZK1sjEgU/JA6hL6UmdDoeLhwOsSoRrUD@0ppU1TERQYCV51k0tUy75TtG26pKi2EtLUl0gbu86mfB8uR5er5fZ@NB1/e391BdfHz@eQv7RbSZjCN8657@HoXP5dFjGYzBhezmej4sJw3oaj@dt@18vmTHz9XhezMGcxtlMBv@8/uHGe7H@eZnC@Ou2Pr3M818 "Haskell – Try It Online") [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 29 bytes ``` ∨/(5≤≢¨a)∧3≤+/30≤↑a←e⊆⍨25≤e←⎕ ``` [Try it online!](https://tio.run/##dVQxTgMxEOzzCrqAAMXnte98X6CAghJRRCKhiQQtHwgJEggKPoCQyDt4yn0k@OxZe@M7ik3O9u6sd2e888fV@d3TfPVwv@82z0v/s5sd22773W2/fnfzk27zQ351OiPVb64/5t36fdG9rLvXne79Fn7dvX320fvlxH9dXF9dTm9I3U4nYq3bsyM2Ur0dnlOVz7XzZryR2Ku9NT6u31NY1/F7kMv7JLw65gt4jGUjVtjrc2ngmPhNOp4RDXFDjMUdDGIcYjTvF3Gcp4r@xBgG9aCmgFEX91Ti/hQxdFPg18CsIkYwxqvEmUFfCPX3cXqEJ/Qh@GjcgzkwMCX6wPcb44FyTwc8oSfhHH6JL4d8zKXGP3PX4NsVmA1iNOrUIz6yry18LXyrnC/EW5Eb68iZxzwQsMrijv9DgSfyVRZOMBASfAhnbRaIJDLgs7jlxWr4tVnAY0LhOI4N8Y0QMZNmD@8T8iJPyC9ET1xPLR5oM/KAFPIpMQwYn0YEZIFphHidELgRtRPuyGckhMqiQA3MQXp4fOdCKIwvuUv8MgeV6JUqhliVa0wPvqxRcij7q8XjcmJYWcEb180c/jNcE@9WDAaXh2iqvxJnLuuUzLAvRGLAGsRhqOhiqJASNXKfmoLHNj@@ZMAklfvCvolfkXswzPBYZf@Dn8n8pd71Wv0D "APL (Dyalog Unicode) – Try It Online") `∨/` are there *any* elements such that `(5≤≢¨a)` 5 < the tally `≢` of days in each series (`a` has all the possible series of days) `∧` and `3≤+/30≤` 3 ≤ the total `+/` number of elements that are ≥ 30 in `↑a←` the matrix formed by `e⊆⍨25≤e←⎕` the series of consecutive elements that are ≥ 25 [Answer] # [Python 2](https://docs.python.org/2/), ~~66~~ 63 bytes ``` lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b*25>b*c],a,1) ``` [Try it online!](https://tio.run/##fVW7TutAEO3zFW6uSCIXuzvrVwTUVLS3MCns4AgkSFAwSHx9sGfP7E4i3VuMbM/jzHv88TO@HA/uvL97Or917/1zl3Wb0/D8tRuW@O7z3WbZr5dl7lbt7pbM9k9d@tyu2n7tivt@vdvm3fR53ndvnz93bTtp5IvWNXkmRGammUs2cV09kZ@IFK@cqJq0Z57BdxnegTtJIkoZsBlFEIqAwLzZg4O1D@/kgoxI0FizgD8PzRqaTvisLZg2aJFYekSMqNmyvIrJqFgpYLiKUUsg2WDJJChWyTwyJ2Q427lYa@THEgefUlEPMipTiSVVlVKFUGvkylxIY81rYEs/HJ5S/wrvNSNV0HSI30WJrk0DjQIaNmGzVaH84DvUfULaLhbj6Wt8CSOYBi88Z1eTFQIkc/n8H806s6WMb2y8SaPChLawDkHWpOHQ7WS/MsQ6oRJ6TRrUNCSiLRZsValhlSYWl1GwN6CzVzXcJFmUaumquB4GXoxaZkGlODwF7L0a0loNslfZEeIRGanRlCFBvFLluFYSHw@OoOqexH5Lba2qhrk6PTblE5c45KM7ouvm1OrU6sQUqh@So/Tm4vzFLhZqxet05mKGVsnqNGvkJXMidQI9tHEUHB8FMioLyb@66kqTliwSkMikzEU3dkt5xAnCKupqstSnbsSahHX9OL0exuzm8Zg9DN2Y/e2@h83NYn88ZePwOWavh4z/KJugt1/O3JVYPR3@ZRSOwKXV@Rc "Python 2 – Try It Online") -3 bytes thanks to Lynn How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number >= 25 is seen the reduce is multiplied by 2. If a number >= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result. A more readable, but longer version looks like this: ``` lambda a:reduce((lambda b,c: 1 if b>0 and c<25 else b*(2 if c<30 else 6)%864), a, 1) ``` Removing extra spaces/parenthesis and replacing `x if cond else y` by `(y,x)[cond]` gives ``` lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b>0and c<25],a,1) ``` Lynn suggested to shorten the condition `b>0and c<25`: `b>0and c<25` --> `b*25>0 and b*c<b*25` --> `b*25>0 and b*25>b*c` --> `b*25>b*c` resulting in ``` lambda a:reduce(lambda b,c:(b*(6,2)[c<30]%864,1)[b*25>b*c],a,1) ``` [Answer] # [Kotlin](https://kotlinlang.org), 57 bytes ``` {var r=1;it.any{r*=2;if(it>29)r*=3;if(it<25)r=1;r%864<1}} ``` (-1 Byte by replacing the explicit Parameter *v->* with the implicit parameter *it*) ``` {var r=1;it.any{v->r*=2;if(v>29)r*=3;if(v<25)r=1;r%864<1}} ``` (-16 bytes using the any{} operation as seen in the [Ruby Solution by G B](https://codegolf.stackexchange.com/a/166729/81015)) ``` {it.stream().reduce(1){r,v->if(r*25>r*v)1 else(r*if(v<30)2 else 6)%864}<1} ``` (-1 byte thanks Lynn: replaced r>0&&v<25 with r\*25>r\*v) ``` {it.stream().reduce(1){r,v->if(r>0&&v<25)1 else(r*if(v<30)2 else 6)%864}<1} ``` This lambda expression takes a List and returns true for a heatwave or false else. Thanks to the magic number 864 and to [Udo Borkowski](https://codegolf.stackexchange.com/users/81057) and Mathis for their ideas. How does if work? Each sequence of numbers is iterated with an *any{}* operation starting at the reduce value 1. The reduce is multiplied by 2 and multiplied with 3 (2\*3=6) if the number is greater or equal 30. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a true return value in the inner lambda called from the *any{}* operation which then stops iterating and returns value of true. [Try it online!](https://tio.run/##nVZta9swEP7eXyHKBvbIhqST39IksH0YDAb90P0Bf2gaM9cpjlsIIb89s@U76ZxRmc0gLEt3zz26N@v3vqur5vJW1mK3FNHP6tCtfjTdJhafN@Lbfl8/lo1Yi8vprWxFu1Z3VfelbI6n9tNa31XbqOo2uoj7Lxi/VjqJB7H2Y56alTqfL6J/tq@NeC6rJirbp8NSfG3b8rh66NqqeeotnW4EPgONbVkfHo8P5fNL/XjoTdc9pftt5GTowXWQ8eK9PV0sBA2TLURIFpSX1Xk/TD@AraX9GDCGNYnf6TgPcujlHXY6yCI24SYjrl0b7GrENOMc9LgHELZh9RPkZlA/R31N6wEMsq9GXSA8g2fGc1u89Iq/ZOeCEUNnAVsp4qsRzw7CVmzPoO8AfTTo6Zl4o9@svEZ@FD@DQzJfEe@5GIKPRzDe6EMrizou7jnyoJzQ@KYcyHCeB/CzUd9o9IuekefxKdDHCeopz8NiJYwTfo@xjx18fDOp1q597Xb/Uq3IAt9Gvc@8J4G@ATl9h4aRVk2FK91luPSVYgdmmpUB3Ct8FfAMtWyosrnXUpQrfPXOVQNhEI7FylgFUwYmU26WA9q0XFjFA50tZV0rm@kkEm1LX@HOFsxUSYK20LeG8XFcwPOx3GkPWGVihtPZKE6uA9FZAllPtnisXe5RzBTzp7zq/sqf3XXB0Nl5/Hk8NOsyOevyCYsz@YNijvURtJf67us6Z@7/Ss5Hiu3lPt/BhH0HwP5YBjGwA@tABwbJ/EB@za5yoPCdxw3EB@l9R7IuNxiP4F8AuxaPndUxPvbO15PORrOX/mLS1U10@93eRZa3fmu7b0V0sO1OVM30ssJvMhMY8eG0Q6X4LBja@W@Tv2xDDZicdNz/MWmn58sf "Kotlin – Try It Online") [Answer] # [Wonder](https://github.com/wonderlang/wonder), 34 bytes ``` (/>@(& <2!> '<29#0)*> '<24#0).cns5 ``` Usage example: ``` ((/>@(& <2!> '<29#0)*> '<24#0).cns5) [25 33 33 25 24 27 34 31 29 31 27 23] ``` # Explanation Verbose version: ``` (some x\\(and <2 (fltr <29) x) (every <24) x) . (cns 5) ``` Take overlapping sequences of 5 consecutive items, then check if any of the sequences have all items > 25 and more than 2 items > 30. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes ``` L5r⁸ṡẎ<25Ẹ$Ðḟ29<S€2<Ẹ ``` [Try it online!](https://tio.run/##y0rNyan8/9/HtOhR446HOxc@3NVnY2T6cNcOlcMTHu6Yb2RpE/yoaY2RDVDk////0UZmOgpGlkBsqqNgbADERkC2BRCbQbCxMZAGihsZIslZQMSMTUA4FgA "Jelly – Try It Online") [Answer] # [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` Æ7)║▄░Ä╟═╙hⁿ╧\ßY8÷K▌µ½x ``` [Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=923729badcb08ec7cdd368fccf5ce15938f64bdde6ab78&i=[30]%0A[29,+29,+29,+30,+30]%0A[31,+29,+29,+28,+24,+23,+29,+29,+26,+27,+33,+20,+26,+26,+20,+30]%0A[23,+31,+29,+26,+30,+24,+29,+29,+25,+27,+24,+28,+22,+20,+34,+22,+32,+24,+33]%0A[23,+24,+25,+20,+24,+34,+28,+32,+22,+20,+24]%0A[24,+28,+21,+34,+34,+25,+24,+33,+23,+20,+32,+26,+29,+29,+25,+20,+30,+24,+23,+21,+27]%0A[26,+34,+21,+32,+32,+30,+32,+21,+34,+21,+34,+31,+23,+27,+26,+32]%0A[29,+24,+22,+27,+22,+25,+29,+26,+24,+24,+20,+25,+20,+20,+24,+20]%0A[23,+33,+22,+32,+30]%0A[28,+21,+22,+33,+22,+26,+30,+28,+26,+23,+31,+22,+31,+25,+27,+27,+25,+28]%0A[27,+23,+32,+23,+22,+28]%0A[25,+20,+30,+29,+32,+25,+22,+21,+31,+22,+23,+25,+22,+31,+23,+25,+33,+23]%0A%0A[30,+29,+30,+29,+30]%0A[1,+1,+25,+30,+25,+30,+25,+25,+25,+25,+25,+25,+25,+25,+30,+1,+1]%0A[31,+34,+34,+20,+34,+28,+28,+23,+27,+31,+33,+34,+29,+24,+33,+32,+21,+34,+30,+21,+29,+22,+31,+23,+26,+32,+29,+32,+24,+27]%0A[26,+29,+22,+22,+31,+31,+27,+28,+32,+23,+33,+25,+31,+33,+34,+30,+23,+26,+21,+28,+32,+22,+30,+34,+26,+33,+20,+27,+33]%0A[20,+31,+20,+29,+29,+33,+34,+33,+20]%0A[25,+26,+34,+34,+31,+28,+32,+30,+34,+23,+26,+33,+30,+22,+30,+33,+24,+20,+27,+23,+30,+23,+34,+20,+23,+20,+33,+20,+28]%0A[34,+23,+31,+34,+34,+30,+29,+31,+29,+21,+25,+31,+30,+29,+29,+28,+21,+29,+33,+25,+24,+30]%0A[22,+31,+23,+23,+26,+21,+22,+20,+20,+28,+24,+28,+25,+31,+31,+26,+33,+31,+27,+29,+30,+30]%0A[26,+29,+25,+30,+32,+28,+26,+26,+33,+20,+21,+32,+28,+28,+20,+34,+34]%0A[34,+33,+29,+26,+34,+32,+27,+26,+22]%0A[30,+31,+23,+21,+30,+27,+32,+30,+34,+29,+21,+31,+31,+31,+32,+27,+30,+26,+21,+34,+29,+33,+24,+24,+32,+27,+32]%0A[25,+33,+33,+25,+24,+27,+34,+31,+29,+31,+27,+23]&m=2) This takes a long time to run, so I disabled auto-run. ### Unpacked (28 bytes) and explanation ``` :efc%4>nc{24>f=a{29>f%2>|&|& :e Set of all contiguous subarrays f Filter, using the rest of the program as a predicate: c Copy subarray on the stack %4> Five or more elements? |& AND nc Copy subarray twice to top { f Filter: 24> Greater than 24? = Equals the original subarray? |& AND a Move subarray to top { f Filter: 29> Greater than 30? %2> Length greater than two? Implicit print if all three conditions are met ``` This'll print all subarrays that can be counted as heat waves, which will be falsy if and only if none exist. [Answer] # [Ruby](https://www.ruby-lang.org/), 89 bytes ``` ->a{(0..a.size).map{|i|(b=a[i..-1].take_while{|t|t>24}).size>4&&b.count{|t|t>29}>2}.any?} ``` [Try it online!](https://tio.run/##fVTbjtpADH1uviJPe5GWaDKe3B42fesX9A2hKnRBRd0FRECrLfDtNPEczxi26oMVGNvHt2PvDvOPy/L5Mmm744PJsi7rV38Wj9lbtz2eVqeH@XM3XWXZJJ9l@@734sf7r9Xr4njan/atdedHtm7d3d08@7k5rPfQNOfWnrNu/fH1fNke9n16P2nTb91rv7hPlptd2qerdTpNpmRmT8nUNk@pCJlRxlfK46utB3GDkHorB6kG6/HN4H/pfwN30ASU0mMziiAUHoHfxggW3s7/Jut1RILGlgXiOVjWsLTyztaCmXsrEk@HjJE1e5Y3ORmVK3kMWzFqCaTce7IISq50DpUTKhz9bOg16mONRUzpqIMYVankErtKsUPoNWrlV2hDz2tgyzwsvtL/Cr9rRqpgaZG/DRrdmwYWBSzyiM1ehYqD/77vs3SWvmySL9t0Oe1nyWL9kiSBo993h08UjcT03zGVARUFkLn@/k9Gm9FT6B2IYSKVWDA2tiHomkgePW6OKyTXBZewayKRI4nEWjzYq1JkliEX11lwNKBzVEV@kipKtZRVWB@DKEYtu6BSIFcBf6dIXCuiO1UdIR/RkaKukAj5SpfD2kl@TCxB1TMJ85be5qob5uY05bGesOS@Hj0R3TerVqtWJ6hQ85AaZTZX5zFMsVAnoI5nMFSYK10duUZOKidSJ9LBGkfD8tEgo6qQ@qubqTRxCYMAiUysXGzDtFREnCisqu4ma12cRujJP9b58hc "Ruby – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 19 bytes ``` Vo≥3#≥30fo≥5Lġ(±≥25 ``` [Try it online!](https://tio.run/##yygtzv7/Pyz/UedSY2UQYZAGYpv6HFmocWgjkGVk@v///2hjAx0jSx0YGQsA "Husk – Try It Online") Using filter (`f`) is one byte shorter than using [checking with a logical and (`&`)](https://tio.run/##yygtzv7/P@zQcrX8R51LjZVBhAGIaepzZKHGoY1AlpHp////o40NdIwsdWBkLAA), also it would be really nice to get rid of the `±` - costing 2 bytes :( ### Explanation ``` V(≥3#≥30)f(≥5L)ġ(±≥25) -- example input: [12,25,26,27,28,29,18,24,32] ġ( ) -- group by ( ≥25) -- | greater or equal to 25: [0,1,2,3,4,5,6,0,0,8] (± ) -- | sign: [0,1,1,1,1,1,1,0,0,1] -- : [[12],[25,26,27,28,29,30],[18,24],[32]] f( ) -- filter by ( L) -- | length: [1,6,2,1] (≥5 ) -- | greater or equal to 5: [0,2,0,0] -- : [[25,26,27,28,29,30]] V( ) -- does any element satisfy ( # ) -- | count occurences where ( ≥30) -- | | elements greater or equal to 30 ( ) -- | : [1] (≥3 ) -- | greater or equal to 3: [0] -- : 0 ``` [Answer] # [R](https://www.r-project.org/), ~~111 93 71 67~~ 66 bytes ``` !Reduce(function(i,j)"if"(j<25,!!i,(i*(2+4*!j<30))%%864),scan(),1) ``` [Try it online!](https://tio.run/##nVQ9j9swDN3vVyQuDpCvLiCJsmwXWTq0U6dr@wMO7gVwhhRo74D796lNPYpMhg4dCH@QfCQfn/T78m7/@PzzdX52x9fz/LL8OrulO7XNcmzc6RD7br9fOrc8uPg@PexPB/Jte38/5tR2f@ans2u70N4dd4cPl5r/1v435NuKdpmfXlzz5dPXb58/Nl1z16z4bnZbFL/EqduJpaHbVQcFdcRxtbQamX95tS1h@@fxncu7oq/OCpQ3B4AEpC8g/G8rEgGQyjvF4iMygBzco2pC8IjgKP8lQZBDCSRJTmgd7XNyvunMm46pYMRBgDPAQklmE6BgfAkUEEbd8qJlH7OyM6KyEJxg3owsHV2RTEqYso@52YGAuoURFWRDEU/ZyID3UcCGEpwiZonWadmaQEKPoKAVOLE31fBdNrGCsVq/P/64EStQ8UwBZVcEtEz@@vkvS57TghF6VYZXObFhaRxD8E2qHrtsLi1at/NlxE2q5ysVSYIkceJgNC377a8b4YIowIXNGSAZJJsTOtiD5FHIq@YrMFl19UABRclUqlVIK3FX4iMjX@hHuha66wGULkVTAmz3U5UgPAdDi7@5sIJOVU98ncouyHIYzSEbzcXUm93IpLInSFPBs94h9UoY9YqsowbjG1V9lAwFROb6TEjAPRLlHiFvxhEuhpslTXoWqwGMvFIgsXV5pqheXDi0llwOSLqcys@muctf "R – Try It Online") Shameless port of [Roland](https://codegolf.stackexchange.com/a/166556/80010) [Schmitz's](https://codegolf.stackexchange.com/a/166548/80010) [answers](https://codegolf.stackexchange.com/a/166555/80010). -4 bytes thanks to Roland and -1 thanks to Giuseppe. TIO links to functional version. Previous version extracted consecutive days>25 using `rle` and saved a whopping 18 bytes thanks to Giuseppe! [Answer] # [Swift 4](https://developer.apple.com/swift/), 50 bytes ``` {$0.reduce(1){$0>0&&$1<25 ?1:$0*($1<30 ?2:6)%864}} ``` [Try it online!](https://tio.run/##jVbbbtswDH33V@ghK@whK2RK8iXY2qc@7BuCPASd0wbo0iDxLkCRb88UmpS4YKsUVJBtieQheXTU46/tZrTnl2FUm0W5/LobV9WnOz@pL@r8NtO3h@Hbj8ehrCv/cqdvbmb1Z3Dqvl7M9MfSvxit7mHRVB@6xp5OZ@V/F2f71@N23P4cHn6vv@9fhqN3t1waPVfQzxXPtl7NC/XOb1nPlf8DRzZifm9YjWZJ78ZvMnYaoGnuaBg/Wv/tssfQmscMlt7BP7O9np5xHSYbtG9oX0/zxUebQnWxYk/sDT22EzL0ZCYUWBGBEJFQZETE@2FawywastWUoUki0oSA@ob5cET0lPTgKC5V2wpsAZeJ2DAPXjNUOcILJubJnQPKJ@TVJXtPESUHAj@5l7WosMgd@VHHOmB2aJ@sg2SH7BMQbk3emYlO9J9rw1ygk5QRlRlF5wcZ0VF0yYZarHXxTBibU0300os@A@G8RIGkBy0qw/VurxhCPTFyUBTc38QzGXpjqTe8D3K4aszfnUVLG5kRemBWK/RWsPDthqf1P4QvGbSP9LJtTlMDSXtBGSO@NXy8qbnUbMijjBHHoKHyWuHdUQGYqCAkFKLcZYgLN8kRThuFmKVr@p70ZOPRDLLuomQHkQCqhMxFixyJgnlSjVGIiIGs4nIIaOp4qUwXQxYnqJ5oBYSVu2uFMDohIDZLkpniAXfSootixZaBGywnzBsWOuZJS89JYWaJt3TNYZQu64LRQsK5VhAlA9iju7qmHfPDH@bi@j@X283r4WH9@Fy@7Q/b3VhuypmuqlNVTK9VcX3i/2tQnP8A "Swift 4 – Try It Online") The closure expression returns 0 for a heatwave or >0 else. Created in collaboration with [Roland Schmitz](https://codegolf.stackexchange.com/users/81015/roland-schmitz) and Mathis. How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number >= 25 is seen the reduce is multiplied by 2. If a number >= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result. [Answer] # [JavaScript (ES6)], 49 bytes ``` a=>a.reduce((b,c)=>b>0&c<25?1:b*(c<30?2:6)%864,1) ``` [Try it online!](https://tio.run/##hVRNU9wwDL3zK/ZSSDpbxracxKHscu2p1x4YDtkQOnQY0gHK398m9pMtduz2oIljS08fT9Kv4X14HV8ef799eZ7vp@PD7jjs9sPly3T/Z5yq6rAd693@sFfn47VpbvTV4XM1XpO6MVdt/cm1dqvr4zg/v85P0@XT/LO6uP0@b75Nw9vmx/A@3V3UX8/k80N1S@qurk8vTb/dsJBaJaNEOikZt4hdhMRdu0i3GK93Cv9tOOe9LooRtA2ePSgDNgHQ360ODcBsOJMJb0QFcG/YIBoLQwdDw/c5Y/aogxExkEV6SNEDtScRK5EJBQzT5Zy0ANYByAuDavFmUSZCOVY7U2IRtfGKBhExORaiRFk40iJBlIqdZxF18kpQjmw6eGamDb7MbIezywF3MDTI3ZQUZdV7GDQw0MmzB2lEFPgPjK7AZx9n6T@DlOYlfAszExtIpQ70Aj69DuGtT00m@8A74VGR4bfQ69M4FJuNjRnAg3RiJJju5mNQ3jmc@SDECBEn1YrB70ozqeBUiXXDTqjUhA3QrRgFJ8bFilIQouU3Eh3P7YRsmJI4yxx9rsXYieQzEs@8aFE6dbIrdco2LpJstpJcWXMj5tWJndgILrkCzOu/tnlsiEZsHZe2diyHFm8udTHZQpmIxEa3MMbaMrm1RUqkzLXrTgju0yhHATCpVCbWjcSLAPI7E/MvifHKNhEb67n29PEv "JavaScript (Node.js) – Try It Online") The arrow function returns 0 for a heatwave or >0 else. *(Port of the [Swift](https://codegolf.stackexchange.com/a/166655/81057) solution to JavaScript)* How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number >= 25 is seen the reduce is multiplied by 2. If a number >= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0. Only when a heat wave was found the reduce can become 0. Once the reduce value is 0 it will be 0 for all future reduces, i.e. also for the end result. [Answer] # [Java (JDK 10)](http://jdk.java.net/), 60 bytes ``` h->h.stream().reduce(1,(r,v)->r*25>r*v?1:r*(v<30?2:6)%864)<1 ``` (-1 byte thanks Lynn: replaced r>0&&v<25 with r\*25>r\*v) ``` h->h.stream().reduce(1,(r,v)->r>0&&v<25?1:r*(v<30?2:6)%864)<1 ``` The lambda expression returns true for a heatwave or false else. Thanks to the magic number 864 and to [Udo Borkowski](https://codegolf.stackexchange.com/users/81057) and Mathis for their ideas. How does if work? Each sequence of numbers is iterated with a reduce operation starting at the reduce value 1. If a number >= 25 is seen the reduce is multiplied by 2. If a number >= 30 is seen the reduce is multiplied by 2 and by 3 = 6. If a number < 25 is seen the reduce starts again at 1. If the reduce is divisible by 864=2\*2\*2\*2\*2\*3\*3\*3 then a heatwave is found, and the result of the modulo operation is 0 which results in a reduce value of 0 and in a return value of true. [Try it online!](https://tio.run/##rVZbb5swFH6GX2FVmgRdisA2l6Rp@jat0iZN6qQ9THtgidPSERKByVRN/e2ZMceXAF1f9uAA9jnfd@7xU37Mr542v07F7rCvOXoS30HLizL4VDT82h1tb9tqzYt9FXyp2aZY55xdu@6h/VkWa7Qu86ZBn/OiQn9c14FdLbjsIJd3FWcPrF6tUNF8ZDn/lh/ZXbUu2w3b3FXoxj09Xq0eg4bXLN95fiC02zXzoplXz47@1aq@xLH4Od5Gi/rSOy5JeIsXif8uS6i/jE6O4wiDHEk14NvmZcOe7/PdoWQNukHdcbDfeq7QUe8k9Gf2N57PkFo0naHhOYnMOc7EomIRay8Rq9Pr9kL4Tvr3EZeQ0XhJdw54CivuseRex4UBh/bvBPdnhIxxpU4MNlDQyUAHq/2BnuKJenmiMCj4Az5JjGRgZ2jZT3oMnA7wE8CMegy5FF5knVGICwH/Oz08kSeIg5TBYIfKAYUVWnFQ9k3lgZiYjvIEMZHnIKfzlQGfyiWGp8pdCu/ZADPtdSgGP/GEjB3XOcQpBtnI8En92OKG7z5nvuv4r3UIr1v@@GaHADs8aXRupSAEf0l4/vzXoqFUi8bdpSsvNFUrF1SDlCFwNjfVaVeRtEB1lh2VBOTmpnumqlTpKV2pn1odpComPrdH8gKP5Lc6jih/Ems6pBPdGwJfaDpM45OJ6o0BE@JGLV7NSQyvtFGdEatLoCKVDyoHuuuVzYMqVfh27nTNqBxEVqzCwQSNjI962gx9tHNoxxdbnZ1ZkzK28qb8VjmEWh5xJGaa6amUmQmu/Y@ss8zUKaHjuBBiTXcKejDR8GCikdDyUcUpHeRxbjpfL8AkoYmLktX5tbhHkxQmhR1/KUdN/nTs1DTRf/YNz7l4HPfFBu3ERcC753VRPXz/gfL6ofHFvcBx5AWBs4azWsyYiv2WVwZPTiXn/lns74J9y4OD0ORl5V18kH/ciwsh4Tjbfe2hs7mFGjmw0AJAg/M/@p50EhhdoPdKaeo2EnRnXg/vS/aX12z8KkfnWzZqE88m7X@2sDPyxT39BQ "Java (JDK 10) – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~50~~ 48 bytes ``` ->a{b=1;a.any?{|r|1>b=[b*2,1,b*6][5<=>r/5]%864}} ``` [Try it online!](https://tio.run/##fVRNj@IwDL33V/SyQhoBm8RJmmoH9odUPdDD3HaFmBlpEPDbmTZ5jg1a7cEqxPbz17NPn9P5/ra7b/aHy7Szvw7bw9/z78v1dLX7aTdML25t19NLHIfwutuffobxR4r@drsPA5lx3bSD69ctC5lF8jNZeXZpFj8Lqbc4SzebL28G/2P5zcizqsLEgp5hGCIUiPy2hHBw9@U3uaIjqnDZNCCih2mCqeP3Ys6otpgRu3okjcSza3zKyqhsqWC4rsBGQNnimoVhrNJ5FE8ocvFz0nHUmFUOUbmtHmJUsZyNai1Jm7jjqDc/Q107n4DOU3H48hQ6/E4FqoOpQw1OVLpDPUwCTKygZ7egIuF/6f44bv8cjpfr17Vp22P7NnyNza05fn68t6vNZrNqFoYKLcs3x5@hkDeZx@//ZLFZPCu7KymM8CgLJpZtCLpeiKMnnQMzxXWZEXa90FgRiM3ZJbt1iso83vCYRg4H@BxWUZ@4jKiWspPtMQhj1LozLAmxAhC8onBSNPeqQEJGrCPFW6YPMuZG163jDAulGFbPpU6d@2tVQ8zTdbJSUV1yVKTHonvn1GYldYWCmglXyfN5vJF1lEHdgCS3sBZplS4J48jX4onUnfQwx9lw5WyQUYVwD7qn0fSyglUARUaKZ9s6MhWSrxQ2Vbc0q72MpPbl39t8/wY "Ruby – Try It Online") Thanks to Roland Schmitz and Udo Borkowski for the idea and the magic number 864. And again to Roland for saving 2 bytes. [Answer] # [Haskell](https://www.haskell.org/), 60 bytes ``` f q|(a,~(_:t))<-span(>24)q=sum[1|x<-a,x>29,take 4a<a]>2||f t ``` [Try it online!](https://tio.run/##fVVLa@NADL77V0yhBxuSZTwav0qa0173F4SwDG29Dc3DjV1oIexPX6@tkWaUHAoRtvX49FZeXf/2st@Pu0N3Og/qpxvcj1@n42n3rNJ0tc6ypHX7/ks9qkRtNqC3iVpsTLNQTKBnQjbkkW3qiexEIHjlRNWkPvM0fZf@nZEnUYApPTrCMEThIZA3uzBkbv07GC8DCHCoWpBHS6o1qRrme3VGzb0asKmloClwNC1votIiWvAYpvKwJUHl3hSJYXIhs5Q8UJKznYkVpxxRZMgrl9USaZEsR6O3VFiIReJ6U7bIJnGoe03Y3BNDT@5BRe@1h6pI1VAGJopkfRpSKUglj@hoVghP9O1rzzMWfnoxJ7FNkuH8MbzGGY2D6Z9oOMFR7KCvn9/RrDNbhvkOY6HjJCFRz1AHSNbE0ZG9Rsc85DLVkvSaOMhihFidTdCsEsPMLS6uw0B3BI9uxfADp1GKtazi/mhyo8XCMyyqx/6WsTggvAQPEL1gRCwDMbk8QhQxFzrsHUfox4phZV9C17m@uSiIvrlPecworDllJNsia2fEbtXiDhWiJ5wl9@f6SoZWFuIK1PEahiRzIavjxIENyQOIS2lJnQ6H8YcDtEiEa1DdtKaJaxiIoEDH5Fk3tEy45DtF2ypLimIbWxLqAn57x1a9X1K3@Jv@fhiybLXsO3dM18Zm74/9x2GTXz5XS7f4XE/Gg3t7Udat3HZtLpdWDePB7Y7T5j@fEqW68@44qHt1cJ2aZHgVBLu9T/HP7O4uz8Z/T@3e/enH5VPX/Qc "Haskell – Try It Online") This combines some ideas from previous Haskell answers in a new form along with [exit by error code](https://codegolf.meta.stackexchange.com/a/4781/101474) to come out ahead. ### How? `(a,~(_:t))<-span(>24)q` puts the prefix of the list which is entirely >24 into `a`, and then tries to match the remainder of the list to the pattern `h:t` (dropping one value `<= 24` and putting the remaining suffix into `t`). This pattern match might fail even on truthy inputs, if the heat wave is at the end of the list, which is where the `~` comes in: it forces Haskell to match the rest of the pattern even if `_:t` can't be matched (an "irrefutable pattern"), in which case `t` is undefined (i.e. set to `_|_`) and will error out if we ever try to use it. Since Haskell has the usual short circuiting on `||`, we will only try to evaluate `f t` on undefined `t` if there was no heat wave in the list, in which case we exit high. If there was a heat wave, we'll find it and short circuit out, returning `True` and exiting low. The irrefutable pattern saves one byte compared to `tail`, which will similarly fail if called on an empty list: ### [Haskell](https://www.haskell.org/), 61 bytes ``` f q|(a,b)<-span(>24)q=sum[1|x<-a,x>29,take 4a<a]>2||f(tail b) ``` [Try it online!](https://tio.run/##fVVLb6MwEL7zK1ypB5DIyvaYl5TmtNf9BVEO7oMtKklooFJXym9fFuwZe5LDShkB8/jmPXm348db38/dcThfJvHTTvbHr/Pp3L2KNN3usixpbT/@EU8iEfs9yEMi8r1uckEEciXHBhXZul7ILASMVy5ULeorT@J36d8JeREFmNKjOxiCKDyE460uNJob/w7aywACnFMt0KNB1RpVNfG9OqEqrwZkajBoDNyZlndRSRYteAxdedgSoZQ3dUQwiskMJg@Y5GqnY8UxRyfS6JXKapAkS5aikQcsLMQiUb0xW8dGcah7jdjUE41P6kGF77WHqlBVYwY6inh9GlQpUEVFdGdWME/47WtPMxZ@Ml@TOCTJdPma3uOMxsH0T2e4wGHsIG@f/6NVZ7UM8x3GQsZJcoQ9czqAsiaODu@1c0xDzlMtUa@Jg8xGiNTJxJlVbJipxcVtGM4dwju3bPiB0ijZWlZxfyS6kWzhCdapx/6WsTjAvAQPEL24iEgGbHJphDBiKnTYO4rQjxXB8r6ErlN9FSuIvLtPKmYU1hwz4m3htdNst2p2hwrWE8qS@nN7JUMrC3YF6ngNQ5KKyeo4cWBC8gDsUhpUx8Oh/eEAyRKhGlR3rWniGgZCKJAxedINLWMu6U7htvKSOrGJLQl1Ab@9cys@r6nNn7PtZhzsKd1pk30@jV/Hvbp@bzc2/94tdpP9eBPGbu1hp6/XNp1s14vnbD7a7rSs/us5EWK4dKdJPIqjHUQr/Flg7PYxdf9mDw8qm/@@tL39Pc6bl2H4Bw "Haskell – Try It Online") ]
[Question] [ # 99 bugs in the code The adaption of "99 bottles of beer on the wall" for computer science where the bugs increase instead of the bottles decreasing is often re-posted around the internet. [Example T-Shirt Here](https://www.reddit.com/r/ProgrammerHumor/comments/8l68th/this_really_how_it_be_tho/?ref=share&ref_source=link). I think it'll be interesting to see potential recursion and random number generation across a huge variety of languages and finding the most efficient ways to do it. There's a fair few other challenges to do with 99 bottles of beer but none seem to have an increasing and decreasing number! # Challenge Your program or function should take no input and then print > > 99 bugs in the code > > > 99 bugs in the code > > > Take one down and patch it around > > > X bugs in the code > > > (blank line) > > > Where X is the previous integer minus 1 plus a random integer in the range [-15,5]. You can merge the minus 1 into the random integer, hence allowing the range [-16,4]. Ranges can be exclusive, so minus one plus (-16,6) or (-17,5). The random integers don't have to be evenly distributed they just have to all be possible. The program always starts with 99 bugs. You can ignore the grammatical error of "1 bugs". The program should stop when the number of bugs is 0 or negative and print > > 0 bugs in the code > > > There should never be a negative number of bugs. The ending should look like > > Y bugs in the code > > > Y bugs in the code > > > Take one down and patch it around > > > 0 bugs in the code > > > (blank line) > > > 0 bugs in the code > > > A trailing new line is acceptable. * Your code can be a full program or a function. * There is no input. * The output should be to stdout or returned. * Warnings/errors in logs/STDERR are okay as long as STDOUT has the required text. See [here](https://codegolf.meta.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781) for more info. This is code-golf so the shortest code in bytes wins. # Example Output [Paste bin example output rigged for -11 bugs each time](https://pastebin.com/Ba4Q8x4Y) [Answer] # [R](https://www.r-project.org/), ~~182~~ ~~140~~ ~~138~~ 135 bytes ``` n=99;while(n)cat(n,b<-" bugs in the code ",n,b,"take one down and patch it around ",n<-max(0,n-sample(21,1)+5),b," ",c(n,b)[!n],sep="") ``` [Try it online!](https://tio.run/##FY1BDsIgEADvvmLlBHFJrImHxvYlxsMWiBDtQgpN/T3CeSYzW608j@Pj8OHrJCtDRTIukxaw7O8MgaF4ByZadxLYCIpCHweRHdh4MBBbSFSMh1CAtriz7eKkV/rJK7LOtKaWvg04qMtd9UITTL@o55lfmF2ahVC1/gE "R – Try It Online") ~~while being reasonably good at random number generation, R is terrible at strings and printing.~~ *JayCe found about a billion bytes, and continues to find new ways to golf this!* [Answer] # Java 8, ~~161~~ 160 bytes ``` v->{String s="",t=" bugs in the code\n";for(int i=99;i>0;s+=i+t+i+t+"Take one down and patch it around\n"+((i-=Math.random()*21+4)<0?0:i)+t+"\n");return s+0+t;} ``` -1 byte thanks to *@JonathanAllan*. [Try it online.](https://tio.run/##LVDBTsMwDL3zFVZPCaVVQVxGyPiC7QLiAhy8JFuztUmVOEVo6reXVKvkd7D99PyezzhiddaXWXUYI@zQuusdgHVkwhGVgf3SArxTsO4Ein16q2HkIk@njFyRkKyCPTiQMI/V9rqSoyyKB5IFHNIpZkmg1oDy2ny7Qhx9YPkKWLnZCLttRCylLalcUHzgxYB3BrT/dYBOw4CkWrAEGHxyOiuUjNlK7pDaOmSG7xm/f3qsnvlr89a8WL7oZBoXwVAKDmLZlCSmWdxcD@nQZder@XFJ1efw7Ob96weQr8n/Ipm@9onqIa@IuVoxl7qOr0@Y5n8) **Explanation:** ``` v->{ // Method with empty unused parameter and String return-type String s="", // Result-String, starting empty t=" bugs in the code\n"; // Temp-String we use multiple times for(int i=99;i>0; // Start `i` at 99, and loop as long as it's larger than 0 s+= // Append to the result-String: i+t // The first line of the verse +i+t // The second (duplicated) line of the verse +"Take one down and patch it around\n" // The third line of the verse +((i-=Math.random()*21-4) // Decrease `i` by a random integer in the range [-16, 4] <0?0:i) // If `i` is now negative, set it to 0 +t+"\n"); // And append the fourth line of the verse return s // Return the result, +0+t;} // appended with an additional line for 0 at the very end ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~137~~ ~~135~~ ~~133~~ 131 bytes ``` $b=' bugs in the code';for($a=99;$a){,"$a$b"*2;"Take one down and patch it around";$a+=-16..4|Random;if($a-lt0){$a=0}"$a$b`n"}"0$b" ``` [Try it online!](https://tio.run/##HczRCoIwFIDhVzmMgVkpFhHI2EtED9DRzRTXOTInXpjPvkb3//9NvFo/99a5GGWjM2iW9wwDQegttGxspjr2B4m6rpXEfDsLibIRx6sSTxwtMFkwvBIgGZgwtD0MAdDzQkak46SLy70sb99HCvijhi5hhQtVviW02v/ci8QuqsTG@AM "PowerShell – Try It Online") The "bugs in the code" section is saved into `$b` for later use. Sets `$a` to `99`, enters a `for` loop on `$a`. First we create an array of two strings `," "*2`, with the string being the `"X bugs in the code"`. Next is just the string `"Take one down and patch it around"`. Then we increment `$a` by selecting a `Random` integer from the range `[-16,4]`. After that, we clamp `$a` to be at minimum zero using an if `if($a-lt0){$a=0}`. Then the string `"Y bugs in the code"`. Finally, after the loop is finished, we put the string `"0 bugs in the code"` onto the pipeline. All of those strings are gathered from the pipeline, and an implicit `Write-Output` gives us newlines between them for free. *Saved two bytes using a `for` loop instead of a `while` loop.* *Saved two bytes by moving `$b` onto its own section.* *Saved two bytes thanks to Adrian Blackburn.* [Answer] # [JavaScript (Node.js)](https://nodejs.org), 127 bytes ``` f=(i=99,t=` bugs in the code `)=>i>0?i+t+`Take one down and patch it around `+((i+=0|Math.random()*21-15)<0?0:i)+t+` `+f(i):0+t ``` [Try it online!](https://tio.run/##FcwxEoIwEEDRnlNsmRhhgjMWMAZOYOcBEkOAVcwysGjj3SPW/81/uLdb/YIz55G6kFJvBJqqOrKxcN@GFTACjwH8XjMrTYONblGxsjf3DEAxQEefCC52MDv2IyCDW2iLXWaVEKiM/l4dj8WyE3oJeTiVeXmWF93qGuX/tMNeoKy14uQprjSFYqJB9ELK9AM "JavaScript (Node.js) – Try It Online") --- # Explanation : ``` f = ( // start of our recursive function i=99,t=` bugs in the code // parameters, 1. num bugs , 2. text `) // using string literal end text with \n => // start function i > 0 ? // if i is greater than 0 i + t + // return value of i, value of t and `Take one down and patch it around // and this text ` // + new line + (( i += // and add 0|Math.random()*21-15) < 0 ? // remove decimal from value obtained by multiplying // random number (between 0 and 1) multiplied by 21 // and then subtracting 15 from it // if that value is less than 0 0 : // add 0 to i i // otherwise add value of i ) // end the parenthesis + t // add value of t to that + `\n` // along with a new line + f(i) // and repeat the process (this is recursive) : // if i > 0 condition not met then 0 + t // return 0 + t. Zero is there so the last line can be // repeated ``` --- Thanks to @tsh for the idea of recursion and implementation (saved some bytes) Any suggestions to golf this further are welcome. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 59 bytes ``` 99[Ð16(4ŸΩ+¾‚{θ©3F“ÿ±À€†€€ƒË“Š}“ƒ¶€µ„‹€ƒš¡€•…¡“ªsõ®>#®]sDŠ» ``` [Try it online!](https://tio.run/##MzBNTDJM/f/f0jL68ARDMw2TozvOrdQ@tO9Rw6zqczsOrTR2e9Qw5/D@QxsPNzxqWvOoYQGIbFpzbNLhbqDE0QW1QPLYpEPbgGKHtj5qmPeoYSdY@ujCQwvBGhY9algGZDbMObSq@PDWQ@vslA@tiy12Obrg0O7//wE "05AB1E – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), ~~156~~ 138 bytes Thanks to [Jonathan's Python 2 answer](https://codegolf.stackexchange.com/a/165781/76162) for the `id` trick ``` r=n=99 z='%d bugs in the code\n' while n:x=n;r+=id(r);n-=min(n,r%21-4);print((z%x)*2+'Take one down and patch it around\n'+z%n) print(z%n) ``` [Try it online!](https://tio.run/##JcyxDsIgGEXhvU/xLwQQO1hd2oa3cHTBQoSoF4I0rX151Lid5TvpXXzEsdasofu@2TRnlq7z7UUBVLyjKVp3AW8WHx6OMKwaY1Y6WJHliFY/AwT2mXWH9iTHlAOKEBtb5a5T/GzujiIc2biADCwlUyZPoZDJcYb9ntXGIJs//GWtHw "Python 3 – Try It Online") ### Explanation: ``` r=n=99 #Initialise r and n to 99 z='%d bugs in the code\n' #Save n while n: #Loop while n is not 0 x=n #Save value of n r+=id(r) #Modify value of r, which changes the hash value n-=min(n,r%21-4) #Change n's value by a random number between 4 and -16 print((z%x)*2+'Take one down and patch it around\n'+z%n) #Print the message print(z%n) #And print the final line ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes ``` ≔⁹⁹θ≔”⧴"pWº⁴tSn/{yBⅈ⁺”ζW›θ⁰«×²﹪ζθ”↶0⪫\`3+¤⸿Zν(z¬hLÀTj'ZXεPraF”≧⁺⁻⁴‽²¹θ﹪ζ×θ›θ⁰¶»﹪ζ⁰ ``` [Try it online!](https://tio.run/##XY67agMxEEXr7FdcFgIjUMAxaYwrV6kMxrhMo6zESkQe2XrY4JBvV2R2IY9ymHvuPYNVcQjK17pJyY1Mq5XEWay7@ewfNd7LmOAY2RoMQZs37iVuLXO1zhvQazQqm0hniYUQ@OwedtFxpoM7mkRLiW3QxQe63ZtF4@Z/f1AfBoENdLgyFGucVB4sXIaKobBuS/f4Vp0mnb0bbaadL6mVOi6JXiT2DQxHWj4LManP9T@rk0jT@2v6W2Va@ur@oy22rrU@Xfw3 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔⁹⁹θ ``` Start with 99 bugs in the code. ``` ≔”⧴"pWº⁴tSn/{yBⅈ⁺”ζ ``` Save the compressed string "%d bugs in the code\n". ``` W›θ⁰« ``` Repeat while there are a positive number of bugs remaining. ``` ײ﹪ζθ ``` Print the number of bugs in the code twice. ``` ”↶0⪫\`3+¤⸿Zν(z¬hLÀTj'ZXεPraF” ``` Print "Take one down and patch it around". ``` ≧⁺⁻⁴‽²¹θ ``` Add a random number of bugs between -17 (exclusive) and 4 (inclusive). ``` ﹪ζ×θ›θ⁰ ``` Print the number of bugs remaining, or 0 if negative. ``` ¶ ``` Leave a blank line between verses. ``` »﹪ζ⁰ ``` After the last verse, print 0 bugs in the code again. [Answer] # JavaScript, ~~189~~ ~~176~~ ~~168~~ 162 bytes ``` f=(x=99)=>{c=console.log;m=Math;a=` bugs in the code `;c(x+a+x+a+"Take one down and patch it around"+(x=m.max(x+m.ceil(m.random()*21-15),0))+a) x?f(x):c(` `+x+a)} ``` [Try it online!](https://tio.run/##FY1BDoIwEEX3nGLCqiPSiIkLJNUTuPMAjKVAlbYEijYxnr3C4u3@@@9Jb5rlpEefW9eoGFvBgihLFJevFNLZ2Q2KD66rjLiR7ysSNTyWbgZtwfcK5GoldSVZyCjbSO/0UuCsgsZ9LJBtYCQve9AeaHKLbdJsTRhuKKyS4VLpgRk@rUtnGO6ORV6ccH9AzAiTcG1ZwLNkdVJv//iLLcP4Bw "JavaScript (Node.js) – Try It Online") Thanks for [Muhammad Salman](https://codegolf.stackexchange.com/users/79762/muhammad-salman) for the missing `console.log` replacement, and for [Oliver](https://codegolf.stackexchange.com/users/61613/oliver) for the x test improvement Thanks for [l4m2](https://codegolf.stackexchange.com/users/76323/l4m2) for golfing this by 8 bytes [Answer] # COBOL (GnuCOBOL), ~~317~~ ~~294~~ ~~279~~ ~~270~~ ~~269~~ ~~249~~ ~~248~~ 247 bytes ### Using `go to` statements: 247 bytes ``` data division.working-storage section. 1 i pic S99 value 99.procedure division.a.perform b 2 times display"Take one down and patch it around"compute i=4+i- random*21 set i to max(0,i)perform b display""if i>0 go to a.b.display i" bugs in the code" ``` [Try it online!](https://tio.run/##RY4xbsMwDEX3nOLDU5vWQhJ08ZAA3bO1F6AlWiFiiYYkJ@3l68pAiywEgff5@K32OrY@zsv2tBHHscgglopohJOb5LqYKalPFFpxhsziqNCD3TVdJfo2F03kGZntemywh2ASi4@uw43GmdF1q8mymxM/BGQmToOmgB4HFAmcK8zTSN/NJ10ZGmta7xEUHSYq9gIpoKRzdI3VMM2FIce3F2mRakbD9rCvPUotUBSBvp52r/L8@PJvb2SAnHbwuubI9OaPQBr0s8@QiHJhWHXcLGaz/NhhJJ@XdkjMdUosSWIWm4/v5/Mv) **Ungolfed** ``` data division. <-- Define the variables we want to use working-storage section. <-- Define global variables used in this program 1 i pic S99 value 99. <-- Define variable i with datatype signed numeric and with two digits procedure division. <-- Define our program a. <-- Define label a, to jump to perform b 2 times <-- Execute the procedure called 'b' twice, see below display "Take one down and..." <-- Display this sentence compute i = 4 + i - (random * 21) <-- Subtract from i some random value set i to max(0,i) <-- If i is negative, then assign 0 to i perform b <-- Execute the procedure 'b' display "" <-- Display an empty string; needed because of the blank line if i > 0 <-- If i is still greater than 0, then we're not done yet go to a. <-- and we'll jump back to 'a' b. <-- Define procedure called 'b'. display i " bugs in the code" <-- Display the value of i and then the given string literal ``` ### Using the `perform` statement as loop control: 269 bytes ``` data division.working-storage section. 1 i pic S99 value 99.procedure division.perform until i=0 perform a 2 times display"Take one down and patch it around"compute i=4+i-(random*21)if i<0 compute i=0 end-if perform a display""end-perform.a.display i" bugs in the code" ``` [Try it online!](https://tio.run/##TY/NasNADITveYrBpzZljRN6MTSB3nNrX0DZlR0Re2X2J6EvX3cNCe5FiJnRN8jqWQfT@zxvjxtx7JN0YimJeji5SSxLPQXtA41GXE317CjR6t01XMX3JiYN1DMi2@W4xg6CSSy@2hY3GjKjbReSZZcD/4Nz6DSMyKV6gBwaPBXCHklGjiUcp4F@qm@6MtSXa717kHeYKNkLJIGCZu8qq@OUExfO@5uYl1AyOm73u1fpIB8NVr8Be2eKvNY9a6rFecjl44cMqXDOfYR4pAsXlONqrjfzr@0G6uNsusBcpvgUxEex8fB5Ov0B) **Ungolfed** ``` data division. <-- Define the variables we want to use working-storage section. <-- Define global variables used in this program 1 i pic S99 value 99. <-- Define variable i with datatype signed numeric and with two digits procedure division. <-- Define our program perform until i = 0 <-- Perform the following code until i = 0 perform a 2 times <-- Execute the procedure called 'a' twice, see below display "Take one down and..." <-- Display this sentence compute i = 4 + i - (random * 21) <-- Subtract from i some random value if i < 0 <-- if i < 0 compute i=0 <-- then assign 0 to i end-if perform a <-- Execute the procedure 'a' display "" <-- Display an empty string; needed because of the blank line end-perform. a. <-- Define procedure called 'a'. display i " bugs in the code" <-- Display the value of i and then the given string literal ``` Note: the last sentence is still printed, because COBOL executes the whole program, and after the `perform until` loop it "falls-through" the label *a*, executing its statements. This behaviour is similar to a `switch case` without `break`. --- * Thanks to tail spark rabbit ear, 1 byte has been saved by using the intrinsic function `max` instead of an `if` statement. * Thanks to tail spark rabbit ear, 1 byte has been saved by replacing the `compute` by the `set` statement. * Thanks to raznagul, 1 byte has been saved by rewriting the formula for the new number of bugs. --- *PS: The numbers are not exactly displayed as required, but COBOL is not that good at auto-converting numbers to a pretty textual representation.* [Answer] # [Python 2](https://docs.python.org/2/), 151 bytes Nice trick `j=i+max(-i,randint(-16,4))` by Jo King, exploiting allowed uneven distribution Saved couple bytes thanks to Mnemonic ``` from random import* i,s=99,'bugs in the code\n' while i:j=max(0,i+randint(-16,4));print i,s,i,s,'Take one down and patch it around\n',j,s;i=j print i,s ``` [Try it online!](https://tio.run/##PYzBCsIwEETv@Yq9tdUVVESopX/h0Utsotlod0OaUv36mF48DMPAvBe@yQkfc35EGSFqNqVoDBLTRhFOfdtidZ@fExBDchYGMfbGlVocvS3Qxfej/tR7pO0KE6d6dzjjqWm6EMuC4sA11VW/LAhbMLIwlC8EnQYHlEBHmdkUK3qcOuq9@rM5/wA "Python 2 – Try It Online") [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~149~~ 148 bytes Saved one byte by changing `randi(21)` and `%i` to `21*rand` and `%.f`. `%.f` ensures the output is a float with zero decimals (i.e. and integer). Inserted a bunch of line breaks instead of commas and semicolons to ease readability. It feels wrong, but it's not longer than the one-liner. ``` x=99;do(p=@(i)printf('%.f bugs in the code\n',i))(x) p(x) disp('Take one down and patch it around') p(max([0,x+=21*rand-17])) disp('')until x<1 p(0) ``` [Try it online!](https://tio.run/##NcyxDsIgEIDh3ae4xcBpNcXFNEriQ7ipAwK1F/UgLVXeHtvB5Z@@/MEm8/GlZN00Bxdk1CdJGHvi1Eqx3LZwHx8DEEPqPNjg/JVFRYgy4yLOcTREKc7m6SGwBxe@DIYdRJNsB5TA9GFkJ2b@Nlle6iqv9U6t@klt1P6G/4fAkRO9IB/VZGss5Qc "Octave – Try It Online") ### Explanation: ``` x=99; % Initialize the number of bugs to 99 do ... until x<1 % Loop until the number of bugs is less than 1 (p=@(i)printf('%.f bugs in the code\n',i))(x) % Create a function handle p that takes % the number of bugs as input and outputs % the string x bugs ... \n p(x) % Call that function with the same number of bugs to get two lines ,disp('Take on down and patch it around') % Outputs that line, including a newline ,p(max([0,x+=21*rand-17])) % Call p again, while updating the number % of bugs. The number of bugs will be % the old one plus the random number, or 0 % if it would have turned negative ,disp('') % A newline p(0) % Finally, the last single line. ``` Using `p((x+=21*rand-17)*(x>0)` instead of `max` saves a byte, but the last line outputs `-0 bugs ...` instead of `0 bugs`. It works with `randi(21)-17`, but then it's the same length as the one above. [Try it online!](https://tio.run/##NYy7DsIwDAB3vsILis1DallQBUF8BCNLSAK1ipwoTSF/H9qB5ZY7XbDZfHytRXfdyQWM@opMMbHkJ6o1w2N6jcACufdgg/N3UTsmwkKruMDxGFHdzOAhiAcXvgJGHESTbQ@cwaQwiVNLjmWr0ywZDy3t2yNtsFwa@k8UTZL5DeXcznFDtf4A "Octave – Try It Online") [Answer] # VBA: ~~212~~ 163 Bytes This solution is based on the one by Chronocidal posted yesterday. This my first post and I don't have enough reputation to comment on his post. This revision contains two enhancements. 1. Using `While/Wend` instead of `For/Next` saves a few characters. 2. Calling a Sub named with a single character is shorter than `GoSub` and the `Exit Sub` and `Return` lines needed to support it. Edit: 3. Removed whitespace and characters that the VBA editor will automatically add back in. See [Tips for golfing in VBA](https://codegolf.stackexchange.com/q/5175/69061) 4. Added suggestions by @EricF, then saw his paste bin algorithm was even smaller so I replaced my algorithm with his and removed whitespace. A key change was appending `vbLF` to the output string so `Debug.Print` did not have to be called as often. Kudos to [EricF](https://codegolf.stackexchange.com/users/79060/erikf). --- ``` Sub b() s=" bugs in the code"&vbLf c=99 While c Debug.? c &s &c &s &"Take one down and patch it around c=c+5-Int(Rnd()*20) c=IIf(c<0,0,c) Debug.? c &s Wend End Sub ``` This was a fun challenge. If you know of an online interpreter like [TIO](https://tio.run "TIO") for VB6/VBScript/VBA please leave a comment. *If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out `Option Explicit`. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).* [Answer] # [LaTeX](https://www.latex-project.org/), ~~368~~ ~~304~~ ~~293~~ ~~287~~ ~~245~~ 240 bytes While not really competitive compared to the other programs in terms of bytes, I just wanted to see how to do this in LaTeX. ``` \documentclass{proc}\newcount\b\b99\usepackage[first=-16,last=5]{lcg}\def~{\the\b\ bugs in the code\\}\def\|{\loop~~Take one down and patch it around\\\rand\advance\b\value{rand}\ifnum\b>0 ~\\\repeat\b0 ~\\~}\begin{document}\|\end{document} ``` More readable: ``` \documentclass{proc} %shortest document class \newcount\b %short variable name \b 99 %set the value to 99 \usepackage[first=-16,last=5]{lcg} %random number generator %\the prints the value of the variable behind it %\def is shorter than \newcommand and can redefine commands \def~{\the\b\ bugs in the code\\} \def\|{ %the function \loop ~ ~ Take one down and patch it around\\ %\rand creates a counter named rand and %stores the random value in it \rand \advance\b\value{rand} %if the counter is smaller than 0, it becomes 0 \ifnum\b>0 ~ \\ %extra newline as required \repeat %if b is equal or smaller than 0, set it to 0 \b 0 ~ \\ %then print like normal %extra print at the end ~ } \begin{document} \| %calling the function \end{document} ``` **Improvements** (per edit): 1. "x bugs in the code" is now a function instead of 4 lines 2. Rewrote the `\if` clause for the `\repeat` as a `\else` 3. Apparently `\value{b}=x` works for initialisation but not in the loop (instead of `\setcounter{b}{x}`) 4. Apparently `\relax` should be used for point 3, but that can also be achieved by inserting a space. Removed the `\else`, used TeX commands instead of LaTeX as these are shorter, and replaced `\'` by `~`. 5. Some code didn't need to be relaxed for some reason. [Answer] # C, ~~169~~ 165 bytes *Thanks to @ceilingcat for saving four bytes!* ``` *s=" bugs in the code";f(i,j){for(i=99;i>0;i=j)printf("%d%s\n%d%s\nTake one down and patch it around\n%d%s\n\n",i,s,i,s,(j=i+rand()%19-15)<0?0:j,s);printf("0%s",s);} ``` [Try it online!](https://tio.run/##NY3BDoIwEETvfMWmCUmrmJSDB6zoT3jkUtsCW@PW0BoPhG9HxDDJbuZtZjPm0Bkzz7tYM7i/uwhIkHoHJljHVMux8GJsw8CxriqFF6mw9uI1IKWWs9zmsaH/vumHg0AObPgQaLLw0sn0gAn0EN5kt2BDrMAirsN9jfthCXORl9WhPIqzvMqTL6JQW4nMI/vxNC8MT43ERTZmsCiurwmfjksh1Hpr@WKm@Qs) [Answer] ## SAS, 210 bytes ``` %macro t;%let b=bugs in the code;%let a=99;%do%until(&a<=0);%put&a &b;%put&a &b;%put Take one down, pass it around;%let a=%eval(&a-%sysfunc(ranbin(0,20,.3))+4);%if &a<0%then%let a=0;%put&a &b;%put;%end;%mend;%t ``` Ungolfed: ``` %macro t; %let b=bugs in the code; %let a=99; %do%until(&a<=0); %put &a &b; %put &a &b; %put Take one down, pass it around; %let a=%eval(&a-%sysfunc(ranbin(0,20,.3))+4); %if &a<0%then%let a=0; %put &a &b; %put; %end; %mend; %t ``` Can save a few bytes if warnings in the log are permitted (put the `&a` into the `&b` macro variable, but that generates an initial warning). [Answer] ## PHP, 126 bytes Run on the command line, using `php -r 'code here'`: ``` $b=" bugs in the code ";for($x=99;print$x.$b,$x;)echo"$x{$b}Take one down and patch it around ",$x-=min($x,rand(-4,16)),"$b "; ``` [Answer] ## [ABAP](https://en.wikipedia.org/wiki/ABAP), 295 bytes ...because why the heck not! ``` REPORT z.DATA:a(16),c TYPE qfranint.a = 'bugs in the code'.data(b) = 99.WRITE:/ b,a.WHILE b > 0.WRITE:/ b,a,/'Take one down and patch it around'.CALL FUNCTION 'QF05_RANDOM_INTEGER' EXPORTING ran_int_max = 21 IMPORTING ran_int = c.b = b + c - 17.IF b < 1.b = 0.ENDIF.WRITE:/ b,a,/,/ b,a.ENDWHILE. ``` It's certainly not competitive compared to other languages, but I even managed to slim it down from 330 bytes I wrote initially, so I count it as a personal win. Since ABAP doesn't allow lines longer than 255 characters, I had to replace a space with a line break. On Windows this initially increased the size to 296 bytes due to CRLF, but it runs fine with just the LF in there. ABAP sure requires many spaces though, so this is no big deal. WRITE simply dumps text the GUI, so I guess that is kind of like stdout? I could probably save some bytes here by using a structure or table, but due to how SAP handles mixed structures (containing chars and numbers) the approach I imagined would only work on non-Unicode systems... Which I personally consider a no-go, despite having access to both. The function module for random numbers is the only one I could find in our system, I suppose there could be one with a shorter name or parameters. No idea! **More or less readable code, comments included:** ``` REPORT z. "Define a (text) and c (random) DATA: a(16), c TYPE qfranint. "A stupid data type for a random INT "This is shorter than using VALUE (saves 3 bytes) a = 'bugs in the code'. "This is slightly shorter than doing ',b TYPE i' and 'b = 99'. (saves 2 bytes) data(b) = 99. "first line has to be outside of loop due to our exit condition (saved me ~5 bytes) WRITE: / b,a. "\n xx bugs in the code WHILE b > 0. WRITE: / b,a, "\n xx bugs in the code /'Take one down and patch it around'. "This ridiculous function for random numbers... "To save some bytes, I leave ran_int_min at it's default "of 1, and set the max to 21 instead, from which I remove "17 later on, resulting in a range of [-16,4] "Compare: " ' - 17' = 5 bytes " ' ran_int_min = -16' = 18 bytes "(saves 13 bytes) CALL FUNCTION 'QF05_RANDOM_INTEGER' EXPORTING ran_int_max = 21 IMPORTING ran_int = c. "Maximum number of bugs added: 4 = 21 - 17 "Maximum number of bugs removed: -16 = 1 - 17 b = b + c - 17. IF b <= 0. b = 0. ENDIF. WRITE: / b,a,/,/ b,a. "\nxx bugs in the code\n\nxx bugs in the code ENDWHILE. ``` Thanks for the challenge! *To my boss: Please don't fire me, I'm just educating myself!* [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~245~~ 234 bytes ``` import StdEnv,Math.Random,System.Time,System._Unsafe,Text f[n,v:l]b|n>0=n<+b<+n<+b+"Take one down and patch it around\n"<+max 0v<+b+"\n"+f[v:l]b=0<+b ``` # ``` f(scan(+)99[n rem 20-16\\n<-genRandInt(toInt(accUnsafe time))])" bugs in the code\n" ``` [Try it online!](https://tio.run/##NY5PS8NAEMXvfoohp4RNSvQgVBJPeigoiImntMhkd/MHs7MlmcQW/OyumxYvj/cG5r2fHDSSM1bNgwaDPbneHO3IULB6piV@Re4270jKmrg4T6zNpuyN/vefHzRho@NSn/imqSheHoZD/UOPaU6ZqDOxqghK/NJgSYOy3wS@DY7IsoOeAUc7k9pTkAmDJ0iXy4PPoqkuZXnqL65g9FA5NOEkkUIRbbcVwagN3KXJ7f1@T1nSalpJd8Qh21VRyisfsGeOokMUQD23E/QE3GmQVmm/5H5lM2A7uWT34p7OhKaX1/A2IDd2NC6p/wA) [Answer] # C#, ~~184~~ 181 bytes My first Code Golf answer! (Based on [Java answer](https://codegolf.stackexchange.com/a/165633/80847) from @Kevin Cruijssen) ``` Func<String>c=()=>{String s="",t=" bugs in the code\n";for(int i=99;i>0;s+=i+t+i+t+"Take one down and patch it around\n"+((i-=new Random().Next(21)-4)<0?0:i)+t+"\n");return s+0+t;}; ``` [Try it online!](https://tio.run/##LY9BT8MwDIXP7a@wekpUVhXEZWQZByRODCGGxGFwCGloLTYHxS4DTfvtpaNY8uGTnp/f8zzzMYWhZ6QW1j8sYWcmWNkJq5WTzuR@65jhIcU2uR0c8ozFCfo8G2578ou1pPFo6a3SdnmYCNgWxZnYAt76lgEJpAvgYxNeqDDvMSkkAbTzucFlbbi0WEp52uLJfQSIFKCJewJHDXw68R2ggEuxp2Z0KJXCmaWwh8dREHdKV/fhW9TFuZ5d6kV9XV@hPpmNWm1SkD4RcFmXYo5mgP@ZasBXxAZWDknxX/bN6/ioZT02zbPsJhLHbaieE0q4QwrKK61Nnh3z4/AL "C# (.NET Core) – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~138 134 133 131~~ 127 bytes **-1** Thanks to Jo King (rearrange so as to use the logic `bugs-=min(bugs,randomNumber)` rather than `bugs=max(0,bugs-randomNumber)`). This allowed the force-quit using a division by zero error, saving a further **6** bytes! ``` r=n=99 t="bugs in the code\n" while 1:r+=id(r);b=n;n-=min(n,r%21-4);print b,t,1/b|b,t,"Take one down and patch it around\n",n,t ``` **[Try it online!](https://tio.run/##FcxBC8IgGAbg@37FhxBs5AhHlyX@i45ddEpK9SruGyPov1udnttT3hwzptaqgZnnjo1w232lBOIYaMk@3CC6PaZnIHWpR5N8XwftDDRG80roIethUuN50KUmMDnJUp3c56@42kegjEA@7yALT8XyEikx2Zo3@N8uIbm1Lw "Python 2 – Try It Online")** [Answer] # [C (gcc)](https://gcc.gnu.org/), 141 137 bytes I used preprocessor macros [for great justice (warning: TV Tropes)](http://tvtropes.org/pmwiki/pmwiki.php/Main/ForGreatJustice) ``` #define _(a)printf("%d bugs in the code\n"#a,i) f(i){for(i=99;_(),i;i+=rand()%21-16,i*=i>0,_(\n))_(Take one down and patch it around\n);} ``` [Try it online!](https://tio.run/##VY7BisJAEETv@YrGIHS7UdSDIDF@gexJb0IYp2dMo/ZIMtk9iN8eR2@eCh5FvbLTs7VDLmqvPTvYdJElzJpt9oWucvpmUW4ukSFn50Ud1Gjo3opGj6Mxw6k/dyAKsXFgA7ujjnJTCGUehR4@tCjVel3WSIWU8lO1RhlpvFxMF6tCJpVs50WNRyWqcW8uDkJycPhXSEW4m2gbkAimDb1yqpXPIbnhZkTxLwgTPDKA7jP7voq/h92OqEzQY4rn8AI "C (gcc) – Try It Online") [Answer] # T-SQL, 188 bytes ``` DECLARE @ INT=99,@b CHAR(18)=' bugs in the code 'a:PRINT CONCAT(@,@b,@,@b,'Take one down and patch it around ')SET @+=5-22*RAND()IF @<0SET @=0PRINT CONCAT(@,@b,' ')IF @>0GOTO a;PRINT '0'+@b ``` SQL allows returns inside string literals, so that helps. `CONCAT()` does an implicit conversion to text so I don't have to worry about `CAST` or `CONVERT`. [Answer] # JavaScript, 138 bytes ``` _=>(I=i=>`Take one down and patch it around ${l=(i>0?i:0)+` bugs in the code `} `+l+l+(i>0&&I(i+Math.random()*21-15|0)))(99).slice(55,-25) ``` ``` f= _=>(I=i=>`Take one down and patch it around ${l=(i>0?i:0)+` bugs in the code `} `+l+l+(i>0&&I(i+Math.random()*21-15|0)))(99).slice(55,-25) console.log(f()) ``` [Answer] # [QB64](https://www.qb64.org/), 134 bytes From my brother. ``` S$="bugs in the code":I=99:WHILE I>0:?I;S$:?I;S$:?"Take one down and patch it around":I=I+INT(RND*21)-15:I=-(I>0)*I:?I;S$:?:WEND:?I;S$ ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~94~~ 92 bytes ``` J99WJ%jb[K"%d bugs in the code"K"Take one down and patch it around"Kk)[JJ=JeS,Z+J-O21 16;%KZ ``` [Try it online](https://pyth.herokuapp.com/?code=J99WJ%25jb%5BK%22%25d+bugs+in+the+code%22K%22Take+one+down+and+patch+it+around%22Kk%29%5BJJ%3DJeS%2CZ%2BJ-O21+16%3B%25KZ&debug=0) --- *Previous version: 94 bytes* ``` J99WJp%jb[K"%d bugs in the code"K"Take one down and patch it around"K)[JJ=JeS,Z+J-O21 16)b;%KZ ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 61 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ;“,Ȥm46Ṛṛ⁽eɼḞF» ÇȮ“"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8»20X+_«¥©17Ç⁷®ßÇ®? 99Ç ``` A niladic link which also works as a full program. **[Try it online!](https://tio.run/##AX0Agv9qZWxsef//O@KAnCzIpG00NuG5muG5m@KBvWXJvOG4nkbCuwrDh8iu4oCcIuG4g@G4ssmg4oG8xItU4bmqyqAv4bqg4oG64bmX4biNXuG6uMaY4rGu4bmWOMK7MjBYK1/Cq8KlwqkxN8OH4oG3wq7Dn8OHwq4/Cjk5w4f//w "Jelly – Try It Online")** (output is flushed after execution is complete but it prints paragraph by paragraph) ### How? ``` ;“,Ȥm46Ṛṛ⁽eɼḞF» - Link 1, helper to construct count-text: number “,Ȥm46Ṛṛ⁽eɼḞF» - compressed string (list of characters) = " bugs in the code\n" ; - concatenate the number with that list of characters ÇȮ“"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8»20X+_«¥©17Ç⁷®ßÇ®? - Link 2, print stuff: number Ç - call the last Link (1) as a monad Ȯ - print and yield that - ...at this point that is then printed again - implicitly due to the start of a new leading - constant chain below “"ḃḲɠ⁼ċTṪʠ/Ạ⁺ṗḍ^ẸƘⱮṖ8» - compressed string (list of characters) - = "Take one down and patch it around\n" - ...once again an implicit print, same reason 20 - twenty X - random int from [1,20] + - add the left argument, the number 17 - seventeen ¥ - last two links as a dyad: « - minimum (of rand[1,20]+n and 17) _ - subtract © - copy this newNumber to the register Ç - call last Link (1) as a monad = f(newNumber) - here we get another implicit print, same reason ⁷ - a new line character - yet another implicit print, same reason ® - recall newNumber from the register ? - if... ® - ...condition: recall from register again - (i.e. if non-zero) ß - ...then: call this Link (2) as a monad - = Link 2(newNumber) Ç - ...else: call the last Link (1) as a monad - = Link 1(0) (since newNumber=0) 99Ç - Main Link: no arguments 99 - yep, you guessed it, ninety nine Ç - call the last Link (2) as a monad ``` [Answer] # Perl, 132 bytes ``` $c=" bugs in the code ";for($i=99;$i>0;$i+=~~rand(21)-16){print$t.$/,($t=$i.$c)x2,"Take one down and patch it around "}print"0$c "x2 ``` [Answer] ## VBA: ~~225~~ 233 Bytes ``` Sub b() For c = 99 To 0 Step -1 GoSub d GoSub d Debug.Print "Take one down and patch it around" c = c + 5 - Int(rnd() * 20) If c < 0 Then c = 0 GoSub d Debug.Print Next c Exit Sub d: Debug.Print c & " bugs in the code" Return End Sub ``` **{EDIT}** *Added the missing `rnd()*`* **Notes:** Uses `GoSub` to print the triplicated line, because it's slightly shorter than assigning the line to a variable and `Debug.Print`ing it. `Debug.Print` without any arguments prints an empty line (no need for a Null or an empty string) A `WorksheetFunction.Max` line would be too long, so I used an "if less than" to prevent negatives.   ## With indentation and comments ``` Sub b() For c = 99 To 0 Step -1 GoSub d '"# bugs in the code" GoSub d '"# bugs in the code" Debug.Print "Take one down and patch it around" c = c + 5 - Int(rnd() * 20) If c < 0 Then c = 0 'Non-negative GoSub d '"# bugs in the code" Debug.Print Next c Exit Sub d: 'This is our GoSub bit Debug.Print c & " bugs in the code" Return End Sub ``` [Answer] # Ruby: 149 bytes ``` n=99;f=" bugs in the code\n";loop{puts"#{n}#{f}"*2+"Take one down and patch it around\n";(n+=rand -16..4)>0?puts("#{n}#{f}\n"):break};puts"0#{f}\n"*2 ``` Should work in pretty much any version of Ruby >= 1.8 I think it might be possible to optimise the strings a bit more, but in general I'm pretty pleased with it - in particular the combo assignment/comparison/break statement and the abuse of optional brackets. Note: the output technically has two trailing newlines; if that needs to be accounted for then it goes up by 4 characters. [Answer] # [Zsh](https://www.zsh.org/), 133 bytes ``` b="%d bugs in the code ";for ((n=99;n;)){printf $b$b"Take one down and patch it around $b " n n n-=RANDOM%21-4,n=n\>0\?n:0};printf $b ``` [Try it online!](https://tio.run/##PcxBC4IwGAbg@37Fy1BQSLDoYmNF0LWC6Ohlc9NJ8E3mJCj67Ysu8dyf1@xS0pLnBnoZZoyE6Cw6byzjovcBRUGyaQSJsnxPYaTYI9OZ5nf1sPBkYfyToMhgUrFzGCNU8AsZlmnGQT@VvB0vp@s536yr7Yoktfu6PdCu/oh/mdIX "Zsh – Try It Online") --- This takes advantage of a few zsh features. * the [alternative loop form](http://zsh.sourceforge.net/Doc/Release/Shell-Grammar.html#Alternate-Forms-For-Complex-Commands): `while list; do list; done` can be written as `while list {list}` * If a format specifier in `printf` is numeric, the corresponding argument is evaluated as an arithmetic expression. So: + we get the value of `n` for free without using a `$` + `n -= RANDOM % 21 - 4, n = n > 0 ? n : 0` is again evaluated without having to use `$((...))`, `$[...]` or similar. The `>` and `?` had to be escaped. + The `printf $b` at the end evaluates an empty argument as 0 for `%d`. * Word splitting on parameter expansion is off by default, so I do not have to quote `$b` anywhere. + This allows allows me to write `$b$b"Take..."` instead of `"$b${b}Take..."`. --- * Saved a few bytes by using actual newlines instead of `\n`, and `for((n=99;n;))` instead of `n=99;while ((n))`. ]
[Question] [ Similar to our threads for language-specific golfing tips: what are general tricks to shorten regular expressions? I can see three uses of regex when it comes to golfing: classic regex golf ("here is a list that should match, and here is a list that should fail"), using regex to solve [computational problems](https://codegolf.stackexchange.com/a/36532/8478) and regular expressions used as parts of larger golfed code. Feel free to post tips addressing any or all of these. If your tip is limited to one or more flavours, please state these flavours at the top. As usual, please stick to one tip (or family of very closely related tips) per answer, so that the most useful tips can rise to the top via voting. [Answer] # When not to escape These rules apply to most flavours, if not all: * `]` doesn't need escaping when unmatched. * `{` and `}` don't need escaping when they are not part of a repetition, e.g. `{a}` matches `{a}` literally. Even if you want to match something like `{2}`, you only need to escape one of them, e.g. `{2\}`. In character classes: * `]` doesn't need escaping when it's the first character in a character set, e.g. `[]abc]` matches one of `]abc`, or when it's the second character after a `^`, e.g. `[^]]` matches anything but `]`. (Notable exception: ECMAScript flavour!) * `[` doesn't need escaping at all. Together with the above tip, this means you can match both brackets with the horribly counter-intuitive character class `[][]`. * `^` doesn't need escaping when it's *not* the first character in a character set, e.g. `[ab^c]`. * `-` doesn't need escaping when it's either the first (second after a `^`) or last character in a character set, e.g. `[-abc]`, `[^-abc]` or `[abc-]`. * No other characters need escaping inside a character class, even if they are meta characters outside of character classes (except for backslash `\` itself). Also, in some flavours `^` and `$` are matched literally when they are not at the start or end of the regex respectively. (Thanks to @MartinBüttner for filling in a few details) [Answer] A simple regular expression to match all printable characters in the [**ASCII**](http://www.asciitable.com/) table. ``` [ -~] ``` [Answer] # Know your regex flavours There are a surprising amount of people who think that regular expressions are essentially language agnostic. However, there are actually quite substantial differences between flavours, and especially for code golf it's good to know a few of them, and their interesting features, so you can pick the best for each task. Here is an overview over several important flavours and what sets them apart from others. (This list can't really be complete, but let me know if I missed something really glaring.) ## Perl and PCRE I'm throwing these into a single pot, as I'm not too familiar with the Perl flavour and they're *mostly* equivalent (PCRE is for Perl-Compatible Regular Expressions after all). The main advantage of the Perl flavour is that you can actually call Perl code from inside the regex and substitution. * [Recursion/subroutines](https://codegolf.stackexchange.com/a/47454/8478). Probably the most important feature for golfing (which only exists in a couple of flavours). * Conditional patterns `(?(group)yes|no)`. * Supports change of case in the replacement string with `\l`, `\u`, `\L` and `\U`. * PCRE allows alternation in lookbehinds, where each alternative can have a different (but fixed) length. (Most flavours, including Perl require lookbehinds to have an overall fixed length.) * `\G` to anchor a match to the end of the previous match. * `\K` [to reset the beginning of the match](https://codegolf.stackexchange.com/a/47517/8478) * PCRE supports both [Unicode character properties and scripts](http://php.net/manual/en/regexp.reference.unicode.php). * `\Q...\E` to escape longer runs of characters. Useful when you're trying to match a string that contains many meta-characters. ## .NET This is probably the most powerful flavour, with only very few shortcomings. * Supports arbitrary-length lookbehinds, [which are matched right-to-left](https://stackoverflow.com/a/13425789/1633117). * Has the unique concept of [balancing groups](https://stackoverflow.com/a/17004406/1633117) - originally designed to match strings with balanced parentheses, they can be used to [perform arithmetic](https://codegolf.stackexchange.com/a/39988/8478) and [match 2D patterns](https://codegolf.stackexchange.com/a/45489/8478). * Also supports conditional patterns. * Has concise [syntax for character class difference](https://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx#Anchor_13): `[\w-[aeiou]]` * The normal character classes like `\d` are Unicode aware. * Supports Unicode [categories and blocks](https://msdn.microsoft.com/en-us/library/20bw873z(v=vs.110).aspx#CategoryOrBlock). One important shortcoming in terms of golfing is that it doesn't support possessive quantifiers like some other flavours. Instead of `.?+` you'll have to write `(?>.?)`. ## Java * [Due to a bug](https://stackoverflow.com/a/3664883/1633117) (see Appendix) Java supports a limited type of variable-length lookbehind: you can lookbehind all the way to the beginning of the string with `.*` from where you can now start a lookahead, like `(?<=(?=lookahead).*)`. * Supports union and intersection of character classes. * Has the most extensive support for Unicode, with character classes for ["Unicode scripts, blocks, categories and binary properties"](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html). * `\Q...\E` as in Perl/PCRE. ## Ruby In recent versions, this flavour is similarly powerful as PCRE, including the support for subroutine calls. Like Java, it also supports union and intersection of character classes. One special feature is the built-in character class for hex digits: `\h` (and the negated `\H`). The most useful feature for golfing though is how Ruby handles quantifiers. Most notably, it's possible to nest quantifiers without parentheses. `.{5,7}+` works and so does `.{3}?`. Also, as opposed to most other flavours, if the lower bound on a quantifier is `0` it can be omitted, e.g. `.{,5}` is equivalent to `.{0,5}`. As for subroutines, the major difference between PCRE's subroutines and Ruby's subroutines, is that Ruby's syntax is a byte longer `(?n)` vs `\g<n>`, but Ruby's subroutines can be used for capturing, whereas PCRE resets captures after a subroutine finishes. Finally, Ruby has different semantics for line-related modifiers than most other flavours. The modifier that's usually called `m` in other flavours is *always* on in Ruby. So `^` and `$` always match the beginning and end of a *line* not just the beginning and end of the string. This can save you a byte if you need this behaviour, but it will cost you extra bytes if you don't, because you'll have to replace `^` and `$` with `\A` and `\z`, respectively. In addition to that, the modifier that is usually called `s` (which makes `.` match linefeeds) is called `m` in Ruby instead. This doesn't affect byte counts, but should be kept in mind to avoid confusion. ## Python Python has a solid flavour, but I'm not aware of any particularly useful features that you wouldn't find anywhere else. **However**, there [is the **regex** module](https://pypi.python.org/pypi/regex), which is intended to replace the `re` module at some point, and which contains a lot of interesting features. In addition to adding support for recursion, variable-length lookbehinds and character class combination operators, it also has the unique feature of **fuzzy matching**. In essence you can specify a number of errors (insertions, deletions, substitutions) which are allowed, and the engine will also give you approximate matches. ## ECMAScript The ECMAScript flavour is very limited, and hence rarely very useful for golfing. The only thing it's got going for it is the [negated empty character class](https://codegolf.stackexchange.com/a/47490/8478) `[^]` to match any character as well as the unconditionally failing empty character class `[]` (as opposed to the usual `(?!)`). Unfortunately, the flavour does not have any features which makes the latter useful for normal problems. ## Lua Lua has its own fairly unique flavour, which is quite limited (e.g. you can't even quantify groups) but does come with a handful of useful and interesting features. * It's got a large number of shorthands for [built-in character classes](http://www.lua.org/pil/20.2.html), including punctuation, upper/lower case characters and hex digits. * With `%b` it supports a very compact syntax to match balanced strings. E.g. `%b()` matches a `(` and then everything up to a matching `)` (correctly skipping inner matched pairs). `(` and `)` can be any two characters here. ## Boost [Boost's regex flavour](http://www.boost.org/doc/libs/1_57_0/libs/regex/doc/html/boost_regex/syntax/perl_syntax.html) is essentially Perl's. However, it has some nice new features for regex substitution, including [case changes and **conditionals**](http://www.boost.org/doc/libs/1_57_0/libs/regex/doc/html/boost_regex/format/boost_format_syntax.html). The latter is unique to Boost as far as I'm aware. [Answer] # Know your character classes Most regex flavours have predefined character classes. For example, `\d` matches a decimal digit, which is three bytes shorter than `[0-9]`. Yes, they might be slightly different as `\d` may also match Unicode digits as well in some flavours, but for most challenges this won't make a difference. Here are some character classes found in most regex flavours: ``` \d Match a decimal digit character \s Match a whitespace character \w Match a word character (typically [a-zA-Z0-9_]) ``` In addition, we also have: ``` \D \S \W ``` which are negated versions of the above. Be sure to check your flavour for any additional escape codes it might have. For example, PCRE has [**`\R`**](https://stackoverflow.com/questions/18988536/php-regex-how-to-match-r-and-n-without-using-r-n/18992691#18992691) for newlines and [Lua](http://www.lua.org/pil/20.2.html) even has classes such as lowercase and uppercase characters. (Thanks to @HamZa and @MartinBüttner for pointing these out) [Answer] # Don't bother with non-capturing groups (unless...) This tip applies to (at least) all popular Perl-inspired flavours. This may be obvious, but (when not golfing) it's good practice to use non-capturing groups `(?:...)` whenever possible. These two extra characters `?:` are wasteful when golfing though, so just use capturing groups, even if you're not going to backreference them. There's one (rare) exception though: if you happen to backreference group `10` at least 3 times, you can actually save bytes by turning an earlier group into a non-capturing group, such that all those `\10`s become `\9`s. (Similar tricks apply, if you use group `11` at least 5 times and so on.) [Answer] # Recursion for pattern reuse A handful of flavours support recursion ([to my knowledge](http://www.regular-expressions.info/subroutine.html), Perl, PCRE and Ruby). Even when you're not trying to solve recursive problems, this feature can save a *lot* of bytes in more complicated patterns. There is no need to make the call to another (named or numbered) group inside that group itself. If you have a certain pattern that appears several times in your regex, just group it and refer to it outside that group. This is no different from a subroutine call in normal programming languages. So instead of ``` ...someComplexPatternHere...someComplexPatternHere...someComplexPatternHere... ``` in Perl/PCRE you could do: ``` ...(someComplexPatternHere)...(?1)...(?1)... ``` or in Ruby: ``` ...(someComplexPatternHere)...\g<1>...\g<1>... ``` provided that is the first group (of course, you can use any number in the recursive call). Note that this is *not* the same as a backreference (`\1`). Backreferences match the exact same string that the group matched last time. These subroutine calls actually evaluate the pattern again. As an example for `someComplexPatternHere` take a lengthy character class: ``` a[0_B!$]b[0_B!$]c[0_B!$]d ``` This would match something like ``` aBb0c!d ``` Note that you cannot use backreferences here while preserving the behaviour. A backreference would fail on the above string, because `B` and `0` and `!` are not the same. However, with subroutine calls, the pattern is actually reevaluated. The above pattern is completely equivalent to ``` a([0_B!$])b(?1)c(?1)d ``` ### Capturing in subroutine calls One note of caution for Perl and PCRE: if group `1` in the above examples contains further groups, then the subroutine calls will not remember their captures. Consider this example: ``` (\w(\d):)\2 (?1)\2 (?1)\2 ``` This will *not* match ``` x1:1 y2:2 z3:3 ``` because after the subroutine calls return, the new capture of group `2` is discarded. Instead, this pattern would match this string: ``` x1:1 y2:1 z3:1 ``` This is different from Ruby, where subroutine calls *do* retain their captures, so the equivalent Ruby regex `(\w(\d):)\2 \g<1>\2 \g<1>\2` would match the first of the examples above. [Answer] # Causing a match to fail When using regex to solve computational problems or match highly non-regular languages, it is sometimes necessary to make a branch of the pattern fail regardless of where you are in the string. The naive approach is to use an empty negative lookahead: ``` (?!) ``` The contents (the empty pattern) always matches, so the negative lookahead always fails. But more often than not, there is a much simpler option: just use a character you know will never appear in the input. E.g. if you know your input will always consist only of digits, you can simply use ``` ! ``` or any other non-digit, non-meta character to cause failure. Even if your input could potentially contain any substrings whatsoever, there are shorter ways than `(?!)`. Any flavour which allows anchors to appear within a pattern as opposed to the end, could use either of the following 2-character solutions: ``` a^ $a ``` Note however that some flavours will treat `^` and `$` as literal characters in these positions, because they obviously don't actually make sense as anchors. In the ECMAScript flavour there is also the rather elegant 2-character solution ``` [] ``` This is an empty character class, which tries to make sure that the next characters is one of those in the class - but there are no characters in the class, so this always fails. Note that this won't work in any other flavour, because character classes can't usually be empty. [Answer] # Optimize you OR's Whenever you have 3 or more alternatives in your RegEx: ``` /aliceblue|antiquewhite|aquamarine|azure/ ``` Check to see if there's a common start: ``` /a(liceblue|ntiquewhite|quamarine|zure)/ ``` And maybe even a common ending? ``` /a(liceblu|ntiquewhit|quamarin|zur)e/ ``` *Note: 3 is just the start and would account for the same length, 4+ would make a difference* --- But what if not all of them have a common prefix? (whitespace only added for clarity) ``` /aliceblue|antiquewhite|aqua|aquamarine|azure |beige|bisque|black|blanchedalmond|blue|blueviolet|brown|burlywood |cadetblue|chartreuse|chocolate|coral|cornflowerblue|cornsilk|crimson|cyan/ ``` Group them, as long as the 3+ rule makes sense: ``` /a(liceblue|ntiquewhite|qua|quamarine|zure) |b(eige|isque|lack|lanchedalmond|lue|lueviolet|rown|urlywood) |c(adetblue|hartreuse|hocolate|oral|ornflowerblue|ornsilk|rimson|yan)/ ``` Or even *generalise* if the entropy satisfies your usecase: ``` /\w(liceblue|ntiquewhite|qua|quamarine|zure |eige|isque|lack|lanchedalmond|lue|lueviolet|rown|urlywood |adetblue|hartreuse|hocolate|oral|ornflowerblue|ornsilk|rimson|yan)/ ``` ^ in this case we're sure we don't get any `clue` or `crown` `slack` `Ryan` This *"according to some tests"* also improves performance, as it provides an *anchor* to start at. [Answer] This one is fairly simple, but worth stating: If you find yourself repeating the character class `[a-zA-Z]` you can probably just use `[a-z]` and append the `i` (case-**i**nsensitive modifier) to your regex. For example, in Ruby, the following two regexes are equivalent: `/[a-zA-Z]+\d{3}[a-zA-Z]+/` `/[a-z]+\d{3}[a-z]/i` - 7 bytes shorter For that matter, the other modifiers can shorten your total length as well. Instead of doing this: `/(.|\n)/` which matches ANY character (because dot doesn't match newline), use the **s**ingle-line modifier `s`, which makes dot match newlines. `/./s` - 3 bytes shorter --- In Ruby, there are a ton of built-in Character Classes for regex. See [this page](http://ruby-doc.org//core-2.1.1/Regexp.html) and search for "Character Properties". A great example is the "Currency Symbol". According to [Wikipedia](http://en.wikipedia.org/wiki/Currency_symbol) there are a ton of possible currency symbols, and to put them in a character class would be very expensive (`[$฿¢₡Ð₫€.....`]) whereas you can match any of them in 6 bytes: `\p{Sc}` [Answer] # `\K` instead of positive lookbehind PCRE and Perl support the escape sequence `\K`, which resets the beginning of the match. That is `ab\Kcd` will require your input string to contain `abcd` but the reported match will only be `cd`. If you are using a positive lookbehind at the start of your pattern (which is probably the most likely place), then in most cases, you can use `\K` instead and save 3 bytes: ``` (?<=abc)def abc\Kdef ``` This is equivalent for *most* purposes, but not entirely. The differences bring both advantages and disadvantages with them: * Upside: PCRE and Perl don't support arbitrary-length lookbehinds (only .NET does). That is, you can't do something like `(?<=ab*)`. But with `\K` you can put any sort of pattern in front of it! So `ab*\K` works. This actually makes this technique vastly more powerful in the cases where it's applicable. * Upside: Lookarounds don't backtrack. This is relevant if you want to capture something in the lookbehind to backreference later, but there are several possible captures which all lead to valid matches. In this case, the regex engine would only ever try one of those possibilities. When using `\K` that part of the regex is being backtracked like everything else. * Downside: As you probably know, several matches of a regex cannot overlap. Often, lookarounds are used to partially work around this limitation, since the lookahead can validate a portion of the string that was already consumed by an earlier match. So if you wanted to match all the characters that *followed* `ab` you might use `(?<=ab).`. Given the input ``` ababc ``` this would match the second `a` and the `c`. This *cannot* be reproduced with `\K`. If you used `ab\K.`, you would only get the first match, because now the `ab` is not in a lookaround. [Answer] # A simple language parser You can build a very simple parser with an RE like `\d+|\w+|".*?"|\n|\S`. The tokens you need to match are separated with the RE 'or' character. Each time the RE engine tries to match at the current position in the text, it will try the first pattern, then the second, etc. If it fails (on a space character here for example), it moves on and tries the matches again. Order is important. If we placed the `\S` term before the `\d+` term, the `\S` would match first on any non-space character which would break our parser. The `".*?"` string matcher uses a non-greedy modifier so we only match one string at a time. If your RE doesn't have non-greedy functions, you can use `"[^"]*"` which is equivalent. ### Python Example: ``` text = 'd="dogfinder"\nx=sum(ord(c)*872 for c in "fish"+d[3:])' pat = r'\d+|\w+|".*?"|\n|\S' print re.findall(pat, text) ['d', '=', '"dogfinder"', '\n', 'x', '=', 'sum', '(', 'ord', '(', 'c', ')', '*', '872', 'for', 'c', 'in', '"fish"', '+', 'd', '[', '3', ':', ']', ')'] ``` ### Golfed Python Example: ``` # assume we have language text in A, and a token processing function P map(P,findall(r'\d+|\w+|".*?"|\n|\S',A)) ``` You can adjust the patterns and their order for the language you need to match. This technique works well for JSON, basic HTML, and numeric expressions. It has been used successfully many times with Python 2, but should be general enough to work in other environments. [Answer] # Capturing groups hold the last value matched `(REGEX)*` will hold in capturing group 1 the last match of `REGEX`. `(REGEX)` can be combined with any such repeaters. For getting the last character of a string, there is the straightforward 5-byter ``` .*(.) ``` which captures the last character in capturing group 1. Another byte can be saved by noting the point in the title of this post, giving the 4-byter ``` (.)* ``` Another example, getting the penultimate character ``` .*(.). # 6 bytes (.)*. # 5 bytes ``` [Answer] ## Optional expressions It is sometimes useful to remember that ``` (abc)? ``` is *mostly* the same as ``` (abc|) ``` There is a small difference though: in the first case, the group either captures `abc` or doesn't capture at all. The latter case would make a backreference fail unconditionally. In the second expression, the group will either capture `abc` or an empty string, where the latter case would make a backreference *match* unconditionally. To emulate the latter behaviour with `?` you'd need to surround everything in another group which would cost two bytes: ``` ((abc)?) ``` The version using `|` is also useful when you want to wrap the expression in some other form of group anyway and don't care about the capturing: ``` (?=(abc)?) (?=abc|) (?>(abc)?) (?>abc|) ``` Finally, this trick can also be applied to ungreedy `?` where it saves a byte even in its raw form (and consequently 3 bytes when combined with other forms of groups): ``` (abc)?? (|abc) ``` [Answer] # Matching any character **Update**: Since the [ECMAScript 2018 specification](https://262.ecma-international.org/9.0/), the flavor has the classic dotAll flag that matches all characters, so the following quoted part is now only true if your browser or system uses a very old version that predates this 2018 update, which would be unusual: > > The ECMAScript flavour is lacking the `s` modifiers which makes `.` > match any character (including newlines). This means there is no > single-character solution to matching completely arbitrary characters. > > > The following is the unedited rest of this older answer: The standard solution in other flavours (when one doesn't want to use `s` for some reason) is `[\s\S]`. However, ECMAScript is the only flavour (to my knowledge) which supports empty character classes, and hence has a much shorter alternative: `[^]`. This is a negated empty character class - that is, it matches any character whatsoever. Even for other flavours, we can learn from this technique: if we don't want to use `s` (e.g. because we still need to usual meaning of `.` in other places), there can still be a shorter way to match both newline and printable characters, provided there is some character we know doesn't appear in the input. Say, we're processing numbers delimited by newlines. Then we can match any character with `[^!]`, since we know that `!` won't ever be part of the string. This saves two bytes over the naive `[\s\S]` or `[\d\n]`. [Answer] # Forget a captured group after a subexpression (PCRE) For this regex: ``` ^((a)(?=\2))(?!\2) ``` If you want to clear the \2 after group 1, you can use recursion: ``` ^((a)(?=\2)){0}(?1)(?!\2) ``` It will match `aa` while the previous one won't. Sometimes you can also use `??` or even `?` in place of `{0}`. This might be useful if you used recursions a lot, and some of the backreferences or conditional groups appeared in different places in your regex. Also note that atomic groups are assumed for recursions in PCRE. So this won't match a single letter `a`: ``` ^(a?){0}(?1)a ``` I didn't try it in other flavors yet. For lookaheads, you can also use double negatives for this purpose: ``` ^(?!(?!(a)(?=\1))).(?!\1) ``` [Answer] # Use atomic groups and possessive quantifiers I found atomic groups (`(?>...)`) and possessive quantifiers (`?+`, `*+`, `++`, `{m,n}+`) sometimes very useful for golfing. It matches a string and disallows backtracking later. So it will only match the first matchable string which is found by the regex engine. For example: To match a string with odd number of `a`'s at the beginning, which is not followed by more `a`'s, you can use: ``` ^(aa)*+a ^(?>(aa)*)a ``` This allows you to use things like `.*` freely, and if there is an obvious match, there won't be another possibility matching too many or too few characters, which may break your pattern. In .NET regex (which doesn't have possessive quantifiers), you can use this to pop group 1 the greatest multiple of 3 (with maximum 30) times (not golfed very well): ``` (?>((?<-1>){3}|){10}) ``` In flavors that have neither of the two features, such as ECMAScript, you could usually use lookahead for this, but may not worth it unless you already need lookahead anyway: ``` (?=(atomic group))\1 ``` [Answer] # Multiple lookaheads that always match (.NET) If you have 3 or more lookahead constructs that always match (to capture subexpressions), or there is a quantifier on a lookahead followed by something else, so they should be in a not necessarily captured group: ``` (?=a)(?=b)(?=c) ((?=a)b){...} ``` These are shorter: ``` (?(?(?(a)b)c)) (?(a)b){...} ``` where `a` should not be the name of a captured group. You can't use `|` to mean the usual thing in `b` and `c` without adding another pair of parentheses. Unfortunately, balancing groups in the conditionals seemed buggy, making it useless in many cases. ]
[Question] [ # Background There's a common riddle that goes something like this: > > A snail is at the bottom of a 30 foot well. Every day the snail is able to climb up 3 feet. At night when they sleep, they slide back down 2 feet. How many days does it take for the snail to get out of the well? > > > The intuitive answer is > > 30 days, because the snail climbs at 1 foot per day for 30 days to reach the top, > > > but actually the answer is > > 28 days, because once the snail is 27 feet in the air (after 27 days), they will simply climb the remaining 3 feet to the top on the 28th day. > > > # Challenge This challenge generalizes this riddle. Given three positive integers as input, representing the total height, the climb height, and the fall height, return the number of days it will take to climb out of the well. If the snail cannot climb out of the well, you may return 0, return a falsy value, or throw an exception. You may also write code that will halt if and only if a solution exists. If you wish, you may take the fall height as a negative integer. # Test Cases ``` (30, 3, 2) -> 28 (84, 17, 15) -> 35 (79, 15, 9) -> 12 (29, 17, 4) -> 2 (13, 18, 8) -> 1 ( 5, 5, 10) -> 1 ( 7, 7, 7) -> 1 (69, 3, 8) -> None (81, 14, 14) -> None ``` # Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins. [Answer] # [Gray Snail](http://www.ostracodfiles.com/pumpkin/Gray%20Snail%20Compiler.html), 1206 bytes for numeric I/O, 149 bytes for unary I/O For fun. Composition of first program: * 451 bytes, converting number into dots * 121 bytes, core function (a separated version is written below) * 634 bytes, converting dots into number Take numeric input and output. Input is `A`, `B`, `C` respectively. Compared to other (near) `O(1)` answer, the code has a complexity of `O(n)`. But for large number, it may eat up your memory first. Hang if no solution is found. ``` INPUT p POP Z r .! f POP Z o . q POP Z p [p] GOTO [Z] 0 POP Z n . GOTO w 1 POP Z n .. GOTO w 2 POP Z n ... GOTO w 3 POP Z n .... GOTO w 4 POP Z n ..... GOTO w 5 POP Z n ...... GOTO w 6 POP Z n ....... GOTO w 7 POP Z n ........ GOTO w 8 POP Z n ......... GOTO w 9 POP Z n .......... GOTO w w POP Z o .[o][o][o][o][o][o][o][o][o][o][n] GOTO [r] [p] GOTO q ! POP Z A .[o] INPUT p POP Z r .@ GOTO f @ POP Z B .[o] INPUT p POP Z r .# GOTO f # POP Z C .[o] POP H N .[B] U POP Z A [A] POP Z B [B] GOTO D [A] GOTO $ [B] GOTO U $ POP Z A .[A][C] POP Z H ..[H] POP Z B .[N] GOTO U D POP Z r . POP Z M . POP Z N ........... POP Z z .[N] POP Z V .[H] + GOTO l[V] [H] POP Z H [H] POP Z z [z] GOTO ( [z] GOTO + ( GOTO ) [H] POP Z z .[N] POP Z M ..[M] POP Z V .[H] GOTO + ) POP Z r .0[r] POP Z M ..[M] POP Z H .[M] POP Z M . POP Z V .[H] POP Z z .[N] GOTO + l POP Z r .0[r] GOTO - l. POP Z r .1[r] GOTO - l.. POP Z r .2[r] GOTO - l... POP Z r .3[r] GOTO - l.... POP Z r .4[r] GOTO - l..... POP Z r .5[r] GOTO - l...... POP Z r .6[r] GOTO - l....... POP Z r .7[r] GOTO - l........ POP Z r .8[r] GOTO - l......... POP Z r .9[r] GOTO - - GOTO / [M] POP Z H .[M] POP Z M . POP Z V .[H] POP Z z .[N] GOTO + / OUTPUT [r] ``` `f` is a (maybe) recursive function to convert integers into dots. Argument is saved in `[p]` and output in `[o]`. `U` is a function testing `S1>=S2`, storing parameter in `B, A` while saving `A-B` into `A`. Code starting from `D` is a stub converting dots into numbers. The underlying principle is the same with my C answer (ripping off falsy output for impossible solutions). ## Standalone version, 149 ~~156~~ ~~157~~ ~~167~~ ~~170~~ ~~230~~ bytes, only support unary I/O Input needs to be dots, e.g. `..........` for `10`. ``` INPUT A INPUT B INPUT C POP N H . GOTO U $ POP N A .[A][C] POP Z H ..[H] U POP Z A [A] POP Z N ..[N] GOTO D [A] GOTO $ .[B] [N] GOTO U D OUTPUT .[H] ``` `U` calculates `A=A-B`, and jumps to `D` when `A<=0`. Otherwise `$` assigns `A+C` to `A` and call `U`. Hang if no solution is found. **Tricks:** abuse the "compiler"'s ability to interpret empty string. You can rip off conditions in `GOTO` statement to make unconditioned jumps and the same trick works for `POP`. **Remark:** I may golf it more by 3 bytes but by doing so, mine and WheatWizard's answer would have the exact same logic. The result is probably the shortest GraySnail solution and I'm trying to prove it. [Answer] > > **Note:** the byte count is being questioned by Martin Ender in the comments. It seems there is no clear consensus about what to do with named, recursive lambda expressions in C# answers. So I have asked [a question in Meta](https://codegolf.meta.stackexchange.com/q/13225/70347) about it. > > > # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 32 31 bytes ``` f=(a,b,c)=>a>b?1+f(a-b+c,b,c):1 ``` [Try it online!](https://tio.run/##jc/Na8MgFADwe/6KdzTUfpisbbIs6WFspw4KPfQwdjDOBCHVonZ0lP7tmbGlH7BDHvqQx/s9lZkhU5q34II11BhYaVVrug26ytHnLoylVjD4UeIbPqiQyFgtZP35BVTXJrz23UQX619j@Xb0vpfsRUiL4SEVUEEOct80WdBWOaK4xCzMC1qUCzKoEB2WA@Zrz6TNgv8mvyppVMNHGy0sXwrJUYXiCYYYQxSGmW8djyFK@uLkCQOZuz09c4fjaV88TzuIIb1c7TCJ@mLn3CKTu2eTvnaW@i8nd/btwPjOCiWvM07@dGr/AA "C# (.NET Core) – Try It Online") A recursive approach. If the snail cannot escape, it ends with the following message: `Process is terminating due to StackOverflowException.` * 1 byte saved thanks to LiefdeWen! [Answer] # GRAY SNAIL, ~~219~~ ~~206~~ ~~169~~ ~~167~~ ~~159~~ ~~156~~ 146 bytes (unary IO) ``` INPUT a INPUT u INPUT d POP U c GOTO 1 3 POP f a [a][d] POP U c ..[c] 1 GOTO 2 [a] GOTO 3 [U] [u] POP f U ..[U] POP f a [a] GOTO 1 2 OUTPUT [c]. ``` I think I can golf this down a bit. [Answer] ## JavaScript (ES6), ~~31~~ ~~28~~ 27 bytes *Saved a few bytes thanks to @Arnauld* I hadn't realized we could fail with an exception. Pretty sure this is optimal: ``` u=>d=>g=h=>h>u?1+g(h-u+d):1 ``` Assign to a variable with e.g. `f=`, then call like `f(climb)(fall)(height)`. Throws `InternalError: too much recursion` if the climb is impossible. --- ## JavaScript (ES6), 38 bytes ``` f=(h,u,d=0)=>h>u?u>0?1+f(h-u,u-d):+f:1 ``` A recursive function that returns the number of days, or `NaN` for never. ### Test cases ``` let f=(h,u,d=0)=>h>u?u>0?1+f(h-u,u-d):+f:1; [ [30, 3, 2], [84, 17, 15], [79, 15, 9], [29, 17, 4], [13, 18, 8], [ 5, 5, 10], [ 7, 7, 7], [69, 3, 8], [81, 14, 14] ].map(x => console.log(x + '', '->', f.apply(null, x))) ``` [Answer] # Excel, ~~51~~ 46 bytes -1 byte thanks to @[Scarabee](https://codegolf.stackexchange.com/users/63618/scarabee). -4 because INT(x) = FLOOR(x,1) ``` =IF(B1<A1,IF(C1<B1,-INT((B1-A1)/(B1-C1)-1)),1) ``` Input taken from Cells A1, B1 and C1 respectively. Returns `FALSE` for invalid scenarios. [Answer] # C (gcc), 39 ~~43~~ ~~44~~ ~~46~~ ~~47~~ ~~58~~ ~~60~~ bytes Only on 32-bit GCC and all optimizaitons turned off. ``` f(a,b,c){a=a>b?b>c?1+f(a-b+c,b,c):0:1;} ``` Return 0 when solution is impossible. A modified version of original recursive solution. Inspired by @Jonah J solution and @CarlosAlejo C# solution. *I'll update the expanded version later (after I finish my Grey Snail answer).* [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), 35 bytes ``` (a,b,c)->b<a?c<b?(a+~c)/(b-c)+1:0:1 ``` [Try it online!](https://tio.run/##bVHfa8IwEH7fX3EUhASja6rO3/N5yCZMYQ/Sh7RGratVmigM6f51d0njprLA5S757r47vtuIo6jt9jLbLD7P@0OUJjHEqVAKXkWSwekBIMm0zJciljDNRJK@ZLO1/JBpCicDYXayjYiJBDN3ZO@Y9qHAYkeptNDojrtkAVskJlOdJ9lqHoLIV4raPnDPr8wThnAmgkUsprXnaCBG8SAaEVH9jukjiWoxrfKe3@NnsKdveXCAeYjcWiqtkKBkN@fU8BlAAy1gEHQK9od0mgx4G63FoNG6Rtrd8heMD66RoFvWANbeABxb8A4CaPwaAMODxv17wNA4uwGeum5ipPJvBuaY2SzNL9x/USqw3OXEqmA16JVK0F8hzIZyqQ6pRnWszPVyjSZv7ofMFsz5JQhC2nel0y@l5ba@O@j6Hleol8Rby2S1xiaVYMFA7aVcuHgp0tSGdXi33ewDSEXRSuY57v@6MTfdxQ@HFmiEI/AmY68H3ttkBpMxEK/qkKpHPTek0aJ4KM4/ "Java (OpenJDK 8) – Try It Online") Math wins! ### Credits * -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen) [Answer] # [Python 2](https://docs.python.org/2/), 37 bytes ``` f=lambda x,y,z:x-y<1or 1+f(x-y+z,y,z) ``` [Try it online!](https://tio.run/##TY3dCoJAEEav9Sk@ulppgtaf0shX6AWyCysloVZRA/XlbWYtCOZjd86cnW3G/lEbf57L9Jm/rvccA400HYbNeNR1C70uFd/Xk1BvLhnd8q5AZbiad6@8g@sMhJEwEXLTIbWC6zRtZXqsMpOZFeFfcZ22EI83260/lynBjlLR5rMKtoSA4HPFHkHFIUHvORHzSMg@WTrI6Qvxk8UBuxZo3qBjBhztkRKbo7dLC3G/kX7H7@VT0U@1KRjFmkfhEosuHw "Python 2 – Try It Online") Finally got my recursive version below my standard calculation (I was passing a count to my function instead of adding one before calling it). # [Python 2](https://docs.python.org/2/), 43 ~~46~~ bytes ``` #43 bytes lambda x,y,z:y/x>0 or[1-(x-y)/(z-y),0][z/y] #46 bytes lambda x,y,z:y/x and 1or[1-(x-y)/(z-y),0][z/y] ``` [Try it online!](https://tio.run/##TY3dioMwEEav9Sk@vEpgisb@2YJ9hH0B9cLdVVrYjaIWjC/vzsQWFuZLmDMnmd5N986ma5uX60/9@/ldYyZHy9XF8y1BNxRmp@ad07Fa@KSkKpbYVWvbDfiqxwYPy9U/J6WvYTATHGEh1HZE7oUw6IeHnRCVtrQR4b8SBkMjXqv8Tv12mRL8KBdtLdQ@IewJKVemCSo7EMyZc2R@FHK@bB3kToWkl80Bux4Y/sFkDDhGkxKbY5KthbivSH/i97JU9I/ONowyw6PDFo@qPw "Python 2 – Try It Online") Shaved 3 bytes by trading "\_\_ and 1" for "\_\_>0". Using boolean trickery, essentially executes: ``` if floor(y/x) > 0: return True # == 1 elif floor(z/y) == 1: return 0 elif floor(z/y) == 0: return 1-floor((x-y)/(z-y)) # Python 2 implicitly treats integer division as floor division # equivalent: 1 + math.ceil((y-x)/(z-y)) # because: -floor(-x) == ceil(x) ``` [Answer] ## [Perl 5](https://www.perl.org/), 37 bytes **35 bytes code +2 for `-pa`.** ``` $i-=$F[2]while++$\,($i+=$F[1])<$_}{ ``` [Try it online!](https://tio.run/##K0gtyjH9/18lU9dWxS3aKLY8IzMnVVtbJUZHQyVTGyRmGKtpoxJfW/3/v7GBgrGC0b/8gpLM/Lzi/7oFiQA "Perl 5 – Try It Online") [Answer] # R, 43 bytes Borrowing from other answers: ``` g=function(a,b,c)`if`(b<a,1+g(a-b+c,b,c),1) ``` Gives error if no solution. [Answer] # [Haskell](https://www.haskell.org/), ~~30~~ ~~29~~ 27 bytes ``` (b!c)a=1+sum[b!c$a+c-b|a>b] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/XyNJMVkz0dZQu7g0NxrIVknUTtZNqkm0S4r9n5uYmWdl5emvockFYtoWFGXmlahoGCsaalr@BwA "Haskell – Try It Online") Shorter than the existing Haskell answer. Perhaps someone else can beat me. This uses a recursive approach to solving the problem. Each recursion is essentially a day of movement for the snail. If the distance left to the end is less than the distance still required we end our recursion. [Answer] # J, 25 bytes First a nice solution, which is a cheat, since it assumes that "anything other than a positive integer result" equals "None": ``` >.>:%/2-/\ ``` ## explanation * `2-/\` use windows of length 2 across our 3 item input, placing a minus sign between each one, which for the input `30 3 2`, eg, returns `27 1` * `%/` put a division symbol between each element of the list, in our case the list has only two items, so it means "divide 27 by 1" * `>:` increment by 1 * `>.` take the ceiling ## official solution Here is the official solution that converts negatives and infinity to 0, which part i was not able to find a satisfyingly terse solution for: ``` 0:`[@.(>&0*<&_)>.>:%/2-/\ ``` [TIO](https://tio.run/##y/oPBAZWCdEOehp2agZaejZq8Zp2enZWqvpGuvoxCsYGOgoKxkBsxIVHlYWJjoKhORCb4lNlbglSATTLEp8qkAIgNjTAaxQI4lNgZgl1twVedxsCLQK53YQLAA) [Answer] # PHP>=7.1, 60 bytes prints 0 for no escape ``` [,$h,$u,$d]=$argv;echo$h>$u?$u>$d?ceil(($h-$d)/($u-$d)):0:1; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/04c117594fa34b83ce7b59dcf4b2abab3404069d) # PHP>=7.1, 67 bytes prints nothing for no escape ``` for([,$h,$u,$d]=$argv;($u>$d?:$h<=$u)&&0<$h+$t*$d-$u*++$t;);echo$t; ``` [PHP Sandbox Online](http://sandbox.onlinephpfunctions.com/code/5a1d438f867643b67a5a6ec2f367072c0c3dec94) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~95~~ 94 bytes ``` $g=$args[0] $c=$args[1] $f=$args[2] $p=0 $d=0 1..$g|%{$d+=1;$p+=$c;if($p-ge$g){$d;exit}$p-=$f} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/XyXdViWxKL042iCWSyUZyjYEstOgbCMgu8DWgEslBUgY6umppNeoVqukaNsaWqsUaNuqJFtnpmmoFOimp6qkawIlrFMrMktqgQK2Kmm1////tzD5b2j@39AUAA "PowerShell – Try It Online") [Answer] # Mathematica, ~~47~~ ~~40~~ 39 bytes ``` If[#==#2,1,⌈(#-#3)/(#2-#3)⌉~Max~0]& ``` *-7 bytes from @KeyuGan* [Answer] # [Ruby](https://www.ruby-lang.org/), ~~49~~ 47 bytes ``` ->h,a,b{h-a<1?1:(1.0*(h-a)/[a-b,0].max+1).ceil} ``` Throws exception if snail can't climb out [Try it online!](https://tio.run/##KypNqvxfbPtf1y5DJ1EnqTpDN9HG0N7QSsNQz0BLA8jT1I9O1E3SMYjVy02s0DbU1EtOzcyp/V9QWlKsUBxtbKBjrGMUywXlWpjoGJrrGJrCBcwtgTwdSzjfyBKkwATONzTWMbTQsUCo1wFCOM/MEmg6UFIZZryhjiHQBpPY/wA "Ruby – Try It Online") [Answer] ## Batch, 66 bytes ``` @set/an=%4+1,a=%1-%2+%3 @if %1 gtr %2 %0 %a% %2 %3 %n% @echo %n% ``` The second last test case printed nothing, and the last test case actually crashed `CMD.EXE`... [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes ``` 0[¼²+D¹<›i¾q}³-D1‹# ``` Explanation: ``` 0 Initialise stack with 0 [ while(true) ¼ increment the counter variable ²+ add the second input to the top of the stack D¹<›i if it is greater than or equal to the first input ¾ push the counter variable q terminate the program } end if ³- subtract the third input from the top of the stack D duplicate top of stack 1‹ if it is less than 1 # break the loop ``` For invalid values, this may return any value less than 1. However, in 05AB1E, only 1 is truthy so this meets the requirement that the output for an invalid value should be falsy. [Try it online!](https://tio.run/##ASwA0/8wNWFiMWX//zBbwrzCsitEwrk84oC6acK@cX3Csy1EMeKAuSP//zMwCjMKMg "05AB1E – Try It Online") [Answer] # PHP, 60 bytes ``` [,$h,$v,$d]=$argv;echo$h>$v?$v>$d?ceil(($h-$d)/($v-$d)):N:1; ``` prints `N` for `None`. Run with `-r`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes ``` .×ηO<²›1k2÷> ``` [Try it online!](https://tio.run/##MzBNTDJM/f9f7/D0c9v9bQ5tetSwyzDb6PB2u///ow1NdRR0LWO5zC0B "05AB1E – Try It Online") Prints `0` if impossible. Input format: ``` [climb, -fall] height ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), 12 bytes ``` @UµV-W §W}aÄ ``` [Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=QFW1Vi1XIKdXfWHE&input=KDc5LCAxNSwgIDkp) Outputs `undefined` for never, after possibly freezing your browser for a while, so please be careful. I'm not convinced this is optimal. `oWV-W l` works on all but the last three cases... [Answer] # Python v2 & v3, 44 Bytes ``` f=lambda x,y,z:1+f(x-(y-z),y,z)if x>y else 1 ``` *^Infinite recursion (error) for None case.* [Answer] # HP-15C Programmable Calculator, 26 Bytes The three numbers are loaded into the stack in order before running the program. The fall height is entered as a negative number. If the snail cannot climb out of the well, the result is either a negative number or error #0 (zero divide error). Op codes in hex: ``` C5 C1 B4 C5 FB 74 1A C4 FA B4 C5 FD C1 C1 A3 70 C6 F0 B4 FA EB F1 FA B2 0A F1 ``` Instruction meanings: ``` x↔y ENTER g R⬆ x↔y − g TEST x≤0 GTO A R⬇ + g R⬆ x↔y ÷ ENTER ENTER f FRAC TEST x≠0 EEX 0 g R⬆ + g INT 1 + g RTN f LBL A 1 ``` You can try the program with [this HP-15C simulator](http://hp-15c.homepage.t-online.de/content_web.htm). [Answer] # Common Lisp, 49 bytes ``` (defun f(a b c)(if(> a b)(1+(f(+(- a b)c)b c))1)) ``` [Try it online!](https://tio.run/##HYlJCoAwDEWv8pc/FBcBRVfeRauBgJTicP5Y3b0hH37VCG67PQXGBSuy0I0zGgs10ZjY/Zblu6IiwXp6uUHD1ENH6NDiCw) Recursive function, stack overflow if no solution found. [Answer] # [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~31~~ 23 bytes Just noticed the requirements changed. This version doesn't check if the snail will ever reach the top of the well. ``` ≈:-:>0|q=q+1┘a=a-b+:]?q ``` The explanation below, for the original version that does check if a solution exists, covers all relevant parts of this code too. --- Original, 31 byte answer: ``` ~:>:|≈:-a>0|q=q+1┘c=c-a+b]?q\?0 ``` ## Explanation ``` ~ IF : cmd line arg 'a' (the increment of our snail) > is greater than : cmd line arg 'b' (the decrement, or daily drop) | THEN ≈ WHILE : cmd line arg 'c' (the height of the well) -a minus the increment (we count down the hieght-to-go) >0| is greater than 0 (ie while we haven't reached the top yet) q=q+1 Add a day to q (day counter, starts at 1) ┘ (syntactic linebreak) c=c-a+b Do the raise-and-drop on the height-to-go ] WEND ?q PRINT q (the number of days) \?0 ELSE (incrementer <= decrementer) print 0 (no solution) ``` [Try it online!](https://repl.it/JRcM/1) (OK, not really: this is a translation of QBIC to QBasic code run in repl.it 's (somewhat lacking) QBasic enviroment) [Answer] # Excel VBA, 47 Bytes Anonymous VBE immediate window function that takes input in from the range `[A1:C1]` from the `ActiveSheet` object outputs to the VBE immediate window This primarily Excel formula based solution appears to be smaller than any purely VBA solution that I can come up with :( ``` ?[If(B1>C1,-Int((B1-A1)/(B1-C1)-1),Int(A1=B1))] ``` [Answer] **Haskell, 47 ~~55~~ bytes (48 if tuple required)** ``` f d c s|d<=c=1|c<s= -1|d>c||c<s=1+(f(d-c+s)c s) ``` tuple variation ``` f(d,c,s)|d<=c=1|c<s= -1|d>c||c<s=1+(f(d-c+s)c s) ``` Explanation ``` f d c s function that does all the heavy lifting =) d - depth c - climb per day s - slide per night |d<=c=1 recursion terminator. 1 day of climbing |c<s= -1 possibility check. top can't be reached |otherwise=1+(f(d-c+s)c s) 1 day plus the rest of the distance ``` [Answer] # Python 3, 41 Bytes ``` f=lambda a,b,c:int(b>=a)or 1+f(a-b+c,b,c) ``` Error for Never [Outgolf @veganaiZe](https://codegolf.stackexchange.com/a/130300/70489) [Answer] # [APL (Dyalog)](https://www.dyalog.com/), 13 bytes ``` (⌈+÷⊢)/0⌈2-/⊢ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBI1HPR3ah7c/6lqkqW8AZBvp6gPZXFyP@qYCZdOAFK2Y//8bG@goKBgDsRGXhYmOgqE5EJtymVuCKKCoJZeRJURUwYTLEKjO0ALItOBSAEkCsaEBlwJIEoy5zCyhhllwWRgCJUEGmgAA "APL (Dyalog Classic) – Try It Online") --- Errors on division by zero if the snail cannot climb out of the well. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 37 bytes ``` (h,c,f)=>h>c?f<c?1+(h-f-1)/(c-f):0:1; ``` Non-recursive lambda. Uses formula found [here](https://stackoverflow.com/questions/17944/how-to-round-up-the-result-of-integer-division). Could be shortened by 6 bytes if "any negative result" is a valid way to return failure; currently returns 0 instead. ]
[Question] [ **Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers. --- This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic). Closed 7 years ago. **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. Since it was Pi day recently, I have [noticed](https://codegolf.stackexchange.com/questions/47759/monte-carlo-estimator-of-pi) a [number](https://codegolf.stackexchange.com/questions/47808/transmit-pi-precisely) of [challenges](https://codegolf.stackexchange.com/questions/47912/calculate-%CF%80-with-quadratic-convergence) that ask you to calculate pi. Of course, a quiche lorraine is *not quite* a pie (you can claim a Bonus Score¹ of +1 if you guessed the challenge off of the title). As such, your job is to **write an algorithm** or **method** that *looks* like it approximates Pi at first glance, but is **guaranteed not to converge** towards Pi. This is an underhanded challenge, so make sure it will output 3.14... for a simple test case, e.g. with 10 iterations of your algorithm. This is also a popularity challenge, so don't go for the obvious `echo(pi)` and say that IEEE 754 floating point rounds some digits up or down. Winner gets a quiche lorraine². *¹ Warning: not actually a bonus score. By claiming the score, you agree to bake me a pie before Pi Day, 2016* ² *Warning: quiche lorraine is used as a metaphor for having your answer marked as 'accepted'* [Answer] ## Algorithm Using the well-known result: ![enter image description here](https://i.stack.imgur.com/ERe8P.png) we define in Python 3: ``` from math import sin from functools import reduce from operator import mul def integrate(f, a, b, n): h = (b-a)/n i = h * sum(f(a+i*h+h/2) for i in range(n)) return i def sinc(x): return sin(x)/x def borwein(n): def f(x): g = lambda i: sinc(x/(2*i+1)) return reduce(mul, map(g, range(n)), 1) return f ``` ## Testing ``` >>> for i in range(1,10): ... pi = 2 * integrate(borwein(i), 0, 1000, 1000) ... print("x[{}] = {}".format(i, pi)) x[1] = 3.140418050361841 x[2] = 3.141593078648859 x[3] = 3.1415926534611547 x[4] = 3.1415926535957164 x[5] = 3.1415926535895786 x[6] = 3.1415926535897953 x[7] = 3.1415926535897936 x[8] = 3.1415926535435896 # ??? x[9] = 3.141592616140805 # ?!! ``` ## Spoiler > > The [Borwein integral](http://en.wikipedia.org/wiki/Borwein_integral) is math's idea of a practical joke. While the identity above holds up to sinc(x/13), the next value is actually: > > > ![enter image description here](https://i.stack.imgur.com/pCTcT.png) > > > [Answer] To find pi, we will integrate this well known differential equation: ![> dy/dt = sin(y)*exp(t)](https://i.stack.imgur.com/UQVsV.gif) With an initial condition ![> 0 < y0 < 2*pi](https://i.stack.imgur.com/zXjJ4.gif) It is well known that this initial value problem converges to π as t increases without bound. So, all we need is to start with a reasonable guess for something between 0 and 2π, and we can perform numerical integration. 3 is close to π, so we will pick y = 3 to start. ``` class PiEstimator { static final int numSteps = 100; static final double dt = 0.1, tMax = numSteps * dt; static double f(double y, double t){ return Math.sin(y) * Math.exp(t); } public static void main(String[] args){ double y = 3; int n = 0; for(double t = 0; t < tMax; t+=dt){ if(n%5 == 0) System.out.println(n + ": " + y); n++; y += f(y,t)*dt; } } } ``` Here are some results at each for different numbers of steps: ``` 0: 3.0 5: 3.0682513992369205 10: 3.11812938865782 15: 3.1385875952782825 20: 3.141543061526081 25: 3.141592653650948 30: 3.1415926535886047 35: 3.1415926535970526 40: 3.1415926517316737 // getting pretty close! 45: 3.1416034165087647 // uh oh 50: 2.0754887983317625 55: 49.866227663669584 60: 64.66835482328707 65: 57.249212987256286 70: 9.980977494635624 75: 35.43035516640032 80: 51.984982646834 85: 503.8854575676292 90: 1901.3240821223753 95: 334.1514462091029 100: -1872.5333656701248 ``` How it works: > > That differential equation is well known because it is extremely difficult to integrate correctly. While for small t values naive integration will produce acceptable results, most integration methods exhibit extreme instability as t gets very large. > > > [Answer] Code: ``` var pi = function(m) { var s2 = 1, s1 = 1, s = 1; for (var i = 0; s >= 0; ++i) { s = s1 * 2 - s2 * (1 + m*m); s2 = s1; s1 = s; } return i*m*2; }; ``` I basically discovered this sequence by accident. It starts out as `1, 1` and every term after that `s(n)` is given by `s(n) = 2*s(n - 1) - s(n - 2) * (1 + m*m)`. The end result is the smallest `n` such that `s(n) < 0` multiplied by `2m`. As `m` gets smaller, it should get more and more accurate. ``` pi(1/100) --> 3.14 pi(1/1000) --> 3.14 pi(1/10000) --> 3.1414 pi(1/100000) --> 3.14158 pi(1/1000000) --> 3.141452 // what? pi(1/10000000) --> 3.1426524 // .. further away from pi ``` I'm pretty sure these are floating point errors as `(1 + m*m)` gets close to one, but I'm not sure. Like I said, I stumbled on this by accident. I'm not sure of its official name. Don't try this with an `m` too small or it will run forever (if `1 + m*m == 1` due to `m` being so small). If anyone knows the name of this sequence or why it behaves like this, I would appreciate it. ]
[Question] [ While I was traveling in the future, I noticed a funny game among kids circa 2275. When they don't want their great-great-great-great-grand parents to understand what they're saying, they use the ***BIBABOBU speak***. Obviously, I couldn't understand anything either with my pre-cyborg era brain and I felt (or technically: *I will feel*) really silly. So, I'd need a decoder for my next visit. ## BIBABOBU? While it's been deprecated for a long time, ASCII is still commonly used in the pop culture of 2275 and this language is based upon it. A string is BIBABOBU-encoded that way: * Convert all characters to their ASCII codes. * Take the 2-digit hexadecimal representation of each code and convert them using the following table: ``` 0: BI 4: BIDI 8: BADI C: BODI 1: BA 5: BIDA 9: BADA D: BODA 2: BO 6: BIDO A: BADO E: BODO 3: BU 7: BIDU B: BADU F: BODU ``` ### Example ``` "Hello!" → 48 65 6C 6C 6F 21 → "BIDIBADI BIDOBIDA BIDOBODI BIDOBODI BIDOBODU BOBA" ``` However, the corresponding **input** would be given without any space to mimic the monotonous intonation that kids are using to make this even harder to understand without implants: ``` "BIDIBADIBIDOBIDABIDOBODIBIDOBODIBIDOBODUBOBA" ``` ## Clarifications and rules * Remember that I need a ***decoder***, not an encoder. * Decoded characters are guaranteed to be in the range **[ 32...126 ]**. * The input is guaranteed to contain en even number of BIBABOBU-encoded hexadecimal digits. * You may take input in either full lowercase or full uppercase. Mixed cases are not allowed. * Because bit flips are quite common during a time travel, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") in order to minimize the risks. ## Test cases NB: Linefeeds are used below for formatting purposes only. You are *not* supposed to handle them. ``` Input: BIDABIDIBIDOBIDABIDUBUBIDUBIDI Output: Test Input: BIDABIDUBIDOBIDABIDOBODIBIDOBUBIDOBODUBIDOBODABIDOBIDABOBIBIDUBIDIBIDOBODUBOBIBUBOBUBOBUBI DUBUBIDABOBA Output: Welcome to 2275! Input: BIDIBADIBIDOBIDABIDOBODIBIDOBODIBIDOBODUBOBODIBOBIBIDABIDIBIDOBADABIDOBODABIDOBIDABOBIBIDA BIDIBIDUBOBIDOBABIDUBIDOBIDOBIDABIDOBODIBIDOBIDABIDUBOBOBABOBIBIDABADABIDOBODUBIDUBIDABOBI BIDOBODIBIDOBODUBIDOBODUBIDOBADUBOBIBIDUBUBIDOBODUBOBIBIDOBIDOBIDUBIDABIDOBODOBIDOBODOBIDU BADABOBA Output: Hello, Time Traveler! You look so funny! Input: BIDIBABIDOBODOBIDOBIDIBOBIBIDUBADABIDOBODUBIDUBIDABOBIBIDOBIDIBIDOBODUBIDOBODOBOBIDUBIDUBI DIBOBIBIDUBIDABIDOBODOBIDOBIDIBIDOBIDABIDUBOBIDUBUBIDUBIDIBIDOBABIDOBODOBIDOBIDIBOBIBIDUBI DUBIDOBADIBIDOBABIDUBIDIBOBIBIDIBADABOBIDUBIDOBODABOBIBIDUBUBIDOBABIDUBADABIDOBADABIDOBODO BIDOBIDUBOBODIBOBIBIDOBIDIBIDOBODUBOBIBIDUBADABIDOBODUBIDUBIDABUBODUBOBIBIDIBADIBIDOBABOBI BIDOBADIBIDOBABOBIBIDOBADIBIDOBABOBA Output: And you don't understand what I'm saying, do you? Ha ha ha! ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~36~~ ~~35~~ 33 bytes Saved 1 byte thanks to *Mr.Xcoder* Saved 2 bytes thanks to *KevinCruijssen* ``` ć©¡®ì®D…IAO©â'D«‚˜®'U«âJskh2ôJHçJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f//SPuhlYcWHlp3eM2hdS6PGpZ5OvofWnl4kbrLodWPGmadnnNonXroodWHF3kVZ2cYHd7i5XF4udf//06eLp5OjkDs6eIPxI5g2h/KR9ChThAeUA1UFUTGEa7DEW4CqhqQTrBKMBuiBtMmCB9sixPCBITpoVDdMDlUtyHTjhAbwepDkVzviWR3KJL9/kh0KNhGoBkA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##fVIxbgIxEOzvFYiGBpo8INKershes9U@IJEiJUqRAikSEgUdf4jSQAFCRFelR7LT5Rd85DgfXtuLCYXt83puZna079PHp9fndv4xa3@XZmdWprHfpqmOiw0CmZ1djyqzPy4@/75MM2Kzt@t6@vZyZ3/qB7ut29nQHgaT@4E9FMNxW2IF3cJukf/mkvu9qxahFJ@pJA9nf5MTAqrbhSJgXM3t5yUyDgtFDwTlIsqQInG3M330DeGPSwuC6eUdMmkmV5JmyZkKDJFdcpE37S09wTcsbcYIojYn@pSc3CvGWBQEQ/t80xhmxqgUUVYslyYwC0ONRIjxuicMAaAKXBDom8NkanRQoHqDzJ0eAspm7L9kOEFg4k94blfgBA) **Explanation** ``` ć©¡ # extract the head ("B") and split input on it ®ì # prepend "B" to each ®D # push 2 copies of "B" …IAO©â # cartesian product with "IAO" 'D« # append "D" to each ‚˜ # add the leftover "B" to the list ®'U«â # cartesian product with "IAOU" J # join each to string sk # get the index of each word of the input in this list h # convert each to hex 2ôJ # format as pairs of chars H # convert to int çJ # convert from ascii-codes to string ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~26~~ ~~24~~ ~~23~~ ~~22~~ ~~20~~ ~~17~~ 15 bytes ``` ṣḢO^1%9%4Ḅḅ⁴b⁹Ọ ``` [Try it online!](https://tio.run/##fVIxDsIwDNx5RZc@AImF0RGLJ08ZWBiQWBAfYCwCsfAKWBkZijrykvQjoQlxEjfAkKRxrnfnk7eb3W5vrXneTHul1bSe1zPTHk176pvHum@eprtY0z2q17k/3KultQoXMCwcFoVvrbTfh@okltIzKQpwHW58QkQNO1NEjKu5/bNYxmFh4oEgXCQZEiTu9qFPviH@MbbAGC/vkFkzpRI3S85UZEjsnAu/SW/5CaFhbjNFkLR1pk/Zqb1iikVAMLav/xrDwhgpFtWCZWwCizDESMQYv3vCGACKwBmBoTnMpkYGBaI3KNzJIaBixn4lozMEZv6Y538F3g "Jelly – Try It Online") ### How it works ``` ṣḢO^1%9%4Ḅḅ⁴b⁹Ọ Main link. Argument: s (string) Ḣ Head; remove and yield the first character of s. ṣ Split s at occurrences of the result ('B'). O Ordinal; map "IAOUD" to A1 := [73, 65, 79, 85, 68]. ^1 Bitwise XOR 1; map A1 to A2 := [72, 64, 78, 84, 69]. %9 Modulo 9; map A2 to A3 := [0, 1, 6, 3, 6]. %4 Modulo 4; map A3 to A4 := [0, 1, 2, 3, 2]. So far, we've mapped "BX" to [x] and "BXDY" to [x, 2, y], where x/y = 0, 1, 2, 3 when X/Y = I, A, O, U. Ḅ Unbinary; map [x] to x and [x, 2, y] to 4x + 2×2 + y = 4(x + 1) + y. ḅ⁴ Convert the resulting array from base 16 to integer. b⁹ Convert the resulting integer to base 256. Ọ Unordinal; replace code points with their characters. ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), 58 bytes ``` {S:g{(B.[D.]?)**2}=chr :16[$0».&{:2[.ords»³X%87 X%4]}]} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqvVrDSS/aRS/WXlNLy6jWNjmjSMHK0CxaxeDQbj21aiujaL38opTiQ7sPbY5QtTBXiFA1ia2Nrf1fnFipkKahEq@pkJZfpGDD5eTp4unkCMSeLv5A7Aim/aF8BB3q5O/kyAVVgKw41CkUTAJFueBC2MwKhZsEoR3hqoAkzAgk2zydQCQEw6xxBLvCzvo/AA "Perl 6 – Try It Online") Heavily inspired by Dennis' Jelly solution. Uses a different magic function `x³ % 87 % 4` which also maps the ASCII codes of `IAOUBD` to `012302`. ### Alternative ~~75~~ 74 bytes version *-1 byte thanks to Jo King* ``` {pack('H',.trans((<B BID BAD BOD>X~ <I A O U>)=>(^16)».base(16))).decode} ``` [Try it online!](https://tio.run/##bU5NC4JAEL37K@YQuQshdPFQJuzioT3taaFTsekKUamoQRL1x7r1x2z8zEMD772Z4fFmMpNf3PpWGDD3zOSnq0lKfYFVpsPz2rpWMI9hUz@akdhbe@GUuU4KQjwOXATAGUIG/u4FngAGEpRPNz7ZL136eTtHXRiCLaVOZMI0Ms@60BXEZHagEKc5eBamCEwRqBLBWpX9/FPFJWdWb5iaFVct49YaV/@y1JjUKRtdyEPE5JrgDXcYzrD2Cx@w6i8 "Perl 6 – Try It Online") ### Alternative 85 bytes version ``` {S:g[....]=chr :4(~$/)*2+|221+^:4(~$/)+^238}o{TR:d/UIAOBD/0123/}o{S:g[B.<![D]>]=0~$/} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqPVoPCGJtkzOKFKxMNOpU9DW1jLRrjIwMteOgfO04I2OL2vzqkCCrFP1QT0d/Jxd9A0MjY32gGMgAJz0bxWiXWLtYWwOg8tr/xYmVCmkaKvGaCmn5RQo2XE6eLp5OjkDs6eIPxI5g2h/KR9ChTv5OjlxQBciKQ51CwSRQlAsuhM2sULhJENoRrgpIwoxAss3TCURCMMwaR7Ar7Kz/AwA "Perl 6 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~100~~ ~~97~~ ~~96~~ 95 bytes -1 byte thanks to ovs -1 byte thanks to G B ``` lambda w:''.join(' 1023546798abdcef'[int(c,35)/7%77%18]for c in w.split('B')[1:]).decode("hex") ``` [Try it online!](https://tio.run/##jVM9b4MwEN35FRZSZJAiWpKmpEgZbGXx5MkTzUD4UKhSQAEp7a@n2GBjhyTqYB8Hj3vvnu7q3/ZUlasu33125/j7mMbgGkLofVVF6UDgv67Wm7f34GMbH9Mky2FUlK2TLNcb9yVYBMHC3x7y6gISUJTg6jX1uWgdiKEb@eHB9dIsqdLMsU/Zj@12bda0DdiBCNiY7AlG/SF72h8kIh3zKTJMMbKXlj1idDzDTNz9Ww3B7lZkqt4QkUL1t6yicRLM7@FIJqRp@a92ng0Mk3qk/rhVITFCAUdq/cyZZL@U61IVpurSHfnN1KZHNPYsO51cmLiZxk@1yASj4YyBIsoB9lQbmWmjWPIyo8qtDjLzw5gN5eR9TUR5QAzPJYKM/RFtdkyvkNEbmqkz54DOJu2RM0xDEE2frPP8DbIPFl9MvnN8N8XuhRaoL/0Ci0w@5w7PXJlC2P0B "Python 2 – Try It Online") [Answer] # [Perl 5](https://www.perl.org/) -p, 67 bytes ``` for$p(<{B,0D,1D,2D}{I,A,O,U}>){s/$p/chr$i+48/ge;$i++}$_=pack'H*',$_ ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0ilQMOm2knHwEXH0EXHyKW22lPHUcdfJ7TWTrO6WF@lQD85o0glU9vEQj891RrI0K5VibctSEzOVvfQUtdRif//38nTxRGIQ4HYH8r2d/J38QTToVAejHaEqwKSUF2ecDUgMRAJwSDZUKhax3/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (legacy), ~~68~~ ~~65~~ ~~60~~ 59 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` .•5Ç¿ÆΓ•2ô.•1ÒKá ¸ΓìŸÆt`ô_zTºγ„KRI‰ι놽òι•4ô«I¬©¡®ìkh2ôJHçJ ``` Input is in lowercase. -3 bytes implicitly thanks to *@Emigna* changing `'b¡εg>}s£` to `'b©¡®ì`. [Try it online](https://tio.run/##fVC9CsIwEH4Vn0Cs2HfwZxN3Tajg4ZDFLk6ddLe7qIuIRUQ7qCDCHa55iL5ITZv@UuyQSy7fz31Jy2TcmIZhM3AOJq3xQyvpqnOb/OjKoM2A9g18SJe874NWiwn54@UIX/IeONvBsBc4V/mkc@Ds8E03@VSiDvl47qGHJ9zjhbz5TLn1u3TshyEHCzhTVXChFsQLuKpqtzmzUsyOe1C9xjQvx7ReJCy75AJWdYLeWYxrVa6LsP@ZIJnHCsziPIhTi4wnssx6RqpI38Yq6aJEIvMrv7TuZ@wCAwr5Up/6G/YD) or [verify all test cases](https://tio.run/##jVI9SwNBEO3zKyS1BBO8vyAm6UKw1VkiOFhs4zZWV8Xe9GJsRHKI6BWJIMIOtvcj7o@cex@zH7kYLHbndu7te28eexSB6F8W0Um36OXxU0R3@pvm2cJ8DygtW326H9PyQK@zBSU/a5rfXFB6fjvVn9lHHj@MJ8M8fss2tMrjR/1F79nGXDqmVK@GOtEveqlfKbm@MmyjU3oeFd3e2WEhcIYCzMKZNAuqKpuzq0pIAZ0G4IOVUNVuuh3b2sWlLFNdwaLMzhSeGopyrxfLALv4r@XyVNM732BvbFtgTCVfIr1h2ko8rCxNWQbHzrnwv9CbX6EZmMd0ETht5elLr6pK0cUSQNCOr/Yaw5YxKVhUBSzbJrAVRvAkbIy7PaENAIPAGYHNcOi9mjAoCGaDlrvwEcjWG/srGeUh0PPHPPs78As). ~~Also, can definitely be golfed with something smarter than the huge compressed strings. Will take another look later on.~~ [Shorter answer already provided by *@Emigna*](https://codegolf.stackexchange.com/a/171401/52210), so make sure to upvote him! **Explanation:** ``` .•5Ç¿ÆΓ• # Compressed string "bibabobu" 2ô # Split in parts of 2 # → ["bi","ba","bo","bu"] .•1ÒKá ¸ΓìŸÆt`ô_zTºγ„KRI‰ι놽òι• # Compressed string "bidibidabidobidubadibadabadobadubodibodabodobodu" 4ô # Split in parts of 4 # → ["bidi","bida","bido","bidu","badi","bada","bado","badu","bodi","boda","bodo","bodu"] « # Merge both lists together # → ["bi","ba","bo","bu","bidi","bida","bido","bidu","badi","bada","bado","badu","bodi","boda","bodo","bodu"] I¬©¡ # Take the input and split on the head (always 'b') # i.e. "bidibadibidobidabidobodibidobodibidoboduboba" # → ["idi","adi","ido","ida","ido","odi","ido","odi","ido","odu","o","a"] ®ì # And prepend a 'b' to each item again # i.e. ["idi","adi","ido","ida","ido","odi","ido","odi","ido","odu","o","a"] # → ["bidi","badi","bido","bida","bido","bodi","bido","bodi","bido","bodu","bo","ba"] k # Map each item to the index of the first list # i.e. ["bidi","badi","bido","bida","bido","bodi","bido","bodi","bido","bodu","bo","ba"] # → [4,8,6,5,6,12,6,12,6,15,2,1] h # Convert everything to hexadecimal # i.e. [4,8,6,5,6,12,6,12,6,15,2,1] # → ["4","8","6","5","6","C","6","C","6","F","2","1"] 2ôJ # Split it in parts of 2 and join them together # i.e. ["4","8","6","5","6","C","6","C","6","F","2","1"] # → ["48","65","6C","6C","6F","21"] H # Convert that from hexadecimal to an integer # i.e. ["48","65","6C","6C","6F","21"] → [72,101,108,108,111,33] ç # And take its ASCII value # i.e. [72,101,108,108,111,33] → ["H","e","l","l","o","!"] J # Then join everything together (and output implicitly) # i.e. ["H","e","l","l","o","!"] → "Hello!" ``` [Answer] # [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~88 86~~ 84 bytes ``` {S:g{B(.*?)B(.D.|.)}=chr :16[$/.map:{first :k,~$_,("",|<ID AD OD UD>X~ <I A O U>)}]} ``` [Try it online!](https://tio.run/##fVJNa8MwDD3Pv0KUUpIRMnbpIWs7HHzRyYdhGIwxSmm2snYryS4lTf96FqeRP@qtB8mx/KL39NB@XW6n7e4AkwLm0NZP2XudR@ntY9xlkR7TuJmvPkrI7qcv47t0t9xndbEpqx/IPpPT@C2JRqPkOEMBXIAUoMTi@QQzBA4S1CJuXpuWFd8lRNvN17qKoWY31fIA6aR4YA1rcxS8C@xCDt8qV33uqsyU7LPM5QBXw41OblBdphYGo2s6n4NoNJazHsg9FZZGek307dze6ubmj0sJhOnpNdIZJmSiYaUWZTrY7uQLvfna3JMPA9OY1gLLrRx@6ZyqZ7S2eBA046urwjAQJnMiVV6XSxEYmOGthLHxb01oDEDPcELgMBw6W@Mbxb3ZeKDOXwIZ7Nh/zigHgY4@6nO9wn8B "Perl 6 – Try It Online") [Answer] # [R](https://www.r-project.org/), ~~141~~ 135 bytes ``` function(x,y="I":"A":"O")intToUtf8(matrix(match(el(strsplit(gsub("D","",x),"B"))[-1],paste0(rep("":y,e=4),y:"U"))-1,,2,T)%*%16:1) ":"=c ``` [Try it online!](https://tio.run/##TY1PC4JAEMXvfYoYEGZihIyIkDwoXjztxT1FBxMtwVTcFfTT21pqHd6bP/xmXjvm24s95l2V6qKusOfBgwhc8I0EUFHpuJY6P@Mr0W3RTyV9Ylai0q1qykLjQ3V3hBAYgHtiCIDoajs3bhKlsz22WYMA7sCZdyQeXJAGsB3mA8dk7Szn5Dq0MXFeOuYIQRT6RpGRmHsZyI@bLdDmx8g/RgRivpHztFR/pYwvf1Zm2k3@1ZI1sT7Q@AY "R – Try It Online") *Thanks to [JayCe](https://codegolf.stackexchange.com/users/80010/jayce) for saving 6 bytes!* Using some modular magic is likely to be shorter, but I'm pretty happy with this as a naive first pass. [Answer] # Japt, ~~43~~ ~~29~~ 28 bytes Unsurprisingly, a port of [Dennis' Jelly solution](https://codegolf.stackexchange.com/a/171415/58974) works out much shorter. Outputs an array of characters. ``` Åqbu)®¬®c ^1 %9%4Ãì2Ãò ®ìG d ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xXFidSmurmMgXjEgJTklNMOs7DLD8iCu7EcgZA==&input=IkJJREFCSURVQklET0JJREFCSURPQk9ESUJJRE9CVUJJRE9CT0RVQklET0JPREFCSURPQklEQUJPQklCSURVQklESUJJRE9CT0RVQk9CSUJVQk9CVUJPQlVCSURVQlVCSURBQk9CQSIKLVA=) --- ## Original, 42 bytes ``` Åqb £`bbidbad¾d`ò3n)ï`ia`q)m¬bXibÃò ®ìG d ``` [Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=xXFiIKNgYmJpZGJhZL5kYPIzbinvYGlhjGBxKW2sYlhpYsPyIK7sRyBk&input=ImJpZGFiaWR1Ymlkb2JpZGFiaWRvYm9kaWJpZG9idWJpZG9ib2R1Ymlkb2JvZGFiaWRvYmlkYWJvYmliaWR1YmlkaWJpZG9ib2R1Ym9iaWJ1Ym9idWJvYnViaWR1YnViaWRhYm9iYSIKLVA=) ### Explanation ``` Åqb £`bbidbad¾d`ò3n)ï`ia`q)m¬bXibÃò ®ìG d Å :Slice off the first character qb :Split on "b" £ :Map `bbidbad¾d` : Compressed string "bbidbadbod" ò3n) : Partition at every 3rd character from the end (["b","bid","bad","bod"]) ï : Cartesian product `ia` : Compressed string "iaou" q : Split ) : End Cartesian product m : Map ¬ : Join b : Index of X : Current element ib : Prepend "b" à :End map ò :Partition at every second element ® :Map ìG : Convert from base-16 digit array to base-10 integer d : Get the character at that codepoint ``` [Answer] # [C (gcc)](https://gcc.gnu.org/), 181 138 136 bytes Hopefully there will be a C compiler in the future to compile this! :-) Thanks to Max Yekhlakov and ceilingcat for the suggestions. ``` v,t,c,d;f(char*s){for(v=t=c=0;d=*s++;)t+=d==66?v=v*16+t,++c>2?v=!putchar(v),c=1:0,-t:d-65?d-79?d-68?d-85?0:3:4+t*3:2:1;putchar(v*16+t);} ``` [Try it online!](https://tio.run/##fVJNc8IgEL3nV1B7CSZ2/ExtUnTIeOGUE6dODw4xmplWO4I51PG3pxADCcZ6YIHl7du3b2CDLWPlc75nX6d0A965SPPDy25RFr7wmZ9Gmct262Ofw3N2OLoFEoihYZSiPve8CAoPpQgFwbJARX8UeML3PLYYy@vTz0moSreAPkOjcOgPRJgOgtkyHby@yRDMZZjPlsNwEk490Z@E43AUmaqKDUaXMt8L8L3O925xyFMIzg4ACgH4x2g4nn5G8q6URdl2I7jLfZ7/bg4ZkAc5yh4qRu72ehBmLoeRcyljsiIxXhEgD4lc@HpIdKZ1oCBOYuwoUFVVF8hFY1pFmXVMqnmuWKqdaqp6xwYlo6YwGJVT8bp0G6xVVLrvtkksEnW70je6sam4laAxVXuFbA3T7aSHTZQow9Cwa1/0m62tveN6YD1mY0HTm7b6J62dVh0bWywIMePTh8JIR1gS66bUYrkVQTpmWF/C2HhfEzEGEMtwjSD1cKT1a2yjsDUb7qizP0HS@WP/OUNbCNLSp3keZ/Af "C (gcc) – Try It Online") --- In case the C compiler of the future only understands BIBABOBU-ified ASCII :-) ``` BIDUBIDOBOBODIBIDUBIDIBOBODIBIDOBUBUBADUBIDOBIDOBOBADIBIDOBUBIDOBADIBIDOBABIDUBOBOBADOBIDUBUBOBADABIDUBADUBIDOBIDOBIDOBODUBIDUBOBOBADIBIDUBIDOBUBODABIDUBIDIBUBODABIDOBUBUBODABUBIBUBADUBOBADOBIDUBUBUBADUBIDUBUBOBADUBOBADUBOBADABIDUBIDIBOBADUBUBODABOBADOBIDUBUBUBODABUBODABUBIDOBUBIDOBUBODUBIDUBIDOBUBODABIDUBIDOBOBADOBUBABUBIDOBOBADUBIDUBIDIBOBODIBOBADUBOBADUBIDOBUBUBODOBUBOBUBODUBIDUBIDOBUBODABOBABIDUBIBIDUBIDABIDUBIDIBIDOBUBIDOBADIBIDOBABIDUBOBOBADIBIDUBIDOBOBADABOBODIBIDOBUBUBODABUBABUBADOBUBIBOBODIBOBODABIDUBIDIBUBADOBOBADOBIDUBUBOBODABUBIDOBUBIDABUBODUBOBADOBIDUBUBOBODABUBIDUBUBADABUBODUBOBADOBIDUBUBOBODABUBIDOBUBADIBUBODUBOBADOBIDUBUBOBODABUBADIBUBIDABUBODUBUBIBUBADOBUBUBUBADOBUBIDIBOBADUBIDUBIDIBOBADOBUBUBUBADOBUBOBUBADOBUBABUBADUBIDUBIBIDUBIDABIDUBIDIBIDOBUBIDOBADIBIDOBABIDUBOBOBADIBIDUBIDOBOBADOBUBABUBIDOBOBADUBIDUBIDIBOBADABUBADUBIDUBODA ``` (Encoder [Try it online!](https://tio.run/##ZVDLbsIwELzzFSZthO04zYPEpXENam899dRT4IBMEoxoQNjkUMS3p@tUrapWllazu57R7KiwUaq/0a3anzcVejR2ow932/no9@ik2wZmvWY7pkSN1XZ9ooZc6sMJCy2pCQJBXKNkKlQYCk1lwslO6ijhfsLZERRsjb1nf3qrfHhekNMx3kUZYVAWfFZwzryXp9c3r9z52WrAAKMsTFZEXHvgo/e1brED61OjmDOBKAXcEXQZITQMTJnm@UpAq2vs/s0TggbUlU4JFtXeVGiwXjeVNdgwoz@qQ40NYe78logBH8@w9DzypY5QFIGkKSGOfdXCB3Am5WTZTgj6M50s44kYON@H@6ZAHkNmMHAdXfuO2X9RdtJKJWNBjYBEiQ0gWSk5X3SyowkPLAsCNU@hHYM3x8QdYUomRcxCW1AT8nwB9f7BVT5zdZYv4mJaZIGl0yItEvHDHBQh2k8 "C (gcc) – Try It Online")) [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~131~~ 128 bytes ``` s=>unescape(s.replace(/B.(D.)?/g,(f,s)=>(-~g(f[1])*4*!!s+g((s||f)[1])).toString(16),g=c=>'IAOU'.search(c)).replace(/../g,'%$&')) ``` [Try it online!](https://tio.run/##fVJBb4MgFL7vX7TZJnSWpsmyS6MLphdOHBZOyw6Goeti1Ijbqdlfd2AFoVYPgDy/977vfbzv9DeVvDnV7basPkWXRZ2M4p9SSJ7WAkjUiLpIuQC7BIEjgq@7PARZKGEUg@1fDrL3/QfcPG9WK/mUAyDP5wzqEERt9dY2pzIH@xcY5hGP4oBgygIkRdrwL8AVxhZHSNUNHu4fAwi7A69KWRUCFZUiAOuEHLFaRC06fLOE9buKriG8m8lgTgZN6FCBDTdzYotSu6lqMTqm98syzBqLZ5hJgj2tIzP16urbhXHsDtuMa1UG0yvSSKe/eSbjA9V6baWRxbho/vka3RMPXhgHRndGDczRQZ2T9YyLjnlZxDrDFrWSiVaaGB3Mq3Kti0z88WbKOnxbE7GeEO8tDIIM/RJnxnzvsNcbnqjz54NOJnLOGeYgiKPP1FmO6Pc5dP8 "JavaScript (Node.js) – Try It Online") Link includes test cases. Alternative version, also 131 bytes: ``` s=>unescape(s.replace(/B.(D.)?/g,s=>(-~g(s[1])*4*!!s[3]+g(s[3]||s[1])).toString(16),g=c=>'IAOU'.search(c)).replace(/../g,'%$&')) ``` [Try it online!](https://tio.run/##fVJBb4MgFL7vX7TZJnQtTdNll8YumF44cVg4NR4Mo66LUSNup2Z/3YEVhFo9APL83ve@9/G@k99E8upc1qu8@BTNKWxkuP/JheRJKYBElSizhAuwjhA4IPi@TpcKAFZ/KZDHTQwXr4vZTB638YsObOPLpQ1DVBcfdXXOU7B5g8s05OE@IJiyAEmRVPwLcIWx5Agp3uDp8TmAsNnxIpdFJlBWpOAE5hE5YLWIWrT7ZhFrdxWdQ/gwksGcDBrRjoF1N3Nii1K7YbUYHdP7dZnKGotHKpMIe1r7ytTj1bdrxb47bDNuVRlMq0gjnf7GKxkfqNZrmfoqxkXzz9fonrjzwjjQu9NrYI4O6pysrTjpmJdFrDNsUisZaKWR0cE8lltdZOCPN1PW4fuaiPWEeG9hEKTrlzgz5nuHvd7wQJ0/H3QwkWPOMAdBHH2GZzqi32fX/AM "JavaScript (Node.js) – Try It Online") Link includes test cases. Edit: Saves 3 bytes thanks to @Shaggy. [Answer] # [Bash](https://www.gnu.org/software/bash/) + common Linux utilities, 75 bytes ``` sed $(printf `printf %s s/{B{O,A,I}D,B}{U,O,A,I}/%x/g\;` {15..0})|xxd -r -p ``` [Try it online!](https://tio.run/##jVI7D4IwEN79FR0k0YSHDk5O17Dc1Ok2BzT4WowRBxLktyOFPqkah/ZS@t33OHrYV5euq44lmy/uj@vteWKFqlHFqqzhjYghxjaPedtQPB6yqM7Ou23BmvUmTVft8lXXJUseLLl3HcccOfQLc9EvGKpQZ1uJCw4zBaCPYDLQsYJB9bvqcumQy31c8pYUdpD515M8jfRg6MF0TC1ozCAvkU6YUEmHFdKUYbDspLr1ne/NraAC65h2BFabHH3hVBoU7Vg8CJr49NMYBsYE16LksUxNYDAMHcL@z@@e0AwAvYFrBKpw6Lwaf1DgZYPAnf8IRPDGvk2GHAQ6/jTP7y/wBg "Bash – Try It Online") [Answer] # [Scala](http://www.scala-lang.org/), 305 bytes Well, I'm pretty sure this can be golfed out. But still, it exists. Takes input lowercase. `f` prints out the result in stdout. EDIT: -8 chars thanks to me not being dumb anymore (spaces); -13 chars thanks to crater2150 ``` var k=Seq("bi","ba","bo","bu") k++=k.init.flatMap(a=>Seq("di","da","do","du").map(a+_))//Putting "bu" here instead of at line 1, and in place of using init, would be interesting... if it did not cause a typing problem var m=Seq[String]() def g(a:Seq[String],b:Int)=k.indexOf(a(b)).toHexString def f(a:String){a.split('b').drop(1).foreach(x=>m:+="b"+x) var i=0 while(i<m.length){print(Integer.parseInt(g(m,i)+g(m,i+1),16).toChar) i+=2}} ``` [Try it online!](https://tio.run/##fVJNb4IwGL73VxAutoHUucMOZpiAmqzJHAflsmVZihTo5GvQTRLjb3dt8YPFzEPf5u37fLXQrGlGD2X4ydbCWFBeGKwVrIgaw62q3eGH1sbGWbIvaIbctM2QqlKq8m0isLEsZ4N5wQWOMyoWtILUmWh4pOCRgkcKHkk4ztXc@kAIKN1c6b4tRc2L5B0iELHYSCAd907tcEwKgbRHxFo/hhSGCGFRPrG2w2harGi6RTuKmyrjAg7CAcJRXVZwhHBc1oyuU9g6k3xsOWZoWm2Xgjt3YJvyjEH@mOOMFYlI0a6SWgJKb5awGle0bphsYAJzmyNLb9YI2aMHlWWa0hoBbjn3@/1hOFzNlyvj1X@ZAxBD0yMz4rmy@p4vF9GLeLLKPfDc2WkW6J7Ivpt1uMus4/tHVPBHhcyuHbrd1fOOdeGp2f@ZyNHP7SH7fkSn9s84/5y58zgxTndzr9KpRP5Z7@9Nb71M0EOQXr6Tzu0T15Qf67ncsnpKGwblbwjA/vAL "Scala – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), ~~142~~ ~~139~~ ~~127~~ 118 bytes ``` lambda s:''.join(chr(16*a+b)for a,b in zip(*[iter(4*F(l[:-2])+F(l[-1])-1for l in s.split('B')[1:])]*2));F=' IAOU'.find ``` [Try it online!](https://tio.run/##jVI9b4MwEN3zK1AWbFKQQFUHqgy2okg3efJEGUhTFFcUELC0f55iwMYONOpgH4bnex9c/d3dqjLq8@NbX2Rfl2vmtLHrBp@VKNH7rUHhi5cdLjivGid7ujiidH5EjbxEdB8NevbOqEhiP0rxQT75YYr9UGILiWyDti5Eh1zq4iSMU5x6Ecav56PrAGHcDXJRXvu6EWXn5GhP4QSUDAtObFhkrGw@L5VTRske73bmRTJeXi5yysd9eLsF5ZscXDNMlWjUsKt2hgqgcp@WoiRb6v5rS54mqsUP0Tfu5SjMKEUiDWNrJmWcSYG6w9Jd5aW@2drMSmbzyvISx8LNDX5mVD4ybkdkwUFHwR@KhJVIRpUAbnW5FwSrYKyx0ZFuawIdBljhKwTMRsGYJjs0YnkjK3X2QLDV7P2VDDcQYOhTfR6/GX5M/ws "Python 2 – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 93 bytes ``` lambda w:''.join('c60238e4d1_b7f95a'[hash(x)%3046%17]for x in w.split('B')[1:]).decode('hex') ``` [Try it online!](https://tio.run/##fVLLjoIwFN3PVxATU9gQUUdnTGbRZjZ31VVXjpmgQMAoECWR@XqmRW5pQV30yek9D275V6VFPm@Sr5/mFJ73UejcNoT4xyLLXXJYzeaLj3gZBb/7dfL5HpJtGl5Tt/ami9lyNQ3Wu6S4OLWT5c7Nv5anrHIJI9422Ow8P4oPRRS7JI1r4jXlJcsrJ3EnDL6pHCAH7/aCiXaWtxPvbYgUBpIz3r0U3QlXqlFyxmoao@7UfB/IqLB0wAiMWtp6Rm7VU6c7U@@G6hdDNYhplSik4WvMhL650qcr9NUxLfxmazNX2nlHx30aPbcw@LmxipbxYUIWGnQS4qVGGGnkDPmFVWWoB0a5WD2jE32sCXQWYGWPCOh8gtFLdmbU8kZH6ux@4KPOe5aMMBBg6MM6r2/kf2n@AQ "Python 2 – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~86~~ 75 bytes ``` ->s{[s.gsub(/B[^B]+/){|x|"546798ABDCEF1023"[x.to_i(31)/7%38%20]}].pack'H*'} ``` [Try it online!](https://tio.run/##jVJNS8NAEL33V5SF0taPpG3U1oPCrFGc0572tKSlFSoiYnAtVJL89piv3cw2tXjYGXbz8t6bx3ztNj/59i6/vNeJ0t6r3m1GPldLHp374yTdp@z66mZ@uwAePjw@TSezgKm99/25ehsF07E/HwSLwWwSZZEXr1/eh89nwyxXjGOIHIqDoSgOVF0097ZLLjiwiz5rMBQvuaxq8UoQ8iijtHx1B4sqqmEhmsjLWh@jBMTLf72Xt1qhdQ/2j0MXBlM5KJFknq6SmVeUvixDy27SMd9cb7RDM7OZtE2h1ZZEX5AuK0UnGQeFNgF50ht2vAludKXDcugDO3k4u2GTPO4JbQboZG4Q2MyHZHfcrMCZDTru3D0QnU37KxlJEEj8GZ7TL8Ai72MdJ6lOe3F/q3TUy/Jf "Ruby – Try It Online") [Answer] # Dyalog APL, ~~74~~ 72 bytes Beginner level solution in Dyalog APL (just started learning this a couple of days ago!). Defines a dfn that takes one right argument (the input). 72 characters, 72 bytes when using the dyalog encoding. Based on Emigna's solution in 05AB1E . ``` {⎕UCS 16⊥¨(1 0⍴⍨≢t)⊂1-⍨(,('B',('B'∘.,'IAO'),¨'D')∘.,'IAOU')⍳t←('B'⍷⍵)⊂⍵} ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes ``` ®+“IAO”+”D®;p“IAOU”Ẏ€ =”B©œṗµḊ¢iⱮ’s2ḅ⁴Ọ ``` [Try it online!](https://tio.run/##y0rNyan8///QOu1HDXM8Hf0fNcwFsua6HFpnXQARCQVyH@7qe9S0hssWyHQ6tPLo5Ic7px/a@nBH16FFmY82rnvUMLPY6OGO1keNWx7u7vn//7@Tp4unkyOQ9HfyB2JPMPZ0ApJAOtTJ0QUmFwrmewL5EDmIOoQcRL8/VFUoiimeLpg2QGhHsDxEF0IfSA63mzyh9jkiqUS2zxPsan@4On@4myF2wHTA/OaI4TqQi/zh5qH6FF/IhCKp8ERyH8wc/CKOAA "Jelly – Try It Online") The technique used is very similar to [Emigna's](https://codegolf.stackexchange.com/a/171401/59487). I will golf this further soon, hopefully. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 178 bytes ``` {(([((((()()()()){}){}){}()){}]{}){{}<>(({}){}){}(<>)}{}<({}(<>))(<>)((()()()())({})()){{(({})){({}[()])<>}{}}<>({}<>)<>{}}{}><>{}{})<>}<>([]){{}({}(((({}){}){}){}){}<>)<>([])}<> ``` [Try it online!](https://tio.run/##ZU47DsMgDL2OPeQGERIoC1MmpihDWqlS1apDV8TZ6bOdBKImgP3w@3D7bs/P8Hhvr1oz0ULysf2ciy1tV2lzGR3ReT86Lrgia1mOTi48kWZVcMa5EK88OojESNyAAHJxUkHDEJNllSzxpRZnSyVCQFdriFMMHjtOM7bXOu@41RQMgbOzbOJPhT8drhxRKlN74/wnGdaU0Byae9rVx@z6tr56S1R@6l4fu@zU5c9dTZoIjzrcfw "Brain-Flak – Try It Online") ### Explanation ``` # Step 1: convert to hex. # For each pair of letters in the input: { ( # Compare first letter to B ([((((()()()()){}){}){}()){}]{}) # If not B, pop previous output, multiply by 4, and put on third stack. # 4 is added automatically from pushing/popping the difference # between the letters B and D. {{}<>(({}){}){}(<>)}{} < # Push second letter in pair to other stack ({}(<>)) # Push 4 and 9 (<>)((()()()())({})()) # Compute 3-((8-(n mod 9)) mod 4) # (same as (n-1) mod 9 mod 4) {{(({})){({}[()])<>}{}}<>({}<>)<>{}}{} > # Add result to third stack (either 0 or 4*previous+4) <>{}{} # Push onto second stack ) <>} # Step 2: Pair up hex digits. # While digits remain on right stack: <>([]){{} # Push top of stack + 16*second on stack to left stack ({}(((({}){}){}){}){}<>)<> ([])} # Switch to left stack for output. <> ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 30 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ć¡Ç1^9%4%εDg≠i421øP]€OžvβžzвçJ ``` Port of [*@Dennis*' insane Jelly answer](https://codegolf.stackexchange.com/a/171415/52210) (just with less convenient builtins). So make sure to upvote him! [Try it online](https://tio.run/##yy9OTMpM/f//SPuhhYfbDeMsVU1Uz211SX/UuSDTxMjw8I6A2EdNa/yP7is7t@novqoLmw4v9/r/38nTxdPJEUj6O/kDsScYezoBSSAd6uToApMLBfM9gXyIHEQdQg6i3x@qKhTFFE8XTBsgtCNYHqILoQ8kh9tNnlD7HJFUItvnCXa1P1ydP9zNEDtgOmB@c8RwHchF/nDzUH2KL2RCkVR4IrkPZg5@EUcA) or [verify all test cases](https://tio.run/##fVKxDgFBEO19hkQnEqJRzkUzmtGsjoRERKWQSIhKc/EXVBqVRKJSOFrxDX7k3J6d3R2LYndvZ9@99@ZlJtP@YDxMl7N5Mb3Gl20SV3uNUr10PzZHz/VmXK9Vk1O7@1zt6Xae3Q@38@JxSHattFjplNMIm5AtzBaZbxWpfM@qBVtyzxSRgStz4xMsKtuZwmJ0Te/vxTIaC4UcCMKFkyFBom9veucb7B@fFhiTy2uk10yoxM2SNmUZHDvnwm/Sm3@CaZjbdBE4beXpk3eqXNHFIiBo21d/jWFgjCIWVYLl0wQGYYiRsDF@94Q2ABSBMwJNc@hNjQwKRG8QuJNDQMGM/UpGeQj0/DHP/wq8AA). **Explanation:** ``` ć¡ # Split the input-string on its first character ('B') # i.e. "BIDABIDIBIDOBIDABIDUBUBIDUBIDI" # → ["IDA","IDI","IDO","IDA","IDU","U","IDU","IDI"] Ç # Convert each character to it's ordinal value # → [[73,68,65],[73,68,73],[73,68,79],[73,68,65],[73,68,85],85,[73,68,85],[73,68,73]] 1^ # XOR it by 1 # → [[72,69,64],[72,69,72],[72,69,78],[72,69,64],[72,69,84],84,[72,69,84],[72,69,72]] 9% # Take modulo-9 # → [[0,6,1],[0,6,0],[0,6,6],[0,6,1],[0,6,3],3,[0,6,3],[0,6,0]] 4% # Take Modulo-4 # → [[0,2,1],[0,2,0],[0,2,2],[0,2,1],[0,2,3],3,[0,2,3],[0,2,0]] ε ] # Now map it to: Dg≠i # If the length is not 1: # i.e. [0,2,1] → 3 → 1 (truthy) # i.e. 3 → 1 → 0 (falsey) 421øP # Multiply the first number by 4, second by 2, and third by 1 # i.e. [0,2,1] and [4,2,1] → [[0,4],[2,2],[1,1]] → [0,4,1] €O # Then sum every inner list # [[0,4,1],[0,4,0],[0,4,2],[0,4,1],[0,4,3],3,[0,4,3],[0,4,0]] # → [5,4,6,5,7,3,7,4] žvβ # Convert this list from base-16 to base-10 # → 1415934836 žzв # Convert this integer from base-10 to base-256 # → [84,101,115,116] ç # Convert this number to ASCII characters # → ["T","e","s","t"] J # Join the characters together (and output implicitly) # → "Test" ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 199 bytes ``` s->{var z="";for(var x:s.substring(1).split("B")){int d=-1;for(var y:x.split("D"))d=-~d*4+"IAOU".indexOf(y);z+=(char)(d>9?d+55:d+48);}return new String(new java.math.BigInteger(z,16).toByteArray());} ``` [Try it online!](https://tio.run/##jVRNj5swFLznV1iczCaxFGm3akNJZRRV8qHisPJp1YM3kKxTAsg2aUiU/vXUGMzHkq56sB/G43nzBj/27Mjm@@jXjR/yTCiw12tUKJ6gbZFuFM9S9OBNNgmTEvxgPAWXCQB58ZrwDZCKKR2OGY/AQe/BZyV4unv5CZjYSddAAfje8Hytd2d1WIEt8G9yvrocmQBn33G8bSZgtTgtJZLFqzQ4uHCRzBOuoBM4rnvhqQKRP1@06HJ5soC1Bui9P9HD49QhOKQO4mkUn8ItLF3vPPXh5o0JF0arL9@i6dPTMpo@fna9q4hVIVKQxr9BLQ5Wj8aJA1NvKOA7kqp4Fwt4ni0@uUhlQaliLAQroasJbp6ptC1fxVJJ4DcGAOAEZE0CrAdZh3pgE8Nm3UUahAF2Zr1T2JzsTtGAmlm/HeHoXXbactcRtyg9W65efhJUcz1sPjzS9b/VVKs6T1cJbk@812IxRkeF7FU1zmSrDit1LUPHbp2ye0Nt/Yibym29nRddbtrLH/YiNRnv@DPAktYH@qFCMlIYBjY7HbC8V0NGrgxuS@vnfU2kdYIMnLcI0lRJevdo6Bge1IZH6oa3IRzdun85Q3sI0tNneT5@gx3zUa51g1b/jLpJTYsu60Z12z59LqWKDygrFMo1SiUp3CKW50kJK6Ru9ZptUo3r7S8 "Java (JDK 10) – Try It Online") ## Credits * -2 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) [Answer] **VBA (Excel), with an *amazing* ~~322~~ 244 bytes** Yeah, and I *LOVE* hexadecimal. (There's no sarcasm font yet, so I'm using italics for now) ~~I'll add comments if someone wants, but I think it's self explanatory.~~ Golfing happened. ``` Sub b(s) For Each c In Split(Replace(s,"D",""),"B") c=Application.Match(c,Array("I","A","O","U","II","IA","IO","IU","AI","AA","AO","AU","IO","OA","OO","OU"),0) If Not IsError(c)Then d=d &c-1:If Len(d)=2Then e=e &Chr("&h"&d):d="" Next Debug.?e End Sub ``` With Comments: ``` Sub b(s) 'For each string between B's (Remove the D's first) For Each c In Split(Replace(s,"D",""),"B") 'Get the index of the element in the array (Can cause error if empty) c = Application.Match (c,Array("I","A","O","U","II","IA","IO","IU","AI","AA","AO","AU","IO","OA","OO","OU"),0) 'If c isn't an error If Not IsError(c) Then 'Subtract 1 from c and add to d --> Array index is 1 based d = d & (c-1) 'If d is 2 characters If Len(d)=2 Then 'Add the char from the hex value of d --> &h forces Hex e = e & Chr("&h" & d) 'Reset d d = "" End if End if Next 'Print the output Debug.Print e End Sub ``` I really tried to get this into the VB Immediate Window, but it doesn't seem to work there... that would cut 11 characters I think. I also wanted to put the Match statement into brackets, but that causes a silent error everytime. Help is appreciated :D [Answer] # [Haxe](https://haxe.org), 228 bytes ``` s->{var l=(u,i)->((i=u.charCodeAt(i))&8==8?0:1)|((i>>1)&2),p=s.split("B"),i=-1,q,o;[while((i+=2)<p.length)String.fromCharCode(l(q=p[i+1],o=q.length-1)+((o>1?l(q,0)+1:0)+((l(q=p[i],o=q.length-1)+o*(l(q,0)+1)*2)*4))*4)].join("");} ``` Not the best, standard library function names are too large :( [Try it online!](http://try-haxe.mrcdk.com/#188Af) [Answer] # Pyth, 35 bytes ``` mCid16cm+4imx"IAOU"k.[N2d4tc-Q\D\B2 ``` Outputs as a list of characters. [Try it here](http://pyth.herokuapp.com/?code=mCid16cm%2B4imx%22IAOU%22k.%5BN2d4tc-Q%5CD%5CB2&input=%22BIDIBADIBIDOBIDABIDOBODIBIDOBODIBIDOBODUBOBA%22&debug=0) ### Explanation ``` mCid16cm+4imx"IAOU"k.[N2d4tc-Q\D\B2 tc-Q\D\B Get the vowels associated with each digit. m .[N2d Pad with a quote. mx"IAOU"k Find each character's position. +4i 4 Convert to base 4 and add 4. c 2 Split the result into pairs. mCid16 Get the associated ASCII characters. ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 36 bytes ``` FS≡ιB⊞υ⁰D⊞υ×⁴⊕⊟υ⊞υ⁺⊟υ⊕⌕AOUι⭆⪪υ²℅↨ι¹⁶ ``` [Try it online!](https://tio.run/##fVBNS8QwEL3vrwg9TaCCinhwT4lFmIOksPYHhDRrA922tIkexN9e06afLG5gJmTeezNvogrZqlqWfX@uWwJYNc6ebGuqT6CUdN/GqoKAoeTnoGSnScSjF5K6rgAXk3t6nKrJpvphLrqDp5hgpVp90ZXVOaR1A476czzk@ixdaVdBWrpuIuxFb6bKIWIii2Jigvj3kHpzFoLHd9nAqSmNHdo8evWrX0cqq1vg3heYmDw801HZ9xwT5MxnwYUPHAO5z/7OOEtmLBvf6N8BC7wVC3oxsbJdF0yuJ4SbjXhQrboB@98TTvPYhrmdh6NrsfDE4jnMmBXzbuzK3eBILP32m976mWzDwI2/uc/tCuvvvso/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` FS≡ι ``` Loop over each input character and switch. ``` B⊞υ⁰ ``` If it's a `B` then push `0` to the predefined empty list. ``` D⊞υ×⁴⊕⊟υ ``` If it's a `D` then pop the last value, increment it, multiply by `4`, and push it again. ``` ⊞υ⁺⊟υ⊕⌕AOUι ``` Otherwise, find the index in the string `AOU`, increment it, and add to the last value. ``` ⭆⪪υ²℅↨ι¹⁶ ``` Split the list into pairs of values, decode as base 16, convert to ASCII, and implicitly print. [Answer] # [Clean](https://github.com/Ourous/curated-clean-linux), ~~145~~ 134 bytes ``` import StdEnv // import things like addition and comparison ?c=(743rem(toInt c))/16 // magical formula that maps ['IAOU'] to [0,1,2,3] @[_,b,'D',d:t]=[?d+ ?b*4+4: @t] // convert B#D# @[_,b:t]=[?b: @t] // convert "B#" @_=[] // handle base case $[u,v:t]=[u<<4+v: $t] // turn the digits into 2-digit numbers $e=e // handle base case ``` # ``` toString o$o@ // convert to string (make numbers (make digits)) ``` [Try it online!](https://tio.run/##fZFda4MwFIbv/RWBCbbTMcakA2nwA3cRGORCvBIpGm0RNBkahf35Zanxq5T1Igk5z3vOeZND6jKjomFFX5egySoqquabtRxEvPikg@YSuPuw39uy2XGGKAdkv399O2hecrJyywgNq3B4ChO3MIGbP9um7QCPp4orkk@RE0xSTU96axjj/fFom4MDdMn0EpYi4lnLtSfQ8baiFwBBYgQoRIEvdxxgudC4UCB3ecaBH84sHu9I3hVTupWpfDyp4psqKLzvoE5/5Cprzbuy/z2hqZ@/UW77odE1XnR48ax6zBnz2/w7d1dHeKl3@9JHPxNvFGjjb67zOOIbqZzNuaeEV4zK6XAWqUExnXkaXJGan/gl5zq7dOIFfYnwh2ZNRbo/) Explained: [Answer] # PHP, 119 bytes ``` foreach(explode(B,$argn)as$i=>$m)($v=$v*16+4*strpos(XIAO,$m[-3]?:B)+strpos(IAOU,$m[-1]?:B))?$i&1||print chr($v&=255):0; ``` assumes uppercase input. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/d554d2d5d0c5a9b5b59e5c61dd6ac3afea7db227). requires PHP 7.1 for older PHP, use `substr($m,-3,1)` and `substr($m,-1)` instead of `$m[-<x>]` (+16 bytes); for younger PHP, put `B`, `XIAO` and `IAOU` in quotes to avoid warning messages (+10 bytes). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 40 bytes ``` 'B"IAOU"©âÐUs'D®ââJ)˜sXíDεSðý}:#khJ2ôHçJ ``` [Try it online!](https://tio.run/##yy9OTMpM/f9f3UnJ09E/VOnQysOLDk8ILVZ3ObQOyFrkpXl6TnHE4bUu57YGH95weG@tlXJ2hpfR4S0eh5d7/f/v5Oni6eQIxJ4u/kDsCKb9oXwEHeoE4QHVQFVBZBzhOhzhJqCqAekEqwSzIWowbYLwwbY4IUxAmB4K1Q2TQ3UbMu0IsRGsPhTJ9Z5Idoci2e@PRIeCbQSaAQA "05AB1E – Try It Online") [Answer] # PHP, 163 bytes ``` function f($s){$t=[I=>0,A=>1,O=>2,U=>3];for($q=explode(B,$s);$a=&$q[++$i];){$a=($a[1]?($t[$a[0]]+1)*4:0)+$t[$a[2*($a[1]==D)]];$i%2?:print(chr(($q[$i-1]<<4)+$a));}} ``` Call `f(string $s)` with the appropriate string of bibabobu-encoded characters, and it will print the decoded string. [Answer] # Python 3, 199 bytes ``` import re lambda s:''.join(eval(re.sub(r'(\d+), (\d+)',r'chr(16*\1+\2)',str(eval(s.replace('I','1').replace('A','2').replace('O','3').replace('U','4').replace('B',',-1+').replace('D','*4+')[1:]))))) ``` Not the shortest but without loops. ]
[Question] [ This is [**Fortnightly Challenge #6**](http://meta.codegolf.stackexchange.com/questions/3578/fortnightly-challenge-ideas). Theme: **Language Design** > > There's [a chatroom](http://chat.stackexchange.com/rooms/21289/fortnightly-challenge-of-2015-02-20-language-design) for this challenge. Come and join us if you want to discuss ideas! > > > And now for something completely different... This fortnight, we want to experiment with a new type of challenge. In this challenge, you will be designing a language! Pattern matching is a very common problem in programming, and often very useful for code golf. Regular expressions, for example, can be used to detect a pattern in a line of text. There are not, however, any established methods to describe and detect two-dimensional patterns. ## The Challenge You're to design a pattern-matching language, which allows the description of two-dimensional patterns in blocks of text. The **mode of operation** of your language will be similar to regular expressions (although your language doesn't have to have anything in common with regex otherwise): * As input, you will receive a rectangular block of text. You may assume that the text consists only of printable ASCII characters (0x20 to 0x7E) as well as newlines (0x0A) to separate the rows of the grid. * If a match, according to the pattern description, can be found as any subset of this block of text, this match should be returned or printed. If the match can be non-rectangular, it should be padded to a rectangular area with some reserved character. If there are several valid matches, you may decide how the returned match is chosen (largest, smallest, first, etc.). For some applications it might be useful if your implementation can return the position of a match instead of the match itself, but this is not a requirement. At the very least, your language should be able to match a pattern as a contiguous, rectangular subregion of its input. **Your answer should contain:** * A **description** of the language. * A **working implementation**. This can be a program, or a set of functions/classes in a language of your choice. * You should demonstrate your language by showing how it can be used to **solve the examples provided below**. Your language does not have to be capable of matching all of them, but you must be able to match **at least 8** of these. If your language can do something fancy we didn't think of, feel free to include it as well. If your answer builds on existing ideas, that is fine, but please give credit where it's due. ### Extensions The above describes the minimum that a valid submission has to satisfy. However, several generalisations could make such a pattern matching language even more useful, including but not limited to: * Being able to anchor the pattern to one or more edges, so that one can check if the entire input region has a certain pattern. * Producing all matches instead of just one. You may choose the semantics of overlapping matches. * Taking non-rectangular text as input. * Allowing patterns to specify non-rectangular matches. In such a case, the output should be padded to a rectangle with some reserved character. * Allowing patterns to specify matches with holes. * Allowing non-contiguous matches, like two characters appearing with a certain offset. * Easy specification of rotations and reflections. * Optionally treat the input cyclically as a cylinder or a torus, such that opposite edges are considered adjacent. ## Scoring The primary goal of this challenge is to produce an effective 2D pattern-matching language which could potentially be used in the future. As such, a scoring system like "shortest combined length to solve the examples" would lead to hard-coding of certain functionality at the expense of general usability. Therefore, we have decided that this challenge is best run as a **popularity contest.** The submission with the most net votes wins. While we can't force how people vote, here are a few guidelines for what voters should ideally look for: * **Expressiveness.** Can the language solve a variety of problems, even beyond the examples presented in this question? Does it support any of the suggested extensions? * **Readability.** How intuitive is the notation (at least to people who know the basic syntax)? * **Golfitude.** This is still CodeGolf.SE. For the purposes of this site, it would of course be nice to have a matching language that needs very little code to describe a pattern. ## Example Problems The following Stack Snippet shows 16 example problems which a 2-D pattern matching language could be able to deal with. Each example contains a short problem description and is then usually followed by one input example where a match can be found and one example where no match can be found (if applicable). As stated above, your language only needs to be able to solve 8 of these problems. Everything on top of that is optional, but should of course increase the number of votes you get. ``` body{font-family:'Helvetica Neue',Arial,sans-serif;color:#444;font-size:13px;width:500px;line-height:1.3}h3{font-size:16px!important;line-height:1.2em!important;margin-bottom:1.2em}code{white-space:pre-wrap;padding:1px 5px;font-family:'Droid Sans Mono',Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;color:#222;background:#eee}p code{padding:1px 5px}pre{overflow:auto;width:auto;width:480px !ie7;max-height:600px;font-family:'Droid Sans Mono',Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;margin-bottom:10px;padding:5px;background:#eee;border-left:2px dotted #ccc;font-size:12px}pre code{white-space:inherit;padding:0;background:0 0} ``` ``` <h3>Problem 1 - Finding Chessboards</h3><p>Match any rectangular subregion, at least 3 columns wide and 3 rows tall, which consists of alternating <code>#</code> and <code>_</code>. The top left corner may be either of those two characters.</p><p><strong>Match</strong></p><pre><code>~______~&#10;~##_#_#~&#10;~#_#_##~&#10;~##_#_#~&#10;~______~&#10;</code></pre><p>(There's an alternating 4x3 region in the centre. The match could be either that or either of its two 3x3 subregions.)</p><p><strong>No match</strong></p><pre><code>#_##&#10;_#_#&#10;__#_&#10;#_#_&#10;#_#_&#10;</code></pre><p>(Contains two 3x2 regions, but no alternating 3x3 region.)</p><h3>Problem 2 - Verifying Chessboards</h3><p>Match the entire input, provided all of it consists of alternating <code>#</code> and <code>_</code>. It may start with either of those two characters.</p><p><strong>Match</strong></p><pre><code>_#_#_#_#&#10;#_#_#_#_&#10;_#_#_#_#&#10;</code></pre><p><strong>No match</strong></p><pre><code>_#_#_#__&#10;__#_#_#_&#10;_#_#_#__&#10;</code></pre><h3>Problem 3 - Detect a Rectangle of Digits</h3><p>Match a rectangle (at least 2x2) consisting only of digits and no other characters.</p><p><strong>Match</strong></p><pre><code>hbrewvgr&#10;18774gwe&#10;84502vgv&#10;19844f22&#10;crfegc77&#10;</code></pre><p>You should match either the 5 wide by 3 tall rectangle (or any subset thereof) or the 2 by 2 rectangle.</p><p><strong>No Match</strong></p><pre><code>uv88wn000&#10;vgr88vg0w&#10;v888wrvg7&#10;vvg88wv77&#10;</code></pre><p>There are no rectangles of digits.</p><h3>Problem 4 - Finding a Word in a Word Search</h3><p>Match the smallest rectangular region containing containing the word "GOLF" in any orientation (horizontal, vertical, diagonal, forwards or backwards). If your language supports non-rectangular matches, you may also match diagonal words without the surrounding rectangle.</p><p><strong>Match</strong></p><pre><code>INOWCEF&#10;IFWNOPH&#10;VULUHGY&#10;GUYOIGI&#10;YTFUGYG&#10;FTGYIOO&#10;</code></pre><p>"GOLF" is found backwards along an upper-left to bottom-right diagonal. This is the region containing it:</p><pre><code>FWNO&#10;ULUH&#10;UYOI&#10;TFUG&#10;</code></pre><p><strong>No Match</strong></p><pre><code>BHTGIVUHSR&#10;BWEVYWHBWB&#10;BHTWBYTWYB&#10;</code></pre><p>("GOLF" cannot be found anywhere.)</p><h3>Problem 5 - Detect Square Inputs</h3><p>Match the entire input if it is a square block of characters.</p><p><strong>Match</strong></p><pre><code>qwerty&#10;asdfgh&#10;zx vbn&#10;uiop[]&#10;`1234 &#10;67890-&#10;</code></pre><p>There are six lines, each of which contains six characters, even though two characters are spaces.</p><p><strong>No Match</strong></p><pre><code> hello&#10; world&#10;</code></pre><p>The two lines don't each contain two characters.</p><h3>Problem 6 - Find Gliders in a Game of Life</h3><p>In Conway's <a href=http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life rel=nofollow>Game of Life</a> one of the most popular and simple patterns is the <a href=http://www.conwaylife.com/wiki/Glider rel=nofollow>glider</a>. There are two different stages in a glider's life cycle:</p><pre><code>## ##&#10;# # and ##&#10;# #&#10;</code></pre><p>Of course, the Game of Life is invariant under rotation and reflection, so in total there are 16 different shapes which resemble a glider at some stage.</p><p>Given input consisting only of <code>#</code> and spaces, match a 3x3 block containing a glider in any orientation. Spaces are significant! (Due to the conditions in the surrounding 5x5 layer, these matches might not be actual gliders, but don't worry about that.)</p><p><strong>Match</strong></p><pre><code>## # &#10; # ## &#10;# # # &#10;# # &#10;## ###&#10; # # &#10; # # &#10;</code></pre><p>This contains three gliders - top right corner, bottom right corner and left centre.</p><p><strong>No match</strong></p><pre><code>## # &#10; # ###&#10;## # #&#10;# # &#10;## ###&#10;</code></pre><h3>Problem 7 - Match Nether Portals</h3><p>Based on <a href=http://codegolf.stackexchange.com/questions/45488/nether-portal-detection>this challenge</a> by Calvin's Hobbies.</p><p>In the game of Minecraft, players can construct inter-dimensional portals using blocks of obsidian arranged into a rectangular frame. Given a 2D slice of the world, match a Nether portal. A valid Nether portal is a rectangle of empty space (<code>.</code>) surrounded on all sides by obsidian (<code>X</code>). The rectangle of space can be from 2 wide by 3 tall to 22 wide by 22 tall. Corners don't matter.</p><p><strong>Match</strong></p><pre><code>....X......&#10;.XXXXXX.XX.&#10;...X...X...&#10;.X.X...XXX.&#10;...X...X.X.&#10;.XXX...X.X.&#10;X..XXXXX.X.&#10;</code></pre><p>This is a 3 wide by 4 tall portal.</p><p><strong>No Match</strong></p><pre><code>XX..XXXX&#10;XX..X..X&#10;XX..X..X&#10;..X.X..X&#10;.X..X.XX&#10;</code></pre><p>This is almost a 2 wide by 3 tall portal, but one obsidian block is missing from the bottom.</p><h3>Problem 8 - Minecraft Chest Placement</h3><p>Based on <a href=http://codegolf.stackexchange.com/q/45720/8478>this challenge</a> by Calvin's Hobbies.</p><p>For this problem, returning the position of the match might be more useful than returning the actual match. "Adjacent" refers only to neighbours in four orthogonal directions. You're given a grid of <code>.</code> (empty cell) and <code>C</code> (chest). Two adjacent chests are considered a "double chest". You should match valid positions for placing additional chests. An empty cell is valid as long as it not adjacent to a double chest or two normal chests. Taking the example from the linked challenge, if the input is</p><pre><code>.......C..&#10;...C..C...&#10;.........C&#10;.CC...CC..&#10;..........&#10;</code></pre><p>the pattern should match the cell marked by <code>*</code> in the following grid:</p><pre><code>******.C**&#10;***C**C.**&#10;*..***..*C&#10;.CC.*.CC.*&#10;*..***..**&#10;</code></pre><h3>Problem 9 - Horizontal and Vertical Alignment</h3><p>Match a part of a column or row if it contains two or more <code>#</code> characters. As an extension, you could return the index of the column or row. If your language supports non-contiguous matches, match <em>only</em> the two <code>#</code>, not the row/column in between.</p><p><strong>Match</strong></p><pre><code>.,.,.,.#.,&#10;,.,#,.,.,.&#10;.,.,.,.,.,&#10;,.,.,.,.,.&#10;.,.#.,##.,&#10;,.,.,.,.,.&#10;</code></pre><p>There are 5 possible matches, three horizontal or two vertical. The horizontal matches are <code>#.,#</code>, <code>##</code>, and <code>#.,##</code>. The vertical matches are <code>#,.#</code> and <code>#.,.#</code>. The language can match any one or more of those.</p><p><strong>No Match</strong></p><pre><code>.,.#.,.,&#10;,.,.,.#.&#10;.,#,.,.,&#10;,.,.,.,#&#10;.#.,.,.,&#10;,.,.#.,.&#10;#,.,.,.,&#10;,.,.,#,.&#10;</code></pre><p>This is also a solution to the Eight Queens problem.</p><h3>Problem 10 - Collinear Points</h3><p>Match a set of three <code>#</code>s that are in a straight line, which can have any orientation, not necessarily horizontal or vertical (i.e. it could be diagonal are long knight's move steps). If your language supports non-contiguous matches, match <em>only</em> the three <code>#</code>, not the characters in between.</p><p><strong>Match</strong></p><pre><code>........&#10;#..#..#.&#10;...#....&#10;#.......&#10;...#....&#10;</code></pre><p>There are three possible matches. They are: the second row, the fourth column, and a diagonal line across 7 columns and 3 rows.</p><p><strong>No Match</strong></p><pre><code>.#..#&#10;#..#.&#10;#....&#10;..#.#&#10;</code></pre><p>There are no collinear <code>#</code>s in this input.</p><h3>Problem 11 - Verify Prelude Syntax</h3><p><a href=http://esolangs.org/wiki/Prelude rel=nofollow>Prelude</a> is an esoteric language, which has very few, but unusual, restrictions on what constitutes a valid program. Any block of printable ASCII text is valid provided that:</p><ul><li>Every column of text contains at most one of <code>(</code> and <code>)</code>.</li><li>Ignoring their vertical position, the <code>(</code> and <code>)</code> are balanced. Each <code>(</code> and be paired with exactly one <code>)</code> to the right of it, and vice-versa.</li></ul><p>The pattern should match any valid Prelude program and fail to match invalid programs.</p><p><strong>Match</strong></p><pre><code>?1-(v #1)- &#10;1 0v ^(# 0)(1+0)#)!&#10; (#) ^#1-(0 # &#10;</code></pre><p><strong>No match</strong></p><pre><code>#(#(##)##)##(&#10;)##(##(##)#)#&#10;</code></pre><p>For more examples, see <a href=http://codegolf.stackexchange.com/q/47239/8478>this challenge</a>.</p><h3>Problem 12 - Avoid the Letter Q</h3><p>Match any 4x4 square of characters that does not contain the letter <code>Q</code> or <code>q</code>.</p><p><strong>Match</strong></p><pre><code>bhtklkwt&#10;qlwQklqw&#10;vtvlwktv&#10;kQtwkvkl&#10;vtwlkvQk&#10;vnvevwvx&#10;</code></pre><p>There is one 4x4 square that does not contain any Qs. This is</p><pre><code>vlwk&#10;twkv&#10;wlkv&#10;vevw&#10;</code></pre><p><strong>No Match</strong></p><pre><code>zxvcmn&#10;xcvncn&#10;mnQxcv&#10;xcvmnx&#10;azvmne&#10;</code></pre><p>The single <code>Q</code> in the center prevents any matches from being formed.</p><h3>Problem 13 - Diamond Mining</h3><p>Locate a diamond in a field of characters. Diamonds are rotated squares formed by the characters <code>/\X</code>. Each corner of the diamond is formed by an <code>X</code>, and the corners are connected in lines formed by <code>\</code> or <code>/</code>, where each side is the same length. A diamond of size 0 has no <code>/\</code> sides. As an extension, you can return all of the diamonds in the field, return only the diamond's characters, and/or return the size of the diamond found.</p><p><strong>Match</strong></p><pre><code>...X......X....&#10;../.\..../.\...&#10;./.X.\..X...X..&#10;X.X.X.XX.\./.\.&#10;.\.X.//.\.X...X&#10;..\./X...X.\./.&#10;.X.X..\./...X..&#10;X.X....X.......&#10;.X.............&#10;</code></pre><p>There are 6 different diamonds in this field. Two are size 0, three are size 1, and one is size 2. Notice how diamonds can overlap parts or nest. You should be able to match diamonds of any size up to a reasonably high limit.</p><p><strong>No Match</strong></p><pre><code>.X......./....&#10;.\....X.......&#10;...X.\.\...X..&#10;..X.\...\.X.\.&#10;...X.X...X.\.X&#10;../X\...\...X.&#10;.X...\.\..X...&#10;..\./.X....X..&#10;...X..../.....&#10;</code></pre><p>No diamonds are found here.</p><h3>Problem 14 - Matching Crosses</h3><p>We'll define a cross as a rectangular region, which has been sliced into a (not necessarily regular) grid of 3x3 subregions. The four corner regions are filled with <code>.</code> whereas the other five regions are filled with <code>#</code>.</p><p><strong>Match</strong></p><pre><code>.......&#10;.###...&#10;######.&#10;######.&#10;.###...&#10;.###...&#10;.###.#.&#10;....###&#10;.....#.&#10;</code></pre><p>There is the small cross in the lower right corner, and the large cross yields 5 potential matches: the top and left arms will always have length 1, but the right and bottom arms can each either have length 1 or 2 - in addition the bottom arm can have length 3 if the right arm has length 1. Note that the full large cross cannot be matched because the top of the small cross would protrude into the lower right region.</p><p><strong>No Match</strong></p><pre><code>.######.&#10;...##...&#10;...##...&#10;........&#10;</code></pre><p>Each arm must have length of at least 1.</p><h3>Problem 15 - Match a Word in a Boggle Board</h3><p><a href=http://en.wikipedia.org/wiki/Boggle rel=nofollow>Boggle</a> is a bit like a word search, except that you change direction after each letter. Given a block of text, if it contains the word <code>panama</code> (<em>case-insensitive!</em>) according to the Boggle rules, match the smallest rectangle containing it. You may decide whether single letters can be reused or not. If your language can handle both, show it off! If you allow letters to be reused you can also choose if a letter can be used twice in a row (i.e. whether staying on the same cell is a valid move). If your language supports non-rectangular matches, match <em>only</em> the word.</p><p><strong>Match without reusing letters</strong></p><pre><code>EmYPhNuy&#10;AaaKVsjL&#10;onlGviCw&#10;DdOgFrRn&#10;ISeHZmqc&#10;zMUkBGJQ&#10;</code></pre><p>(There's a snaking <code>panamA</code> or <code>panAma</code> towards the upper left corner, depending on the order it's matched in.)</p><p><strong>Match with reusing letters</strong></p><pre><code>ExYPhNuy&#10;AfEKVsjL&#10;oblGviCw&#10;DdOgArRn&#10;ISepnmqc&#10;zMUkBGJQ&#10;</code></pre><p>(There's a <code>pAnAmA</code> towards the lower right corner, where all three <code>A</code> are the same.)</p><p><strong>No Match</strong></p><pre><code>BpbrzTHY&#10;mAJVRLuF&#10;jyXSPknK&#10;hoeGcsEl&#10;QCZagNMI&#10;dvUOqixt&#10;</code></pre><h3>Problem 16 - Wrap around the Edges</h3><p>Match a rectangle of <code>#</code>, at 3x3 in size, which may wrap around the edges of the input.</p><p><strong>Match</strong></p><pre><code>#..##&#10;#..##&#10;.....&#10;#..##&#10;</code></pre><p>(The 9 <code>#</code> form exactly one 3x3 region if you consider the edges to be adjacent.)</p><p><strong>No Match</strong></p><pre><code>...##&#10;#..##&#10;#..##&#10;#..#.&#10;</code></pre>&#10; ``` (No, you don't need to read that HTML code. Hit the "Run code snippet" button to get it nicely rendered by your browser, which you can then also view full screen.) [Answer] # SnakeEx Solves 15/16 problems so far! **[Online Interpreter](http://www.brianmacintosh.com/snakeex/)!** - [Full Language Spec](http://www.brianmacintosh.com/snakeex/spec.html) - [Javascript Source](http://www.brianmacintosh.com/snakeex/snake-ex.js) ![interpreter screenshot](https://i.stack.imgur.com/nfggG.png) The idea behind this language is to define 'snakes' that move around the text checking characters using a regex-like syntax. A program in SnakeEx consists of a list of definitions for snakes using different sequences of commands. Snakes can spawn other snakes using these definitions, which is where SnakeEx gets most of its power - we can match branching structures and even do recursion (see Paren Matching example). Every program will essentially look like a set of regexes, but with the addition of **direction** commands of the form **`<dir>`** that change the snake's direction, and **call** commands of the form **`{label<dir>params}`** that spawn more snakes. For an entry point, the interpreter spawns one snake using the first definition, moving to the right. It's not terribly concise, but it's very powerful and (I think) pretty readable. # Updates * Changed ! to logical not and ~ to not mark matches * Added `<!>` to solve colinear * Solved Matching Crosses * Solved chessboards in a less terrible way * Added bounded closure syntax `%{min,max}` * Added recursion example # Solutions ***15 solved, 1 in progress*** You can easily try out these programs out using the Online Interpreter linked above! **Problem 1 - Finding Chessboards** ``` m:{v<R>2}{h<>1} v:{c<L>A1}+ h:{c<R>A2}+ c:_?(#_)+#? ``` For a detailed introduction, start at Problem 3. **Problem 2 - Verifying Chessboards** ``` m:{v<R>2}{h<>1} v:${c<L>A1}+$ h:${c<R>A2}+$ c:$_?(#_)+#?$ ``` Book-ending the appropriate snakes with the out-of-bounds symbol `$` is one way to make a program match only the entire input. **Problem 3 - Detect a Rectangle of Digits** ``` m:{c<R>A1}%{2,} c:[0-9]%{2,} ``` The `m` snake moves right, spawning at minimum 2 snakes (`%{2,}` is a closure meaning "2 to infinity") using definition c (`c`) and moving right (`<R>`), or rather down in this case, because all directions are relative to the current snake. The `A` param is sugar that just specifies that the spawning snake should move after the call. The `1` parameter is how we restrict matches to rectangles - number parameters put snakes in "groups". A match does not count unless all snakes in the same group travel exactly the same distance. **Problem 4 - Finding a Word in a Word Search** ``` m:<*>GOLF ``` The direction command `<*>` specifies that the snake should turn in any diagonal or orthogonal direction. Then, it looks for the simple regex. **Problem 5 - Detect Square Inputs** ``` m:{v<R>1}{h<>1} v:${c<L>A1}+$ h:${c<R>A1}+$ c:$.+$ ``` The key here is the special character `$`, which only matches if the snake is out-of-bounds. We spawn a horizontal snake and a vertical one; each of those spawns more snakes as it runs along the edge, and all of those are in the same group and must be the same length. **Problem 6 - Find Gliders in a Game of Life** ``` m:<+>[({l1<R>A}{l2<R>A}{l3<R>})({l1<L>A}{l2<L>A}{l3<L>})] l1:##\. l2:[(#\.)(\.#)]# l3:#\.\. ``` `m` starts in any of the four orthogonal directions (`<+>`), achieving rotation. Then, it looks either left or right for the three rows in order, achieving reflection. (Note that I have replaced the spaces with periods only because the HTML textareas used in my interpreter seem to do stupid things if they have multiple spaces in a row) **Problem 7 - Match Nether Portals** ``` m:{e<R>A1}{d<R>A1}%{2,22}{e<R>1} e:~.X%{3,22}~. d:X\.+X ``` The `m` snake moves right, spawning a snake to check the left edge, 2-22 snakes to check the middle columns, and finally a snake to check the right edge. The `~` operator indicates that whatever follows should be checked but should not be marked as part of the solution. Bounded closures now allow us to fully and properly solve this problem! **Problem 8 - Minecraft Chest Placement** ``` m:~{s<>}~!{d<+>}\. s:<+>.<BR>([$\.]<R>)%{3} d:.<+>CC ``` Here we use a logical not (`!`), which matches if and only if the following token does not match anything. The declaration `d` detects a double chest in a particular direction, so `!{d<+>}` makes sure there are no double chests in any orthogonal direction. `s` moves in a little diamond around the current square, verifying at least 3 of those spaces are either empty or off the board. The trailing `\.` finally matches the square, assuming all the preceding conditions succeeded. **Problem 9 - Horizontal and Vertical Alignment** ``` m:<R>?#~.*# ``` The snake `m` optionally turns right (`<R>?`) before matching the sequence. `.` is a wildcard, like in regex. **Problem 10 - Colinear Points** ``` m:<!>#~.*#~.*# ``` With the addition of the `<!>` direction, we can solve this now! `<!>` is like `<+>` but instead of branching in four directions, it branches in every possible direction. **Problem 12 - Avoid the letter Q** ``` m:{h<R>A}%{4} h:[^Qq]%{4} ``` Just spawns 4 snakes that each look for four characters that are not the letter Q. **Problem 13 - Diamond Mining** ``` m:{tl<RB>1}{tr<RF>1} tl:X/*{bl<L>1}X tr:X\\*{br<R>1}X bl:X\\*X br:X/*X ``` This one's pretty neat. `m` spawns two snakes, one going to its back right, and one to its forward right. Each of those follows the slashes to an X, then spawns another snake at a right angle to its current direction, which follows the slashes to the bottom X. **Problem 14 - Matching Crosses** ``` m:{a<R>A}+{b<R>A}+{a<R>A}+ a:{e<>P1}{c<>P2}{e<>P3} b:{c<>P1}{c<>P2}{c<>P3} e:\.+ c:#+ ``` Here's the first time I've used the `P`iggyback parameter. Normally the snakes are independent, but if you make a call with this parameter, the calling snake will be moved with the callee. So `e2` can check a sequence of '.', then a sequence of '#', then another sequence of '.', and have them all be separate calls so we can group them with '1, '2', and '3', forcing their lengths to match up. **Problem 15 - Match a Word in a Boggle Board** ``` m{I}:<*>p<*>a<*>n<*>a<*>m<*>a ``` Simple, if wordy. `I` parameter specifies case-insensitivity (we can specify parameters on definitions as well as in calls). The snake turns in any direction, matches the character, turns again, and so forth. ``` m{EI}:<*>p<*>a<*>n<*>a<*>m<*>a ``` This is the no-reusing-characters version. The `E`xclusive parameter forbids the snake from matching any character that has already been marked, much like feersum's slime trails. **Problem 16 - Wrap around the Edges** ``` m{W}:{c<R>WA}%{3} c:### ``` The `W` parameter allows the snake to wrap when it runs out-of-bounds. We also have `H` and `V` to allow only horizontal or vertical wrapping. **Extra - Maze Solver** ``` m{E}:$(<P>\.)+$ ``` Solves an ASCII maze where the walkable floor is periods. The `<P>` direction means forward, left, or right (sugar for `[<F><L><R>]`). **Extra - Paren Matching** ``` m:\(~{r<>P}\) r:[^\(\)]*(\({r<>P}\))?[^\(\)]* ``` Haven't figure out how to do Prelude yet, but here's a first step! Here I use the `r` snake recursively to match corresponding parenthesis by checking that there are no unmatched parenthesis between them. **Extra - [ASCII Topology: Counting Loops](https://codegolf.stackexchange.com/a/48260/32671)** [Answer] # Slip, Python 3.4 ([Github wiki](https://github.com/Sp3000/Slip/wiki), [online interpreter](https://slip-online.herokuapp.com/)) Like feersum's submission this is also based on traversing the grid, but like CarpetPython's submission this is based on regex. Somehow it looks like I managed to take the middle ground. There's a quite a lot of unimplemented features which I want to add, so where relevant I've noted what I intend to do when I get time. --- ## Updates *(See Github page for detailed news)* * **Apr 5 2015**: Slip now has an [online interpreter](https://slip-online.herokuapp.com/)! It's still in its early stages, so there might be a few bugs. * **Apr 5 2015**: Efficiency update! Now does nether portals big input a lot faster (2s). Also there's been a number of syntax changes, so be sure to check the wiki. Group numbering also fixed. --- Slip has a match pointer which starts at a particular square and is initially facing rightward. When a char is matched, the pointer moves forwards in the current direction (although the implementation doesn't do things exactly in that order). The match pointer's direction can be set to a particular direction with `^<digit>`, where `^0`, `^1`, `^2`, ..., `^7` set the pointer to N, NE, E, ..., NW respectively (going clockwise). The following shortcuts are also available: * `^*` checks all 8 orthogonal or diagonal directions, * `^+` checks all 4 orthogonal directions. *(Future plan: Allow setting of arbitrary directions, e.g. `(1, 2)` for knight's move)* For example ([**Problem 4 - Finding a word in a word search**](https://slip-online.herokuapp.com/?code=%5E%2aGOLF&input=INOWCEF%0AIFWNOPH%0AVULUHGY%0AGUYOIGI%0AYTFUGYG%0AFTGYIOO&config=v)), ``` ^*GOLF ``` tries all 8 orthogonal or diagonal directions, looking for the word "GOLF". By default, Slip tries all possible starting squares and returns one result from each, filtering out duplicates, so a grid like ``` GOLF O L FLOG ``` returns only the top row and bottom row as matches (since the top row and left column "GOLF"s start from the same square). To get all matches, the `o` overlapping match mode can be used. Similarly ([**Problem 15 - Match a word in a Boggle board**](https://slip-online.herokuapp.com/?code=p%5E%2aa%5E%2an%5E%2aa%5E%2am%5E%2aa&input=EmYPhNuy%0AAaaKVsjL%0AonlGviCw%0ADdOgFrRn%0AISeHZmqc%0AzMUkBGJQ&config=irv)), ``` p^*a^*n^*a^*m^*a ``` matches `panama` by trying a different direction each time. Use the `i` flag for case insensitivity. Slip reuses chars by default, but this can be toggled with the `r` no-repeat flag. *(Future plan: a search mode modifier which automatically checks sets of directions after each move so that repeating `^*` is unnecessary)* The match pointer's direction can also be rotated 90 degrees left or right with `<` or `>` respectively. For instance, ``` `#`#< `#< <`#<`# ``` looks for the pattern ``` # ## ## ``` by looking in the following order: ``` 765 894 123 ``` This allows us to solve [**Problem 6 - Finding gliders**](https://slip-online.herokuapp.com/?code=%5E%2B%28%60%23%60%23%20%3E%60%23%20%3E%20%60%23%3E%60%23%3E%20%7C%60%23%60%23%20%3C%60%23%20%3C%20%60%23%3C%60%23%3C%20%7C%20%60%23%60%23%3E%20%60%23%3E%20%20%3E%60%23%3E%60%23%7C%20%60%23%60%23%3C%20%60%23%3C%20%20%3C%60%23%3C%60%23%29&input=%23%23%20%20%20%23%20%20%0A%20%20%23%20%23%23%20%20%0A%23%20%20%20%23%20%23%20%0A%23%20%23%20%20%20%20%20%0A%23%23%20%20%20%23%23%23%0A%20%20%20%23%20%23%20%20%0A%20%23%20%20%20%20%23%20&config=v) with ``` ^+(`#`# >`# > `#>`#> |`#`# <`# < `#<`#< | `#`#> `#> >`#>`#| `#`#< `#< <`#<`#) ``` where parts 1 and 2 encode the glider shapes, and parts 3 and 4 encode their reflected counterparts. Note that Slip uses backtick ``` for escaping. This is because Slip has another form of movement which gives the language its name — the slip command. `/` slips the match pointer orthogonally to the left, while `\` slips the match pointer orthogonally to the right. For example, ``` abc ghi def ``` can be matched by `abc\def/ghi`. While not particularly useful on its own, slipping becomes more important when combined with the `(?| <regex> )` stationary group, which acts like a matching lookahead. The regex inside is matched, then at the end of it the position and direction of the match pointer are reset to the state before the stationary group. For example, ``` abc def ghi ``` can be matched with `(?|abc)\(?|def)\(?|ghi)`. Similarly, [**Problem 12 - Avoid the letter Q**](https://slip-online.herokuapp.com/?code=%5E%2aGOLF&input=INOWCEF%0AIFWNOPH%0AVULUHGY%0AGUYOIGI%0AYTFUGYG%0AFTGYIOO&config=v) can be solved with ``` %(\(?|[^qQ]{4})){4} ``` where `%` is a no-slip command to stop the first `\` from activating. Slip also has a length assert `(?_(<group num>) <regex> )`, which only matches the regex inside if its match length is the same length as that of the given group num. For example, [**Problem 13 - Diamond mining**](https://slip-online.herokuapp.com/?code=%5E1X%28%60%2F%2a%29X%3E%28%3F_%281%29%60%5C%2a%29X%3E%28%3F_%281%29%60%2F%2a%29X%3E%28%3F_%281%29%60%5C%2a%29&input=...X......X....%0A..%2F.%5C....%2F.%5C...%0A.%2F.X.%5C..X...X..%0AX.X.X.XX.%5C.%2F.%5C.%0A.%5C.X.%2F%2F.%5C.X...X%0A..%5C.%2FX...X.%5C.%2F.%0A.X.X..%5C.%2F...X..%0AX.X....X.......%0A.X.............&config=v) can be easily solved with ``` ^1X(`/*)X>(?_(1)`\*)X>(?_(1)`/*)X>(?_(1)`\*) ``` which tries to match the top left side of the diamond first, then asserts that the other three sides are the same length. *(Run with `v` flag for verbose output)* ``` Match found in rectangle: (8, 0), (12, 4) X / \ X X \ / X Match found in rectangle: (0, 0), (6, 6) X / \ / \ X X \ / \ / X Match found in rectangle: (2, 2), (4, 4) X X X X Match found in rectangle: (10, 2), (14, 6) X / \ X X \ / X Match found in rectangle: (5, 3), (9, 7) X / \ X X \ / X Match found in rectangle: (0, 6), (2, 8) X X X X ``` A golfier alternative is ``` ^1X(`/*)(X>(?_(1)`\*)X>(?_(1)`/*)){2} ``` which matches the first side twice. Many of the other problems can be solved using slipping, stationary groups and length asserts: [**Problem 14 - Matching crosses:**](https://slip-online.herokuapp.com/?code=%28%3F%7C%28%60.%2B%29%28%60%23%2B%29%28%60.%2B%29%29%28%5C%28%3F%7C%28%3F_%282%29%60.%2B%29%28%3F_%283%29%60%23%2B%29%28%3F_%284%29%60.%2B%29%29%29%2a%28%5C%28%3F%7C%28%3F_%282%29%60%23%2B%29%28%3F_%283%29%60%23%2B%29%28%3F_%284%29%60%23%2B%29%29%29%2B%28%5C%28%3F%7C%28%3F_%282%29%60.%2B%29%28%3F_%283%29%60%23%2B%29%28%3F_%284%29%60.%2B%29%29%29%2B&input=.......%0A.%23%23%23...%0A%23%23%23%23%23%23.%0A%23%23%23%23%23%23.%0A.%23%23%23...%0A.%23%23%23...%0A.%23%23%23.%23.%0A....%23%23%23%0A.....%23.&config=v) ``` (?|(`.+)(`#+)(`.+))(\(?|(?_(2)`.+)(?_(3)`#+)(?_(4)`.+)))*(\(?|(?_(2)`#+)(?_(3)`#+)(?_(4)`#+)))+(\(?|(?_(2)`.+)(?_(3)`#+)(?_(4)`.+)))+ ``` Once you capture the widths of the `.`s and `#`s in the first row, it's just slipping all the way down. Output: ``` Match found in rectangle: (0, 1), (5, 5) .###.. ###### ###### .###.. .###.. Match found in rectangle: (4, 6), (6, 8) .#. ### .#. ``` This one can probably be golfed with a bit of recursion, once I get a few bugs sorted out. [**Problem 3 - Detect a rectangle of digits:**](https://slip-online.herokuapp.com/?code=%28%3F%7C%60d%60d%2B%29%28%5C%28%3F%7C%28%3F_%281%29%60d%2B%29%29%29%2B&input=hbrewvgr%0A18774gwe%0A84502vgv%0A19844f22%0Acrfegc77&config=v) ``` (?|`d`d+)(\(?|(?_(1)`d+)))+ ``` Match a top row of two or more digits, then make sure every line below is the same length. ``d` is a predefined character class equivalent to `[0-9]`. Note that this finds [all matches](http://pastebin.com/jvfB0EAD). [**Problem 7 - Match nether portals:**](https://slip-online.herokuapp.com/?code=%28%3F%7C.X%7B2%2C22%7D.%29%5C%28%28%3F%7C%28%3F_%281%29X%60.%2BX%29%29%5C%29%7B3%2C22%7D%28%3F_%281%29.X%2B.%29&input=...................................%0A..XXXX....XXXX....XXXXXXXXX........%0A..X..X...X....X..X.........X..XXXX.%0A..X..X...X....X..X.......X.X..X....%0A..X..X...X....XXXX.........X..X..X.%0A..XXXX....XXXX...XXXXXXXXXXX..X..X.%0A.............X...X....X...X...XXXX.%0A.............X...X....X...X........%0A..............XXX......XXX.........%0A...................................&config=v) ``` (?|.X{2,22}.)\((?|(?_(1)X`.+X))\){3,22}(?_(1).X+.) ``` which outputs, for the top example in the [original thread](https://codegolf.stackexchange.com/questions/45488/nether-portal-detection): ``` Match found in rectangle: (2, 1), (5, 5) XXXX X..X X..X X..X XXXX Match found in rectangle: (9, 1), (14, 5) .XXXX. X....X X....X X....X .XXXX. Match found in rectangle: (13, 4), (17, 8) .XXXX X...X X...X X...X .XXX. ``` Finally, some other features of Slip include: * `$0, $1, $2, ..., $7` anchor the north edge, north-east corner, east edge, etc. `$+` anchors any edge and `$*` anchors any corner. * `$` followed by a lowercase character sets an anchor at the current position, which can later be matched by `$` followed by the corresponding uppercase character, e.g. `$a` and `$A`. * `#` toggles the no-move flag, which stops the match pointer from moving forward after the next match. * `,` matches a char like `.`, but doesn't add it to the output, allowing for non-contiguous matches while being able to be recognised by `(?_())`. ... and more. There's really too many to list on this page. ## Other problems [**Problem 1 - Finding chessboards:**](https://slip-online.herokuapp.com/?code=%28%3F%7C%60%23%3F%28%60_%60%23%29%2B%60_%3F%29%28%3F_%281%29%28%3F%7C...%2B%29%29%28%5C%28%3F_%281%29%28%3F%7C%60%23%3F%28%60_%60%23%29%2B%60_%3F%24a%29%29%29%2B%3C%28%3F%7C%60%23%3F%28%60_%60%23%29%2B%60_%3F%29%28%3F_%289%29%28%3F%7C...%2B%29%29%28%5C%28%3F_%289%29%28%3F%7C%60%23%3F%28%60_%60%23%29%2B%60_%3F%29%29%29%2B%24A&input=%7e______%7e%0A%7e%23%23_%23_%23%7e%0A%7e%23_%23_%23%23%7e%0A%7e%23%23_%23_%23%7e%0A%7e______%7e&config=v) ``` (?|`#?(`_`#)+`_?)(?_(1)(?|...+))(\(?_(1)(?|`#?(`_`#)+`_?$a)))+<(?|`#?(`_`#)+`_?)(?_(9)(?|...+))(\(?_(9)(?|`#?(`_`#)+`_?)))+$A ``` The two chessboard problems certainly aren't Slip's forte. We match the top row then make sure it's at least length 3 and alternates between `#` and `_`, then slip and match subsequent rows. By the end, the `$a` anchor should be at the bottom right of the chessboard. We then turn left and repeat for columns, making sure we match `$A` at the end. [**Problem 2 - Verifying chessboards:**](https://slip-online.herokuapp.com/?code=%247%25%28%5C%28%3F%7C%60_%3F%28%60%23%60_%29%2a%60%23%3F%242%29%29%2B%245%3C%25%28%5C%28%3F%7C%60_%3F%28%60%23%60_%29%2a%60%23%3F%240%29%29%2B%243&input=_%23_%23_%23_%23%0A%23_%23_%23_%23_%0A_%23_%23_%23_%23&config=) ``` $7%(\(?|`_?(`#`_)*`#?$2))+$5<%(\(?|`_?(`#`_)*`#?$0))+$3 ``` Like the previous problem, we check that each row is correct, then rotate left and do the same for columns. Anchors are used to make sure only the whole board is matched. [**Problem 9 - Horizontal and vertical alignment:**](https://slip-online.herokuapp.com/?code=%3E%3F%60%23%2C%2a%60%23&input=.%2C.%2C.%2C.%23.%2C%0A%2C.%2C%23%2C.%2C.%2C.%0A.%2C.%2C.%2C.%2C.%2C%0A%2C.%2C.%2C.%2C.%2C.%0A.%2C.%23.%2C%23%23.%2C%0A%2C.%2C.%2C.%2C.%2C.&config=v) ``` >?`#,*`# ``` We apply the optional ? quantifier to the `>` rotate command so that we either match rightward or downward. We find all 5 in the example with `o` overlapping mode, but only 4 without it since `#.,##` and `#.,#` start from the same position. [**Problem 10 - Collinear points**](https://slip-online.herokuapp.com/?code=%5E%2B%60%23%28%3F%7C%28%2C%2a%29%3C%28%2C%2a%29%29%28%28%28%3F_%282%29%2C%2a%29%3C%28%3F_%283%29%2C%2a%29%2C%3E%29%2B%23%60%23%29%7B2%7D&input=.........%0A%23..%23..%23..%0A...%23.....%0A%23........%0A...%23.....%0A.%23..%23...%23&config=v) ``` ^+`#(?|(,*)<(,*))(((?_(2),*)<(?_(3),*),>)+#`#){2} ``` Match a `#` then some horizontal chars and some vertical chars, then repeat until the second `#`, and repeat until the third `#`. [**Problem 5 - Detecting square inputs:**](https://slip-online.herokuapp.com/?code=%247.%28.%2a%29%3E%28%3F_%281%29.%2a%29%243%3E%28%28%3F%7C.%2a%29%5C%29%2a&input=qwerty%0Aasdfgh%0Azx%20vbn%0Auiop%5B%5D%0A%601234%20%0A67890-&config=) ``` $7.(.*)>(?_(1).*)$3>((?|.*)\)* ``` Anchor the top left corner, and check that the top edge is the same length as the right edge, before anchoring the bottom right corner. If the input passes this, then we go up backwards to match the whole input. [**Problem 8 - Minecraft chest placement:**](https://slip-online.herokuapp.com/?code=%5E%2B%28%28%24%5E%7C%28%3F%7C%60.%29%29%3E%29%7B3%7D%28%24%5E%7C%60.%7CC%3C%28%28%24%5E%7C%28%3F%7C%60.%29%29%3E%29%7B3%7D%29&input=.......C..%0A...C..C...%0A.........C%0A.CC...CC..%0A..........&config=p) ``` `.^+(($^|(?|`.))>){3}($^|`.|C<(($^|(?|`.))>){3}) ``` Run with the `p` flag to get the positions of each match. `$^` is an anchor which matches if the next move would put the match pointer out of bounds. First we match a `.`, then check that we're surrounded by three `.`s/boundaries, then makes sure that the fourth surrounding square is also a `.`/boundary or is a single chest (by checking *its* surrounding squares). [**Problem 11 - Verify Prelude syntax**](https://slip-online.herokuapp.com/?code=%247%3E%25%28%2F%28%3F%7C%5B%5E%28%29%5D%2B%244%29%28%3F1%29%3F%7C%2F%28%3F%7C%5B%5E%28%29%5D%2a%60%28%5B%5E%28%29%5D%2a%244%29%28%3F1%29%3F%2F%28%3F%7C%5B%5E%28%29%5D%2a%60%29%5B%5E%28%29%5D%2a%244%29%28%3F1%29%3F%29%241&input=%3F1-%28v%20%20%231%29-%20%20%20%20%20%20%20%20%20%20%20%20%20%0A1%20%20%200v%20%5E%28%23%20%20%20%200%29%281%2B0%29%23%29%21%0A%20%20%20%20%28%23%29%20%20%5E%231-%280%20%23%20%20%20%20%20%20%20&config=): ``` $7>%(/(?|[^()]+$4)(?1)?|/(?|[^()]*`([^()]*$4)(?1)?/(?|[^()]*`)[^()]*$4)(?1)?)$1 ``` Took a few tries, but I think this one's correct. Here we use recursion, which has the same syntax as PCRE. This approach requires that the input is rectangular, but once I get non-rectangular matching done that assumption won't be necessary. Here's the same approach, golfed with more recursion: ``` $7>%((/(?|([^()]*)$4)|/(?|(?4)`((?3))(?1)?/(?|(?4)`)(?3)))*)$1 ``` **Problem 16 - Wrap around the edges:** ``` %(\(?|`#{3})){3} ``` *(Note: Wrapping has not yet been pushed to the online interpreter)* This requires the wrapping flag `w`. Technically the initial `%` for no-slip is not necessary, but then the match would be counted as starting from one square higher. [**Problem EX 1 - Maze solver:**](https://slip-online.herokuapp.com/?code=S%28%5E%2B%60.%29%2a%5E%2BE&input=%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B%0AS.%7C...%7C...%7C...%7C...%7C.%7C%0A%2B.%2B-%2B.%2B.%2B.%2B-%2B.%2B.%2B.%2B.%2B%0A%7C.......%7C...%7C.%7C.%7C.%7C.%7C%0A%2B.%2B-%2B-%2B-%2B-%2B.%2B.%2B.%2B.%2B.%2B%0A%7C.%7C...%7C...%7C.%7C.%7C.%7C...%7C%0A%2B.%2B.%2B.%2B.%2B.%2B.%2B.%2B.%2B-%2B-%2B%0A%7C.%7C.%7C...%7C.%7C.%7C.%7C.....%7C%0A%2B.%2B.%2B-%2B-%2B.%2B.%2B.%2B-%2B-%2B.%2B%0A%7C.%7C...%7C...%7C.%7C.....%7C.%7C%0A%2B.%2B-%2B.%2B-%2B-%2B.%2B-%2B-%2B.%2B.%2B%0A%7C...%7C.....%7C...%7C.....%7C%0A%2B-%2B.%2B-%2B-%2B.%2B-%2B.%2B.%2B-%2B-%2B%0A%7C.%7C.%7C...%7C...%7C.%7C...%7C.%7C%0A%2B.%2B.%2B-%2B.%2B-%2B.%2B.%2B-%2B.%2B.%2B%0A%7C.%7C.....%7C.......%7C...%7C%0A%2B.%2B-%2B-%2B-%2B.%2B-%2B.%2B.%2B.%2B-%2B%0A%7C.....%7C...%7C...%7C.%7C...%7C%0A%2B-%2B-%2B.%2B-%2B-%2B.%2B-%2B-%2B.%2B.%2B%0A%7C.................%7C.E%0A%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B-%2B&config=r) ``` S(^+`.)*^+E ``` Problem from [BMac's comment in chat](http://chat.stackexchange.com/transcript/message/20427532#20427532). Use the `r` flag for no repeat mode so that the match pointer doesn't get stuck going back and forth. **[Problem EX 2](https://slip-online.herokuapp.com/?code=%28%3F%7CO%28%2C%2a%29%2C%28%3F_%282%29%2C%2a%29O%29%28%3F_%282%29%28%5C%28%3F%7C%2C%29%29%2a%29%5C%28%3F%7C%2C%28%3F_%282%29%2C%2a%29O%29%28%3F_%282%29%28%5C%28%3F%7C%2C%29%29%2a%29%5C%60%5C%28%3F_%282%29%60_%2a%29%60_%28%3F_%282%29%60_%2a%29%60%2F&input=%7e%7B%24FJ%2aTBNFU%2aYBVEXGY%25%0AFOCO%24%26N%7C%3EZX%7DX_PZ%3C%3E%7D%2B%0AX%24OOPN%20%5E%25%C2%A3%29LBU%7BJJKY%25%0A%40%5C_%2F%24%C2%A3%21SXJ%2a%29KM%3E%3E%3FVKH%0ASDY%25%C2%A3ILO%28%2B%7BO%3AHO%28UR%24W%0AXVBFTER%5E%26INLNLO%2a%28%26P%3A%0A%3E%3FLKPO%29UJO%24%C2%A3%5E%26L%3A%7D%7e%7B%26%0A%7e%40%3F%7D%7B%29JKOINLM%40%7e%7DP%3EOU%0A%3A%40%3CL%3A%3A%40%5C___%2FGER%25%5E%2aBI%0A%40%7BPO%7B_%29%3A%3C%3EKNUYT%2a%26G%26%5E&config=v) - [Facial recognition](https://codegolf.stackexchange.com/questions/3117/facial-recognition):** ``` (?|O(,*),(?_(2),*)O)(?_(2)(\(?|,))*)\(?|,(?_(2),*)O)(?_(2)(\(?|,))*)\`\(?_(2)`_*)`_(?_(2)`_*)`/ ``` Note that I'm only matching faces, not doing any clearing. Note that the question contains euro symbols, which will need to be replaced by some printable ASCII to work. [Answer] # PMA/Snails (C++) I envision the language as snails moving around a grid and executing commands. The snails leave a trail of slime on each square which they move onto, which by default causes the square to be subsequently unmatchable. A match is successful if the end of the list of commands is reached. There are enough operators now that we're going to need a precedence list to keep track of them. The operations are resolved in the following order: 1. Inside of groups `( ) [ ]` 2. Split along alternation character `|` 3. Evaluate everything to the left of a ``` as a group 4. Quantifiers `*[m],[n]*` and `*n*` 5. Assertions `= !` 6. Concatenation The interpreter is written in C++. The abysmal source code can be found [here](https://github.com/feresum/PMA). ## Problem 4: Word Search The program ``` z\G\O\L\F ``` is sufficient to get a truthy or falsey value for whether the word is found. `z` (one of the 15 absolute or relative directional commands) matches in any octilinear direction. Multiple consecutive direction commands are ORed together. For example `ruldy` would be nearly equivalent to `z`, as those are the commands for right, up, left, down, and any diagonal direction. However, the directions would be tested in a different order. The first character matched is always the one the snail starts on, regardless of direction. `\`<character> matches a single literal character. The default strategy is to try the pattern at every square in the bounding box of the left-justified input, and output the number of matches. If a boolean value `1` or `0` is required, the following program can be used: ``` ? z\G\O\L\F ``` If there is at least one newline in the source file, the first line is treated as options for the initial conversion of the input into a rectangular form. The `?` option prints 0 or 1 depending on whether there is a match anywhere. ## Problem 15: Boggle After implementing alternation, it is now possible to solve Boggle. It would be better to use case-insensitive matching for this one, but implementing that is not my highest priority. ``` \p|\P)z(\a|\A)z{\n|\N)z{\a|\A}z(\m|\M)z(\a|\A ``` `|` works exactly the same as a 1-dimensional regex. There are two matching pairs of delimiters for grouping, namely `()` and `{}`. A closing bracket will close any open groups of the opposite type which stand between it and the nearest of the same type. For example, following `{({{)`, only the leftmost group remains open. As you can see, unmatched grouping symbols at the edges are implicitly closed. There is another grouping command ``` which I will not go into now. ## Problem 8: Minecraft Chests The program prints the number of valid chest placements. This was the first one I actually had to golf, and reduced my byte count (17) a few times. ``` \.!(o\C)2o(!\Cw)3 ``` * `\.` matches a dot literally, at the starting point of the match. * `!(o\C)2` is equivalent to `!((o\C)2)` as quantification is higher precedence than assertion. `<atom> <number>` means to repeat `<atom>` exactly `<number>` times. `o` turns the snail in any orthogonal direction. `!` is a negative assertion. Thus this part checks for the absence of an adjacent double chest. * `o` turns in some orthogonal direction. + `(!\Cw)3` asserts that there is no `C` in front of the snail, and then turns counterclockwise, 3 times. ## Problem 2: Verifying chessboards ``` & \#!(o^_)|\_!(o^# ``` The `&` option sets the program's output as `1` if the match succeeds at all positions, and `0` otherwise. `^c` matches a character that is not `c`, equivalently to `[^c]` in regex. As a whole, the program means: Print 1 if at every position in the bounding rectangle of the input, there is either a `#` which is not orthogonally adjacent to a character that is not `_`, or an `_` which is not orthogonally adjacent to a character that is not `#`; otherwise 0. [Answer] # [Grime](https://github.com/iatorm/grime), Haskell ## Introduction Grime is based on [Boolean grammars](http://en.wikipedia.org/wiki/Boolean_grammar). The basic idea is to construct rectangular patterns from smaller components, and check whether they are found in the input matrix. So far, Grime only supports rectangular matches, and solves at least 11 problems more or less elegantly. *EDIT:* Fixed the crosses (thanks to DLosc for spotting the bug), and added diamond mining. *EDIT2:* Added character classes, inspired by those of Slip. Also changed the syntax of option flags, improved the expression parser, and added the no-Q problem. *EDIT3:* Implemented size constraints, and added the Nether portals problem. ## Usage A Grime program is called a *grammar*, and the correct file extension for a grammar is `.gr`, although this is not enforced. The grammar is evaluated as ``` runhaskell grime.hs [options] grammarfile matrixfile ``` where `matrixfile` is a file containing the character matrix. For example, the digits grammar would be evaluated as ``` runhaskell grime.hs digits.gr digit-matrix ``` For extra speed, I recommend compiling the file with optimizations: ``` ghc -O2 grime.hs ./grime digits.gr digit-matrix ``` By default, the interpreter prints the first match it finds, but this can be controlled using the option flags: * `-e`: match only the entire matrix, print `1` for match and `0` for no match. * `-n`: print the number of matches, or the entire matrix if `-e` is also given. * `-a`: print all matches. * `-p`: print also the positions of the matches, in the format `(x,y,w,h)`. * `-s`: do not print the matches themselves. * `-d`: print debug information. Options can also be specified within the grammar, by inserting them before any line and adding a comma `,` (see below for examples). ## Syntax and Semantics A Grime grammar consists of one or more *definitions*, each on a separate line. Each of them defines the value of a *nonterminal*, and one of them must define the anonymous *toplevel nonterminal*. The syntax of a definition is either `N=E` or `E`, where `N` is an uppercase letter and `E` is an *expression*. Expressions are constructed as follows. * Any character escaped with `\` matches any `1x1` rectangle containing that character. * `.` matches any single character. * `$` matches a `1x1` rectangle outside the character matrix. * `_` matches any rectangle of zero width or height. * The pre-defined character groups are `d`igit, `u`ppercase, `l`owercase, `a`lphabetic, alpha`n`umeric, and `s`ymbol. * New character classes can be defined by the syntax `[a-prt-w,d-gu]`. The letters on the left are included, and those on the right are excluded, so this matches exactly the letters `abchijklmnoprtvw`. If the left side is empty, it is taken to contain all characters. The comma can be omitted if the right side is empty. The characters `[],-\` must be escaped with `\`. * An unescaped uppercase letter is a nonterminal, and matches the expression it is assigned. * If `P` and `Q` are expressions, then `PQ` is just their horizontal concatenation, and `P/Q` is their vertical concatenation, with `P` on top. * `P+` is one or more `P`s aligned horizontally, and `P/+` is the same aligned vertically. * The Boolean operations are denoted `P|Q`, `P&Q` and `P!`. * `P?` is shorthand for `P|_`, `P*` for `P+|_`, and `P/*` for `P/+|_`. * `P#` matches any rectangle that contains a match of `P`. * `P{a-b,c-d}`, where `abcd` are nonnegative integers, is a *size constraint* on `P`. If `P` is a character class, then the expression matches any `mxn` rectangle containing only those characters, provided that `m` is between `a` and `b` inclusive, and `n` is between `c` and `d` inclusive. In other cases, the expression matches any rectangle that has the correct size and that `P` also matches. If `a` or `c` are omitted, they are taken to be `0`, and if `b` or `d` are omitted, they are infinite. If the hyphen between `a` and `b` is omitted, then we use the same number for both ends of the interval. If the entire `c-d` part is omitted, both axes are constrained. To clarify, `{-b}` is equivalent to `{0-b,0-b}`, and `{a-,c}` is equivalent to `{a-infinity,c-c}`. ## Notes Grime does allow paradoxical definitions like `A=A!` with undefined behavior. However, they will not cause crashes or infinite loops. Grime supports non-rectangular inputs; the rows are simply aligned to the left, and the gaps can be matched using `$`. In the future, I'd like to implement the following: * Faster matching. Currently, the interpreter does not take into account the fact that, for example, `.` can only match `1x1` rectangles. Until it finds a match, it tries all rectangles of all sizes in order, instantly failing for each of them. * Rotation and reflection operations, for the word search and glider challenges. * Non-rectangular matches using *contexts*, which would be helpful in the Boggle board challenge. For example, `Pv(Q>R)` means `P` with bottom context (`Q` with right context `R`). It would match the L-shaped patterns ``` PPP PPP QQQRRRR QQQRRRR QQQRRRR ``` ## The Tasks Given roughly in order of complexity. ### Rectangle of digits ``` d{2-} ``` This is simple: a rectangle of digits of size at least `2x2`. ### No q or Q ``` [,qQ]{4} ``` This is almost as simple as the first one; now we have a more restricted size and a custom character class. ### Horizontal and vertical alignment ``` \#.*\#|\#/./*/\# ``` Now we have some escaped characters. Basically, this matches one `#`, then any number of any characters, then `#`, either horizontally or vertically. ### Detect square inputs ``` S=.|S./+/.+ e,S ``` This grammar is very simple, it basically defines that a square is either a `1x1` rectangle, or a smaller square with one column tacked on its right edge, and one row tacked to the bottom of that. Note also the `e` option before the toplevel nonterminal, which toggles entire-input verification. ### Finding a word in a word search ``` G=\G O=\O L=\L F=\F GOLF|FLOG|G/O/L/F|F/L/O/G|G.../.O../..L./...F|...G/..O./.L../F...|F.../.L../..O./...G|...F/..L./.O../G... ``` This one's horrible, since Grime has no operations for rotation or reflection. It is also extremely slow, since Grime does not know that the matches can only be of size `4x1`, `1x4` or `4x4`. The glider problem could be solved similarly, but I'm too lazy to write that down. ### Nether Portals ``` .\X+./\X/+\.{2-22,3-22}\X/+/.\X+. ``` With the size restriction operator, this one's not that hard. The middle part `\.{2-22,3-22}` matches any rectangle of `.` of the correct sizes, and then we just add columns of `X`s on both sides, and tack rows of `X`s with ignored ends on the top and bottom of that. ### Matching crosses ``` E=\.+/+ F=\#+/+ EFE/F/EFE&(E/F/E)F(E/F/E) ``` What we have here is a conjunction (logical AND) of two expressions. The nonterminal `E` matches a nonempty rectangle of `.`s, and `F` a nonempty rectangle of `#`s. The left side of the conjunction matches rectangles of the type ``` ...####.. ...####.. ...####.. ######### ######### .....##.. .....##.. ``` where we have `EFE` on the top, then `F`, and then `EFE` again. The right side matches the transposes of these, so we get exactly the crosses. ### Diamond mining ``` C=./+ T=\X|CTC/\/.+\\ B=\X|\\.+\//CBC CTC/\X.+\X/CBC ``` The nonterminal `C` is a shorthand for any `1xn` column. The top half of a diamond is matched by `T`: it is either a single `X`, or another `T` surrounded by a column on both sides, and a row `/[something]\` below that. `B` matches the bottom of a diamond in the same way, and the toplevel nonterminal is just row of the form `X[something]X` between a top half and a bottom half. ### Finding chessboards ``` (\#\#|\#/\#|\_\_|\_/\_)#!&[#_]{3-} ``` The right-hand side `[#_]{3-}` matches any `3x3` or larger rectangle of `#`s and `_`s, while the left-hand side guarantees that it does not contain two adjacent `#`s or `_`s. ### Verifying chessboards ``` e,(\#\#|\#/\#|\_\_|\_/\_)#!&[#_]+/+ ``` This is basically the same as above, except that we can match any non-empty rectangle, but need to use the `e` flag for entire input verification. ### Verify Prelude syntax ``` A=[,()]/* P=A*|P(A/\(/A)P(A/\)/A)P e,P ``` This is probably the most interesting grammar so far. The nonterminal `A` matches any column not containing `(` or `)`, and `P` matches either some number of `A`s, or two matched parentheses, between and outside which there are more `P`s. [Answer] # The Re2d class, Python 2 *Update: added "9. Alignment" problem.* My approach is to use the Python re module to do the searching and matching. The Re2d class prepares the text for processing, executes the re functions, and formats the results for output. Note that this is not a whole new language - it is the standard regular expression language projected into 2 dimensions with added flags for extra 2D modes. The class has the following usage: ``` re2dobject = Re2d(<horizontal pattern>, [<vertical pattern>], [<flags>]) ``` Both patterns are standard linear text RE patterns. If a vertical pattern is not supplied, the class will use the horizontal pattern for matching vertically too. The flags are the standard RE flags with some 2D extensions. ## Testing ``` 1. Finding chessboards Chessboard pattern at (2, 1, 4, 3) print '\n1. Finding chessboards' reob1 = Re2d('#(_#)+_?|_(#_)+#?') found = reob1.search('~______~\n~##_#_#~\n~#_#_##~\n~##_#_#~\n~______~') print 'Chessboard pattern at', found assert not reob1.search('#_##\n_#_#\n__#_\n#_#_\n#_#_') ``` The search method found a chessboard pattern and returns a 4-tuple position. The tuple has the `x,y` position of the first character of the match, and the `width, height` of the area matched. Only one pattern is given so it will be used for horizontal *and* vertical matching. ``` 2. Verifying chessboards Is chess? True print '\n2. Verifying chessboards' reob2 = Re2d('^#(_#)*_?|_(#_)*#?$') print 'Is chess?', reob2.match('_#_#_#_#\n#_#_#_#_\n_#_#_#_#') assert not reob2.match('_#_#_#__\n__#_#_#_\n_#_#_#__') ``` The chessboard was verified with the match method which returns a boolean. Note that the `^` and `$` start and end characters are required to match the *whole* text. ``` 3. Rectangle of digits Found: [(0, 1, 5, 3), (1, 1, 4, 3), (2, 1, 3, 3), (3, 1, 2, 3), (0, 2, 5, 2), (1, 2, 4, 2), (2, 2, 3, 2), (3, 2, 2, 2), (6, 3, 2, 2)] Not found: None print '\n3. Rectangle of digits' reob3 = Re2d(r'\d\d+', flags=MULTIFIND) print 'Found:', reob3.search('hbrewvgr\n18774gwe\n84502vgv\n19844f22\ncrfegc77') print 'Not found:', reob3.search('uv88wn000\nvgr88vg0w\nv888wrvg7\nvvg88wv77') ``` We now use the `MULTIFIND` flag to return all of the possible matches for the 2+ digit block. The method finds 9 possible matches. Note that they can be overlapping. ``` 4. Word search (orthogonal only) Words: [(0, 0, 4, 1), (0, 3, 4, 1), (3, 3, -4, -1), (3, 2, -4, -1), (3, 0, -4, -1)] [(0, 0, 1, 4), (3, 0, 1, 4), (3, 3, -1, -4), (0, 3, -1, -4)] Words: ['SNUG', 'WOLF', 'FLOW', 'LORE', 'GUNS'] ['S\nT\nE\nW', 'G\nO\nL\nF', 'F\nL\nO\nG', 'W\nE\nT\nS'] No words: [] [] print '\n4. Word search (orthogonal only)' words = 'GOLF|GUNS|WOLF|FLOW|LORE|WETS|STEW|FLOG|SNUG' flags = HORFLIP | VERFLIP | MULTIFIND reob4a, reob4b = Re2d(words, '.', flags), Re2d('.', words, flags) matching = 'SNUG\nTEQO\nEROL\nWOLF' nomatch = 'ABCD\nEFGH\nIJKL\nMNOP' print 'Words:', reob4a.search(matching), reob4b.search(matching) print 'Words:', reob4a.findall(matching), reob4b.findall(matching) print 'No words:', reob4a.findall(nomatch), reob4b.findall(nomatch) ``` This test shows the use of vertical and horizontal flipping. This allows matching words that are reversed. Diagonal words are not supported. The `MULTIFIND` flag allows multiple overlapping matches in all 4 directions. The findall method uses search to find the matching boxes then extracts the matching blocks of text. Note how the search uses negative width and/or height for matches in the reverse direction. The words in the vertical direction have new line characters - this is consistent with the concept of 2D character blocks. ``` 7. Calvins portals Portals found: [(3, 1, 5, 6)] Portal not found None print '\n7. Calvins portals' reob7 = Re2d(r'X\.{2,22}X|.X{2,22}.', r'X\.{3,22}X|.X{3,22}.', MULTIFIND) yes = '....X......\n.XXXXXX.XX.\n...X...X...\n.X.X...XXX.\n...X...X.X.\n.XXX...X.X.\nX..XXXXX.X.' no = 'XX..XXXX\nXX..X..X\nXX..X..X\n..X.X..X\n.X..X.XX' print 'Portals found:', reob7.search(yes) print 'Portal not found', reob7.search(no) ``` This search needed separate patterns for each dimension as the minimum size is different for each. ``` 9. Alignment Found: ['#.,##', '##'] ['#\n.\n,\n.\n#', '#\n,\n.\n#'] Found: [(3, 4, 5, 1), (6, 4, 2, 1)] [(7, 0, 1, 5), (3, 1, 1, 4)] Not found: None None print '\n9. Alignment' reob9a = Re2d(r'#.*#', r'.', MULTIFIND) reob9b = Re2d(r'.', r'#.*#', MULTIFIND) matching = '.,.,.,.#.,\n,.,#,.,.,.\n.,.,.,.,.,\n,.,.,.,.,.\n.,.#.,##.,\n,.,.,.,.,.' nomatch = '.,.#.,.,\n,.,.,.#.\n.,#,.,.,\n,.,.,.,#\n.#.,.,.,\n,.,.#.,.\n#,.,.,.,\n,.,.,#,.' print 'Found:', reob9a.findall(matching), reob9b.findall(matching) print 'Found:', reob9a.search(matching), reob9b.search(matching) print 'Not found:', reob9a.search(nomatch), reob9b.search(nomatch) ``` This set of 2 searches finds 2 vertical and 2 horizontal matches, but cannot find the embedded `#.,#` string. ``` 10. Collinear Points (orthogonal only) Found: [(0, 1, 7, 1)] [(3, 1, 1, 4)] Not found: None None print '\n10. Collinear Points (orthogonal only)' matching = '........\n#..#..#.\n...#....\n#.......\n...#....' nomatch = '.#..#\n#..#.\n#....\n..#.#' reob10h = Re2d(r'#.*#.*#', '.') reob10v = Re2d('.', r'#.*#.*#') flags = MULTIFIND print 'Found:', reob10h.search(matching, flags), reob10v.search(matching, flags) print 'Not found:', reob10h.search(nomatch, flags), reob10v.search(nomatch, flags) ``` Here we use 2 searches to find matches in both directions. It is able to find multiple orthogonal matches but this approach does not support diagonal matches. ``` 12. Avoid qQ Found: (2, 2, 4, 4) Not found: None print '\n12. Avoid qQ' reob12 = Re2d('[^qQ]{4,4}') print 'Found:', reob12.search('bhtklkwt\nqlwQklqw\nvtvlwktv\nkQtwkvkl\nvtwlkvQk\nvnvevwvx') print 'Not found:', reob12.search('zxvcmn\nxcvncn\nmnQxcv\nxcvmnx\nazvmne') ``` This search finds the first match. ``` 13. Diamond Mining .X. X.X .X. .X. X.X .X. ..X.. ./.\. X...X .\./. \.X.. ..X.. ./.\. X...X .\./. ..X.. .XX.\ //.\. X...X .\./. ..X.. ...X... ../.\.. ./.X.\. X.X.X.X .\.X.// ..\./X. .X.X..\ Diamonds: [(2, 2, 3, 3), (0, 6, 3, 3)] [(8, 0, 5, 5), (10, 2, 5, 5), (5, 3, 5, 5)] [(0, 0, 7, 7)] Not found: None None None print '\n13. Diamond Mining' reob13a = Re2d(r'.X.|X.X', flags=MULTIFIND) reob13b = Re2d(r'..X..|./.\\.|X...X|.\\./.', flags=MULTIFIND) reob13c = Re2d(r'...X...|../.\\..|./...\\.|X.....X|.\\.../.|..\\./..', flags=MULTIFIND) match = ''' ...X......X.... ../.\..../.\... ./.X.\..X...X.. X.X.X.XX.\./.\. .\.X.//.\.X...X ..\./X...X.\./. .X.X..\./...X.. X.X....X....... .X............. '''.strip().replace(' ', '') nomatch = ''' .X......./.... .\....X....... ...X.\.\...X.. ..X.\...\.X.\. ...X.X...X.\.X ../X\...\...X. .X...\.\..X... ..\./.X....X.. ...X..../..... '''.strip().replace(' ', '') for diamond in reob13a.findall(match)+reob13b.findall(match)+reob13c.findall(match): print diamond+'\n' print 'Diamonds:', reob13a.search(match), reob13b.search(match), reob13c.search(match) print 'Not found:', reob13a.search(nomatch), reob13b.search(nomatch), reob13c.search(nomatch) ``` The diamond problem is more difficult. Three search objects are needed for the three sizes. It can find the six diamonds in the test set, but it does not scale to variable sized diamonds. This is only a partial solution to the diamond problem. ## Python 2 code ``` import sys import re DEBUG = re.DEBUG IGNORECASE = re.IGNORECASE LOCALE = re.LOCALE UNICODE = re.UNICODE VERBOSE = re.VERBOSE MULTIFIND = 1<<11 ROTATED = 1<<12 # not implemented HORFLIP = 1<<13 VERFLIP = 1<<14 WRAPAROUND = 1<<15 # not implemented class Re2d(object): def __init__(self, horpattern, verpattern=None, flags=0): self.horpattern = horpattern self.verpattern = verpattern if verpattern != None else horpattern self.flags = flags def checkblock(self, block, flags): 'Return a position if block matches H and V patterns' length = [] for y in range(len(block)): match = re.match(self.horpattern, block[y], flags) if match: length.append(len(match.group(0))) else: break if not length: return None width = min(length) height = len(length) length = [] for x in range(width): column = ''.join(row[x] for row in block[:height]) match = re.match(self.verpattern, column, flags) if match: matchlen = len(match.group(0)) length.append(matchlen) else: break if not length: return None height = min(length) width = len(length) # if smaller, verify with RECURSIVE checkblock call: if height != len(block) or width != len(block[0]): newblock = [row[:width] for row in block[:height]] newsize = self.checkblock(newblock, flags) return newsize return width, height def mkviews(self, text, flags): 'Return views of text block from flip/rotate flags, inc inverse f()' # TODO add ROTATED to generate more views width = len(text[0]) height = len(text) views = [(text, lambda x,y,w,h: (x,y,w,h))] if flags & HORFLIP and flags & VERFLIP: flip2text = [row[::-1] for row in text[::-1]] flip2func = lambda x,y,w,h: (width-1-x, height-1-y, -w, -h) views.append( (flip2text, flip2func) ) elif flags & HORFLIP: hortext = [row[::-1] for row in text] horfunc = lambda x,y,w,h: (width-1-x, y, -w, h) views.append( (hortext, horfunc) ) elif flags & VERFLIP: vertext = text[::-1] verfunc = lambda x,y,w,h: (x, height-1-y, w, -h) views.append( (vertext, verfunc) ) return views def searchview(self, textview, flags=0): 'Return matching textview positions or None' result = [] for y in range(len(textview)): testtext = textview[y:] for x in range(len(testtext[0])): size = self.checkblock([row[x:] for row in testtext], flags) if size: found = (x, y, size[0], size[1]) if flags & MULTIFIND: result.append(found) else: return found return result if result else None def search(self, text, flags=0): 'Return matching text positions or None' flags = self.flags | flags text = text.split('\n') if type(text) == str else text result = [] for textview, invview in self.mkviews(text, flags): found = self.searchview(textview, flags) if found: if flags & MULTIFIND: result.extend(invview(*f) for f in found) else: return invview(*found) return result if result else None def findall(self, text, flags=0): 'Return matching text blocks or None' flags = self.flags | flags strmode = (type(text) == str) text = text.split('\n') if type(text) == str else text result = [] positions = self.search(text, flags) if not positions: return [] if flags & MULTIFIND else None if not flags & MULTIFIND: positions = [positions] for x0,y0,w,h in positions: if y0+h >= 0: lines = text[y0 : y0+h : cmp(h,0)] else: lines = text[y0 : : cmp(h,0)] if x0+w >= 0: block = [row[x0 : x0+w : cmp(w,0)] for row in lines] else: block = [row[x0 : : cmp(w,0)] for row in lines] result.append(block) if strmode: result = ['\n'.join(rows) for rows in result] if flags & MULTIFIND: return result else: return result[0] def match(self, text, flags=0): 'Return True if whole text matches the patterns' flags = self.flags | flags text = text.split('\n') if type(text) == str else text for textview, invview in self.mkviews(text, flags): size = self.checkblock(textview, flags) if size: return True return False ``` [Answer] # TMARL *Template Matching and Recognition Language* ## Description My interpreter takes up 24K chars (*code snippets take up characters?*), so the full description can be found [here](http://pastebin.com/W3NdB62w). The best part: the interpreter is in Javascript, meaning you can try it right here! ``` var reservedOutsideInput = "\u0007"; var templateChar = "$" function run(){ var program = getCode(); evaluate(program,{},{}) } function getCode(){ return document.getElementById('code-area').value; } //3 types of objects - templates, match arrays, and integers function evaluate(program, variables,referenceObject){ variables["I"] = {}; variables["I"].value = getInput().split("\n"); variables["I"].type = "array"; var lines = program.split("\n"); var argumentExpected = null; var jumpTo = null; for(var l = 0; l<lines.length; l++){ if(!!jumpTo){ l = jumpTo.line; } var line = lines[l]; if(line[0] === templateChar){ //next few lines is a template var template = findTemplate(lines,l); if(argumentExpected !== null){ argumentExpected(template); }else{ referenceObject.value = template; referenceObject.type = "template"; } l += template.length - 1; }else{ var i = 0; if(!!jumpTo){ i = jumpTo.index; jumpTo = null; } while(i < line.length){ var character = line[i]; if(character === "P"){ output(referenceObject); argumentExpected = null; }else if(character === "R"){ argumentExpected = function(arg){ referenceObject.value = rotate(referenceObject.value,arg); referenceObject.type = "template"; }; }else if(character === "M"){ referenceObject.value = mirror(referenceObject.value); referenceObject.type = "template" argumentExpected = null; }else if(character === "^"){ if(referenceObject.type === "int"){ argumentExpected = function(num){ referenceObject.value = Math.pow(referenceObject.value,num); referenceObject.type = "int"; } }else{ argumentExpected = function(template){ referenceObject.value = appendVertically(referenceObject.value,template,true); referenceObject.type = "template"; } } }else if(character === "v"){ argumentExpected = function(template){ referenceObject.value = appendVertically(referenceObject.value,template,false); referenceObject.type = "template"; } }else if(character === "<"){ argumentExpected = function(template){ referenceObject.value = appendHorizontally(referenceObject.value,template, true); referenceObject.type = "template"; } }else if(character === ">"){ argumentExpected = function(template){ referenceObject.value = appendHorizontally(referenceObject.value,template, false); referenceObject.type = "template"; } }else if(character === "&"){ argumentExpected = function(searchArg){ referenceObject.value = referenceObject.value.concat(searchArg); referenceObject.type = "search" } }else if(character === "*"){ if(referenceObject.type === "int"){ argumentExpected = function(num){ referenceObject.value*=num; referenceObject.type = "int"; } }else{ argumentExpected = function(num){ referenceObject.value = multiply(referenceObject.value,num); referenceObject.type = "template"; } } }else if(character === "+"){ argumentExpected = function(num){ referenceObject.value+=num; referenceObject.type = "int"; } }else if(character === "-"){ argumentExpected = function(num){ referenceObject.value-=num; referenceObject.type = "int"; } }else if(character === "/"){ argumentExpected = function(num){ referenceObject.value = referenceObject.value / num; referenceObject.type = "int"; } }else if(character === "%"){ argumentExpected = function(num){ referenceObject.value = referenceObject.value % num; referenceObject.type = "int"; } }else if(character === "!"){ if(referenceObject.value === 0){ referenceObject.value = 1; }else{ referenceObject.value = 0; } referenceObject.type = "int"; }else if(character === "~"){ argumentExpected = function(num){ var original = copyTemplate(referenceObject.value); while(num > 1){ referenceObject.value = appendHorizontally(referenceObject.value,original,true); num--; } referenceObject.type = "template"; } }else if(character === "L"){ referenceObject.value = referenceObject.value.length; referenceObject.type = "int"; }else if(character === "S"){ argumentExpected = function(num){ var firstOnly = true; var anyRotation = true; if(num >= 4){firstOnly = false;} else{firstOnly = true;} if(num%2 === 0){anyRotation = true;} else{anyRotation = false;} referenceObject.value = search(getInput(),referenceObject.value, anyRotation,firstOnly); if(firstOnly){referenceObject.type = "match"} else{referenceObject.type = "search";} } }else if(character === "G"){ argumentExpected = function(num){ if(referenceObject.type === "search"){ referenceObject.value = referenceObject.value[num]; referenceObject.type = "match" }else if(referenceObject.type === "match"){ if(num === 0){ referenceObject.value = referenceObject.value.x; referenceObject.type = "int" } if(num === 1){ referenceObject.value = referenceObject.value.y; referenceObject.type = "int"; } if(num === 2){ referenceObject.value = referenceObject.value.match; referenceObject.type = "2darray" } }else if(referenceObject.type === "array"){ referenceObject.value = referenceObject.value[num]; referenceObject.type = "string"; }else if(referenceObject.type === "string"){ referenceObject.value = referenceObject.value.charAt(num); referenceObject.type = "char"; } } }else if(character === "("){ var parenthese = getParentheses(lines, l, i); var temp = evaluate(parenthese.content,variables,{}); if(!!argumentExpected){ argumentExpected(temp.value); }else{ referenceObject.value = temp.value; referenceObject.type = temp.type; } //keep the program in the loop to catch the jump l--; jumpTo = {line: parenthese.lineEnd, index: parenthese.indexEnd}; break; }else{ if(character < '0' || character > '9'){ if(!!variables[character]){ //the variable exists if(argumentExpected !== null){ argumentExpected(variables[character].value); }else{ referenceObject.value = variables[character].value; referenceObject.type = variables[character].type; } }else{ variables[character] = {}; variables[character].value = cloneReference(referenceObject); variables[character].type = referenceObject.type; } }else{ //character must be argument (its a number) if(argumentExpected !== null){ argumentExpected(parseFloat(character)); }else{ referenceObject.value = parseFloat(character); referenceObject.type = "int"; } } } i++; } } } return referenceObject; } function cloneReference(referenceObject){ var newObject = {}; if(referenceObject.type === "template"){ newObject = copyTemplate(referenceObject.value); } if(referenceObject.type === "2darray"){ newObject = copy2D(referenceObject.value); } if(referenceObject.type === "int"){ newObject = referenceObject.value; } if(referenceObject.type === "search"){ newObject = []; for(var i=0;i<referenceObject.value.length;i++){ newObject.push({x:referenceObject.value[i].x,y:referenceObject.value[i].y,match:referenceObject.value.match}); } } if(referenceObject.type === "match"){ newObject = {x:referenceObject.value.x,y:referenceObject.value.y,match:referenceObject.value.match} } if(referenceObject.type === "string"){ newObject = referenceObject.value; } if(referenceObject.type === "array"){ newObject = copy(referenceObject.value); } if(referenceObject.type === "char"){ newObject = referenceObject.value; } return newObject; } //returns {content, lineEnd, indexEnd} function getParentheses(lines, line, index){ var pointer = {line:line, index:index}; var stack = [1]; var content = ""; while(stack.length > 0){ pointer.index++; if(lines[pointer.line].length === pointer.index){ pointer.line++; pointer.index = 0; content+="\n"; } var character = lines[pointer.line].charAt(pointer.index); if(character === '('){ stack.push(1); } if(character === ')'){ stack.pop(); } content += character; } pointer.index++; if(lines[pointer.line].length === pointer.index){ pointer.line++; pointer.index = 0; content+="\n"; } content = content.substring(0, content.length-1); return {content:content, lineEnd:pointer.line, indexEnd:pointer.index}; } function getInput(){ return document.getElementById("input").value; } function search(input, t, anyRotation, first){ var inputArray = input.split("\n"); processInput(inputArray); var possibleTemps = [t]; if(anyRotation){ possibleTemps.push(copyTemplate(rotate(t,1))); possibleTemps.push(copyTemplate(rotate(t,2))); possibleTemps.push(copyTemplate(rotate(t,3))); } var matches = []; for(var v = 0; v < possibleTemps.length; v++){ var template = possibleTemps[v]; for(var y = 0; y < inputArray.length; y++){ for(var x = 0; x < inputArray[y].length; x++){ var good = true; var match = matchTemplate(template); for(var ty = 0; ty < template.length; ty++){ for(var tx = 0; tx < template[ty].length; tx++){ var inputChar = null; if(!!inputArray[y+ty]){ if(!!inputArray[y+ty][x+tx]){ inputChar = inputArray[y+ty][x+tx]; } } if(!charMatch(template[ty][tx],inputChar)){ good = false; }else{ match[ty][tx] = inputChar; } } } if(good){ if(first){return {x:x,y:y,match:match}} matches.push({x:x,y:y,match:match}) } } } } return matches; } function processInput(inputArray){ //add 'bell' character to outsides for edge recognition var filledTop = Array.apply(null, new Array(inputArray[0].length)) .map(String.prototype.valueOf,reservedOutsideInput); var filledBottom = Array.apply(null, new Array(inputArray[inputArray.length-1].length)) .map(String.prototype.valueOf,reservedOutsideInput); for(var row = 0; row < inputArray.length; row++){ inputArray[row] = inputArray[row].split(""); inputArray[row].splice(0,0,reservedOutsideInput); inputArray[row].push(reservedOutsideInput); } inputArray.splice(0,0,filledTop); inputArray.push(filledBottom); } function charMatch(templateC,inputChar){ if(templateC.inCharClass === false && templateC.options[0] === "*" && templateC.escaped === false){ return true; } if(templateC.inCharClass === false && templateC.options[0] === "D" && templateC.escaped === false){ return inputChar >= '0' && inputChar <= '9' } if(templateC.inCharClass === false && templateC.options[0] === "L" && templateC.escaped === false){ return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".indexOf(inputChar) > -1; } if(templateC.inCharClass === false && templateC.options[0] === "U" && templateC.escaped === false){ return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(inputChar) > -1; } if(templateC.inCharClass === false && templateC.options[0] === "l" && templateC.escaped === false){ return "abcdefghijklmnopqrstuvwxyz".indexOf(inputChar) > -1; } if(templateC.inCharClass === false && templateC.options[0] === "%" && templateC.escaped === false){ return inputChar === reservedOutsideInput; } if(templateC.options.indexOf('%') === -1 && inputChar === reservedOutsideInput){ return false; } var good = false; if(templateC.not){ good = true; } for(var i=0;i<templateC.options.length;i++){ var option = templateC.options[i]; console.log(templateC.not + ","+templateC.options) if(templateC.not && option === inputChar){ good = false; } if(templateC.not === false && option === inputChar){ good = true; } } return good; } function multiply(template, num){ var original = copyTemplate(template); while(num > 1){ template = template.concat(original); num--; } return template; } function copyTemplate(template){ var newTemp = []; for(var y = 0; y< template.length; y++){ newTemp[y] = []; for(var x = 0; x < template[y].length;x++){ newTemp[y][x] = copyChar(template[y][x]); } } return newTemp; } function copyChar(character){ return {not:character.not,options:copy(character.options),escaped:character.escaped,inCharClass:character.inCharClass}; } function rotate(template,amount){ while(amount > 0){ var temp = box(template); var newTemplate = []; for(var x = 0; x < temp[0].length; x++){ newTemplate[x] = []; for(var y = 0; y < temp.length; y++){ newTemplate[x][temp.length-y-1] = temp[y][x]; } } template = copyTemplate(newTemplate); amount--; } return template; } function box(template){ var maxWidth = 0; var maxHeight = template.length; for(var y = 0; y < template.length;y++){ if(template[y].length > maxWidth){maxWidth = template[y].length;} } var newTemplate = []; for(var row = 0 ; row < template.length; row++){ newTemplate[row] = []; for(var x = 0; x < template[row].length;x++){ newTemplate[row][x] = copyChar(template[row][x]); } while(newTemplate[row].length < maxWidth){ newTemplate[row].push({not:false,inCharClass:false,options:["*"],escaped:false}); } } return newTemplate; } //t1 over t2 function appendVertically(t1, t2, t1OnTop){ var newTemplate = []; if(!t1OnTop){ newTemplate = copyTemplate(t2).concat(copyTemplate(t1)); }else{ newTemplate = copyTemplate(t1).concat(copyTemplate(t2)); } return newTemplate; } function appendHorizontally(t1, t2, t1OnLeft){ var maxWidthT1 = 0; var maxWidthT2 = 0; for(var row=0;row<t1.length;row++){ if(t1[row].length > maxWidthT1){maxWidthT1 = t1[row].length;} } for(var row2 = 0; row2 < t2.length;row2++){ if(t2[row2].length > maxWidthT2){maxWidthT2 = t2[row2].length;} } var newTemplate = []; for(var r=0;r<Math.max(t1.length,t2.length);r++){ newTemplate[r] = []; if(t1OnLeft){ if(!!t1[r]){ newTemplate[r] = newTemplate[r].concat(copyCharArray(t1[r])); } if(!!t2[r]){ while(newTemplate[r].length < maxWidthT1){ newTemplate[r].push({not:false,inCharClass:false,options:["*"],escaped:false}); } newTemplate[r] = newTemplate[r].concat(copyCharArray(t2[r])) } }else{ if(!!t2[r]){ newTemplate[r] = newTemplate[r].concat(copyCharArray(t2[r])); } if(!!t1[r]){ while(newTemplate[r].length < maxWidthT2){ newTemplate[r].push({not:false,inCharClass:false,options:["*"],escaped:false}); } newTemplate[r] = newTemplate[r].concat(copyCharArray(t1[r])) } } } return newTemplate; } function copyCharArray(array){ var newArray = []; for(var i = 0; i<array.length;i++){ newArray.push(copyChar(array[i])); } return newArray; } function mirror(template){ template = box(template); for(var row = 0; row < template.length; row++){ template[row].reverse(); } return template; } function copy(array){ var newArray = []; for(var i=0;i<array.length;i++){ newArray.push(array[i].slice()) } return newArray; } function copy2D(array){ var newArray = []; for(var i=0;i<array.length;i++){ newArray.push(copy(array[i])); } return newArray; } function matchTemplate(template){ var result = []; for(var y=0;y<template.length;y++){ result[y]=[]; for(var x=0;x<template[y].length;x++){ result[y][x] = template[y][x].options[0]; } } return result; } //finds the template in the code and returns a template object function findTemplate(lines,lineNum){ var start = lineNum; while(lineNum < lines.length && lines[lineNum].indexOf(templateChar) > -1){lineNum++} var end = lineNum - 1; var templateArray = []; for(var l = start; l<=end; l++){ var subArray = []; var line = lines[l]; var started = false; for(var i = 0; i<line.length;i++){ if(started){ var character = line[i]; var real = {}; real.escaped = false; real.options = []; real.inCharClass = false; real.not = false; if(character === "["){ var content = getCharClass(line,i); if(content.charAt(0) === "^"){ real.not = true; real.inCharClass = true; content = content.substring(1,content.length); } for(var j = 0; j<content.length;j++){ real.options.push(content.charAt(j)); } i+=content.length+1; if(real.not){i++;} }else if(character === "\\"){ real.options.push(line[i+1]); real.escaped = true; i++; }else{ real.options.push(character); } subArray[subArray.length] = real; } if(line[i] === templateChar && started === false){started = true;} } templateArray[templateArray.length] = subArray; } return templateArray; } function getCharClass(line, index){ var stack = [1]; var pointer = index; var content = ""; while(stack.length > 0 && pointer < line.length+1){ pointer++; if(line[pointer] === ']'){ stack.pop(); } if(line[pointer] === '['){ stack.push(1); } content+=line[pointer]; } content = content.substring(0,content.length-1); return content; } function output(object){ if(object === undefined){ realOutput("undefined"); } else if(object.type === "template"){ for(var i = 0; i<object.value.length;i++){ var result = ""; result+=templateChar; for(var k = 0; k < object.value[i].length;k++){ result+=object.value[i][k].options[0]; } realOutput(result); } }else if(object.type === "search"){ for(var a = 0; a < object.value.length; a++){ realOutput("[x: "+object.value[a].x+", y: "+object.value[a].y+ ", match: "+object.value[a].match+"]"); } }else if(object.type === "match"){ realOutput("x: "+object.value.x+", y: "+object.value.y+ ", match: "+object.value.match); }else if(object.type === "2darray"){ for(var h = 0; h<object.value.length;h++){ var temp = "" for(var b = 0; b < object.value[h].length; b++){ temp += object.value[h][b]; } realOutput(temp); } }else{ realOutput(object.value); } } function realOutput(text){ document.getElementById("output").value += text+"\n"; } function clearOutput(){ document.getElementById("output").value = ""; } ``` ``` html,body{ margin:0; padding:0; height:100%; width:100%; overflow:auto; } #code-area,#input,#output{ width:80%; height:20%; margin:5px; } #run-button{ margin:5px; } span{ margin:5px; } ``` ``` <span>Code:</span> <br> <textarea id="code-area"></textarea> <br> <span>Input:</span> <br> <textarea id="input"></textarea> <br> <button id="run-button" onclick="run()">Run</button> <button id="clear-button" onclick="clearOutput()">Clear</button> <br> <span>Output:</span> <br> <textarea id="output"></textarea> ``` And for the problems: ## #1 - Finding Chessboards ``` $#_# a $_#_ bvacvbS5&(avcS5)G0G2P ``` `&` appends searches. The G2 at the end gets the 3rd element in a match element, the actual match. The first 2 elements are x and y coordinates (1 based, not 0). ## #3 - Detect a Rectangle of Digits ``` $DD $DD S1G2P ``` I think this one is pretty straightforward. ## #4 - Finding a Word in a Word Search ``` $GO\LF a $G $*O $**\L $***F S6&(aS6)G0G2P ``` The `S` argument is even so that it will search for all rotations. It is greater than 4 because it can then be appended to the next search (individual matches cannot be appended). ## #5 - Detect Square Inputs ``` IL-(IG0L)!P ``` Not sure if this is completely legal, since it only determines the squareness correctly if the input is a rectangle. It compares the length of the input `IL` with the length of the first row `IG0L` and inverts it. ## #6 - Find Gliders in a Game of Life ``` $## $# # $# a $ ## $## $ # bS6&(bMS6)&(aS6)&(aMS6)G0G2P ``` Finally, a use for mirror! ## #12 - Avoid the Letter Q ``` $[^Qq] ~4*4S1G2P ``` S1 because only 1 match is needed. I will do some of the harder ones later. ]
[Question] [ ## Goal This is a simple challenge. Your goal is to unscramble a string by swapping each letter with the next letter of the same case, while leaving non-letter characters unchanged. [![example](https://i.stack.imgur.com/ubgD2.png)](https://i.stack.imgur.com/ubgD2.png) ## Step by step explanation 1. The first character is a `E`. We look for the next letter in upper case: it's a `C`. We swap these characters, which leads to `CdoE!`. 2. We advance to the next character: this is a `d`. We look for the next letter in lower case: it's a `o`. We swap these characters, which leads to `CodE!`. 3. We advance to the next character: this is the `d` that we've just moved here. We ignore it, because it has already been processed. 4. We advance to the next character: this is the `E` that was moved here at step #1. We ignore it, because it has already been processed. 5. We advance to the next character: this is a `!`. We ignore it, because it's not a letter. ## Rules * You can assume that the input string is made exclusively of printable ASCII characters, in the range 32 - 126. * You may write either a full program or a function, which either prints or returns the result. * If the input string contains an odd number of letters, the last remaining letter can't be swapped with another one and should remain in place, no matter its case. The same logic applies if the string contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters. * This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden. ## Test cases ``` Input : lLEhW OroLd! Output: hELlO WorLd! Input : rpGOZmaimgn uplRzse naC DEoO LdGf Output: prOGRamming puzZles anD COdE GoLf Input : eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg Output: tHe quICK BROWN fOx juMPS OvER THE LAzy dOg Input : NraWgCi: Nsas-eNEiTIsev rNsiTG!! Output: WarNiNg: Case-sENsITive sTriNG!! ``` Not-so-random test cases: ``` Input : (^_^) Output: (^_^) Input : AWCTY HUOS RETP Output: WATCH YOUR STEP Input : hwn oeesd acsp nawyya Output: who needs caps anyway Input : SpMycaeIesKyBorekn Output: MySpaceKeyIsBroken Input : D's mroyr, Ivam. I'e faardi I act'n od htta. Output: I'm sorry, Dave. I'm afraid I can't do that. ``` [Answer] # [Retina](https://github.com/m-ender/retina), 53 bytes Not really clever, but a clean and quite readable solution ``` ([a-z])(.*?)([a-z]) $3$2$1 ([A-Z])(.*?)([A-Z]) $3$2$1 ``` [Try it online!](https://tio.run/nexus/retina#@68RnahbFaupoadlrwllc6kYqxipGHJpRDvqRsGlwGyo1P//fkWJ4enOmVYKfsWJxbqpfq6ZIZ7FqWUKRX7FmSHuiooA "Retina – TIO Nexus") [Answer] # [MATL](https://github.com/lmendo/MATL), 22 bytes ``` 2:"tttk<f2etAZ))P5M(Yo ``` [Try it online!](https://tio.run/nexus/matl#@29kpVRSUpJtk2aUWuIYpakZYOqrEZn//796qmeJQmmhh7ezQpBTuL@/QoVfmkJpVoCvv0JwVZCrgkeIj4Krf1mKQqVjujoA) Or [verify all test cases](https://tio.run/nexus/matl#DcpNC4IwGADge7/itcvq0EXoIl1Mh0pzExtIQtDAaZZfbVPKP28@5@ex2M7WGPM@lbY0br7fJ8d4d@uXu88X1BD8zICpnhQW2iA1BCxvRd1WHYxDk85aQic88HHPgBRBuR4ZGRg/4cWD9JwxBl9awvhKYgbXOcUQcgKYTQX83GrdVIms8moHqBb6ICmueaTlBIrqmgeWhf4). ### How it works ``` 2:" % Do the following twice ttt % Input string (implicit). Push three more copies k % Convert to lowercase <f % Indices of characters that had their code point increased by % the lowercase conversion, i.e. that were uppercase letters 2e % Convert to 2-row matrix. This pads a zero in the lower-right % corner if necessary tAZ) % Keep only columns that don't contain zeros. Thus if there % was a character that can't be swapped it will be ignored ) % Get 2-row matrix of characters at those positions P % Flip vertically. This does the swapping 5M % Push matrix of original indices again ( % Write the swapped characters onto their original positions Yo % Change case. In the first iteration, this prepares the % string so the second iteration will process the letters that % were originally lowercase. In the second iteration, it % undoes the change of case % End (implicit) % Display (implicit) ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~20~~ ~~19~~ 18 bytes ``` s2UF, nŒlTÇyJịŒsµ⁺ ``` [Try it online!](https://tio.run/nexus/jelly#BcE9DoIwGADQvaf42HVxdFOsgGJrEEN0I6Eghj9bIcKmC4Mb53DURTYJB4GL4HuDmOyXIxS1VWA2Zb7q6mdbid@nv3@Hrn43Zf94HYYh0PHJAspj3ZEQTxR6DG0/9CJIk8AoBIPIlmGBYwq6o7iIaVdIL@paBmNuUQo34kJ63m4o7AoDg2rqgGnmQD7zEOG25cn@FIiwxZgR7JuaYBlwInxTkaQ/ "Jelly – TIO Nexus") ### How it works ``` nŒlTÇyJịŒsµ⁺ Main link. Argument: s (string) Œl Convert to lowercase. n Test for inequality. T Truth; yield all indices of 1's. Ç Call the helper link. Yields [A, B] (pair of lists). J Indices; yield I := [1, ..., len(s)]. y Translate; replace the integers of I that occur in A with the corresponding integers in B. Œs Swapcase; yield s with swapped case. ị Use the translated index list to index into s with swapped case. µ Combine all links to the left into a chain. ⁺ Duplicate the chain, executing it twice. s2UF, Helper link. Argument: J (list of indices) s2 Split J into pairs. If the length is odd, the last list will be a singleton list. U Upend; reverse each pair. This is a no-op for singletons lists. F Flatten, concatenating the pairs. , Pair the previous result with J. ``` [Answer] # Bash + Unix utilities, ~~77~~ ~~62~~ ~~57~~ ~~56~~ 54 bytes ``` sed -r "s/([$1)([^$1*)([$1)/\3\2\1/g"||$0 a-z]|$0 A-Z] ``` Input in stdin. Output in stdout. (In this last version, stderr happens to be written to also, but PPCG consensus seems to be that that's OK -- [stderr is simply ignored.](http://meta.codegolf.stackexchange.com/questions/4780/should-submissions-be-allowed-to-exit-with-an-error/4781#4781)) Edit 1: Thanks to @Dennis for 15 bytes! Improvements: (a) Taking input via stdin; (b) combining 2 sed scripts into one; and (c) replacing tr with substitution via bash parameter expansion; (b) and (c) disappeared in Edit 2. Edit 2: Shorter by 5 additional bytes. Used a function call to replace both (b) and (c) in Edit 1. Edit 3: One more byte -- passed ] as part of the function arguments. Edit 4: Replaced the two function calls with calls to the program itself when it has no arguments. Testbed and sample output: ``` for x in 'lLEhW OroLd!' 'rpGOZmaimgn uplRzse naC DEoO LdGf' 'eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg' 'NraWgCi: Nsas-eNEiTIsev rNsiTG!!' '(^_^)' 'AWCTY HUOS RETP' 'hwn oeesd acsp nawyya' 'SpMycaeIesKyBorekn' "D's mroyr, Ivam. I'e faardi I act'n od htta."; do ./swapping <<<"$x" 2>/dev/null; done hELlO WorLd! prOGRamming puzZles anD COdE GoLf tHe quICK BROWN fOx juMPS OvER THE LAzy dOg WarNiNg: Case-sENsITive sTriNG!! (^_^) WATCH YOUR STEP who needs caps anyway MySpaceKeyIsBroken I'm sorry, Dave. I'm afraid I can't do that. ``` [Answer] ## ES6, ~~185~~ 95 bytes ``` i=>(o=[...i]).map((c,j)=>/[a-z]/i.test(c)?o[e=c>"Z"]=1/(b=o[e])?o[o[j]=o[b],b]=c:j:0)&&o.join`` ``` Solution severely shortened with the help of @Neil, @Arnauld and @edc65 Explanation ``` f = i => // Get array of characters from input string (o = [...i]) .map((c, j) => // Check if it's a text character, otherwise skip it /[a-z]/i.test(c) ? // Get last character position for case // merged with setting a variable for if the character is lowercase // merged with storing the current case character position, // under properties on the array (with keys "true" or "false") o[e = c>"Z"] = // Check if there exists a character position to switch with // merged with storing the current position for quick access 1/(b=o[e]) ? // This statement will end up returning the Array subset, // which will be falsy in the above conditional since (1/[])==false o[ // Switch left character to the right o[j]=o[b] // Switch right character to the left ,b]=c : // No character exists for case, so return current character position j // It was not a text character, so do nothing :0 ) // Join array and return as result && o.join``; `lLEhW OroLd! NraWgCi: Nsas-eNEiTIsev rNsiTG!! rpGOZmaimgn uplRzse naC DEoO LdGf eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg (^_^) AWCTY HUOS RETP hwn oeesd acsp nawyya SpMycaeIesKyBorekn D's mroyr, Ivam. I'e faardi I act'n od htta` .split`\n` .map(testCase => console.log(f(testCase))); ``` [Answer] # [Python](https://docs.python.org/), 82 bytes ``` lambda s:S(r.lower(),t,S(r,t,s)) import re S=re.sub r='([A-Z])(.*?)'*2 t=r'\3\2\1' ``` [Try it online!](https://tio.run/nexus/python3#VY5NS8NAGITv@RVvT7tb2oD1VghS45IW464kgUCNhy3ZxJV8@e6mav98Gi9CLwPDPDNMBQEUU6PaU6nAblOKftN/a6Rs5Vazm9Uy5pl26NEBai8NUPt2PHkYEPq2Wx/fGfWXD4wsN54LkBT3xaa4I9OApnO0oqSJ@UcOEvu4XJB56j/AIZLHVpm27mAcmuRiNXQqhCfeS4jLqLqh9cHB@LV/DiF5zKWEH1HB@Pn6IiG9JBz2WQxcnkv43dU3PYEqr0OzBWGVXWvBTXaw@gworMmixd@l6Qo "Python 3 – TIO Nexus") [Answer] # QBasic, 229 bytes ``` LINE INPUT s$ FOR i=1TO LEN(s$) c$=MID$(s$,i,1) IF"@"<c$AND"[">c$THEN IF u THEN MID$(s$,u,1)=c$:MID$(s$,i,1)=u$ u=-i*(u=0) u$=c$ ELSEIF"`"<c$AND"{">c$THEN IF l THEN MID$(s$,l,1)=c$:MID$(s$,i,1)=l$ l=-i*(l=0) l$=c$ END IF NEXT ?s$ ``` ### Strategy We loop through the input string. When we encounter an uppercase letter, we store it and its position. The second time we encounter an uppercase letter, we use those stored values to swap it with the previous one. Same for lowercase. (I was about to post a rather longer version that used an array, because I thought that QBasic strings were immutable. Then I stumbled across the fact that `MID$(strng$, index, length) = replacement$` works just fine. Live and learn.) ### Ungolfed + commented ``` LINE INPUT text$ FOR i = 1 TO LEN(text$) char$ = MID$(text$, i, 1) IF "A" <= char$ AND "Z" >= char$ THEN ' Uppercase IF upperIndex = 0 THEN ' This is the first of a pair of uppercase letters ' Store the letter and its index for later upperLetter$ = char$ upperIndex = i ELSE ' This is the second of a pair of uppercase letters ' Put it at the position of the previous uppercase letter ' and put that letter at this letter's position MID$(text$, upperIndex, 1) = char$ MID$(text$, i, 1) = upperLetter$ upperIndex = 0 END IF ELSEIF "a" <= char$ AND "z" >= char$ THEN ' Lowercase IF lowerIndex = 0 THEN ' This is the first of a pair of lowercase letters ' Store the letter and its index for later lowerLetter$ = char$ lowerIndex = i ELSE ' This is the second of a pair of lowercase letters ' Put it at the position of the previous lowercase letter ' and put that letter at this letter's position MID$(text$, lowerIndex, 1) = char$ MID$(text$, i, 1) = lowerLetter$ lowerIndex = 0 END IF END IF NEXT i PRINT text$ ``` [Answer] ## C++11 (GCC), ~~154~~ 149 bytes ``` #include<algorithm> [](std::string s){int*p,u,l=u=-1;for(auto&c:s)(c|32)-97<26U?p=&(c&32?u:l),~*p?(std::swap(c,s[*p]),*p=-1):*p=&c-&s[0]:0;return s;} ``` [Answer] ## Qbasic, ~~436~~ 408 bytes ``` LINE INPUT a$:b=len(a$):FOR a=1TO b:t$=MID$(a$,a,1) IF"@"<t$AND"[">t$THEN b$=b$+"U":u$=u$+t$ ELSEIF"`"<t$AND"{">t$THEN b$=b$+"L":l$=l$+t$ ELSE b$=b$+t$ END IF:NEXT FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT FOR x=1TO b:t$=MID$(b$,x,1) IF"U"=t$THEN u=u+1:z$=z$+MID$(g$,u,1) ELSEIF"L"=t$THEN l=l+1:z$=z$+MID$(h$,l,1) ELSE z$=z$+t$ END IF:NEXT:?z$ ``` *Saved one byte thanks to DLosc. Saved several more by changing handling of non-letter chars.* This basically consists of three parts: * Splitting the input into 3 strings (Uppercase, Lowercase, and a map (also holding the other chars)) * Flipping the uppercase and lowercase letters * Using the map to (re)construct the output. A more detailed explanation (note that this is of an earlier version of the code, but the principle still applies): ``` ' --- Part I: Reading the input LINE INPUT a$ 'This FOR loop takes one character at a time b=len(a$):FOR a=1TO b ' And checks in what category the character belongs t$=MID$(a$,a,1):SELECT CASE t$ ' For each group, char t$ is added to that group (u$ for uppercase, ' l$ for lowercase. The map in b$ is updated with a U or L on this index, ' or with the non-letter char t$. CASE"A"TO"Z":b$=b$+"U":u$=u$+t$ CASE"a"TO"z":b$=b$+"L":l$=l$+t$ CASE ELSE:b$=b$+t$ END SELECT:NEXT ' --- Part II: Swapping within case-groups ' Loop through u$ and l$ twp chars at a time, and add those chunks in reverse order ' to g$ and h$. Because mid$ doesn't fail past the end of a string (but returns ""), ' this automatically compensates for odd-length groups. FOR x=1TO b STEP 2:g$=g$+MID$(u$,x+1,1)+MID$(u$,x,1):h$=h$+MID$(l$,x+1,1)+MID$(l$,x,1):NEXT ' --- Part III: Read the map to put it all back together FOR x=1TO b:t$=MID$(b$,x,1) ' See what group was in this spot, then read the next char from the flipped string. ' This keeps an index on those strings for the next lookup. IF t$="U"THEN u=u+1:z$=z$+MID$(g$,u,1) ELSEIF t$="L"THEN l=l+1:z$=z$+MID$(h$,l,1) ' The map contains a non-letter char, just drop that in ELSE z$=z$+t$ ' And finally,display the end result. END IF:NEXT:?z$ ``` [Answer] # [Perl 5](https://www.perl.org/), 48 + 1 (-p) = 49 bytes ``` for$p(qw/([a-z]) ([A-Z])/){s/$p(.*?)$p/$3$2$1/g} ``` [Try it online!](https://tio.run/##K0gtyjH9/z8tv0ilQKOwXF8jOlG3KlZTQSPaUTcqVlNfs7pYHyijp2WvqVKgr2KsYqRiqJ9e@/9/UYG7f1RuYmZuep5CaUFOUFVxqkJeorOCi2u@v4JPinvav/yCksz8vOL/ugUA "Perl 5 – Try It Online") [Answer] # PHP, ~~108~~ ~~93~~ 83 bytes ``` <?=preg_replace([$a="/([a-z])([^a-z]*)([a-z])/",strtoupper($a)],"$3$2$1",$argv[1]); ``` --- ### Previous version (93 bytes) ``` <?=preg_replace(["/([a-z])([^a-z]*)([a-z])/","/([A-Z])([^A-Z]*)([A-Z])/"],"$3$2$1",$argv[1]); ``` Thanks to @user59178 for reminding me that [`preg_replace()`](http://php.net/manual/en/function.preg-replace.php) can take arrays of strings as arguments. --- ### The original answer (108 bytes) ``` $f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1", $f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1])); ``` The code is wrapped here to fit the available space. It can be executed from the command line: ``` $ php -d error_reporting=0 -r '$f=preg_replace;echo$f("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1",$f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1]));' 'lLEhW OroLd!' ``` A 1-byte shorter version is possible on PHP 7 by squeezing the assignment of `$f` inside its first call: ``` echo($f=preg_replace)("/([a-z])([^a-z]*)([a-z])/",$r="$3$2$1", $f("/([A-Z])([^A-Z]*)([A-Z])/",$r,$argv[1])); ``` --- Both solutions, with test cases and ungolfed versions can be found on [Github](https://github.com/axiac/code-golf/blob/master/unscramble-those-case-very-sensitive-strings.php). [Answer] # Mathematica, 96 bytes ``` s[#,r="([a-z])(.*?)([a-z])"]~(s=StringReplace[#,RegularExpression@#2->"$3$2$1"]&)~ToUpperCase@r& ``` A port of [Leo's Retina answer](https://codegolf.stackexchange.com/a/109122/56178), which uses regular expressions. [Answer] # [Python 2](https://docs.python.org/2/), 124 bytes ``` s=input();u=str.isupper exec"r='';i=0\nfor c in s:r+=c[u(c):]or filter(u,s+s[::-1])[i^1];i+=u(c)\ns=r.swapcase();"*2 print s ``` Not as short as [my regex-based solution](https://codegolf.stackexchange.com/a/109143/12012), but I think it's still interesting. [Try it online!](https://tio.run/nexus/python2#Fc7BToNAFIXhfZ/iwgYotrHGFWQWiqRtRMZUEhIpJgQGHEOH8V6m1r484vbkS84vLqIGtG17IiaVNqPrhYbRiGtJRmuBCzELG5njhJLdHlU7INQgFVCAPqsL49ZeUM5jK/tRoGtuyKciCFab0ivkx6YMpc/@0VERwzX9VLquSMw39vJuoVGqEWiaA5b3k9Mn8WcOHIeksZyFg3rL30@VPHUKjO4PVxKgqgie4oFD0mzb2Yj9COZ79xzB4THnHC5pC@br9YXD2/UQwy5LIObnBn4fulmnWOVdJANIqaKVSGOZ7UmcAVOS2daynD8 "Python 2 – TIO Nexus") [Answer] # [Bean](https://github.com/patrickroberts/bean), 83 bytes Hexdump: ``` 00000000 26 53 d0 80 d3 d0 80 a0 5d 20 80 0a a1 81 81 00 &SÐ.ÓÐ. ] ..¡... 00000010 23 81 01 20 80 0a a1 81 81 02 23 81 01 a8 db c1 #.. ..¡...#..¨ÛÁ 00000020 ad da dd a9 a8 db de c1 ad da dd aa bf a9 a8 db .ÚÝ©¨ÛÞÁ.Úݪ¿©¨Û 00000030 c1 ad da dd 29 a4 b3 a4 b2 a4 31 a8 db e1 ad fa Á.ÚÝ)¤³¤²¤1¨Ûá.ú 00000040 dd a9 a8 db de e1 ad fa dd aa bf a9 a8 db e1 ad Ý©¨ÛÞá.úݪ¿©¨Ûá. 00000050 fa dd 29 úÝ) 00000053 ``` Equivalent JavaScript: ``` a.replace(/([A-Z])([^A-Z]*?)([A-Z])/g,'$3$2$1').replace(/([a-z])([^a-z]*?)([a-z])/g,'$3$2$1') ``` Explanation: Implicitly taking the first line of input unformatted as `a` (since newlines can't be part of scrambled string), and implicitly outputs unscrambled string by sequentially replacing uppercase, then lowercase pairs. ### [Try demo here.](https://patrickroberts.github.io/bean/#h=JlPQgNPQgKBdIIAKoYGBACOBASCACqGBgQIjgQGo28Gt2t2pqNvewa3a3aq/qajbwa3a3Smks6SypDGo2+Gt+t2pqNve4a363aq/qajb4a363Sk=&i=bExFaFcgT3JvTGQh&f=0&w=1) ### [Try test suite here.](https://patrickroberts.github.io/bean/#h=JlfQgNPQgKB4IICIQKBdU9CA09CAoF0ggAqhgYEAI4EBIIAKoYGBAiOBASCAe1ZYgQOo28Gt2t2pqNvewa3a3aq/qajbwa3a3Smks6SypDGo2+Gt+t2pqNve4a363aq/qajb4a363SkK&i=bExFaFcgT3JvTGQhCnJwR09abWFpbWduIHVwbFJ6c2UgbmFDIERFb08gTGRHZgplSXQgdXFIS0MgUkJXT08geE5mIHVqUE1PIFN6UkUgSFRMIEVPdmQgeUFnCk5yYVdnQ2k6IE5zYXMtZU5FaVRJc2V2IHJOc2lURyEh&f=0&w=1) [Answer] # Ruby, 81 bytes ``` puts f=->(i,s){i.gsub /([#{s})([^#{s}*)([#{s})/,'\3\2\1'}[f[$*[0],'a-z]'],'A-Z]'] ``` [Answer] ## JavaScript (ES6), 80 bytes Based on **[Leo's Retina answer](https://codegolf.stackexchange.com/a/109122/58563)**. ``` s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase()) ``` This works because the only uppercase characters in the code `.replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')` are `A` and `Z`, which are used to describe the character ranges. This is precisely what we need to transform into lowercase in order to process the second pass. ### Test cases ``` let f = s=>eval("s"+(r=".replace(/([A-Z])([^A-Z]*)([A-Z])/g,'$3$2$1')")+r.toLowerCase()) console.log(f("lLEhW OroLd!")); console.log(f("rpGOZmaimgn uplRzse naC DEoO LdGf")); console.log(f("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg")); console.log(f("NraWgCi: Nsas-eNEiTIsev rNsiTG!!")); console.log(f("(^_^)")); console.log(f("AWCTY HUOS RETP")); console.log(f("hwn oeesd acsp nawyya")); console.log(f("SpMycaeIesKyBorekn")); console.log(f("D's mroyr, Ivam. I'e faardi I act'n od htta.")); ``` [Answer] # ES6 155 - 195 bytes I know there's already a better answer, but I wanted to try without regex. This one works on punctuation too, but that seems to violate the `(^_^)` test. In that case I have another `c()` function, given below. ``` f=(s)=>{d={};s=[...s];for(i in s){b=s[i];for(j in s)if(i<j&!d[i]&c(s[j])==c(b)){d[j]=1;s[i]=s[j];s[j]=b;break}}return s.join('')} c=c=>~(c.charCodeAt()/32) f("M I'o DaG") //> I'M a GoD f("(^_^)") //> )_^^( c=c=>((c!=c.toUpperCase())<<1|c!=c.toLowerCase())||c.charCodeAt() f("M I'o DaG") //> I'M a GoD f("(^_^)") //> (^_^) ``` ### Explanation ``` f=(s)=>{ d={}; //list of indexes already swapped s=[...s]; //string to array, stolen from above ES6 answer for(i in s){ b=s[i]; //keep a note of what we are swapping for(j in s) //iterate over the array again if( i<j & !d[i] & c(s[j])==c(b) ){ //only pay attention after we pass i'th //only swap if this char hasn't been swapped //only swap if both chars in same 'category' d[j]=1; //note that the latter char has been swapped s[i]=s[j]; s[j]=b; break //avoid swapping on the same 'i' twice } } return s.join('') //return as string } ``` [Answer] # [Perl 6](http://perl6.org/), 56 bytes ``` {for "A".."Z","a".."z" ->@c {s:g/(@c)(.*?)(@c)/$2$1$0/}} ``` Takes a string variable as an argument, and modifies it in-place so that after calling the lambda the variable contains the result. Longer than it would be in Perl, because: * The new regex syntax is more verbose, e.g. writing out the character classes would look like `<[A..Z]>` instead of `[A-Z]`. * Regexes are first-class source code parsed at compile time, and a string can only be interpolated into them at run-time if it consists of a self-contained subregex (i.e. you can't interpolate a string into a character class). * Explict `EVAL`, which would allow more flexibility, requires the golf-unfriendly `use MONKEY-SEE-NO-EVAL;` pragma. On the plus side, an array in a `@` variable can be referenced directly in a regex, and is treated as an alternation. --- # [Perl 6](http://perl6.org/), 65 bytes ``` {reduce ->$_,@c {S:g/(@c)(.*?)(@c)/$2$1$0/},$_,"A".."Z","a".."z"} ``` Functional version (outputs the result as the return value of the lambda). [Answer] # R, 343 Bytes Terribly clumsy R solution: ``` f <- function(x) { y=unlist(strsplit(x,"")) z=data.frame(l=ifelse(y %in% letters,0,ifelse(y %in% LETTERS,1,2)),s=y) l <- list(which(z$l==0),which(z$l==1)) v <- unlist(l) for(j in 1:2) for (i in seq(1,ifelse(length(l[[j]])%%2==1,length(l[[j]])-2,length(l[[j]])-1),2)) l[[j]][i:(i+1)] <- rev(l[[j]][i:(i+1)]) z[v,] <- z[unlist(l),] return(z$s) } f("D's mroyr, Ivam. I'e faardi I act'n od htta.") # [1] I ' m s o r r y , D a v e . I ' m a f r a i d I c a n ' t d o t h a t . ``` [Answer] ## Python 2, 181 bytes Much longer than it should be but anyway: ``` def F(s): for l in[i for i,c in enumerate(s)if c.isupper()],[i for i,c in enumerate(s)if c.islower()]: for a,b in zip(l[0::2],l[1::2]):s=s[:a]+s[b]+s[a+1:b]+s[a]+s[b+1:] print s ``` This first creates two lists: one of the indices of the uppercase characters and one for the lowercase characters. Each of these lists is looped through in pairs of indices, and the characters at those indices are switched. I'll golf this down tomorrow, but for now it's time to sleep. [Answer] # [Pip](https://github.com/dloscutoff/pip), 28 bytes ``` Y[XLXU]aRy.`.*?`.y{Sa@0a@va} ``` Takes input as a command-line argument. [Try it online!](https://tio.run/nexus/pip#@x8ZHeETERqbGFSpl6CnZZ@gV1kdnOhgkOhQllj7////4ALfyuTEVM/UYu9Kp/yi1Ow8AA "Pip – TIO Nexus") ### Explanation This is a regex solution, using the builtin regex variables `XL` (lowercase letters, ``[a-z]``) and `XU` (uppercase letters, ``[A-Z]``). ``` a is 1st cmdline arg; v is -1 (implicit) Y[XLXU] Yank a list containing XL and XU into y y.`.*?`.y Concatenate y, `.*?`, and y itemwise, giving this list: [`[a-z].*?[a-z]`; `[A-Z].*?[A-Z]`] aR In a, replace matches of each regex in that list... { } ... using this callback function: Sa@0a@v Swap the 0th and -1st characters of the match a and return the resulting string Print (implicit) ``` When the second argument to `R` is a list, the replacements are performed in series; thus, the lowercase replacement and the uppercase replacement don't interfere with each other. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~121~~ 129 bytes ``` BEGIN{FS=OFS=""}{for(a=1;a<=NF;a++){if($a~/[A-Z]/?U>0?p=U+(U=0):0*(U=a):$a~/[a-z]/?L>0?p=L+(L=0):0*(L=a):0>0){t=$a;$a=$p;$p=t}}}1 ``` [Try it online!](https://tio.run/##Lc1bb4JAEAXg9/0VoyERalV8laLxgkpcWaMQUpvaTGRR6gW6i1o09K9bavpwMi/fOYOX3f3es0a2cxsuTFakXM5vnqkbtEgYCxXNpoEvpjM0sFrVblGoKvjTeOvWlu@NjtfWO4npVdWiobX0p@Ki1noArF0LQB@AVlX6D@gf0Nu6dktNBQ0FTSUxlMRM8zxv3u97am19YCKmQYmIZMSWB4wOmyOckv38KjkcsQ8DK2ZAg1FIuJ3C6Ws86cO85zMG304Ip8/ZlMHiOrdg7FKw2DmArLshjkB/049a4EiUNe5YkWtLfgbhyMgdlUpEXX2sNNL1@@4rjD22gLnlzsj2coSYcxkArmVS/L9kGZJFMs3WyG0uJ1kvFnx3JIOKhIOIM/EM9hkPdbArHEJEEURgF@W0UgwFsE1TrJNf "AWK – Try It Online") Note: Link has 8 extra bytes to allow multiline input Usage is fairly typical, but does require a version of `AWK` that accepts an empty string as the field separator (most versions of `gawk` but I'm pretty sure the original `AWK` would fail :( ) It's very straightforward as it simply iterates over each character and checks if it's found one of that case before. If so, it swaps the characters and resets the checked index. On the learning side of things, I'd never used an assignment statement within an assignment statement in `AWK` before. For some reason it had never come up. :) I might be able to shave a couple of bytes by saying to assign OFS and FS outside a `BEGIN` block via command-line assignment or similar, but it's "cleaner" this way. *Adding the TIO link showed me that I had a transcription error that required 8 bytes to fix :( (I left out `0*(U=a):`)* [Answer] # [Stax](https://github.com/tomtheisen/stax), 18 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` âß:}\]ó☺æ■jφ╛jz/Φi ``` [Run and debug it](https://staxlang.xyz/#p=83e13a7d5c5da20191fe6aedbe6a7a2fe869&i=lLEhW+OroLd%21%0ArpGOZmaimgn+uplRzse+naC+DEoO+LdGf%0AeIt+uqHKC+RBWOO+xNf+ujPMO+SzRE+HTL+EOvd+yAg%0ANraWgCi%3A+Nsas-eNEiTIsev+rNsiTG%21%21%0A&a=1&m=2) The general approach is regex-based. * Two times do: * Find all matches for `[a-z].*?[a-z]`. * Swap the first and last character in matches. * Invert case. [Answer] # [R](https://www.r-project.org/), ~~223~~ ~~163 bytes~~ 148 bytes EDIT: -60 bytes by implementing a for loop EDIT: -15 bytes from Giuseppe ``` u=utf8ToInt(scan(,''));for(i in c(65,97)){l=which(u%in%i:(i+25));x=sum(l|1)%/%2;u[l[1:(x*2)]]=u[c(matrix(l,2)[2:1,1:x])]};cat(intToUtf8(u,T),sep="") ``` [Try it online!](https://tio.run/##Dc5NC4IwGADgv2LC8H1rEA76muzYIRC6GB3Eg6zEwdxibjSofvvy/hwel1IQwQ/Hxl6Mh1n2BmhRIFaDdaAyZTIJ@x09HRA/WrxHJUcIRBmiOKgN2y0yijlMoL8lki1hVWh1W3KIa4ZdJ0IrYeq9UxE0ZdgyXtKSxw67XyV7D8r4xt6WAATaIJ2fL5HnmHJdn8d7dnW2fqzy9Ac "R – Try It Online") Works by testing if character is a lowercase or uppercase, places them in a matrix, inverts the matrix to extract the values in a swapped format. Then output with `cat`. Try it online struggles with `scan(,'')` if the code is more than one line, hence the semicolons throughout the single line of code. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~212~~ ~~206~~ ~~205~~ 203 bytes * Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing ~~six~~ ~~seven~~ nine bytes. ``` #define I(a,b)if(S[j=i]/a&b/S[i]){for(;S[++j]<a|S[j]>b;);j<l?s[i]=S[j],s[j]=S[i]:0;} i,j,l;f(char*S){char*s=calloc(l=-~strlen(S),1);for(i=~0;++i<strlen(S);)if(!s[i]){s[i]=S[i];I(65,90)I(97,'z')}puts(s);} ``` [Try it online!](https://tio.run/##PU9hb9owFPzOr3ik6mKX0LIP29SadFppRKPSZCJISNC0MokNzoKT2oEuMPrXWdJU/fL8dHfv7hx1l1F0PJ7EjAvJwEXUWmDBUTBPbBFe0C@Li2AuQrznmUIkmHc6Sdin/yo6vF4QTJJ@@lNXArtGLF0Nu9Zf9cihJazESglH0YqqswDv319tRzRNswildvdNFyplEgXY@opJnSDstx7pdET/kyF1m7Z@7/ARJELiou/frMsedtHlD8vcmfiQbwqNNCaHz7/MqutcCVlwZDzKU/0ou9dgWJUlr31bayokwvvWDBnpyFlNwVfZKG4buEZUPvRnlWK9lLDJ0/FOM5B0ALdO5sMoHvJGxtwCNi939wMY30x9H/56HDbJ7wcfgt3YgbvJCBx/G0P5a9kceIpOlwNxBZ6muss8R0xczbagPC0mw/ZHOnp6fsLNunqVkDGmY6CRzqsOr2VJGyrIH8qIMpfp@/ImU@yPbPBbU8NaZaWywN3S9Tm4JgNOqYoFuJVNYVaWMayKgp4b@HD8Dw "C (gcc) – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~26~~ 23 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2FÐlø€Ë≠āsƶ0KD2ô혇<è.š ``` I/O as a list of characters. [Try it online](https://tio.run/##yy9OTMpM/f/fyO3whJzDOx41rTnc/ahzwZHG4mPbDLxdjA5vObz29JxHDQttDq/QO7rw//9opRwlHSUfIHYF4gwgDgdiBSD2B@IiIM6HyqcAsaJSLAA) or [verify all test cases](https://tio.run/##HY2xTsJAGID3e4ofFjShxDASEwOlQqX0SFvT6IA56QHVtlfv2uIRTdTNuPgADrI56GaIs1UX34IXqY3jN3zfxwQ59WlxlVX1KE6TFkB1T9ZRFafJP5ZkF839/DHIPzZ3r/nD5v7561b8rHcG3Wb@nr/9Pm1uVrv5S@N7VVwf1D/Xe0VgaHMXMGeGV0E87uHjkPjhLII0DqyloBARFboaw2B4vSmiegLpRX@ggtVxMYZLcwrp2WiIwV5aGvQdAzSceSDbM2Ry4s5UvwWmIEKhpuY7uqAZcFP4Tq9SQVvjk/E2aruqcwT9Q2yDpTkjNF9EwCgVHpCJiMv/QkqC7HgoJ4TqVAxkh3F6HqFuTUDImeR10DMSNkCvUZgSwj0f9FJOamXIg3mSkEahKBFTArKUfw). **Explanation:** ``` 2F # Loop 2 times: Ð # Triplicate the current character-list # (which will use the implicit input-list in the first iteration) l # Lowercase all letters of the top copy ø # Zip/transpose the top two lists; pairing them together, and swapping # rows/columns €Ë≠ # Check for each pair whether they're NOT the same # (so uppercase characters that have now become lowercase) ā # Push a list in the range [1, length] (without popping) s # Swap so the mapped list is at the top again ƶ # Multiply each 1/0 by its 1-based index 0K # Remove all 0s D # Duplicate this list of 1-based indices 2ô # Split it into parts of size 2 í # Reverse each part ˜ # Flatten the list of swapped indices ‡ # Transliterate the indices with the swapped indices in [1, length] < # Decrease each by 1 (because 05AB1E uses 0-based indexing) è # Index them into the current character-list .š # And swap all cases (lowercase to uppercase, and vice-versa) # (after the loop, the resulting character-list is output implicitly) ``` [Answer] # Java 7, 117 bytes ``` String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);} ``` EDIT: Just noticed I have a similar answer as [*@Leo*'s Retina answer](https://codegolf.stackexchange.com/a/109122/52210), even though I've thought about it independently.. **Ungolfed:** ``` String c(final String s) { String x = "([a-z])(.*?)([a-z])", y = "$3$2$1"; return s.replaceAll(x, y).replaceAll(x.toUpperCase(), y); } ``` **Test code:** [Try it here.](https://ideone.com/1aavz3) ``` class M{ static String c(String s){String x="([a-z])(.*?)([a-z])",y="$3$2$1";return s.replaceAll(x,y).replaceAll(x.toUpperCase(),y);} public static void main(String[] a){ System.out.println(c("lLEhW OroLd!")); System.out.println(c("rpGOZmaimgn uplRzse naC DEoO LdGf")); System.out.println(c("eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg")); System.out.println(c("NraWgCi: Nsas-eNEiTIsev rNsiTG!!")); System.out.println(c("(^_^)")); System.out.println(c("AWCTY HUOS RETP")); System.out.println(c("hwn oeesd acsp nawyya")); System.out.println(c("SpMycaeIesKyBorekn")); System.out.println(c("D's mroyr, Ivam. I'e faardi I act'n od htta.")); } } ``` **Output:** ``` hELlO WorLd! prOGRamming puzZles anD COdE GoLf tHe quICK BROWN fOx juMPS OvER THE LAzy dOg WarNiNg: Case-sENsITive sTriNG!! (^_^) WATCH YOUR STEP who needs caps anyway MySpaceKeyIsBroken I'm sorry, Dave. I'm afraid I can't do that. ``` ]
[Question] [ Given a side-view of a mini-golf course and the power of the swing, determine if the ball will make it into the hole. --- A course will be in this format: ``` ____ ____ _ __/ \ / U \ __/ \ / \_ \_/ ``` The ball starts directly **before** the first piece of ground on the left and follows the contour of the course until it reaches the hole (an upper-case `U` below the current level of the ground). If it reaches the hole, output a truthy value. The power of the swing will be the initial speed of the ball. The ball moves to the next character on the right at each iteration, then the speed is altered depending on the character it is now on. If the speed reaches `0` or less before the hole, output a falsey value. * `_` decreases the speed by `1` * `/` decreases the speed by `5` * `\` increases the speed by `4` Courses can optionally be padded with spaces. The power of the swing will always be a positive integer. You do not need to worry about the ball going too fast to enter the hole, rolling backwards or jumping/bouncing off hills. ## Test Cases ``` Input: 27 ____ ____ _ __/ \ / U \ __/ \ / \_ \_/ Output: true ---------- Input: 26 ____ ____ _ __/ \ / U \ __/ \ / \_ \_/ Output: false ---------- Input: 1 U Output: true ---------- Input: 1 _ U Output: false ---------- Input: 22 /U / / / \/ Output: true ---------- Input: 999 _ _ \ / \ / \ / U Output: true ---------- Input: 5 / /U Output: false ---------- Input: 9 /\/\/\/\/U Output: false ---------- Input: 16 _/\ _ \ __ /\/\/\ / \ / \ / \ / \__/ \ / \____________ _/ \_/ U Output: true ``` This is code mini-golf, shortest answer in bytes wins! [Answer] # Pyth, 27 bytes ``` .Am<sXsd"_\ /"[1_4Z5)Q._C.z ``` [Demonstration](https://pyth.herokuapp.com/?code=.Am%3CsXsd%22_%5C+%2F%22%5B1_4Z5%29Q._C.z&input=16%0A_%2F%5C+++++++++++++++++++++++++++++++++++++++++_%0A+++%5C++++++__+++++++%2F%5C%2F%5C%2F%5C++++++++++++++++++%2F+%0A++++%5C++++%2F++%5C+++++%2F++++++%5C++++++++++++++++%2F++%0A+++++%5C__%2F++++%5C+++%2F++++++++%5C____________+_%2F+++%0A++++++++++++++%5C_%2F++++++++++++++++++++++U+++++&debug=0) This code does something very clever and not at all type-safe with `X`. Check it out below. **Explanation:** ``` .Am<sXsd"_\ /"[1_4Z5)Q._C.z Implicit: Z = 0, Q = eval(input()) Q is the initial power. .z Take all input, as a list of lines. C Transpose, giving all columns. ._ Form all prefixes. m Map over the prefixes. sd Concatenate the prefix. X "_\ /"[1_4Z5) Change '_' to 1, '\' to -4, ' ' to 0, and '/' to 5. In particular, 'U' is left unchanged. s Reduce on addition. If all elements were numbers, this results in the total change in power. If there was a 'U', it results in a string. < Q If the previous result was a number, this compares it with the initial input to see if the ball is still rolling. If the previous result was a string, this slices off the first Q characters, which always has a truthy result. .A Test whether all of the prefixes mapped to a thruthy result. ``` [Answer] ## Haskell, ~~111~~ 109 bytes ``` import Data.List g"_"=1 g"/"=5 g _= -4 f n=all(>0).scanl(-)n.map g.fst.span(/="U").(>>=words).transpose.lines ``` Usage example: ``` *Main> f 27 " ____ ____ _ \n __/ \\ / U \\ \n__/ \\ / \\_\n \\_/ " True *Main> f 26 " ____ ____ _ \n __/ \\ / U \\ \n__/ \\ / \\_\n \\_/ " False ``` How it works: ``` lines -- split into list of lines at nl transpose -- transpose (>>=words) -- turn each line into words (i.e. remove spaces) fst.span(/="U") -- take all words up to but excluding "U" map g -- turn each word into the speed modifier scanl(-)n -- build list of partial sums starting with n -- note: speed modifiers are negative so we -- use (-) with scanl to build sums all(>0) -- return true if all sums are greater than 0 ``` Edit: @user81655 found 2 bytes to save. Thanks! [Answer] # Ruby, ~~104~~ 87 characters ``` ->s,t{t.lines.map(&:bytes).transpose.map{|o|(c=o.max)==85||s<0?break: s+=c*3%14-6} s>0} ``` Sample run: ``` 2.1.5 :001 > track = ' ____ ____ _ 2.1.5 :002'> __/ \ / U \ 2.1.5 :003'> __/ \ / \_ 2.1.5 :004'> \_/ 2.1.5 :005'> ' => " ____ ____ _ \n __/ \\ / U \\ \n__/ \\ / \\_\n \\_/ \n" 2.1.5 :006 > ->s,t{t.lines.map(&:bytes).transpose.map{|o|(c=o.max)==85||s<0?break: s+=c*3%14-6};s>0}[27, track] => true 2.1.5 :007 > ->s,t{t.lines.map(&:bytes).transpose.map{|o|(c=o.max)==85||s<0?break: s+=c*3%14-6};s>0}[26, track] => false ``` [Answer] # Japt, 38 bytes ``` Vz r"%s|U[^]*" ¬e@UµX¥'_?1:X¥'/?5:-4 ¬ ``` `[Try it here!](http://ethproductions.github.io/japt?v=master&code=VnogciIlc3xVW15dKiIgrGVAVbVYpSdfPzE6WKUnLz81Oi00IKw=&input=MjYgIiAgICAgIF9fX18gICAgICAgX19fXyBfICAgCiAgIF9fLyAgICBcICAgICAvICAgIFUgXCAgCl9fLyAgICAgICAgXCAgIC8gICAgICAgIFxfCiAgICAgICAgICAgIFxfLyAgICAgICAgICAgIg==)` Beating CJam! # Explanation Basically takes the string input, rotates it 90deg clockwise, strips out spaces and newlines, removes the hole and everything after it, and splits along chars. Then checks if ball ever gets to zero or below using the `every` function. [Answer] ## CJam, ~~40~~ 39 bytes ``` liqN/:.e>'U/0="\_/"[4W-5]er{1$+}/]:e<0> ``` Input has the power on the first line and the course starting on the second line. Output is `0` or `1`. [Test it here.](http://cjam.aditsu.net/#code=liqN%2F%3A.e%3E'U%2F0%3D%22%5C_%2F%22%5B4W-5%5Der%7B1%24%2B%7D%2F%5D%3Ae%3C0%3E&input=16%0A_%2F%5C%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_%0A%20%20%20%5C%20%20%20%20%20%20__%20%20%20%20%20%20%20%2F%5C%2F%5C%2F%5C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%20%0A%20%20%20%20%5C%20%20%20%20%2F%20%20%5C%20%20%20%20%20%2F%20%20%20%20%20%20%5C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%2F%20%20%0A%20%20%20%20%20%5C__%2F%20%20%20%20%5C%20%20%20%2F%20%20%20%20%20%20%20%20%5C____________%20_%2F%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%5C_%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20U%20%20%20%20%20) ### Explanation ``` li e# Read power and convert to integer. qN/ e# Read course and split into lines. :.e> e# Flatten course by folding maximum over columns. 'U/ e# Split around the hole. 0= e# Keep the first chunk. "\_/"[4W-5]er e# Replace \, _, / with 4, -1, 5, respectively. { e# For each of those costs... 1$+ e# Copy the previous power and add the cost. }/ e# This leaves all partial sums on the stack. ] e# Wrap them in an array. :e< e# Find the minimum. 0> e# Check whether it's positive. ``` [Answer] ## Retina, ~~82~~ ~~81~~ ~~77~~ ~~74~~ ~~68~~ ~~67~~ 68 bytes ``` +`(?<=(.)*) (?=.*¶(?<-1>.)*(.)) $2 \\ >>>> +`>_|>{5}/|>¶ ^>*U ``` [Try it online](http://retina.tryitonline.net/#code=K2AoPzw9wrYoLikqKSAoPz0uKsK2KD88LTE-LikqKC4pKQokMgpcXAo-Pj4-CitgPl98Pns1fS98wrYKCl4-KlU&input=Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4KICAgICAgX19fXyAgICAgICBfX19fIF8gICAKICAgX18vICAgIFwgICAgIC8gICAgVSBcICAKX18vICAgICAgICBcICAgLyAgICAgICAgXF8KICAgICAgICAgICAgXF8vICAgICAgICAgICA&debug=on) * Input is represented in *unary base*, as n `>`s - for example, 4 is `>>>>\n`. (is this legal?) * `+`(?<=(.)*) (?=.*¶(?<-1>.)*(.))` `$2` - flatten the course - replace spaces with the character below them. After this stage the data will look like this: ``` >>>>>>>>>>>>>>>>>>>>>>>>>> __/__/____\\\_///____U_\\_ __/__/ \\\_/// U \\_ __/ \\_// \_ \_/ ``` We can just ignore everything after the first `U`, we will not reach there anyway. * `>` represent a step we are allowed to make, or the remaining energy. * Replace each `\` with four `>` - a slope gives us additional energy. * Loop: contentiously remove `>_` or `>>>>>/` until there are none left. `_`s and `/`s *consume* energy. * Finally, try to match `^>*U` - check if we can reach `U` with positive energy (or no energy). This will output `0` or `1`. --- Another close option with ~~91~~ 79 bytes is: ``` +`(?<=¶(.)*) (?=.*¶(?<-1>.)*(.)) $2 ^(>)+\n(?<-1>_|/(?<-1>){4}|\\(?<1>){5})+U ``` [Try it online](http://retina.tryitonline.net/#code=K2AoPzw9wrYoLikqKSAoPz0uKsK2KD88LTE-LikqKC4pKQokMgpeKD4pK1xuKD88LTE-X3wvKD88LTE-KXs0fXxcXCg_PDE-KXs1fSkrVQ&input=Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4-Pj4KICAgICAgX19fXyAgICAgICBfX19fIF8gICAKICAgX18vICAgIFwgICAgIC8gICAgVSBcICAKX18vICAgICAgICBcICAgLyAgICAgICAgXF8KICAgICAgICAgICAgXF8vICAgICAgICAgICA&debug=on) This is the same approach but with a balancing group instead of a contentious replace. I'm sure both of these can be golfed further, so any one of them may end up shorter. [Answer] ## ES6, 117 bytes ``` (c,p)=>c.split` `.map(s=>[...s.slice(0,c.match(/^.*U/m)[0].length-1)].map(c=>p+=c=='/'?-5:' \\'.indexOf(c)))&&p>0 ``` Ungolfed: ``` function hole(course, power) { width = course.match(/^.*U/m)[0].length - 1; // calculate width to hole lines = course.split("\n"); for (i = 0; i < lines.length; i++) { line = lines[i].slice(0, width); // ignore extraneous parts of the course for (j = 0; j < line.length; j++) { switch (line[j]) { // accumulate remaining power case '/': power -= 5; break; case '\\': power += 4; break; case ' ': break; default: power--; break; } } } return power > 0; } ``` Edit: Saved 4 bytes thanks to ՊՓԼՃՐՊՃՈԲՍԼ. [Answer] # JavaScript (ES6), ~~108~~ ~~107~~ 106 bytes This is the solution I came up with when I created the challenge. ``` (p,c)=>[...(l=c.split` `)[w=0]].map((_,i)=>l.map(t=>(g=t[i])-1|p<=0?0:p-=g>"]"?1:g>"U"?-4:g>"/"?w=1:5))&&w ``` ## Explanation Takes the power as a number and the course as a string. Returns `1` for `true` or `0` for `false`. The course must be padded with spaces. ``` (p,c)=> [...(l=c.split` `) // l = array of lines [w=0]] // w = true if the ball has entered the hole .map((_,i)=> // for each index i l.map(t=> // for each line t (g=t[i]) // g = the character at the current index -1|p<=0?0: // do nothing if g is a space or the ball has no speed left p-= g>"]"?1 // case _: subtract 1 from p :g>"U"?-4 // case \: add 4 to p :g>"/"?w=1 // case U: set w to true (it doesn't matter what happens to p) :5 // case /: subtract 5 from p ) ) &&w // return w ``` ## Test ``` var solution = (p,c)=>[...(l=c.split` `)[w=0]].map((_,i)=>l.map(t=>(g=t[i])-1|p<=0?0:p-=g>"]"?1:g>"U"?-4:g>"/"?w=1:5))&&w ``` ``` Power = <input type="number" id="power" value="16" /><br /> <textarea id="course" rows="6" cols="50">_/\ _ \ __ /\/\/\ / \ / \ / \ / \__/ \ / \____________ _/ \_/ U </textarea><br /> <button onclick="result.textContent=solution(+power.value,course.value)">Go</button> <pre id="result"></pre> ``` [Answer] ## Python (3.5) ~~169~~ 160 bytes A recursive solution without the transpose function (zip) ``` def f(c,p):c=c.splitlines();l=len(c);f=lambda x,h,v:v if'U'==c[h][x]or v<1 else f(x+(h==l-1),(h+1)%l,v+{"_":-1,"\\":4,"/":-5," ":0}[c[h][x]]);return f(0,0,p)>0 ``` ## Ungolfed c for course, p for power, v for speed, h for height ``` def f(c,p): c=c.splitlines() l=len(c) tmp = {"_":-1,"\\":4,"/":-5," ":0} f=lambda x,h,v:v if'U'==c[h][x]or v<1 else f(x+(h==l-1),(h+1)%l,v+tmp[c[h][x]]) return f(0,0,p)>0 ``` ## Usage ``` f(16,"_/\ _\n \ __ /\/\/\ / \n \ / \ / \ / \n \__/ \ / \____________ _/ \n \_/ U ") f(9,"/\/\/\/\/U") ``` [Answer] ## Pyth, 35 bytes ``` VC.z=-Q@(1_4 5)x"_\\/"JrN6IqJ\U>Q_5 ``` Explanation ``` - Autoassign Q = eval(input()) - Autoassign .z = rest of input VC.z - For N in zip(*.z) =-Q - Q -= ... JrN6 - Autoassign J to N.strip() (get rid of spaces) @(1_4 5)x"_\\/" - {"_":1, "\\": -4, "/": 5, "U":5}[J] ("U" isn't defined but that's what it is according to how str.index works) IqJ\U - If J == "U" >Q_5 - print Q > -5 () ``` [Answer] # Ruby, 85 characters ``` ->i,s{s.lines.map(&:bytes).transpose.any?{|o|(c=o.max)==85||i<0||!(i+=c*3%14-6)};i>0} ``` Adapted @manatwork's answer [Answer] **JavaScript, ~~266~~ ~~263~~ 244 bytes** ``` (s,a)=>{var f=(e,x)=>{for(var i=1;D=e[i][x],i<e.length;i++)if(D!=" ")return D},o=a.split(` `),l=o.reduce((a,b)=>Math.max(a.length||a,b.length)),b="";for(i=0;i<l;i)b+=f(o,i++);for(i=0;b[i]!="U"&&s>0;i++)s-=b[i]=="_"?1:b[i]=="/"?5:-4;return s>0} ``` **Ungolfed** ``` (s,a)=>{ var f=(e,x)=>{ for(var i=1;D=e[i][x],i<e.length;i++) if(D!=" ") return D }, o=a.split(` `), l=o.reduce((a,b)=>Math.max(a.length||a,b.length)), b=""; for(i=0;i<l;) b+=f(o,i++); for(i=0;b[i]!="U"&&s>0;i++) s-=b[i]=="_"?1:b[i]=="/"?5:-4; return s>0 } ``` **Usage** ``` var o = (s,a)=>{var f=(e,x)=>{for(var i=1;D=e[i][x],i<e.length;i++)if(D!=" ")return D},o=a.split(` `),l=o.reduce((a,b)=>Math.max(a.length||a,b.length)),b="";for(i=0;i<l;)b+=f(o,i++);for(i=0;b[i]!="U"&&s>0;i++)s-=b[i]=="_"?1:b[i]=="/"?5:-4;return s>0} o(27, ` ____ ____ _ __/ \\ / U \\ __/ \\ / \\_ \\_/ `); // will return true ``` [Answer] # Java, 219 Bytes ``` boolean p(int v,String c){int z=c.length(),f[]=new int[z],e,i,k;for(String r:c.split("\n"))for(i=-1;++i<r.length();)if((e=r.charAt(i))>32)f[i]=e;for(i=-1,e=0;++i<z&v>0;)v-=(k=f[i])>94?1:k>91?-4:k>84?(e=1):5;return 0<e;} ``` * Flatten the course, because the y-coordinate doesn't matter, unfortunately Java doesn't have a vertical trim. It also doesn't have a String-transpose. * Iterate over the flattened course and keep track of the ball speed. [Answer] # Octave, ~~111~~ 110 bytes ``` function g(v,s) A([95,47,92])=[1,5,-4];all(v>cumsum(A(m=max(cat(1,strsplit(s,'\n'){:}),[],1)))(1:find(m==85))) ``` ### Explanation: * Split the input on newlines and convert that annoying cell array to a matrix * Flatten the matrix by finding the `max` for each column * Map the characters `'_/\'` to `[1, 5, -4]` (all other characters less than `'_'` are mapped to `0`) * Calculate the cumulative sum of all elements of the mapped array * Output `True` if all cumulative sums from the beginning of the course to the cup are less than the start velocity (`False` otherwise). --- Here is a test case that I had already developed similar to the second one proposed by @Erwan and a couple of results: ``` s9 = /\ / \ _/ \ \ \ U g(11,s9) %False ans = 0 g(17,s9) %True ans = 1 ``` And here's the first test case: ``` s10 = _ / U\ / \ \ \ \ \ \_ >> g(11,s10) ans = 0 >> g(12,s10) ans = 1 ``` [Answer] ## C, 629 Bytes ``` #include <string.h> #include <stdlib.h> #include <string.h> bool swing(char *c, unsigned int p) { char *olc = calloc(strlen(c), 1); int x = 0; char *n = c; while(1) { if(*n == '\0') break; else if(*n == ' ') x += 1; else if(*n == '\n') x = 0; else { olc[x] = *n; x += 1; } n++; } int hd = 0; for(char *i = olc; i != strchr(olc, 'U'); i++) { if(*i == '_') hd += 1; else if(*i == '/') hd += 5; else hd -= 4; } free(olc); if(hd < p) return 1; return 0; } ``` Ungolfed: ``` bool swing(char *course, unsigned int power) { const size_t course_len = strlen(course); char *one_line_course = calloc(course_len, sizeof(char)); assert(one_line_course); int x_pos = 0; char *next = course; //Convert to one line representation while(1) { if(*next == '\0') { break; } else if(*next == ' ') { x_pos += 1; } else if((*next == '\n') || (*next == '\r')) { x_pos = 0; } else { one_line_course[x_pos] = *next; x_pos += 1; } next++; } //Calculate power vs distance const char *hole_location = strchr(one_line_course, 'U'); int hole_distance = 0; for(char *i = one_line_course; i != hole_location; i++) { if(*i == '_') { hole_distance += 1; } else if(*i == '/') { hole_distance += 5; } else { hole_distance -= 4; } } free(one_line_course); if(hole_distance < power) { return true; } else { return false; } } ``` Basically I just make one pass to convert the input string to fit everything in one line, then [Answer] # Python, ~~212~~ ~~201~~ ~~188~~ 143 bytes Much of the credit for this iteration of this script goes to @Erwan, who gave me an entirely different approach to try and some tips that saved me 55 bytes in the end. Not recursive, so should be substantially different from the other python solution. ``` def g(c,p): o=[''.join(x).split()[0] for x in zip(*c.split('\n'))] t={"_":1,"/":5,"\\":-4} for v in o: if v=="U" or p<1:return p>0 p-=t[v] ``` Ungolfed a bit: ``` def g(course,power): course=course.split('\n') # split into lines course=zip(*course) #transpose and flatten course, then remove spaces one_line_course=[''.join(x).split[0] for x in zip(*course)] terrain_values={"_":1,"/":5,"\\":-4} for char in one_line_course: if char=="U" or power<1: return power>0 # true when power remains, false otherwise power-=terrain_values[char] ``` [Answer] # [J](http://jsoftware.com/), 47 bytes ``` 1 e.(<:4([:+/\1 5 _4{~i.&3{.])@-.~'_/\U',@i.|:) ``` [Try it online!](https://tio.run/##jVLLasMwELzvVww91DFNJMvNA6s1BAo99VTQKTIilISkl35ASn7d1SuySuLSFQaNNJrdHe9nf8eKPVqJAlNUkPabMby8v732Ajs2eZbzyUY@cC2wgJmfzkd2/3hiXbmesXNhuFbFdH1k37LsS9q2DN0TMzU6p1URfBgbyLYOkAfcnWl/47fKAYrnl7sBGEIWeqA5wZJo93H4gkCLeok9tgFXDq88vi5Q2WeJJUZINm3iiT94oQ9FsR2KtVNsgTTPs9W1k8GtfBezKHlDyQryrkRd51iu2TTNaG2cuALyPhYjXK7jsl27POmBF8fNkrnGf8NQ@ulIgxEyXpN5aFNHT7NZSRo5ObDtaAyjlY1PFjDJwrGJyuK3y2IZfLDv@x8 "J – Try It Online") ]
[Question] [ Computers are everywhere nowadays - in cars, trains, skateboards, even nuclear reactors. The possibility that your software will run in a time travelling device is just a matter of time. Can you deal with it? Can you at least detect it? Your task: 1. Write a program that loops and keeps querying the system time, in order to detect time travel. 2. If time moves forward a day or more between two consecutive queries, it's forward time travel. In this case, your program should print: `TS TS: YYYY? You mean we're in the future?` 3. If time moves back, by any amount, between two consecutive queries, it's backward time travel. In this case, your program should print: `TS TS: Back in good old YYYY.` 4. `TS TS` are the timestamps before and after the time travel. `YYYY` is the destination year. 5. Timestamps may be in any format, that includes at least the 4-digit year, month, day, hour, minute and second, separated by non-digits. Limitations: 1. You must support dates in the 19th, 20th and 21st centuries, at least. 2. You must use a language that existed before this challenge was posted. 3. You must post your answers only after this challenge was posted. 4. You must use a language that existed before your answer was posted. 5. You may edit your answer only after you've posted it. 6. Your program must not print any output other than the required output. An occasional "Great Scott!" is allowed. This is code-golf. The shortest answer wins. Relevant movie references will probably make your answer too long, but might get you upvotes. [Answer] ## Python 2, 210 bytes ``` from datetime import* o=0 while 1:n=datetime.now();o=o or n;print"%s;%s: %s? You mean we're in the future?"%(o,n,n.year)if(n-o).days>=1else"%s;%s: Back in good old %s."%(n,o,n.year)if(n<o)else"Great Scott!";o=n ``` Timestamps are printed in in `YYYY-MM-DD HH:MM:SS` format, separated with semicolons. Switched to Python 2 from 3 since it's 2 chars shorter to print. Spams stdout with `Great Scott!` for ~~normies~~ non-time-travellers, since it's easier and cheaper to do that than set up a conditional print. [Answer] # JavaScript (ES6), 263 bytes ``` n=Date;o=n.now();(function g(){k=new n;j=new n(o);s=`${k} ${o} `;if(n.now()-o>86400)console.log(`${s}${k.getFullYear()}? You mean we're in the future?`);if(o-n.now()>84600){console.log(`${s}Back in good old ${k.getFullYear()}.`);}o=n.now();setTimeout(g,100);}()); ``` This could probably do with some rewriting to make it more efficient/small. Source: ``` n=Date; o=n.now(); (function go() { k=new n; j=new n(o); s=`${k} ${o} `; if (n.now() - o > 86400) { console.log(`${s}${k.getFullYear()}? You mean we're in the future?`); } if (o - n.now() > 84600) { console.log(`${s}Back in good old ${k.getFullYear()}.`); } o=n.now() setTimeout(go,100); }()); ``` [Answer] # Bash + coreutils, 177 ``` d()(date -d@"$@") for((b=`date +%s`;a=`date +%s`;b=a)){ t=`d $a`\ `d $b` ((a<b))&&d $b "+$t: Back in good old %Y." ((a>b+86400))&&d $b "+$t: %Y? You mean we're in the future?" } ``` [Answer] # Python 3, 195 ``` from datetime import* n=datetime.now p=n() while 1: c=n();f=(p,c,p.year);s=(0,("%s %s: %s? You mean we're in the future?"%f,"%s %s: Back in good old %s."%f)[p.day>c.day])[p>c];p=c if s:print(s) ``` Currently doesn't print Great Scott because I can't find a good way of only making it occasional. [Answer] # CJam, 118 bytes ``` et:Tes{es_@-[TS*Set:TS*':S]\_864e5<{[1$et0="? You mean we're in the future?"N]o}|0<{[_"Back in good old "et0='.N]o}&}g ``` This does not work with the online interpreter. Sample output after adjusting my computer's time twice: ``` 2015 10 21 11 2 45 1 3 -10800000 2015 10 23 11 2 45 0 5 -10800000: 2015? You mean we're in the future? 2015 10 23 11 2 53 448 5 -10800000 2015 10 21 11 2 52 0 3 -10800000: Back in good old 2015. ``` [Answer] # Ruby, 194 bytes I haven't had the time to really cut this down to size yet. I'm sure there are a few optimizations hiding in there. ``` require 'time';t=nil;while 1;n=Time.now;if t;s="#{t} #{n}: ";y=n.year;puts t>n ? "#{s}Back in good old #{y}" : (n>t+86400 ? "#{s}#{y}? You mean we're in the future?": "Great Scott!");end;t=n;end ``` Ungolfed (and a lot more readable): ``` require 'time' t=nil while 1 n=Time.now if t # on second or later pass s="#{t} #{n}: " # prepare the timestamp y=n.year puts t>n ? # if we go back "#{s}Back in good old #{y}" : # timestamp + phrase (n>t+86400 ? # else, more than one day forward "#{s}#{y}? You mean we're in the future?": # timestamp + future "Great Scott!") # Great Scott! end t=n # set a new jump point end ``` Edit: corrected to ask OS for time, rather than a human. [Answer] # Lua 5.3, 174 bytes ``` T=os.time P=print l=T()::a::t=T()b=l.." "..t..": "y=os.date('%Y',t)_=t<l and P(b.."Back in good old "..y)or t>l+86399 and P(b..y.."? You mean we're in the future?")l=t goto a ``` This is playing heavily off of the "Timestamps may be in any format" rule ... which I took the liberty of using the format of "seconds since Jan 1, 1970" If I keep my shoddy interpretation of printing timestamps, and adopt the structure of MeepDarknessMeep, I can (unethically) squeeze this down to ... # 155 bytes ``` T=os.time::G::l=t or T()t=T()_=(t>l+86399or t<l)and print(l.." "..t..": "..os.date(t<l and"Back in good old %Y"or"%Y? You mean we're in the future?"))goto G ``` [Answer] # Lua 5.3, ~~179~~ ~~178~~ ~~173~~ ~~171~~ ~~169~~ ~~168~~ 163 bytes ``` q="%Y %c: "c=os.date::a::d=f f=os.time()_=d and(f-d>86399or f<d)and print(c(q,d)..c(q..(f<d and"Back in good old %Y."or"%Y? You mean we're in the future?")))goto a ``` Side note: If you take out the need for a full year number then subtract six bytes. The reason is that lua's (or windows' or someone's!) %c doesn't output the full year. Because of this, the timestamps may look weird! This also takes advantage of timestamps being able to be seperated by any non digit characters! Thanks for notifying me of my old math.abs reference and other improvements @thenumbernine :) # Lua 5.3, 151 bytes This is 'copying' off of @thenumbernine's method of displaying time by just showing the timestamp instead of the actual date. This isn't competitive since I think it is a bit of cheating, just posting it here to display my work :) ``` ::a::d=f f=os.time()_=d and(f-d>86399or f<d)and print(d.." "..f..os.date(f<d and": Back in good old %Y."or": %Y? You mean we're in the future?"))goto a ``` [Answer] # Python, 170 165 bytes ``` from datetime import* n=datetime.now c=n() while 1: p=c;c=n() if(c-p).days:print p,"%s:"%c,["%s? You mean we're in the future?","Back in good old %s."][c<p]%c.year ``` This owes a lot to Morgan Thrapp's answer. The main trick here is timedelta normalization, which conveniently makes timedelta.days negative when moving even slightly towards the past, and 0 when moving less than a day to the future. [Answer] # Caché ObjectScript, 199 bytes ``` l s k=86400 f s e=+$H,t=$P($H,",",2) s:'d d=e,s=t s z=$ZDT(h)_" "_$ZDT($H)_": ",y=h\365+1841 w:e>d !,z,y,"? You mean we're in the future?" w:(k*t+e)<(k*s+d) !,z,"Back in good old ",y s h=$H,d=e,s=t ``` This problem is solvable in plain old MUMPS, but would be unreasonably lengthy, since ANSI MUMPS lacks [the `$ZD[ATE]T[IME]` intrinsic function](http://docs.intersystems.com/ens20091/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_fzdatetime) for formatting dates into human-readable timestamps. This program will probably not detect time-travel to before 1 Jan 1841, nor time-travel to after 31 Dec 9999, since these are the bounds of [the `$H[OROLOG]` timekeeping intrinsic](http://docs.intersystems.com/ens20091/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_vhorolog). This program also only has second-level precision; sub-second-level backwards time glitches will likely escape its notice. [Answer] ## TSQL, 355 bytes At the work so no fancy cool languges stick with your SQL Server production server =) Golfed version ``` declare @a datetime=getdate(),@b datetime,@d float,@ char(99),@y char(4)while 0=0begin select @b=getdate(),@d=cast(@b as float)-cast(@a as float),@y=' '+DATEPART(y,@b),@=cast(@a as char(20))+' '+cast(@a as char(20))+': 'if @d>=1set @=@+@y+'? You mean we''re in the future?'if @d<0set @=@+'Back in good old '+@y+'.'print @ set @a=@b end ``` More readable version with minor changes. ``` declare @t0 datetime = getdate(), @t1 datetime, @d float, @m varchar(99), @y char(4) while 0=0 begin set @t1 = getdate() set @d = cast(@t1 as float) - cast(@t0 as float) set @y = ' ' + DATEPART(yy, @t1) set @m = cast(@t0 as varchar(30)) + ' ' + cast(@t0 as varchar(30)) + ': ' if @d >= 1 set @m = @m + @y + '? You mean we''re in the future?' if @d < 0 set @m = @m + 'Back in good old ' + @y + '.' print @m set @t0 = @t1 end ``` SQL is not that bad in respect to timestamps since it's a first class data type. For the golf's sake we are using a type with 3 milliseconds precision. The loop itself takes less that that to iterate (depending of your server). The key here is internaly that time stamp is a float and the integer type counts how many days passed. It ill work fine in January 1, 1753, through December 31, 9999 date range. [Answer] # VBA, 258 Bytes ### Ran with:Excel 2007 in Windows 7 **305 bytes** if Usability is required > > WARNING This MAY Max your CPU and Crash Excel/Windows if you are on a Single Threaded single core computer (Most likely found in 1985) > > > ``` Sub q() h=CDbl(Now()) While 1 t=CDbl(Now()) If t>h+1 Then Debug.Print (CDate(t) & " " & CDate(h) & ":" & Year(t) & "? You mean we're in the future?") If t<h Then Debug.Print (CDate(t) & " " & CDate(h) & ": Back in good old " & Year(t) & ".") h=t Wend End Sub ``` If you want this Code to be "Testable" then add `Application.Wait (Now() + TimeValue("0:00:01"))` after `h=t` ### Output ``` 10/22/2015 3:04:45 PM 10/22/2015 3:04:43 PM:2015?You mean we're in the future? 10/22/2015 3:06:48 PM 10/22/2015 3:06:46 PM: Back in good old 2015. ``` Below is the test file I used. I'm Honestly Amazed at how little security Windows has sometimes. May not run as expected on all computers > > Run at Own Risk Could Have Major lasting Side Effects!!!! > > `Sub DOC() > t = 31346.6868055556 > Date = DateSerial(Year(t), Month(t), Day(t)) > Time = TimeSerial(Hour(t), Minute(t), Second(t)) > q > End Sub` > > > [Answer] # C: 363 bytes Minified using [this handy script](https://github.com/Scylardor/cminify/blob/master/minifier.py): ``` #include<stdio.h> #include<time.h> void p(time_t*t){char b[64];strftime(b,64,"%FT%T",localtime(t));printf("%s ",b);}int main(void){time_t a,b,d=60*60*24;int y;time(&a);while(1){time(&b);y=localtime(&b)->tm_year+1900;if(b<a){p(&a);p(&b);printf("Back in good old %d\n",y);}else if(b>a+d){p(&a);p(&b);printf("%d? You mean we're in the future?\n",y);}a=b;sleep(1);}} ``` Original: ``` #include <stdio.h> #include <time.h> void p(time_t * t) { char b[64]; strftime(b, 64, "%FT%T", localtime(t)); printf("%s ", b); } int main(void) { time_t a, b, d = 60*60*24; int y; time(&a); while(1) { time(&b); y = localtime(&b)->tm_year+1900; if (b < a) { p(&a); p(&b); printf("Back in good old %d\n", y); } else if (b > a + d) { p(&a); p(&b); printf("%d? You mean we're in the future?\n", y); } a = b; sleep(1); } } ``` Example run: ``` 2015-10-23T23:30:03 1985-06-14T16:27:00 Back in good old 1985 1985-06-14T16:27:07 1999-02-09T14:15:00 1999? You mean we're in the future? 1999-02-09T14:15:09 2015-02-09T14:15:00 2015? You mean we're in the future? 2015-02-09T14:15:36 2015-10-21T07:28:00 2015? You mean we're in the future? 2015-10-21T07:29:06 1985-10-26T09:00:00 Back in good old 1985 1985-10-26T09:00:28 2055-11-12T06:38:00 2055? You mean we're in the future? 2055-11-12T06:38:12 1919-10-07T00:09:57 Back in good old 1919 1919-10-07T00:09:57 2055-11-12T06:38:14 2055? You mean we're in the future? # tried to go to 1955 - fail. 2055-11-12T06:39:09 2015-10-23T23:32:03 Back in good old 2015 # auto-time back to 2015 because my laptop didn't like the jump to 2055! ``` I could get rid of 10 bytes by removing the `sleep` I guess. By the way, some time-jumping handiness for Mac/Linux: ``` sudo date 1026090085 # Sat 26 Oct 1985 09:00:00 sudo date 1021072815 # Wed 21 Oct 2015 07:28:00 sudo date 1112063855 # Intended to be 1955 but is 2055. Don't use! ``` [Answer] # JavaScript (ES6) 181 174 170 Bytes ``` for(a=Date;c=b||a.now(),b=d();e=new a(b).getFullYear(),f=`${a(c)} ${a(b):`})b>c+864e5?(g=alert)`${f} ${e}? You mean we're in the future?`:c>b&&g`${f} Back in good old `+e ``` **Note:** Has not been tested with a real time machine. This code runs in Firefox, Chrome, Edge, Node.js Harmony (or [io.js](http://iojs.org) for that matter). But, I use `alert`, so that will have to be replaced by `console.log` for [Node](http://nodejs.org) and [Io](http://iojs.org) Suport: (187 Bytes) ``` for(a=Date,b=0;c=b||(d=a.now)(),b=d();e=new a(b).getFullYear(),f=`${a(c)} ${a(b):`})b>c+864e5?(g=console.log)`${f} ${e}? You mean we're in the future?`:c>b&&g`${f} Back in good old ${e}.` ``` Explained: ``` // Using for like a while loop, defining relevant variables: for (a = Date, b = 0; // Defing b and c: c becomes b, b becomes now. Also defining a shorthand for Date.now: c = b || a.now(), b = d(); // Defining Variables Relevant to this loop: e is the year according to b, f is the "TS TS:" string: e = new a(b).getFullYear(), f = `${a(c)} ${a(b):` ) // If b is greater than c plus a day (in milliseconds): b > c + 864e5 ? // Alert Time Forwand String: (g = alert) `${f} ${e}? You mean we're in the future?`: // else if c is greater than b: c > b && // Alert Time Back String: g `${f} Back in good old `+e ``` [Answer] ## Processing, 270 bytes ``` int p;long x=System.currentTimeMillis();void draw(){int q=millis(),y=year();if(q<p){t(p);print("Back in good old "+y+".");}if(q>p+86400000){t(p);print(y+"? You mean we're in the future?");}p=q;}void t(int m){print(new java.util.Date(x+m)+" "+new java.util.Date()+": ");} ``` Expanded: ``` int p; long x=System.currentTimeMillis(); void draw() { int q=millis(), y=year(); if (q<p) { t(p); print("Back in good old "+y+"."); } if (q>p+86400000) { t(p); print(y+"? You mean we're in the future?"); } p=q; } void t(int m) { print(new java.util.Date(x+m)+" "+new java.util.Date()+": "); } ``` Sample output: ``` Wed Oct 21 13:21:59 EDT 2015 Mon Oct 19 13:21:59 EDT 2015: Back in good old 2015. Mon Oct 19 13:22:08 EDT 2015 Wed Oct 21 13:22:08 EDT 2015: 2015? You mean we're in the future ``` [Answer] # Ruby, ~~160~~ ~~157~~ ~~155~~ 154 bytes A lot of things to golf here ``` a=Time.new;loop{b,s,y=Time.new,"#{a} #{b}: ",b.year;$><<(a>b ? s+"Back in good old #{y}.\n":b>a+86400 ? s+"#{y}? You mean we're in the future?\n":"");a=b} ``` [Answer] # Mathematica, 295 bytes The program asks the OS every second for new TS. ``` f:=LocalTime[] p=Print; y:=DateString[#,"Year"]& s:=ToString[#]<>" "& d:=QuantityMagnitude@DateDifference[a,b] j=StringJoin; While[True, a=b; b=f; Pause@1; Which[d>=0, p@(j@@{s@a,s@b,": ",y@b, "? You mean we are in the future?"}), d<0, p@(j@@{s@a,s@b," Back in good old ",y@b,"."})]]; ``` # Output Tested by manually feeding in date/time. ``` DateObject[{2015, 10, 23}, TimeObject[{18, 36, 17.9618}], TimeZone -> \ -4.] DateObject[{2015, 10, 25}, TimeObject[{18, 42, 0.264913}], \ TimeZone -> -4.] : 2015? You mean we are in the future? DateObject[{2015, 10, 23}, TimeObject[{18, 43, 0.141572}], TimeZone -> -4.] DateObject[{2015, 10, 23}, TimeObject[{18, 42, 3.30681}], TimeZone -> -4.] Back in good old 2015. ``` Definitely could have format the output better. It does fulfill the requirements as stated. [Answer] # Javascript 173 169 162 bytes Javascript is pretty popular... ``` for(e=Date,n=e.now;o=n(a=alert);)d=new e,f=d.getFullYear(n(o>n(s=d+` ${e(o)}:`)&&a(s+`Back in good old ${f}.`))-o>864e5&&a(s+f+`? You mean we're in the future?`)) ``` Explanation (Older version of the code): ``` for(e=Date,n=e.now,a=alert,o=n();;o=n()) //Set up the variables and update o, the previous time d=new e,s=d+` ${e(o)} `,f=d.getFullYear(), //d is the date, s is a string with the 2 timestamps, f is the year n()-o>8.64e7&&a(s+f+`? You mean we're in the future?`), //Future check o>n()&&a(s+`Back in good old ${f}.`) //Past check ``` [Answer] # Groovy, 244 bytes ``` def s=9999,d={new Date()},y={it.year+1900},f={t,n->"$t $n: ${y(n)}? You mean we're in the future?"},p={t,n->"$t $n: Back in good old ${y(n)}."},t=d() while(!sleep(s)){n=d() c=n.time-t.time println c<0?p(t,n):c>s*2?f(t,n):'Great Scott!' t=n} ``` ]
[Question] [ Create a program which prints the amount of characters its source has in English words. If your program is nine letters long it should print "nine". Capitalization is ignored: in case you're printing "one" (somehow) you can print "one", "oNe", "ONE" or anything else. Base ten is required. Proper spacing is also required. In the (unlikely but just for specification) case your program reaches one billion characters or more, use the American number scale. A billion here is 10^9 and a million is 10^6. Do not use "one hundred and one": use "one hundred one". Do not use the hyphen. Print forty four, not forty-four. Test cases with a fake program: ``` 10.(96 0s later)..01 prints one HuNdreD ONE -- okay: proper spacing, no "and" 10.(96 0s later)..01 prints one HuNdreDONE -- not okay: wrong spacing 10.(96 0s later)..01 prints one thousand two hundred two -- not okay: base 3 rather than base 10 10...(999999996 0s later) prints nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-six: not okay, wrong number and includes hyphens ``` Golfy challenge, as always: shortest code wins. You're free to post after the green tick has been given, though. This serves more for completeness for hard to program languages. Malbolge, anyone? [Answer] # [Poetic](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html), 400 bytes ``` Type fourhundred chars? I say, I think I have an angle. I say "Gosh, could I just go create some poem? Clearly it comes a long way, writing stuff I say." I compose the entire written poem, and someone reads a tiny, tiny portion. "Surely, it all is garbage," cried a big fat crybaby. Would HE frankly notice how many long, tedious hours I took? The crybaby whined a lot. I watched, then I ignored him. ``` [Try it online!](https://mcaweb.matc.edu/winslojr/vicom128/final/tio/index.html?LZBNboUwDIT3nMJijbgCi6pqu@6TujbEJCkhRvkp4vSvE1opSmRnNN/Yj@sQWrUmV6NJYmhxnPJEH5T5GvAU5@OG1/GPEEccG2Ts7n/q3zS7gRatwUDzXXMhq7Qk4SKUdRc6VPaJXoJwChf5AvEumZiCRktng5zJF48il7quf@SxBwHKQ7MggpDE4pPc0iLxdh2QxdwQjUJAmmYLJ1i2G6JUvMax6z9rkoA28BwC@UyW08xWhh5hPcZmmr2llZEvXTPP19h93VO9v9KaOG4IH7X4RcjpSTvDv00AlBivNaNdU24LU92m7oHM/050YoU3ImgZoTi5LE7M0AaLqL2N2lbv/D4@nzObXw) Prints `Four HunDrED`. (I tried to make it print some number in the 300s, but I can't seem to do so in under 400 bytes.) Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols. [Answer] # [Google Translate](https://translate.google.com/) (3 bytes) ``` 一 ``` [Try it online!](https://translate.google.com/?text=%E4%B8%80) It's the Chinese character for "*one*" (matching the number of characters in the source code), though the score's due to the character itself being 3 bytes. --- # [Google Translate](https://translate.google.com/) (3 bytes) ``` tre ``` [Try it online!](https://translate.google.com/?text=tre) It's Italian for "*three*". [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 40 bytes ``` +[+++++>++<]>.+++++++++.+++.++.+++++.+++ ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1obBOy0tW1i7fS0YUAPgvXgnP//AQ "brainfuck – Try It Online") The last three characters don't actually do anything useful, but it's easier to output `forty` than `thirty seven`. The ascii code for `f` is 102, which is 2/5 of 255, found by the initial loop. After that, all the characters in the output just happen to be in ascending alphabetical order. [Answer] # [MathGolf](https://github.com/maxbergmark/mathgolf), 2 bytes Well, MathGolf has a string compression library that seems to compress "two" to 1 byte. You need a command to decompress this. ``` ╩_ ``` [Try it online!](https://tio.run/##y00syUjPz0n7///R1JXx//8DAA "MathGolf – Try It Online") [Answer] # [Python 3](https://docs.python.org/3/), 15 bytes ``` exit("fifteen") ``` ...prints to STDERR. **[Try it online!](https://tio.run/##K6gsycjPM/7/P7Uis0RDPS0zrSQ1NU9d8/9/AA "Python 3 – Try It Online")** (see the "debug" panel) [Answer] # [COW](https://bigzaphod.github.io/COW/), 800 bytes ``` MoO!! MoO MoO!! MoO MoO MoO!! MoO MoO MoO MoO!! MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MMM MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO Moo MoO MoO MoO MoO Moo MOo MOo!! Moo MoO Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO Moo MMM Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO!! MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO!! Moo MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MOo MOo!! MOo MOo MOo MOo MOo Moo MOo MOo MOo MOo MOo MOo MOo MOo MOo MOo Moo MMM!! MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO MoO Moo MMM MoO Moo MOo Moo! ``` [Try it online!](https://tio.run/##S84v///fN99fUZELSCqgsDB52EVwi@KXwSXr60u8ftJUkaYSp@p8Baxi/mAM1pGPRyVhe/KhYZBPff9QVzfchHwydaOEmj@ch8D5WMRwYUi4UeSjfKTUBzdV8f9/AA "COW – Try It Online") Prints `EIGHT HUNDRED` [Answer] # CSS, 30 bytes ``` body::after{content:'thirty';} ``` --- # CSS (Google Chrome only), 26 bytes This should be saved in an empty file between `<style>` and `</style>` tag, doesn't work on FireFox or Stack Exchange's code snippets. Tested on Windows Chrome 77. ``` :after{content:'twenty six ``` [Answer] # [PHP](https://php.net/), 4 bytes ``` four ``` [Try it online!](https://tio.run/##K8go@P8/Lb@06P9/AA "PHP – Try It Online") --- # [PHP](https://php.net/), 9 bytes ``` <?= nine; ``` [Try it online!](https://tio.run/##K8go@P/fxt5WIS8zL9X6/38A "PHP – Try It Online") [Answer] # Malbolge, 40 bytes ``` (CB%#9]~}5:3Wyw/4-Qrqq.'&Jkj(h~%|Bd.-==; ``` [Answer] # [Labyrinth](https://github.com/m-ender/labyrinth), 10 bytes ``` 84.69.78.@ ``` **[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fwkTPzFLP3ELP4f9/AA "Labyrinth – Try It Online")** ### How? ``` - initially the main stack contains infinite zeros [0,0,0,...] 8 - multiply the top of the stack by ten and add eight [8,0,0,...] 4 - multiply the top of the stack by ten and add four [84,0,0,...] . - pop, mod 256, print character T 6 - multiply the top of the stack by ten and add six [6,0,0,...] 9 - multiply the top of the stack by ten and add nine [69,0,0,...] . - pop, mod 256, print character E 7 - multiply the top of the stack by ten and add seven [7,0,0,...] 8 - multiply the top of the stack by ten and add eight [78,0,0,...] . - pop, mod 256, print character N @ - exit ``` [Answer] # [Piet](https://github.com/cincodenada/bertnase_npiet), 90 codels [![enter image description here](https://i.stack.imgur.com/7I3fq.png)](https://i.stack.imgur.com/7I3fq.png) [Try it online!](https://tio.run/##hZJNSwMxEIbv/or3KIoh3x8ehGyStb0sYgteFLyIFDwIFk/qX68z2922nhzCMsySJ@/MO@@bl@1uJ6e4RkxwErbBBsgKmaEyf6WcT4VNsBHWwmlA3A23Yorlot6f7UmKWMc76SQnVoTUx0pL8AHNEOtPvIqJpYnVThCujBIsrIKz0BHOwFXEhqhYYJF71uOy5vX56onziWWIZSRLKAZ9RN9DZ5iG0o11BeOhiZVRLZRnNCQDLm6EFP6KstXEssSiQezfVwqZNBZWwQ2OTVEld0z0VJdIHbA4X83tCf920OWIFUhFQXUIhhukm3TICt1B9ugVOoVgYQyS5xw/QnwshRguCbc1B5YnVvYIHtYgFIQeocIEKOo3IUV0Fbmgd0g0LM9QiM/yJb7DPPztxArso4YigxoqTY0uBESP0nj8pM4F@MR/6Zcf3Tz4mIeHjRDPs67ILAVVeAmSg5bcCyuS7ONxReTor2P6yAL1th4XrA0TK/HsLTKp0PxspFX8N6roSMxu9ws "Piet – Try It Online") ## In pseudo-code: The characters are pushed onto stack. To save space, their ASCII values minus 100 are stored. When the string is built, a loop pops, adds 100 to, and prints each character to STDOUT. ``` ; Place sentinel 0 on stack push 1 not ; Place 21 (y) on stack push 7 push 3 mul ; Place 16 (t) on stack push 4 dup mul ; Place 1, 10, 5, 10 (e, n, i, n) on stack push 1 push 10 push 5 push 10 ; Check if top of stack is non-zero ; Place a 1 if it is, a 0 otherwise dup not not write_loop: ; Turn DP (Direction Pointer) as many steps ; clock-wise as value on top of stack ; If we had a zero on stack, we continue into ; the yellow area and get trapped, ending execution pointer ; If not, we continue ; Add 100 to top of stack push 5 push 4 push 5 mul mul add ; Pop and print character outc ; Turn DP one step to the right push 1 pointer dup not not ; Check if top of stack is non-zero ; Place a 1 if it is, a 0 otherwise dup not not ; We're now back at beginning of the writing loop, sort of like a jmp write_loop ``` [Answer] # [Emoji](https://esolangs.org/wiki/Emoji), 18 bytes ``` ⛽eighteen🚘➡ ``` [Try it online!](https://tio.run/##S83Nz8r8///R7L2pmekZJampeR/mz5rxaN7C//8B "Emoji – Try It Online") --- # [Emoji](https://esolangs.org/wiki/Emoji), 8 chars ``` ⛽eight🚘➡ ``` [Try it online!](https://tio.run/##S83Nz8r8///R7L2pmekZJR/mz5rxaN7C//8B "Emoji – Try It Online") [Answer] # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 40 bytes (3×14=42 codels) ``` ttllldabknmEmqusbeeeeeute_rbacqtuljvff ? ``` [Try Piet online!](https://piet.bubbler.one/#eJxNTEEKwzAM-4vOCsRt0zX5SulhdBkUuq2Q7TT69yk5zRZCtmR_sb5uGWmePT3H1tbRxAMjLzSjiaOwcNY0MLCvbl3_Iei-qkmxrvn6ERT3skZO1KO-IdbQQpR8IME5B2LfHtLmVZpyWZHu171kYnsen7c8nD-a3ycB) ![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/27967a267a6089516184efccc12f182afdd73a58/images/CodeGolfSE/194480-2.svg) Prints `FORTY`. A fantastic use case of a white trap :) Also I like the fact that the program is packed so perfectly. ### How it works A classic 3-row layout with a `1 DP+` at the left edge. ``` Commands Stack 2 3 dup dup * [2 3 9] dup dup 1 - * [2 3 9 72] 2 - [2 3 9 70] Setup the stack so that repeatedly adding and printing gives FORT dup outC + dup outC + dup 1 DP+ outC + dup outC [84] Print FORT, turning right at R2C1 > [84] No-op (stack underflow) to take care of the crossing 5 + outC [] Finally print Y ``` --- # [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 50 bytes (4×13=52 codels) ``` ttttliametf M tt iillldedMnjlvjcfll i Mkmuuljcbjjj ``` [Try Piet online!](https://piet.bubbler.one/#eJwtjNEOgjAUQ__lPnfJrsqQ_crCg8GZkKCSoE-Gf7cF1qVdt3P3s-F9r5ZLidiV4BFOd3jL7md4x9ajMEWoRu20yU8C5WJaXHVH90azG7EPHL8o0FDpgC5MSUDX97ClzpYthGCwaXzy7JGLrS6D5cdtWipsfM3fD99s_QNFMSv_) ![](https://github.com/Bubbler-4/svg-stuff-and-tools/raw/cec86b3ba829e541ef0525c4bed6dace09626a04/images/CodeGolfSE/194480.svg) Prints `fifty`. Not sure if I can do 40, but I guess pretty much unlikely. ### How it works The execution path: First row -> (turn right) -> 3rd-to-last column -> (turn right) -> last row in reverse -> (turn right twice) -> 3rd row -> transfer to 2nd row at the red 5 block -> end. ``` ...>>>>>>>v X .. ....>>+>X >>>>>>>.. v X ^<<<<<<<<.. ``` Commands: ``` Commands Stack 6 dup 3 * 1 - * [102] Push 102 ('f') dup outC [102] Print 'f' dup 3 + outC [102] Print 'i' (= 'f' + 3) dup outC [102] Print 'f' 2 dup dup + [102 2 4] dup * - - [116] Add 14 to 'f' (= 't') dup outC [116] Print 't' 5 inC + outC [] Add 5 and print 'y' (inC is ignored; it is to reuse the crossing purple cell) ``` [Answer] # [Hexagony](https://github.com/m-ender/hexagony), 6 bytes, 17 cycles ``` s;i>x@ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/7/YOtOuwuH/fwA "Hexagony – Try It Online") Now the letters `six` are in more natural order, and the program finishes one cycle faster. ### How it works For more thorough explanation, see the previous answer below. ``` A B C > D E . Execution path: ABC>CBAD>ADB.>.CE ^^ ^^ ^^ ^ s; i; x; @ ``` --- # [Hexagony](https://github.com/m-ender/hexagony), 6 bytes, 18 cycles ``` x>i;s@ ``` [Try it online!](https://tio.run/##y0itSEzPz6v8/7/CLtO62OH/fwA "Hexagony – Try It Online") Inspired by [boboquack's 9-byte solution](https://codegolf.stackexchange.com/a/194788/78410). The following quote was a big hint: > > I'm slightly disappointed that I couldn't get `six` to work (that would be pushing it with *three characters, one output, one redirection and one termination*). > > > ### How it works (or, How I got to this solution) A 6-byte program is laid out on a hexagon of side length 2, and the 7th instruction is necessarily a no-op: ``` ? ? ? ? ? ? . ``` Since I needed at least one mirror, I tried out various mirrors placed at various places, until I found this: ``` A > B C D E . ``` Assuming the current memory is always positive (and there are no branches/mirrors/IP changers among `ABCDE`), the IP follows the path ``` A>ADCB>.CAD>DAC.BE ``` The cell `C` is run exactly three times, and the cells right before `C` are `D`, `B`, and `A` respectively. And the cell `E` is first run after three runs of `C`. This is exactly what we want: write one of `s`, `i`, or `x` on the memory and print it, and then terminate! Now back to the actual source code: ``` x > i ; s @ . ``` And the execution path, linearized, with significant instructions emphasized: ``` x>xs;i>.;xs>sx;.i@ ^^^ ^ ^^ ^ ^^ Print 's' ^ ^ Print 'i' ^^ Print 'x' ^ Terminate ``` [Answer] # [SOGL V0.12](https://github.com/dzaima/SOGLOnline), 3 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md) Well, SOGL has a string compression library that seems to compress "three" to 3 bytes. ``` @0‘ ``` [Try it Here!](https://dzaima.github.io/SOGLOnline/?code=QDAldTIwMTg_,v=0.12) [Answer] # Brainf\*\*\*, 90 bytes ``` +[+[>>+<+<-]>]>[>+>+>+>+>+>+<<<<<<-]>.>-----.>.>---------.>++++++.>+++++++++++.<+><><><><> ``` [Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1o72s5O20bbRjfWLtYu2k4bAW3AACiuZ6cLAnowBoSjDQYwGsKx0bazgcL//wE "brainfuck – Try It Online") [Answer] # [Lost](https://github.com/Wheatwizard/Lost), 30 bytes ``` v<<<<<<<>>>>>>> >%?"thirt/J"+@ ``` ~~Contains the unprintable character ESC with unicode value 27 after the `^` on the second line.~~ Thanks to *@JoKing* getting rid of the unprintable (for the same byte-count). [Try it online](https://tio.run/##y8kvLvn/v8wGAuwggMtO1V6pJCOzqETfS0nb4f///7qOAA) or [verify that it's deterministic](https://tio.run/##y8kvLvn/v8wGAuwggMtO1V6pJCOzqETfS0nb4f///7qO/3XDAA). ### Explanation: **Explanation of the language in general:** Lost is a 2D path-walking language. Most 2D path-walking languages start at the top-left position and travel towards the right by default. Lost is unique however, in that ***both the start position AND starting direction it travels in is completely random***. So making the program deterministic, meaning it will have the same output regardless of where it starts or travels, can be quite tricky. A Lost program of 2 rows and 5 characters per row can have 40 possible program flows. It can start on any one of the 10 characters in the program, and it can start traveling up/north, down/south, left/west, or right/east. In Lost you therefore want to lead everything to a starting position, so it'll follow the designed path you want it to. In addition, you'll usually have to clean the stack when it starts somewhere in the middle. **Explanation of the program:** All arrows, including the reflect `/` in the string, will lead the path towards the leading `>` on the second line. From there the program flow is as follows: * `>`: travel in an east/right direction * `%`: Put the safety 'off'. In a Lost program, an `@` will terminate the program, but only when the safety is 'off'. When the program starts, the safety is always 'on' by default, otherwise a program flow starting at the exit character `@` would immediately terminate without doing anything. The `%` will turn this safety 'off', so when we now encounter an `@` the program will terminate (if the safety is still 'on', the `@` will be a no-op instead). * `?`: Clean the top value on the stack. In some program flows it's highly likely we have a partial string on the stack, so we use this to wipe the stack clean of that potential string. * `"`: Start a string, which means it will push the integer code-points of the characters used. * `thirt/J`: Push the code-points for these characters, being `116 104 105 114 116 47 74` respectively * `"`: We're done pushing code-points of this string * `+`: Add the top two values together: (47+74=) `121` * `@`: Terminate the program if the safety is 'off' (which it is at this point). After which all the values on the stack will be output implicitly. Using the `-A` program argument flag, these code-points will be output as characters instead. *Two things to note:* The top part could also have been `v<<<<<<<<<<<<<<` instead. Lost will wrap around to the other side when moving in a direction. So using `v<<<<<<<>>>>>>>` could be a slightly shorter path, and since it's the same byte-count anyway, why not use it. :) Also, the first line contains an additional trailing `>` to make the byte-count from 29 to 30. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` “Ɱ9» ``` **[Try it online!](https://tio.run/##y0rNyan8//9Rw5xHG9dZHtr9/z8A "Jelly – Try It Online")** [Answer] ## JavaScript, ~~16~~ 10 bytes -6 each from Night2's suggestion in the comments [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/v6AoM68koSQ1L@H/fwA) (`alert` doesn't work in TIO, so I'm using `print`) ``` alert`ten` ``` --- ## Javascript, ~~26~~ 20 bytes [Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Pzk/rzg/J1UvJz89oaQ8Na@kMuH/fwA) ``` console.log`twenty`; ``` [Answer] # [Keg](https://github.com/JonoCode9374/Keg), 3 bytes -1 from Jono2906 for reminding me the string compression 2 can play the 3 byte game! ``` ‘0⅀ ``` [TIO](https://tio.run/##y05N////UcMMg0etDf//AwA) ## Old answer, 4 bytes You can't get shorter than 4. (Without using string compression of course.) 4 is the smallest English word that is the same length as the number it represents. Just some good old-fashioned Ascii/auto-pushing Keg golfing! ``` four ``` [Try it online!](https://tio.run/##y05N//8/Lb@06P9/AA "Keg – Try It Online") ## Explanation ``` four# Push 4 onto the stack #Implicit Print ``` [Answer] # Shakespeare Programming Language, 800 bytes [Try it online!](https://tio.run/##jVFLDoIwEL3KHEAblsadJi7cGVgZ46LUESvlEyhRTo9TCUIBgSbTTOfz@t5Mnqqq2jgO7EuN@ZoO3KVSmLHdk79X7FSIcMV2QsNxyzyBMRrncog1ZmBKgMc3MFVX89qekwJkDvqBkBcRJHfbE4WP5HLwZfA1wTX0X3QzL0UeEkzJBoglBayWZcWpDOYLF6DplxTY3L8Mn@TfkO3a@Fc92KFWFyOMfBo@paao1khfwu3c@3xpJgS/YDL9xsZqAFuKi4IrNbc386mlZamwzg7@kKq3YKuaJjUqoA1U1Qc) (Whitespace added for readability) ``` 800 Bytes---- filler.Ajax,.Puck,.Act I:. Scene I:.[Enter Ajax and Puck]Ajax: You is the sum ofthe sum ofthe cube ofa big big cat a big big cat a cat.Speak thy. You is the sum ofyou a big big cat.Speak thy. You is the sum ofyou a big pig.Speak thy. You is the sum ofyou a cat.Speak thy. You is the sum ofyou twice twice the sum ofa big cat a cat.Speak thy. You big big big big big cat.Speak thy. You is twice the sum ofyou a big big cat.Remember you.Speak thy. You is the sum oftwice you the cube ofthe sum ofa big pig a pig.Speak thy. You is the sum ofyou the sum ofa big big big pig a cat.Speak thy. Recall.You is the sum ofyou a big big pig.Remember you.Remember you.Speak thy. You is the sum ofyou twice the sum ofa big big big cat a pig.Speak thy. Recall.You is the sum ofyou a cat.Speak thy. Recall.Speak thy. ``` Prints EIGHT HunDRED. The math to get from one letter to another was very complicated and there was little room for error. This is probably improvable in terms of code, but 700 is most likely impossible. Little improvement saving 2 bytes in the actual code because I missed out on optimizing 2\*(4+2) to 2\*2\*(2+1) for some reason. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 64 bytes ``` class P{static void Main(){System.Console.Write("sixty four");}} ``` I had to see what a non-competitive language would score. [Try it online!](https://tio.run/##Sy7WTc4vSv3/PzknsbhYIaC6uCSxJDNZoSw/M0XBNzEzT0OzOriyuCQ1V885P684PydVL7wosyRVQ6k4s6KkUiEtv7RISdO6tvb/fwA "C# (.NET Core) – Try It Online") [Answer] # Excel, 4 bytes ``` four ``` Uninteresting answer, not using a formula. --- ### Excel, 5 bytes ``` 'five ``` Using a formula, requires at least 3 extra bytes (`=`, `"`, `"`). ### Excel, 6 bytes ``` ="six" ``` ### Excel, 12 bytes ``` ="tw"&"elve" =T("twelve") ``` ### Excel, 14 bytes ``` =T("fourteen") ``` ### Excel, 16 bytes ``` =IF(1,"sixteen") ``` ### Excel, 18 bytes and upwards ``` =TRIM(" % ") ``` Insert required text, padded with required whitespace. [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), ~~164~~ 160 bytes ``` "One hundred sixty" is waiting at Writer's Depot. Go to Writer's Depot: w 1 r 3 l 2 l. Pickup a passenger going to Post Office. Go to Post Office:n 1 r 2 r 1 l. ``` [Try it online!](https://tio.run/##XcyxCsIwFIXhvU9x6OJWaN06C47t5hzam3ix5Ibkhtanj1EQxOEsP5xPzcGltJMn3LNfI61IfOgTVnJswQm7YWXvYBS3yErxlHChINo1V4HKXx139Ig4Y8OArWtmXh45wCCYlMg7inDy9upzlqSYrOWFvthPGv1HGur6KpXyAg "Taxi – Try It Online") This also throws an error because I don't return the taxi to the garage so my boss fires me. It's not a requirement to not throw errors, though, so I guess I'm fired. [Answer] # [vemf](https://selaere.github.io/vemf/doc/docs.html), ~~6~~ 5 bytes ``` "five ``` Outputs `five`. [try it online](https://selaere.github.io/vemf/wasm/index.html?code=ImZpdmU&fmt=0) [Answer] # [Python 3](https://docs.python.org/3/), 16 bytes ``` print("sixteen") ``` [Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ6k4s6IkNTVPSfP/fwA "Python 3 – Try It Online") Also works in [Proton](https://tio.run/##KyjKL8nP@/@/oCgzr0RDqTizoiQ1NU9J8/9/AA). [Answer] # [ink](https://github.com/inkle/ink), 4 bytes ``` Four ``` [Try it online!](https://tio.run/##y8zL/v/fLb@06P9/AA "ink – Try It Online") Predictably enough, it prints `Four` [Answer] ## Batch, 10 bytes ``` @ echo ten ``` If you think the extra space after the `@` is ugly, the next possible answer is: ``` @echo twelve ``` [Answer] # [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 3 bytes ``` “„í ``` [Try it online!](https://tio.run/##MzBNTDJM/f//UcOcRw3zDq/9/x8A "05AB1E (legacy) – Try It Online") Using dictionary [Answer] # [Bash](https://www.gnu.org/software/bash/), ~~15~~ 9 bytes ``` echo nine ``` [Try it online!](https://tio.run/##S0oszvj/PzU5I18hLzMv9f9/AA "Bash – Try It Online") Thanks to: - @Night2 for saving me 6 bytes ]
[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. Given an integer array, write a program that determines if it is sorted in ascending order. Remember that this is a code trolling question. I am looking for most interesting ways that people come up with. The answer with most upvotes wins. This question is inspired by a 'creative' solution that a candidate gave me in an interview :) --- The 'creative' solution was something like this: > > * Because for a sorted array > > > + all the elements on the left side of any element must be smaller > + all the elements on the right side of any element must be bigger > > > Therefore, run a main loop for all elements and check the above two conditions by running two nested loops inside the main one (one for left side and one for right side) > > > I was shocked!!. [Answer] ## Ruby Everyone knows: sorting is very slow and takes many cycles (the best you can do is something with `n log(n)`). Thus it is quite easy to check if the array is sorted. All you have to do is compare the runtime of sorting the array and sorting the sorted array. ``` array = [1, 5, 4, 2, 3] ## measure the time needed to sort the array 1m times tstart = Time.now 1000000.times { array.sort } trun = Time.now - tstart ## now do a reference measurement on a sorted array array.sort! tstart = Time.now 1000000.times { array.sort } treference = Time.now - tstart ## compare run times if trun > treference print "array was not sorted" else print "array was sorted" end ``` [Answer] # Javascript ``` array = prompt("Give the array"); while (true) { sorted = prompt("Is it sorted?"); if (/yes|Yes/.test(sorted)) { alert("The array is sorted."); break; } else if (/no|No/.test(sorted)) { alert("The array is not sorted."); break; } else { alert("Dear user:\n\nPlease refer to the manual (RTFM) to observe how to use the system accordingly to the defined business rules.\nNow, try again."); } } ``` [Answer] ## Java - Recursive Subsets Welcome to Stack Overflow! This is an excellent first question, as it stumps even some veteran coders. Let me give you a bit of background information before I just hand out the code: Determining sortedness can be a difficult task at first glance. For any set of length n, there are n! possible ways of ordering it. These are called [permutations](http://en.wikipedia.org/wiki/Permutation). If your array has distinct elements, *only one of those possibilities is sorted!* To find the sorted one, you have to sift through them all until you find the right (possibly only) one, discarding all the others. ### What? Surely it isn't *that* hard... Algorithms with n! complexity take a long time for larger inputs, but with a bit of work we can get around that, and move down a whole order of complexity. That's still exponential time, but it's [much better](http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions) than factorial. To do this, we only need consider the following mathematical fact: If an array is sorted, then every one of its (relatively ordered) [subsets](http://en.wikipedia.org/wiki/Subset) is sorted as well. You can ask the experts over at [Mathematics](https://math.stackexchange.com/) for a formal proof, but it's intuitively true. For instance, for the set `123`, the proper subsets are `1 2 3 12 13 23`. You can see they are all ordered. Now if the original was `213`, you'd have `2 1 3 21 23 13`, and right away you can see that `21` is out of order. The reason this is important is because there are far fewer than n! subsets. In fact, there are only 2n-2 subsets we need to look at. We can exclude the set containing the entire array of original numbers, as well as the empty set. Still, 2n-2 can be a lot of work. As with most things that exceed polynomial time, a [divide-and-conquer](http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm) approach works well here. The simplest approach? [Recursion](http://en.wikipedia.org/wiki/Recursion_%28computer_science%29)! The basics steps are simple. For every subset of your input, you generate *smaller* subsets. Then for each of those, you do the same thing. Once your subsets are down to size 2, you simply check which one is bigger. Since you shrink the size of the subsets each time, it actually goes quicker than you'd expect. The key fact here is that you can *exit early*, as soon as you find a *single* subset out of order. You don't *have* to search through them all. If one is bad, the whole group is bad. This is a speed consideration you don't see in a lot of these other answers. ### Enough talk, let's have the code! I've done this in [Java](http://en.wikipedia.org/wiki/Java_%28programming_language%29) since it's a popular language and easy to read. The elegance of the recursion should be apparent: ``` import java.util.ArrayList; public class SortChecker { static final Integer[] input = {1, 2, 3, 4, 5}; public static void main(String[] args) { if(isSorted(input)) System.out.println("The array is sorted properly."); else System.out.println("The array was not sorted properly."); } public static boolean isSorted(Integer[] in){ if(in.length == 1) return true; if(in.length == 2) return (in[0] <= in[1]); ArrayList<Integer[]> subsets = getSubsets(in); for(Integer[] next : subsets){ if(!isSorted(next)) return false; } return true; } public static ArrayList<Integer[]> getSubsets(Integer[] in){ ArrayList<Integer[]> subsets = new ArrayList<Integer[]>(); int bitmasks = (1 << in.length) - 1; for (int i = 1; i < bitmasks; i++){ ArrayList<Integer> subset = new ArrayList<Integer>(); for (int j = 0; j < in.length; j++) if ((i & (1 << j)) > 0) subset.add(in[j]); subsets.add(subset.toArray(new Integer[1])); } return subsets; } } ``` > > For the record, I got bored and killed it after waiting 15 minutes for a sorted 12-element array. It'll do 11 elements in about 45 seconds. Of course, it really *does* exit earlier for non-sorted, so that's, um, good. Update: On a fresh reboot, it does 12 elements in 13 minutes. 13 takes almost 3 hours, and 14 is at 20 hours and counting. [Answer] # C++ - a brute force method Everybody knows that brute force methods are always the fastest. ``` bool issorted(std::vector<int>& list) { switch (list.size()) { case 0: case 1: return true; case 2: return list[0]<=list[1]; case 3: return list[0]<=list[1] && list[1]<=list[2]; case 4: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3]; case 5: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4]; case 6: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5]; case 7: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6]; case 8: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7]; case 9: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8]; case 10: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9]; case 11: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10]; case 12: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11]; case 13: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12]; case 14: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13]; case 15: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14]; case 16: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15]; case 17: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16]; case 18: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17]; case 19: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18]; case 20: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19]; case 21: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20]; case 22: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21]; case 23: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22]; case 24: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23]; case 25: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24]; case 26: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25]; case 27: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26]; case 28: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27]; case 29: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28]; case 30: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29]; case 31: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30]; case 32: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31]; case 33: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32]; case 34: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33]; case 35: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34]; case 36: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35]; case 37: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36]; case 38: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37]; case 39: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38]; case 40: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39]; case 41: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40]; case 42: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41]; case 43: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42]; case 44: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43]; case 45: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44]; case 46: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45]; case 47: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46]; case 48: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47]; case 49: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48]; case 50: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49]; case 51: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49] && list[49]<=list[50]; case 52: return list[0]<=list[1] && list[1]<=list[2] && list[2]<=list[3] && list[3]<=list[4] && list[4]<=list[5] && list[5]<=list[6] && list[6]<=list[7] && list[7]<=list[8] && list[8]<=list[9] && list[9]<=list[10] && list[10]<=list[11] && list[11]<=list[12] && list[12]<=list[13] && list[13]<=list[14] && list[14]<=list[15] && list[15]<=list[16] && list[16]<=list[17] && list[17]<=list[18] && list[18]<=list[19] && list[19]<=list[20] && list[20]<=list[21] && list[21]<=list[22] && list[22]<=list[23] && list[23]<=list[24] && list[24]<=list[25] && list[25]<=list[26] && list[26]<=list[27] && list[27]<=list[28] && list[28]<=list[29] && list[29]<=list[30] && list[30]<=list[31] && list[31]<=list[32] && list[32]<=list[33] && list[33]<=list[34] && list[34]<=list[35] && list[35]<=list[36] && list[36]<=list[37] && list[37]<=list[38] && list[38]<=list[39] && list[39]<=list[40] && list[40]<=list[41] && list[41]<=list[42] && list[42]<=list[43] && list[43]<=list[44] && list[44]<=list[45] && list[45]<=list[46] && list[46]<=list[47] && list[47]<=list[48] && list[48]<=list[49] && list[49]<=list[50] && list[50]<=list[51]; } } ``` The actual routine is longer (it goes to std::npos), but I'm limited to 30000 characters in posting here. [Answer] ## Inform Inform is a language for writing interactive fiction games for the classic Infocom Z-machine interpreter. To avoid spoilers, I'm giving the results of my program first, then the source code. *Edit: I made a small revision to allow adding numbers to the array, and included a charming room description.* ``` Sorted An Interactive Fiction by Jonathan Van Matre Release 1 / Serial number 140301 / Inform 7 build 6G60 (I6/v6.32 lib 6/12N) SD Sorting Room You are in the Sorting Room, a sterile expanse of pure white. Translucent lucite walls leak a lambent clinical light into the spotless room. You can see a safe (closed), a flask of poison, a radioactive isotope attached to a radiation detector that triggers a hammer, an array (empty) and Erwin Schrodinger here. >open safe You open the safe. >put flask in safe (first taking the flask of poison) You put the flask of poison into the safe. >put isotope in safe (first taking the radioactive isotope attached to a radiation detector that triggers a hammer) You put the isotope detector assembly into the safe, carefully placing the hammer next to the fragile glass of the flask of poison. >get array Taken. >put numeral 1 in array (first taking the numeral 1) You put the numeral 1 into the array. >put 2 in array (first taking the numeral 2) You put the numeral 2 into the array. >put 3 in array (first taking the numeral 3) You put the numeral 3 into the array. >examine array In the array are a numeral 3, a numeral 2 and a numeral 1. >put array in safe You put the array into the safe. >ask Erwin about whether the array is sorted Erwin grumbles and complains, "You haven't finished the experiment" >close safe You close the safe. >ask Erwin about whether the array is sorted Erwin beams and proudly announces, "Indeterminate!" ``` And herewith the source code: ``` "Sorted" by Jonathan Van Matre The Sorting Room is a room. "You are in the Sorting Room, a sterile expanse of pure white. Translucent lucite walls leak a lambent clinical light into the spotless room." The safe is a container. The safe is in the Sorting Room. The safe is openable. The safe is closed. There is a flask of poison in the Sorting Room. There is a radioactive isotope attached to a radiation detector that triggers a hammer in the Sorting Room. There is an array in the Sorting Room. The array is a container. There is a numeral 1 in the Sorting Room. The numeral 1 is undescribed. There is a numeral 2 in the Sorting Room. The numeral 2 is undescribed. There is a numeral 3 in the Sorting Room. The numeral 3 is undescribed. There is a numeral 4 in the Sorting Room. The numeral 4 is undescribed. There is a numeral 5 in the Sorting Room. The numeral 5 is undescribed. There is a numeral 6 in the Sorting Room. The numeral 6 is undescribed. There is a numeral 7 in the Sorting Room. The numeral 7 is undescribed. There is a numeral 8 in the Sorting Room. The numeral 8 is undescribed. There is a numeral 9 in the Sorting Room. The numeral 9 is undescribed. In the Sorting Room is a man called Erwin Schrodinger. Understand the command "ask" as something new. Understand "ask [someone] about [text]" as asking it about. After inserting the isotope into the safe: If the safe encloses the flask, say "You put the isotope detector assembly into the safe, carefully placing the hammer next to the fragile glass of the flask of poison."; Instead of asking Erwin about something: If the safe is closed and the safe encloses the flask and the safe encloses the array and the safe encloses the isotope, say "Erwin beams and proudly announces, 'Indeterminate!' "; Otherwise say "Erwin grumbles and complains, 'You haven't finished the experiment' "; ``` [Answer] # Doge Ruby First you must run this setup code ``` class Array;alias ruby sort;end def self.method_missing x,*a;x;end def very x;$a=x;end def many x;$b=$a.send x;end def wow;puts $a==$b;end ``` Then just store the array in a variable called `coding` and run: ``` very coding many ruby so algorithm wow ``` And your answer will be printed (true or false). Please also add the doge code for optimal performance: ``` #~! SET DOGE=1 PERFORMANCE=OPTIMAL ONERROR=nil PIC= # ***=* # **===* # ***=-=& &&**& # **==--= ***===* # &***=---* $*=------*& # &***=---=* $**=----;;=& # &**==----=& &*===---;;;-* # &**==----=* &**=-==--;;;;= # ****=-----=* &&*==--=---;;;;- # **===------=& $&*==-------;;;;- # **===-------=*&$$ &*==------;;;;;;;- # **==----==-====***&&&&&&&&$$ &*==-;;---;;;;;;;;-& # &*=---=====================*******=---;---;;;;;;;-;;= # *=======*=========================---;;--;;;;;;;;;;;* # *===***=======================------;;--;;""""";;;;;= # *=*****========================;--;;;;--;;""""";;;;;* # &*********====-----===============;;;;;----;"","";-;;-& # ***********====----================-;;;;----;",,";;---- # &************===---====================-;;;;;;",,"";----= # &*************===---=====================-;;;;",,,";-----* # ******=*******===--=======================--;",,,"";-----& # &**************==--=========================-;"","";----;- # ****************==---====****=====-===========--;";;-;;;";= # ****************==----==*******===--=============--;----;--= # &*****=;"";==***===----==*******===----=============------;-=$ # &&&***;"",,"-**====---==********=====-===============----;;;-& # &&&&&*=-;;";";*==========****=***======--=========***==---;;;-& # $&&&&&&=="",,,-===**=======***==-;-=================**===--;;;;* # &&&&&&&-="",,"==***==***======-",,,";=-===================--";;= # &&&&&**=-""";==****=***===---;"-=-,,,"--===================-;;;=& # &&&&&&***--;=***********=---;,,-*",,,,,"--==================--;--* # &&&&&***=*=*************=-;;","=-,,,,,,"-====================----=$ # &&&&&&*******************==--","-;,,,,,"-====*****=============-===& # $&&&&&&******************===---",";"""";=******************=====-===* # &&&&&&&&&*****************======--;;--==********************=========& # &&&&&&&&&&&******=**********===========*==*****&&************=========* # &&&&&&&&*=---;--==**********==============*********************=======*& # &&&&&&&-""""";;"";=**********==**=========*****&&&**************=======* # &&&&&&&*,,,,,,,,,,,"-****&************=*******&&&&&&&************========& # &&**&&&=,,,,,,,,,,,,;*&&&&***********************&&&&&&***********=======* # &&&*&&&*",,,,,,,,,,,;*&&&*************&&**********&**************========*& #&&&&&&&&-"",,,,,,,,,,-*&&&**********&**&&&&&&&******************==========** #&&&&&&&*=,,,,,,,,,,,"-***************&&&&&&&&&*****************====--======*& #&&***&&*=;,,,,,,,,,";=*==*****************&&&***************=======--=======& #*&&&&**=-;",,,,,,"";-=*********=**&*********&&**************=======--======** #&&&&&**=-""",,,,,"";==**==***===**********************======***===---=======*& #&&&&&**=-;"""""","";;=-===*======*********************==******====----======*& #*&&&&**=-;""""""""";=-============*****************==*********====---==--===** #&&&&&***=",,,,,,"""";--=============*******==****************====----=--====**& #&&&&&****"",,,,,,,,,;-=========--===****====******************====--==-======*& #&&&&&&&&*-"",,,,,,,,,"--==--;"""";====**===********************======--======** #&&&&&&***=-;",,,,,,,,,,,;",,,""";-=======********************===-------=======* #&&&&&&&****=;""""""""",,,"""";;--==**====*******************=====--------=====* # &&&&&&&***=-;;;;;;;;;"";;;;;---==***====*****************=====--=--------====*$ # &&&&&&*****=-;-----=--------=====*=======****************====-==---------=====& # &&&&&******==-==-=============***========*************======----=--------====& # &&&&************==========================***********=====----------------===* # $&&&&***************====================***********=*======-------------=--==* # &&*&************=====================**************======--------------=====* # &******************=================**************=========-----------======* # &***********=*****================************==========------;-------=====* # &*****************================***********=============---------========* # &*************===================**********==***========--------========*** # **************==================********====**===*=====--------=======**** # &************=============================*****=*=====--------=======***** # &****=*******=============================**============--=======*=****** # $*****=====**===========================***===================**********& # &*****=====================-====-====*=*=====*=======--==*************** # &*****===========---==--===============**=**=*========***************** # &*****====---=---------========********======***===******************* # *****=======-=-------======*******=**==****==*==********************* # $***======================******===********************************** # &***===================*******==***=******************************=& # &***=========-=========*************==***************************=& # ******===*=======*=*****************==*************************==& #~! END ``` This is the easiest way. --- (the ASCII art was generated by a script I wrote up, derived from [this image](http://ih2.redbubble.net/image.14690032.8531/fc,550x550,white.u5.jpg).) [Answer] # PHP You'd love the easiness and straightforwardness of the following solution. The overall concept and the cutting edge functions used in this masterpiece of coding will immediately bring you up to the elite list of the top developers of the World. ``` function is_sorted($input) { mysql_connect('localhost', 'name', 'password'); mysql_select_db('database'); mysql_query(' CREATE TEMPORARY TABLE sorting_table ( `value` int NOT NULL )'); foreach ($input as $value) { mysql_query('INSERT INTO sorting_table VALUES (' . $value . ')'); } $i = 0; $result = 'SORTED'; $query = mysql_query('SELECT * FROM sorting_table ORDER BY value ASC'); while ($value = reset(mysql_fetch_row($query))) { if ($input[$i++] != $value) { $result = 'NOT SORTED'; break; } } mysql_query('DROP TABLE sorting_table'); return $result; } print is_sorted(array(10, 20, 30, 40, 50)); ``` [Answer] ## C# - The power of statistics What you really need to do to solve this is to re-frame the question in a way that makes the solution obvious. Because this is basically a "true-false" type question, what you are essentially asking is "how can I be 100% certain that the array is sorted?" If one word pops out of that question, it is the word "certain". What is the best way to measure certainty? You got it: statistics. Other answers here only check to see if the array is sorted in *one direction*. This solution tests both ascending and descending order at the same time. The trick is to take an array of the same size that you already know is sorted (easy to make one yourself) and then find out how well the ordering of each array correlates with the other one. Calculating the Kendall tau rank correlation coefficient is the easiest way to do this: ``` using System; namespace Homework { class Example { static void Main(string[] args) { int[] n1 = { 23, 50, 16, 57, 19, 60, 40, 7, 30, 54 }; int[] n2 = { 7, 16, 19, 23, 30, 40, 50, 54, 57, 60 }; int[] n3 = { 60, 57, 54, 50, 40, 30, 23, 19, 16, 7 }; Console.WriteLine(isSorted(n1)); Console.WriteLine(isSorted(n2)); Console.WriteLine(isSorted(n3)); } static string isSorted(int[] a) { double t = 0; int n = a.Length; //Build a 'known' sorted array. int[] k = new int[n]; for (int i = 1; i < n; i++) { k[i] = i; } //Find the Kendall's tau coefficient. //First the numerator... for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { t += Math.Sign(a[i] - a[j]) * Math.Sign(k[i] - k[j]); } } //...then the denominator. int d = n * (n-1) / 2; //This gives the correlation coefficient. double sortedness = t / d; //1 is perfect correlation (ascending), -1 is perfectly non-correlated (descending). if (Math.Abs(sortedness) == 1) { return "Sorted"; } else { return "Unsorted"; } } } } ``` Output: ``` Unsorted Sorted Sorted ``` This function is also very easy to extend the functionality of, as it would be trivial to add functionality like "Mostly sorted" or "More sorted than not" or "Completely random". **Edit** Almost forgot to go over the efficiency of the algorithm. This is currently O(7). There is one in the method name, one in each of the "for" keywords, one in the "double" declaration, and two in the uses of the variable "sortedness". You can improve this all the way down to O(0) (which is as low as you can go) by renaming the function, changing the double to a decimal, disemvoweling "sortedness" to "srtdnss", and converting the for loops to while loops. [Answer] # Ruby Following strategy will eventually reveal if an array is sorted: 1. *A* be an array (either sorted or unsorted, e.g. [1,2,3] or [1,3,2]) 2. *P* be an array holding all permutations of *A* 3. If *A* is sorted, it is either the maximum or minimum of *P* (which basically are the sorted versions of *A* in Ruby) [Online version](http://repl.it/PTj) for testing. ``` class Array def is_sorted? permutations = permutation.to_a self == permutations.max || self == permutations.min end end ``` [Answer] # C# - non-deterministic solution This code probably works. ``` static bool isSorted(int[] s) { var rnd = new Random(); for (var i = 0; i < s.Length * s.Length * s.Length; i++) { var i1 = rnd.Next(0, s.Length); var i2 = rnd.Next(0, s.Length); if (i1 < i2 && s[i1] > s[i2] || i1 > i2 && s[i1] < s[i2]) return false; // definitely not sorted } return true; // probably sorted } ``` [Answer] **Python** If the list is sorted, every number is either less than or equal to the next number. Therefore removing the left-most number will bring the average value up, otherwise the list isn't sorted. We will put this in a loop to check each number ``` def is_sorted(lst): def _avg(lst): return sum(lst)/(1.0*len(lst)) for i in range(len(lst)-1): if _avg(lst[i:]) > _avg(lst[i+1:]): return False return True ``` is\_sorted([1,2,3]) #True is\_sorted([3,2,1]) #False is\_sorted([1,4,3,2,0,3,4,5]) #False --- The observant reader will notice that it doesn't exactly work like that. is\_sorted([1,4,3,2,0,3,4,11]) #False is\_sorted([1,4,3,2,0,3,4,12]) #True is\_sorted([1,2,1,2,1,2,1,2,99]) #True [Answer] **Bash** ``` mkdir -p nums mynums=(1 2 3 4) for i in "${mynums[@]}" do touch "nums/$i" done result=`ls -v nums` resultarray=(${result}) for i in "${!resultarray[@]}" do if [ ${resultarray[$i]} != ${mynums[$i]} ]; then echo "not sorted!" rm -rf nums/* exit 1 fi done echo "sorted!" rm -rf nums/* ``` --- touch a file for each element in the array, ls the directory and compare the ls result to the original array. I am not very good with bash, I just wanted to give it a try :) [Answer] # C# The notions of "smaller" or "bigger" are ***so much 2013***. Real programmers only use the `modulo` operator! ``` private static void Main() { List<int> list = new List<int> { 1, 5, 7, 15, 22}; List<int> list2 = new List<int> { 1, 5, 15, 7, 22 }; bool a = IsSorted(list); // true bool b = IsSorted(list2); // false } private static bool IsSorted(List<int> list) { for(int i = 0; i % list.Count != list.Count() - 1; i++) { if (list[i] % list[i + 1] != list[i] && list[i] != list[i + 1]) { return false; } } return true; } ``` [Answer] # Scala Checking if an array is sorted is easy! Just check if the first element is less than the second. Then sort the rest and see if they're equal. Unfortunately, sorting is a difficult problem. There aren't many well-known or efficient algorithms for sorting an array; in fact it's a huge blind-spot in the current state of computer science knowledge. So I propose a simple algorithm: shuffle the array and then check if it's sorted, which, as already stated, is easy! Keep shuffling until it's sorted. ``` object Random { def isSorted(list: List[Int]): Boolean = { if (list.size <= 1) { true } else { sort(list.tail) == list.tail && list.head <= list.tail.head } } def sort(list: List[Int]): List[Int] = { val rand = new scala.util.Random() var attempt = list do { attempt = rand.shuffle(attempt) } while (!isSorted(attempt)) attempt } def main(args: Array[String]): Unit = { println(isSorted(List(1, 2, 3))) println(isSorted(List(1, 3, 2))) println(isSorted(List(1, 2, 3, 4, 5, 6, 7, 8))) } } ``` I assume this outputs "true, false, true". It's been running for a while now... [Answer] A sorted array of integers has the property that every sub-array (say elements n through m of the array) is also a sorted array of integers. This obviously implies that the best method is a RECURSIVE function: ``` bool isSorted_inner(const std::vector<int> &array, int start, int length){ if (length == 2){ if (array[start] < array[start+1]){ return true; }else{ return false; } }else{ return isSorted_inner(array, start, length-1) && isSorted_inner(array, start+1, length-1); } } bool isSorted(const std::vector<int> &array){ return isSorted_inner(array, 0, array.size()); } ``` It may not be the fastest method but it is none-the-less a VERY ACCURATE test of whether or not a list is ordered. It is also incredibly easy to read and understand this code because it uses a FUNCTIONAL paradigm, and is therefore free of the horrors of state changing and iterative loops. I hope this will be useful information for you. [Answer] # C# - longest increasing subsequence For a sorted array, the length of the longest increasing subsequence is equal to the length of the array. I copied the algorithm from [here](http://tj-devjournal.blogspot.hu/2012/07/longest-increasing-sequence-c.html), only modified it to be non-decreasing instead of increasing. ``` static bool isSorted(int[] s) { return s.Length == LongestIncreasingSeq(s); } static public int LongestIncreasingSeq(int[] s) { int[] l = new int[s.Length]; // DP table for max length[i] int[] p = new int[s.Length]; // DP table for predeccesor[i] int max = int.MinValue; l[0] = 1; for (int i = 0; i < s.Length; i++) p[i] = -1; for (int i = 1; i < s.Length; i++) { l[i] = 1; for (int j = 0; j < i; j++) { if (s[j] <= s[i] && l[j] + 1 > l[i]) { l[i] = l[j] + 1; p[i] = j; if (l[i] > max) max = l[i]; } } } return max; } ``` [Answer] Stonescript (c) LMSingh - 0 minus (4102 palindromed). Following is written in Stonescript(c), a language copyrighted and used by me many centuries ago, i.e. in olden times before the midgetframes. NOTE: It is a precursor to Sanskrit. ``` 1. Find a very straight stick in the jungle. 2. Sum up all the values of the array elements and find that many equal sized stones. 3. Line up all the values of the array along the side of straight stick from step 1. Each value is to be represented by number of stones for each array element like so... ``` Example of an array with 8 elements. Sorted in descending order :-) ``` o oo oo oooo ooooo ooooo ooooo oooooo ooooooo oooooooo ======== 12345678 ``` -- Code continued. ``` 4. E-ball-uate. (In Shakespearean English that means Eye ball it.) 4.1 Run your eye from array position 1 top towards array position 8 top. 4.2 If it looks sorted, then it is. 4.2.1 Start jumping up and down and thumping chest. 4.2.2 Go to happy end. 4.3 If something isn't quite right, like in case of example below then it isn't. 4.3.1 Kick the stones in frustration and anger! Cuz it really is not sorted! 4.3.2 Go to sad end. ``` Example of an array with 8 elements. Not sorted :-( ``` o oo oo oo o ooooo ooooo ooooo oooooo ooooooo oooooooo ======== 12345678 ``` -- Code continued. ``` 5. Sad end. 5.1 Eat an apple. 5.2 Fall from grace to next line. 6. Happy end. ``` =-=-=-=-=-= On further optimization, step 4 punch leaves can be replaced with the following punch leaves. =-=-=-=-=-= ``` 4. Roll a stone from top of position 1 towards top of position 8, pushing the rolling stone towards the top stone for each position while moving to the right. 4.1 If rolling stone reaches the position 8 then it's sorted. 4.1.1 Start jumping up and down and thumping chest. 4.1.2 Go to happy end. 4.2 If the rolling stone gets stuck in a trough, then it isn't. 4.3.1 Kick the stones in frustration and anger! 4.3.2 Go to sad end. ``` =-=-=-=-=-= For you all code sleuths and power debuggers out there, I've intentionally added a bug in the above second variation of step 4. Can you find it? [Answer] # Javascript This is what made you shocked about the "creativity": > > * Because for a sorted array > > > > ``` > * all the elements on the left side of any element must be smaller > * all the elements on the right side of any element must be bigger > > ``` > * Therefore, run a main loop for all elements and check the above two conditions by running two nested loops inside the main one (one for left side and one for right side) > > > So, i give a javascript implementation of the described algorithm: ``` function checkArraySorted(array) { for (a = 0; a < array.length; a++) { for (b = 0; b < a; b++) { if (array[b] > array[a]) return false; } for (b = a + 1; b < array.length; b++) { if (array[b] < array[a]) return false; } } return true; } ``` Lets test it: ``` checkArraySorted([]); > true checkArraySorted([1]); > true checkArraySorted([1, 2]); > true checkArraySorted([2, 1]); > false checkArraySorted([1, 2, 3]); > true checkArraySorted([1, 2, 3, 4]); > true ``` Seems to work perfectly! It has a complexity of `O(n²)`, ideal for an algorithm that should be `O(n)`, but by doing `O(n²)` it becomes more efficient, since this is a measure of efficiency, so `O(n²)` is more efficient than `O(n)`. [Answer] # C Hereafter, "sorted" means "sorted in ascending order". An array is not sorted iff `a[i]>a[i+1]` So if we let `x=a[i]-a[i+1]`, `x` will be positive iff the array is not sorted. To test for `x` being positive, we can break it down into two parts: `x` is not negative, and `x` is not zero A simple test for whether `x` is negative is that we test whether `x*x` is equal to `x*abs(x)`. This condition should be false if `x` is negative, since `(-1)*(-1)==1`. To test for zero, we can use another simple test: `0./(float)x` is Not a Number iff `x` is zero. So here's the entire code: (assumes the array has 5 elements) ``` #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int i, a[5]; for(i=0;i<5;i++) scanf("%d",&a[i]); int sorted=1; for(i=0;i<4;i++) { int x=a[i]-a[i+1]; if(x*x==x*abs(x)&&!isnan(0./(float)x)) { sorted=0; break; } } puts(sorted?"sorted":"not sorted"); return 0; } ``` [Answer] It is all about how certain you wish to be. Since no certainty was given the following is actually quite good performance wise. The code below gives a good guess, but if you are sure you should repeat the function a couple of times. If you wish to be *really* sure, you should run it in a loop and do it a dozen of times. Perfect scalability! ``` #include <stdio.h> #include <stdlib.h> #include <time.h> static const int size = 100; int issorted(int *array, int size) { int idx = random() % size; return (array[idx] >= array[0]); } void check_array(int *array, int size) { if (issorted(array, size)) { puts("The array is sorted but I am not 100% sure."); } else { puts("The array is definitely not sorted in ascending order."); } } int main(void) { int *array = malloc(sizeof(int) * size); int i = 0; srand(time(NULL)); for (i = 0; i < size; i++) { array[i] = random(); } check_array(array, size); for (i = 0; i < size; i++) { array[i] = i + 1; } check_array(array, size); free(array); return 0; } ``` Isn't this a treat? [Answer] # C ``` int is_sorted(int *T, int n) { return false; } ``` Works with probability 1-(1/n!) and complexity O(1). Obviously the best method for very large random arrays. As the complexity is only O(1), for a better estimation, run twice. [Answer] # C This function does more than just tell you if the array is sorted. It tells you how many elements are in the right place. It can be used for any type of data. Note the importance of using descriptive variable names to make your code easy to follow. On the other hand, we do not need to declare the variable i, as it is bound to be declared somewhere else in the program. ``` int sortcheck(array_to_be_checked[10]) { int number_of_elements_in_right_place=0; for (i = 1; i = 10; i++) number_of_elements_in_right_place += i == array_to_be_checked[i]; return number_of_elements_in_right_place; } ``` Edit: This is a better way for larger arrays. The advantage of this is that it is similar to the way a human would check. ``` int sortcheck(array_to_be_checked[32767]) { i=rand(); j=rand(); while( (array_to_be_checked[i] > array_to_be_checked[j]) = (i > j) ) { printf("I think it's sorted"); i=rand(); j=rand(); }; printf("It wasn't sorted"); } ``` [Answer] # JavaScript + more statistics I liked the solution suggested by @Cominterm a lot. But comparing to an already sorted list? That's cheating! Instead, I calculate the array's autocorrelation (correlation between the array and the array left shifted one position). Then, I shuffle the array lots of times and each time compare it's new autocorrelation to the original autocorrelation. If the array was sorted, the original autocorrelation would be the highest most of the time! <http://jsfiddle.net/dB8HB/> Bonus: If your p-value < 0.05, the output will automate the task of claiming that the array is sorted for you. What more could you ask for? Bonus2: Although this implementation uses JavaScript's O(n) array functions for convenience, the approach could use sampling to run in constant time! ``` <form name="out"><textarea name="put" cols="80" rows="3">Press the button</textarea></form> <button onclick="startstop();">The button</button> <script> var iid=input=0, my=document.forms, isit={'true':0.5,'false':0.5}, ownAutocorr; function startstop(){ if(iid){ clearInterval(iid); if(1 - isit.true / (isit.true+isit.false)<0.05){my.out.put.value+="\nYour array is sorted! (p<0.05)";} iid=input=0;isit={'true':0.5,'false':0.5} } else { input=JSON.parse("["+prompt("Comma separated integers")+"]"); ownAutocorr=pearsonCorrelation(input,cloneShiftArray(input)); iid=setInterval(trial,50); } } function trial(){ var newArr=shuffle(input.slice(0)); var newAutocorr=pearsonCorrelation(newArr,cloneShiftArray(newArr)); isit[newAutocorr<ownAutocorr]++; my.out.put.value="Your array is sorted with probability " + (isit.true / (isit.true+isit.false)).toFixed(2); } function cloneShiftArray(oldArr){ var newArr=oldArr.slice(0); //clone the array var len=oldArr.length; //shift the array one for(var l=0;l<len-1;l++){ //performance is important so we'll use bitwise operators newArr[l]^=newArr[l+1]; newArr[l+1]^=newArr[l]; newArr[l]^=newArr[l+1]; } newArr[l]+=newArr[l-1 ]; return newArr; } function pearsonCorrelation(p1, p2) { //Borrowed from teh interwebs var len = p1.length; var sum1=sum2=sum1Sq=sum2Sq=pSum = 0; for (var l = 0; l < len; l++) sum1 += p1[l]; for (var l = 0; l < len; l++) sum2 += p2[l]; for (var l = 0; l < len; l++) sum1Sq += Math.pow(p1[l], 2); for (var l = 0; l < len; l++) sum2Sq += Math.pow(p2[l], 2); for (var l = 0; l < len; l++) pSum += p1[l] * p2[l]; var num = pSum - (sum1 * sum2 / len); var den = Math.sqrt((sum1Sq - Math.pow(sum1, 2) / len) * (sum2Sq - Math.pow(sum2, 2) / len)); if (den == 0) return 0; return num / den; } function shuffle(array) {//also borrowed var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } </script> ``` [Answer] # JavaScript/SVG - sunDialsort This solution does not use the <,<=,> or >= comparators. I've attempted to make it read as little like a sort function as possible. ## Method * Plot the values as dots along an arc. * For an ascending array each value will make the total width of the drawing wider and not decrease the starting X (exception: two identical values). * As width can't shrink a != will suffice, * As X cannot increase an == will suffice. * to fix for two identical values each dot is actually a line, of increasing length. Where the unit length is less than 1/number of values. ## Trolling I've added the following face-palms along the journey of reading this very bad code. * function may look like its going to sort the array, named it sunDialsort (bonus bad capitalization) * used lit-geek reference for all variable names * used the regex hammer to count the number of elements in the array * used an alert box * the solution for the edge case where 2 consecutive variables are the same doubled the amount of code (a one liner could have sorted it), put lots of this code early to confuse the purpose of the function. * instead of finding the min and max find the longest number and round up to the next power of ten, hopefully this will throw people off the scent. ## xml ``` <body> <svg id="dial" height="400" width="400" transform=""></svg> </body> ``` ## function ``` sunDialsort = function (values) { var twas = values.toString(); var brillig = twas.match(/,/g).length + 1; //<1> //find the sig figs we are working with (longest number) var and = [], the = 0; for (var jabberwock = 0; jabberwock < twas.length; jabberwock++) { switch (twas.charAt(jabberwock)) { case ("."): break; //dont count case (","): and.push(the); the = 0; break; default: the++; } } and.push(the); var slithy = Math.max.apply(Math, and); //assume did/toves based on number of characters var toves = Math.pow(10, slithy); var did = toves * -1; console.log(did + "," + toves + "," + brillig); //for each number make a horizontal svg line of length (jabberwock*acuuracy) var gyre = 1 / brillig; var gimble, wabe, all, mimsy, were, borogoves, mome, raths; var outgrabe = true; for (jabberwock = 0; jabberwock < brillig; jabberwock++) { gimble = document.createElementNS('http://www.w3.org/2000/svg', 'path'); gimble.setAttribute("stroke", "blue"); //green is not a creative colour gimble.setAttribute("d", "M0 20 h " + (jabberwock * gyre)); wabe = (values[jabberwock] - did) / (toves - did); mimsy = 90 - (wabe * 180); gimble.setAttribute("transform", "rotate(" + mimsy + ")"); document.getElementById("dial").appendChild(gimble); borogoves = document.getElementById("dial").getBBox(); if (mome) { raths = (borogoves.width != all && were == borogoves.x); console.log("test " + raths); all = borogoves.width; if (!raths) { outgrabe = false } } else { were = borogoves.x; all = borogoves.width; mome = true; } } return outgrabe }; alert(sunDialsort([1, 2, 3, 3, 4341, 556])); ``` If anyone wants to test there is a version here with readable variable names. <http://jsfiddle.net/outRideACrisis/r8Awy/> [Answer] # C As a binary search only works on sorted arrays, to check if an array is sorted, all we need to do is verify that a binary search works for all elements of the array. If it fails to find any element, we know the array is not sorted. The command-line arguments passed must all be decimal integers without leading zeroes. ``` #include <stdlib.h> #include <string.h> int compar(const void *a, const void *b) { char *const *sa = a, *const *sb = b; int cmp = strlen(*sa) - strlen(*sb); if (cmp == 0) cmp = strcmp(*sa, *sb); if (cmp == 0) cmp = sa - sb; return cmp; } int main(int argc, char *argv[]) { if (argc-- && argv++) { for (int i = 0; i != argc; i++) { if (bsearch(argv+i, argv, argc, sizeof *argv, compar) != argv+i) { return 1; } } } return 0; } ``` [Answer] # Javascript ``` a = prompt("Please enter the data"); r = prompt("Does your array arouse moral distaste and contempt?"); if ((/yes/i).test(r)) alert("The array is sordid."); ``` [Answer] # C * Make a copy of the array * sort the copy in descending order * check if this array is the reverse of the given array ``` #include<stdio.h> #include<stdlib.h> #include <stddef.h> #include<string.h> int main(){ int arr[100],i,j,temp; int a[] = {1,2,3,4,5,6,7,8,9,10}; char b[256]; printf("Loading the program please wait..."); int s = sizeof(a)/sizeof(a[0]); for(i=0; i<999999999; i++);//best way to make the program more realistic system("cls"); for(i=0;i<s; i++ ) arr[i] = a[i]; for(i=0;i<s;i++){ for(j=i;j<s;j++){ if(arr[i] < arr[j]){ temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } //sorting array in descending order int p = 0; for(i=0; i<s; i++) { if (a[s-i-1] != arr[i]) p++; } if(p>0) printf("No"); else printf("yes"); getch(); } ``` [Answer] # Mathematica This algorithm seems to work, but it is a bit slow. There may be quicker ways to sort but I haven't found them. 1. Take a random ordering of the list and check whether it is in order (with `OrderedQ`). 2. If it is, stop. Otherwise, repeat step 1. --- The following code sorted the list in just over 18 seconds. ``` a = {23, 50, 16, 57, 19, 60, 40, 7, 30, 54}; n = 1; Timing[While[! OrderedQ[a], a = RandomSample[a]; n++]] n a ``` > > {18.581763, Null} > > 8980699 > > {7, 16, 19, 23, 30, 40, 50, 54, 57, 60} > > > [Answer] # JavaScript ``` function isSorted(arr) { if (arr.length === 1 && typeof arr[0] !== 'number' || arr[0].toString().indexOf('.') !== -1 || arr[0] > (-1 >>> 0) || arr[0] !== arr[0] || arr[0] === Infinity) { // Return false in the case of one non-number element. // isSorted returns false for arrays containing non-numbers for consistency // with PHP, but that doesn’t work for one element, so that’s the purpose // of this check. return false; } var obj = {}; var i; for (i = arr.length; i--;) obj[arr[i]] = true; for (var x in obj) if (arr[++i] != x) return false; return true; } ``` This function may return `false` incorrectly, but not on modern browsers; you can check for this and provide a slower fallback (as described in the question) if necessary: ``` var isModern = /chrome/i.test(typeof navigator === 'object' && navigator.userAgent); if (!isModern) { isSorted = function() { // I develop on good browsers, so the implementation is left as an exercise // to the reader if he or she wants to support outdated browsers. }; } ``` They say this gives unpredictable results on negative numbers, but what it’s really all up to is how good you are at predicting things. [Answer] # Java (Levenshtein Distance) In this implementation, I clone the original array and sort the cloned instance. Then, the Levenshtein distance is calculated. If it is zero, then the original array was sorted. *Note: The getLevenshteinDistance() implementation is taken from Jakarta Commons Lang and modified to work on int[] instead of CharSequence.* ``` import java.util.Arrays; public class CheckSorting { public boolean isSorted(int[] array) { int[] sortedArray = Arrays.copyOf(array, array.length); Arrays.sort(sortedArray); return CheckSorting.getLevenshteinDistance(array, sortedArray) == 0; } public static int getLevenshteinDistance(int[] s, int[] t) { int n = s.length; int m = t.length; if (n == 0) { return m; } else if (m == 0) { return n; } if (n > m) { int[] tmp = s; s = t; t = tmp; n = m; m = t.length; } int p[] = new int[n + 1]; int d[] = new int[n + 1]; int _d[]; int i; int j; int t_j; int cost; for (i = 0; i <= n; i++) { p[i] = i; } for (j = 1; j <= m; j++) { t_j = t[j - 1]; d[0] = j; for (i = 1; i <= n; i++) { cost = s[i - 1] == t_j ? 0 : 1; d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } _d = p; p = d; d = _d; } return p[n]; } } ``` ]
[Question] [ Your task is simple: given two integers \$a\$ and \$b\$, output \$\Pi[a,b]\$; that is, the product of the range between \$a\$ and \$b\$. You may take \$a\$ and \$b\$ in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. \$a\$ will always be less than \$b\$. Note that the end may be exclusive or inclusive of \$b\$. I'm not picky. ^\_^ ## Test cases ``` [a,b) => result [2,5) => 24 [5,10) => 15120 [-4,3) => 0 [0,3) => 0 [-4,0) => 24 [a,b] => result [2,5] => 120 [5,10] => 151200 [-4,3] => 0 [0,3] => 0 [-4,-1] => 24 ``` --- This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins. --- ## Leaderboard The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template: ``` ## Language Name, N bytes ``` where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance: ``` ## Ruby, <s>104</s> <s>101</s> 96 bytes ``` If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header: ``` ## Perl, 43 + 2 (-p flag) = 45 bytes ``` You can also make the language name a link which will then show up in the snippet: ``` ## [><>](http://esolangs.org/wiki/Fish), 121 bytes ``` ``` var QUESTION_ID=66202,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] # Jelly, 2 bytes ``` rP ``` Takes two numbers as command line arguments. [Try it online.](http://jelly.tryitonline.net/#code=clA&input=&args=MQ+NQ) Note that this is inclusive range. For the cost of a byte (3 bytes), we can make this exclusive: ``` ’rP ``` [Try it online.](http://jelly.tryitonline.net/#code=4oCZclA&input=&args=NQ+MQ) Note that the arguments must be given in the order `b a` for this version. ## Explanation ### Inclusive ``` a rP b r dyadic atom, creates inclusive range between a and b P computes product of the list ``` ### Exclusive ``` b ’rP a ’ decrement b (by default, monadic atoms in dyadic chains operate on the left argument) r range P product ``` [Answer] ## [ArnoldC](https://esolangs.org/wiki/ArnoldC), ~~522~~ 511 bytes First post on codegolf ! I had fun doing this. Exclusive range. ``` LISTEN TO ME VERY CAREFULLY f I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE a I NEED YOUR CLOTHES YOUR BOOTS AND YOUR MOTORCYCLE b GIVE THESE PEOPLE AIR HEY CHRISTMAS TREE r YOU SET US UP 1 HEY CHRISTMAS TREE l YOU SET US UP 1 STICK AROUND l GET TO THE CHOPPER r HERE IS MY INVITATION r YOU'RE FIRED a ENOUGH TALK GET TO THE CHOPPER a HERE IS MY INVITATION a GET UP 1 ENOUGH TALK GET TO THE CHOPPER l HERE IS MY INVITATION b LET OFF SOME STEAM BENNET a ENOUGH TALK CHILL I'LL BE BACK r HASTA LA VISTA, BABY ``` Explanations (Thanks Bijan): ``` DeclareMethod f MethodArguments a MethodArguments b NonVoidMethod DeclareInt r SetInitialValue 1 DeclareInt l SetInitialValue 1 WHILE l AssignVariable r SetValue r MultiplicationOperator a EndAssignVariable AssignVariable a SetValue a + 1 EndAssignVariable AssignVariable l SetValue b > a EndAssignVariable EndWhile Return r EndMethodDeclaration ``` [Answer] ## Python, 30 bytes ``` f=lambda a,b:a>b or a*f(a+1,b) ``` Inclusive range. Repeatedly multiplies by and increments the left endpoint, until it is higher than the right endpoint, in which case it's the empty product of 1 (as True). [Answer] ## Minecraft 15w35a+, program size 456 total (see below) [![enter image description here](https://i.stack.imgur.com/i1QUG.png)](https://i.stack.imgur.com/i1QUG.png) This calculates `PI [a,b)`. Input is given by using these two commands: `/scoreboard players set A A {num}` and `/scoreboard players set B A {num}`. Remember to use `/scoreboard objectives add A dummy` before input. Scored using: `{program size} + ( 2 * {input command} ) + {scoreboard command} = 356 + ( 2 * 33 ) + 34 = 456`. This code corresponds to the following psuedocode: ``` R = 1 loop: R *= A A += 1 if A == B: print R end program ``` Download the world [here](http://www.mediafire.com/download/uapxuk2ppror5ms/PPCG__Product_over_a_Range.zip). [Answer] ## TI-BASIC, 9 bytes ``` Input A prod(randIntNoRep(A,Ans ``` Takes one number from `Ans` and another from a prompt. Also 9 bytes, taking input as a list from `Ans`: ``` prod(randIntNoRep(min(Ans),max(Ans ``` [Answer] ## Python 2, ~~44~~ 38 bytes ``` lambda l:reduce(int.__mul__,range(*l)) ``` Pretty much the obvious anonymous function answer. EDIT: Thanks to xnor for saving 6 bytes with some features I didn't know. [Answer] ## Pyth, 5 bytes ``` *FrQE ``` Pyth doesn't have product, so we reduce \* over the range. Uses exclusive range. [Answer] # R, 22 bytes ``` function(a,b)prod(a:b) ``` [Answer] # Mathematica, 15 bytes ``` 1##&@@Range@##& ``` A shorter solution that only works for non-negative integers: ``` #2!/(#-1)!& ``` [Answer] # JavaScript (ES6), 34 bytes ``` (a,b)=>eval("for(c=a;a<b;)c*=++a") ``` Sometimes the simplest answer is the best! Just a `for` loop inside `eval`. Inclusive range. [Answer] # [Japt](https://github.com/ETHproductions/Japt), 7 bytes Easy challenges like this are always fun. :) ``` UoV r*1 ``` [Try it online!](http://ethproductions.github.io/japt?v=master&code=VW9WIHIqMQ==&input=NSAxMA==) ### Explanation ``` UoV r*1 // Implicit: U = first input, V = second input UoV // Generate range [U,V). r*1 // Reduce by multiplication, starting at 1. ``` Wow, this seems pathetic compared to the other answers so far. I need to work on Japt some more... [Answer] ## Seriously, 4 bytes ``` ,ixπ , Read list [a,b] from stdin i Flatten it to a b x Pop a,b, push range(a,b) π Pop the list and push its product. ``` Hex Dump: ``` 2c6978e3 ``` [Try it online](http://seriouslylang.herokuapp.com/link/code=2c6978e3&input=[3,6]) [Answer] # Prolog, 45 bytes **Code:** ``` p(A,B,C):-A=B,C=A;D is A+1,p(D,B,E),C is A*E. ``` **Explained:** ``` p(A,B,C):-A=B, % A is unifiable with B C=A % Unify C with A ; % OR D is A+1, % D is the next number in the range p(D,B,E), % Recurse on the range after the first element C is A*E. % The result C is the product of the first element and the result of the recursion ``` **Example:** ``` p(5,10,X). X = 151200 p(-4,-1,X). X = 24 ``` [Answer] ## Octave, 15 bytes ``` @(a,b)prod(a:b) ``` Straightforward. Uses the inclusive range. [Answer] ## CJam, ~~6~~ ~~19~~ ~~18~~ 10 bytes Thanks to Dennis and RetoKoradi for help with golfing! ``` q~1$-,f+:* ``` [Try it online](http://cjam.aditsu.net/#code=q%7E1%24-%2Cf%2B%3A*&input=2%205) Takes input as `a b`. Calculates `PI [a,b)`. *Note: this program is 6 bytes long, and only works if `a` and `b` are positive.* ``` q~,>:* ``` [Try it online](http://cjam.aditsu.net/#code=q%7E%2C%3E%3A*&input=2%205) Takes input as `a b`. Calculates `PI [a,b)`. [Answer] ## Haskell, ~~19~~ 17 bytes ``` a#b=product[a..b] ``` Usage example: `2#5`-> `120`. [Answer] # Julia, 16 bytes ``` f(a,b)=prod(a:b) ``` Note: if the range object `a:b` (which is literally stored as a start value and a stop value, and internally includes a "increment by 1 on each step" value) is permitted as the input, then just 4 bytes are required: `prod`. [Answer] # C, 32 bytes For `[a,b)`: ``` f(a,b){return a-b?a*f(a+1,b):1;} ``` For `[a,b]` (On Katenkyo's suggestions, 32 bytes again) : ``` f(a,b){return a<b?a*f(a+1,b):b;} ``` [Answer] # Bash + GNU utilities, 13 ``` seq -s* $@|bc ``` Assumes there are no files in the current directory whose names start with `-s`. Start and end (inclusive) are passed as command-line parameters. This simply produces the sequence from start to end, separated by `*`, then pipes to `bc` for arithmetic evaluation. [Answer] ## JavaScript (ES6), 22 bytes I can't believe none of us JS golfers thought to use recursion... ``` a=>F=b=>a-b?b*F(b-1):a ``` Assign to a variable with e.g. `var q = a=>F=b=>a-b?b*F(b-1):a`, then call like `q(2)(5)`. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes ``` ⟦₃× ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG04vK/z@av@xRU/Ph6f//R0cb6ZjG6kSb6hgaAKl4Ex1jIGUAJoEcg9hYAA "Brachylog – Try It Online") Input is passed as `[A,B]`. The range is exclusive of B, but could be made inclusive by replacing the `₃` with `₂`. [Answer] # [MATL](https://esolangs.org/wiki/MATL), 4 bytes Inclusive Range ``` 2$:p ``` [**Try it online!**](http://matl.tryitonline.net/#code=MiQ6cA&input=Mgo1) ### Explanation ``` 2$: % Implicitly grab two input arguments and create the array input1:input2 p % Take the product of all array elements ``` Thanks to [@Don Muesli](https://codegolf.stackexchange.com/users/36398/don-muesli) for helping me get the hang of this whole MATL thing. [Answer] # [Jolf](https://github.com/ConorOBrien-Foxx/Jolf), 4 bytes [Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=T3JqSg) ``` OrjJ jJ two inputs r range between them [j,J) O product ``` [Answer] # Ruby, 22 bytes ``` ->i,n{(i..n).reduce:*} ``` **Ungolfed:** ``` -> i,n { (i..n).reduce:* # Product of a range } ``` **Usage:** ``` ->i,n{(i..n).reduce:*}[5,10] => 151200 ``` [Answer] ## PowerShell, 30 Bytes ``` param($a,$b)$a..$b-join'*'|iex ``` Takes input as two integers, creates a range with `..`, then `-join`s that with asterisks, pipes it into `Invoke-Expression` (similar to `eval`). The range operator in PowerShell is inclusive. Pretty competitive with non-golfing languages. [Answer] # J, 8 bytes ``` [:%/!@<: ``` ### Usage ``` >> f =: [:%/!@<: >> f 10 5 << 15120 ``` where `>>` is STDIN and `<<` is STDOUT. ### Explanation It computes `∏[a,b]` as `(b-1)!/(a-1)!`. ``` minus_one =: <: factorial =: ! of =: @ monadic =: [: division =: %/ f =: monadic division factorial of minus_one ``` ## Previous 13-byte version Written when I had no idea what `J` even is :p ``` */(}.[:>:i.)/ ``` Usage: ``` */(}.[:>:i.)/ 5 10 30240 ``` Explanation: ``` */ NB. multiply over ( }. NB. remove [the first x items] from [:>: NB. increment all of i. NB. the numbers from 0 to [y-1] ) / NB. insert the above code into the following numbers ``` Detailed explanation: ``` i.10 would produce 0 1 2 3 4 5 6 7 8 9 >:i.10 would make it 1 2 3 4 5 6 6 7 8 9 10 the [: is used to make the ">:" take only one argument (a monad) because if it takes two arguments, it is a different function. so [:>:i.10 becomes 1 2 3 4 5 6 7 8 9 10 }. means take away the first [x] items from the following list, so 5}.1 2 3 4 5 6 7 8 9 10 becomes 6 7 8 9 10 the two slashes "/" in the code are actually the same for example, */6 7 8 9 10 becomes 6*7*8*9*10 ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~8~~ 3 [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") ``` ×/… ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn///B0/UcNy/6nPWqb8Ki371HfVE//R13Nh9YbP2qbCOQFBzkDyRAPz@D/RgppCqZcpkDS0IDr0HoTIMOYywBMQniH1hsCAA "APL (Dyalog Extended) – Try It Online") `…` range `×/` multiplication across This is an "atop" so `a(×/…)b` is `×/a…b`. [Answer] # [R](https://www.r-project.org/), 21 bytes *Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126) for [helping me brainstorm input methods](https://chat.stackexchange.com/transcript/message/55468258#55468258).* ``` prod((a=scan()):a[2]) ``` Uses inclusive range. [Try it online!](https://tio.run/##K/r/v6AoP0VDI9G2ODkxT0NT0yox2ihW878Rl@l/AA "R – Try It Online") ### Explanation ``` a=scan() Read the two inputs as a vector and assign it to a ( ): Use a as the lower end of a range (R interprets this as "use the first element of the vector" by default) a[2] Use the second element of a as the upper end of the range prod( ) Take the product of all numbers in the range ``` [Answer] # [Desmos](https://www.desmos.com), 19 bytes ``` f(a,b)=∏_{n=a}^bn ``` [Try it on Desmos!](https://www.desmos.com/calculator/iqtrnjbvwn) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes Code: ``` ŸP ``` Explanation: ``` Ÿ # Inclusive range [input, ..., input] P # Total product of the list # Implicit printing top of the stack ``` ]
[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/19801/edit). Closed 7 years ago. [Improve this question](/posts/19801/edit) So, I want you to make a PNG image that says "Hello world!" and nothing else on a distinguishable background using only an image making API (eg ImageMagick) and return the image. Fewest characters win, as usual. Oh, and you can use any color text. [Answer] # Bash + ImageMagick: ~~35~~ 33 Default font, default text size, default colours: ``` convert label:Hello\ world! a.png ``` and here's the result: ![Hello, World!](https://i.stack.imgur.com/QqBBL.png) Thanks to [DigitalTrauma](/users/11259/digitaltrauma) and [sch](/users/8330/sch) for the help :-D [Answer] # Mathematica ~~28~~ 27 This creates and exports the sentence, "Hello world!", as a PNG image. 1 char saved by Mechanical snail. ``` ".png"~Export~"Hello world!" ``` --- **Testing** This imports the PNG image. The image was enlarged by dragging the image box handles. ![png](https://i.stack.imgur.com/8kZ5Y.png) [Answer] # HTML, 1494 I know this won't win, but I didn't see this here before. ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAANEAYAAABNymQSAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAABCAAAADQDi7GgjAAADvElEQVRYw+1YPa9pTRReRIJKEPHdiEJBoVVIRCenpCJBfCQEDeI3qAh/QCIRUchp0KCUaISgROO7QMRHSGS9xX73u+85592Xe47uepqJZ9bMrFnzrJm1MfBfwAsvAADzM8HhcDgczv2Bj9r9KRgMBoPBeJz/2/DdODwaV+bjU77wN+AliBc+4OmCmE6n0+kUwGKxWCwWAKFQKBQKAfR6vV6vBygWi8Vi8efr7Ha73W4H4HK5XC4XgFQqlUqlADKZTCaTAbjdbrfbTdndg8FgMBgMANVqtVqtUnwikUgkEgBisVgsFgOQFRfZkny/3+/3+z/3i7zC8/l8Pp8HkEgkEomE3u/tdrvdbgEcDofD4aDirVar1Wo1QCaTyWQyj8f1iyAul8vlcqEco2tJu88IBoPBYBDA7/f7/X6A5XK5XC4ByuVyuVwGSCaTyWQSYDAYDAaD7wsiHo/H43EAFovFYrEAxuPxeDwGGI1Go9GI4skDvYe3t7e3tzeAer1er9cpvtlsNptNAC6Xy+VyAYbD4XA4pPwnea1Wq9Vqn+dXu91ut9sAjUaj0WjQ28VisVgsRgl0MplMJhOAXq/X6/UAOp1Op9OhH8/j8Xg83i8EfgKbzWaz2XgXdHYCgUAgEJBfLfQtkQFfx/+/V195uVwul8sRV6vVarX6ak8IEVGpVCqVyvv7IQKISBwsIpHBiBqNRqPRIBIHiJhOp9PpNGIqlUqlUoihUCgUCj3PL3Kf6/V6vV7fjwNxAyEuFovFYvHVnuTp4moymUwmE/Wb9f0c/b3iut1ut9sFIDZO9c9ms9lsBsDn8/l8/s/Xu1c932632+12fx6dTqfT6QD2+/1+vwcolUqlUgnAaDQajUYAs9lsNpsBstlsNpulMjISiUQikef7JRKJRCLRfb+ZTCaT+ZuH/95XCflU/odHM/9Ru3A4HA6HEaPRaDQaRbxer9frFbHVarVaLURCMFSm3MsAOt7j8Xg8HkSfz+fz+RDP5/P5fEY8nU6n0wnR6/V6vV6qfRSBQCAQCFAZXCgUCoUC4vF4PB6PiMRBISoUCoVCgUg8nc/zi27/dP3kPHa73W63IxKCRjwcDofDAZGoWejnrdVqtVrtl/mfLQiiyEG02Ww2m416QogiB/H9/f39/f3xDdPx5DpOp9PpdCISxRfVkjxp9ygqlUqlUqHWm8/n8/mc6ievWKvVarVa6ff/Xb/+VBCbzWaz2VCCIOOtUqlUKhViLpfL5XKPx5XxseOFvx2v/yFe+ICXIF74gH8A5ia8gOmPT18AAAASdEVYdGxhYmVsAEhlbGxvIHdvcmxkIbl+3UEAAAAASUVORK5CYII= ``` Well apparently StackExchange will not allow data links so you must copy & paste it into your browser's address bar. --- @squeamish ossifrage got it down to 176: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAHAQAAAAC0VvlnAAAAOklEQVR4nGLIv/57/+9rDGDqAkPOterN0YIM3KG712pdZcgI3bW26gZD9lUwlRNWW1wtAAAAAP//AwCcyhjs3+7tWQAAAABJRU5ErkJggg ``` --- 114 ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACUAAAAEAQAAAAAhFcs9AAAAIElEQVQIHWOJit1f7szy58v9DAWWPaEMP7hZHHgi1aMB ``` --- @primo got it down to 112: ``` data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAAEAQAAAADKInA+AAAAH0lEQVR4nGOIj///7wVDZOBdoQ4G4dCrYWuA7JNiHQ ``` [Answer] # C# - 168 chars C# is better! ;) ``` using System.Drawing;class a{static void Main(){var s=new Bitmap(99,9);Graphics.FromImage(s).DrawString("Hello world!",new Font("",5),Brushes.Red,0,0);s.Save(".png");}} ``` Saves as .png in the current directory. Rule abuse: * Minimum font/image size has not been specified, so I settled for the minimum readable ;) * Filename is empty (only extension!), but it works flawlessly. To mirror the Java answer, here is the indented code: ``` using System.Drawing; class a { static void Main() { var s = new Bitmap(99, 9); Graphics.FromImage(s).DrawString("Hello world!", new Font("", 5), Brushes.Red, 0, 0); s.Save(".png"); } } ``` .net's API is a lot cleaner. [Answer] ## Linux shell + various utilities: 48 bytes My first thought was to print `Hello World!` in the console, and then take a screenshot (after a small delay to avoid the race condition) using `scrot`: ``` echo Hello World\!;scrot -d1 ``` (28 bytes). Unfortunately, this fails the "and nothing else" requirement: it will generally show other things like window decorations. So instead, do it inside a full-screen `xterm`. This covers up any other windows and hides window decorations. It also satisfies the background-color requirement, since `xterm` defaults to a white background. Because `xterm` displays a black cursor, we also need to tell it to hide the cursor. That can be accomplished using a terminal escape sequence: ESC `[` `?` `2` `5` `l`. The option to make it full-screen is `-fullscreen`. However, it seems to work if you abbreviate the option to the shortest unambiguous possibility, `-fu`, saving 8 bytes. The final code (48 bytes) is: ``` xterm -fu -e 'echo \x1b[?25lHello World!;scrot -d1' ``` (where `\x1b` denotes a literal ESC character, which takes 1 byte). By default, `scrot` writes the screenshot to a timestamped PNG file in the current directory. It works on my system: ![output](https://i.stack.imgur.com/pTGcd.png) [Answer] ## Processing, 38 37 This might be considered cheating, but: ``` text("HeΠo World!",9,8);save(".png"); ``` ![enter image description here](https://i.stack.imgur.com/11AqF.png) --- 38 char solution: ``` text("Hello World!",9,9);save(".png"); ``` Saves this image as `.png`: ![enter image description here](https://i.stack.imgur.com/oxVAX.png) [Answer] # Java - ~~340~~ ~~339~~ ~~292~~ ~~261~~ ~~239~~ ~~236~~ 233 chars This outputs a file just called `p` with a transparent background and white text: ``` import java.awt.image.*;class R{public static void main(String[]y)throws Exception{BufferedImage b=new BufferedImage(80,9,2);b.getGraphics().drawString("Hello World!",5,9);javax.imageio.ImageIO.write(b,"png",new java.io.File("p"));}} ``` Here a properly-indented version. Should be pretty clear what is going on: ``` import java.awt.image.*; class R { public static void main(String[] y) throws Exception { // 2 = BufferedImage.TYPE_INT_ARGB BufferedImage b = new BufferedImage(80, 9, 2); b.getGraphics().drawString("Hello world!", 5, 9); javax.imageio.ImageIO.write(b, "png", new java.io.File("p")); } } ``` You might argue that white text in a transparent background is awful for reading and the file being called just `p` without the `.png` extension is awful too. So this longer variant version with 290 chars use red text and outputs a file called `p.png`: ``` import java.awt.image.*;import java.awt.*;class R{public static void main(String[]y)throws Exception{BufferedImage b=new BufferedImage(80,9,2);Graphics g=b.getGraphics();g.setColor(Color.RED);g.drawString("Hello world!",5,9);javax.imageio.ImageIO.write(b,"png",new java.io.File("p.png"));}} ``` That properly-indented: ``` import java.awt.image.*; import java.awt.*; class R { public static void main(String[] y) throws Exception { // 2 = BufferedImage.TYPE_INT_ARGB BufferedImage b = new BufferedImage(80, 9, 2); Graphics g = b.getGraphics(); g.setColor(Color.RED); g.drawString("Hello world!", 5, 9); javax.imageio.ImageIO.write(b, "png", new java.io.File("p.png")); } } ``` [Answer] # Fortran 90, 104 94 bytes: Aight, game on. Fortran 90, using the g2 graphics library and implict typing, so "d" is a real: ``` d=g2_open_gd('h',80.,12.,g2_gd_png) call g2_string(d,1,1,'Hello world!') call g2_close(d) end ``` Needs to have the g2 library installed, then just compile with ``` gfortran -lg2 -fsecond-underscore p.f90 ``` Thanks [Kyle Kanos](https://codegolf.stackexchange.com/users/11376/kyle-kanos) for suggesting to drop "program p"! I'm pretty satisfied that I beat C#, C + Cairo, Java, Javascript, Python and Ruby! And now also Perl! Example output: ![example PNG produced by Fortran](https://i.stack.imgur.com/JjgJY.jpg) [Answer] # R, 52 39 chars ``` png() frame() text(.5,1,"Hello World!") ``` Saves as Rplot001.png in current directory. To be run as a script in non-interactive (batch) mode. Thanks to Sven Hohenstein and Michael Hoffman for updates! [Answer] ## PHP + gd2 - 86 bytes ``` <?imagestring($i=imagecreatetruecolor(97,16),4,2,0,'Hello world!',65535);imagepng($i); ``` `imagecreatetruecolor` is used instead of the shorter `imagecreate`, because colors can used directly without having to allocate them with `imagecolorallocate`. `65535` corresponds to hex color `#00FFFF`, a.k.a. cyan. I could have used `255` for blue, but it's fairly hard to see on a black canvas. ![](https://i.stack.imgur.com/S9ZA0.png) If the requirement that the background must be white or transparent is to be strictly enforced, I think the best that can be done is **98 bytes**: ``` <?imagestring($i=imagecreatetruecolor(97,16),4,2,0,'Hello world!',imagefilter($i,0));imagepng($i); ``` The `0` sent to `imagefilter` is the value of the constant `IMG_FILTER_NEGATE`, which of course negates the image. The result, `1`, is then used as the paint color (`#000001`): ![](https://i.stack.imgur.com/htNz7.png) Another option at **108 bytes**: ``` <?imagestring($i=imagecreatetruecolor(97,16),4,2,imagecolortransparent($i,0),'Hello world!',1);imagepng($i); ``` Setting black to be transparent, and drawing with `#000001` instead. ![](https://i.stack.imgur.com/YAKen.png) --- ## PHP + *No Library* - 790+ bytes ``` <? echo pack('CA3N2',137,'PNG',218765834,13); echo $ihdr = pack('A4N2C5','IHDR',45,7,1,0,0,0,0); echo hash('crc32b',$ihdr,true); $data = '--------0 0 0 0 0 0 0---'. '--------0 0 0 0 0 0 0---'. '--------0 0 00 0 0 00 0 0 00 0 0 0 000 0---'. '--------0000 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0---'. '--------0 0 0000 0 0 0 0 0 0 0 0 0 0 0 0 0 0---'. '--------0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ---'. '--------0 0 000 0 0 00 0 0 00 0 0 000 0---'; $bytes = join(array_map(chr,array_map(bindec,str_split(strtr($data,' -',10),8)))); $cmp = gzcompress($bytes); echo pack('N',strlen($cmp)); echo $idat = 'IDAT'.$cmp; echo hash('crc32b',$idat,true); echo pack('NA4N',0,'IEND',2923585666); ``` Ahh, that's better. No bloat; exactly as much as required, and not a chunk more. The result is this **109 byte** png: ![](https://i.stack.imgur.com/xiS99.png) Or, URI encoded (which seems to be trending...) at **168 bytes**: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAHAQAAAAC0VvlnAAAANElEQVR4nGPIv/7//+8LDFAq51r15mgBBu7Q3Wu1LjBkhO5aW3WBIfsqkLrBkBNWW1wtAACw2RlgLInRogAAAABJRU5ErkJggg` Supposing we wanted to cut that down a bit more, let's say we replace the data string with this: ``` $data = '--------0 0 0 0 0 0 0'. '--------0 0 00 0 0 000 0 0 000 00 0 000 0'. '--------0000 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0'. '--------0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 '. '--------0 0 000 0 0 000 00 00 000 0 0 000 0'; ``` (and update the header to the new dimensions, 40x5), the output would be this **96 byte** png: ![](https://i.stack.imgur.com/mbPoc.png) Which URI encodes to **150 bytes**: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAFAQAAAAAft5MoAAAAJ0lEQVR4nGPIv/7//y6GnCvlLosYuEJLQ1cxZF4tDV3NkBNS5LoIANqBDTt5Av0NAAAAAElFTkSuQmCC` I think that's about as small as you're going to be able to get, and still be considered "human readable". ### Further Analysis You may have noticed that we've been toting along an extra byte at the beginning of each scanline (denoted by `--------`). This isn't solely for decoration. Each byte specifies the [filtering](http://www.w3.org/TR/PNG/#9Filters) used by each scanline. According to the PNG specification, *"Filtering transforms the PNG image with the goal of improving compression."* So let's try that. The are five different filtering operations which can be applied independently to each scanline. The PHP implementation that I used for each can be seen here: <http://codepad.org/xCQpBPC3> where `$bytes` represents the raw bytes for the current scanline, and `$prior` represents the raw, unfiltered bytes for the scanline above the current. Let's start with the first 45x7 image. Seven scanlines each with 5 different filterings makes 78125 different possibilities to grind through. The initial encoding of the data block was 52 bytes in length, and after a bit of grinding zlib found a one byte improvement using filtering pattern [1, 1, 1, 1, 0, 0, 0] (that is, the first four scanlines with Sub filtering, and the last three unfiltered). The result is this **108 byte** png: ![](https://i.stack.imgur.com/20ks7.png) Which of course looks identical to the last. But I'm not convinced that zlib is producing the best possible encoding, and I think i have [good reason](http://garethrees.org/2007/11/14/pngcrush/) to be skeptical. I decided to try [AdvanceComp](http://en.wikipedia.org/wiki/AdvanceCOMP) (which uses the same DEFLATE engine used for 7-zip), and [Zopfli](http://en.wikipedia.org/wiki/Zopfli), an implementation which claims to *"find a low bit cost path through the graph of all possible deflate representations."* Sure enough, Zopfli mananged to compress the same data data pattern [1, 1, 1, 1, 0, 0, 0] down to 50 bytes, producing this **107 byte** png: ![](https://i.stack.imgur.com/krcuM.png) Once again, visually identical. (As a point of interest, it should probably be mentioned at this point that AdvanceComp with the setting `-z3` (compress-extra (7z)) didn't manage to find anything shorter than 60 bytes - the data was left uncompressed. It seems it refuses to compress anything this short). The above URI encodes to **165 bytes**: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAHAQAAAAC0VvlnAAAAMklEQVR4AWPMz9Bg+HMVRuVkLbVYsZWR2yvtU+0yhozQXWurLjBkXwVSNxhywmqLqwUA+IMVKa7QjrYAAAAASUVORK5CYII` Fully 11 bytes shorter than [squeamish ossifrage's attempt](https://codegolf.stackexchange.com/questions/19801/#comment40035_19907) at more or less an identical image. Onwards to the 40x5 image. Five lines with 5 filterings each means we only have 3125 possibilities this time. The original encoding was 39 bytes in length, and with a bit of grinding, zlib found quite a few 38s. The one I've chosen is [1, 0, 0, 2, 0], which contains the largest number of unfiltered lines, and Sub and Up filters on lines 0 and 4, which are the simplest. Zopfli wasn't able to improve this result any further. The result is this **95 byte** png: ![](https://i.stack.imgur.com/uUp0G.png) Which URI encodes to **149 bytes**: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAFAQAAAAAft5MoAAAAJklEQVR4nGPMz9Bg2M2Qc6XcZREDV2hp6Cqm+AYGBkaGnJAi10UAju4JJ/1zkEIAAAAASUVORK5CYII` You might be tempted to think that the last 18 or so bytes of this aren't necessary. After all, this **121 byte** URI will still display correctly, at least in Chromium: `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAFAQAAAAAft5MoAAAAIUlEQVR4nGPMz9Bg2M2Qc6XcZREDV2hp6Cqm+AYGBkaGnJAi10U` But if you save it to a file, it will break in very many image viewers. In fact, any compliant decoder is required to report an error. So what have we chopped off? From end towards beginning: * 4 bytes - CRC32 for `IEND` chunk (always `0xAE426082`) * 4 bytes - `IEND` chunk marker (always `IEND`) * 4 bytes - `IEND` chunk length (always `0x00000000`) * 4 bytes - CRC32 for `IDAT` chunk * 4 bytes - Adler32 for zlib data * 1 byte - Stop marker for zlib data Additionally adjusting the `IDAT` length marker down by 5 (to compensate for the bytes we deleted) seems to "fix" the image in Windows Previewer. [Answer] # C + Cairo: ~~238~~ ~~221~~ 202 bytes ``` #include <cairo/cairo.h> main(){cairo_surface_t*s=cairo_image_surface_create(0,99,50);cairo_t*c=cairo_create(s);cairo_move_to(c,0,9);cairo_show_text(c,"Hello world!");cairo_surface_write_to_png(s,"o");} ``` $ cc `pkg-config cairo --libs --cflags` mini.c && ./a.out && display o Here is the un-minified version: ``` #include <cairo/cairo.h> void main (int argc, char* argv[]) { cairo_t *cr; cairo_surface_t *surf; surf = cairo_image_surface_create (0, 99, 50); cr = cairo_create (surf); cairo_move_to (cr, 0, 9); cairo_show_text (cr, "Hello world!"); cairo_surface_write_to_png (surf, "out.png"); } ``` Best enjoyed while listening to [this song](http://www.youtube.com/watch?v=1S1fISh-pag) :) [Answer] > > make a PNG image that ***says*** "Hello world!" … > > > You'll hopefully excuse my very loose interpretation of the above requirement. :) ### OSX bash: ``` printf '"Hello world!" and nothing else on a distinguishable background using only an image making API (eg ImageMagick) and return the image.' > hello.png say -f hello.png ``` [Answer] # Javascript! ~~105~~ ~~104~~ 101 ``` c=document.createElement('canvas');open(c.toDataURL(c.getContext('2d').fillText('Hello world!',0,9))) ``` Outputs this size-optimized and pretty image: ![Hello world!](https://i.stack.imgur.com/mrh2g.png) [Answer] # Octave, 47 ``` axis('off') title("Hello World!") print -dpng x.png ``` ![ ](https://i.stack.imgur.com/eWOfv.png) [Answer] # Sage notebook, 22 ``` text("Hello world",0j) ``` [Answer] ## Ruby, 138 I'm golfing this hole with just my putter. (I chose a PNG library without fonts or a string draw method.) ``` require'chunky_png';i=ChunkyPNG::Image.new 34,4 136.times{|v|i[*(v.divmod(4))]=9*(0xb0fae0f02e0eae0ece00eae0f0f0bf0f2f&1<<v)>>v};i.save ?h ``` Actual output is 34x4 pixels. (Enlarged below.) This plots very, *very* small and *nearly* transparent hand-drawn chars onto a very small transparent background. Image is saved to a PNG file named `h`. ![output](https://i.stack.imgur.com/9gpZ7.png) [Answer] ## TI-BASIC, 22 ``` Text(0,0,"HELLO WORLD! ``` White background. Use TI-Connect if you wish to retrieve it from the calculator. Resulting PNG: ![enter image description here](https://i.stack.imgur.com/uSMmm.png) [Answer] # BASH + RST + ImageMagick = 43 chars Just for fun, here's another (quite ugly) one: ``` echo 'Hello World!'|rst2pdf|convert - a.png ``` Output: ![Hello World!](https://i.stack.imgur.com/PCzg4.png) [Answer] **Gnuplot** Not really a true competitor, just for fun. ([homepage](http://www.gnuplot.info/)) ``` #!/usr/bin/gnuplot set terminal pngcairo set output "hw.png" set label "Hello\nWorld!" unset xtics unset ytics set yrange [-1:+1] plot -1 notitle ``` or, as a oneliner (thanks to Phil H): 74 characters ``` se te pngc;se ou "q.png";se la "Hello world!";se yr[-1:1];uns ti;pl -1 not ``` [Answer] ## **Perl, 95:** The whole command incantation: ``` perl -MGD::Simple -e'$i=new GD::Simple;moveTo$i 9,50;string$i "Hello world!";print$i->png'>.png ``` Because of (reasonable) module defaults, it's **95** characters (or **92** if single letter file name allowed). On Windows we need to `binmode STDOUT`, the shortest way I think can be `-M-encoding`+ get rid of double colons: ``` perl -MGD'Simple -M-encoding -e"$i=new GD'Simple;moveTo$i 9,50;string$i 'Hello world!';print$i->png">.png ``` i.e. **105** ![enter image description here](https://i.stack.imgur.com/qdMlx.png) [Answer] ## Data URI: 446 Following Chloe's idea, applied some basic optimisation to the image. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAALCAAAAAAFX7+TAAABBUlEQVQoz2P4Tylg+M8IohiRRUCIkC6E0sFlwhFBJo5kmPAdWSYmuTsgGa6y/3pMf/8yLYEJMcQwARXckmZi8YCawAAG//8L537ZxbEMaoKCwuvXCkogE2y0/nMyL1vC/BcmxKC6AqhAXurBc1kGkNUINzCBDIqFmsB84f//c8wgmcVs91j13d3U4EIMl0AKmM78/38GqJQXyQSWQ///H3sJMwGo7ALYhL/MQUq1wkK1cCEGsE+ZgSacAzKNkUxQ1/kygfEczBeKb18rKICDS4U58SUT8ye4EMQEBelHz+WAzEokE+6IM7HkI4ekLDgk/5cxnPrPK/4fLgQxARSSUdCQpBQAAFZKE8rQG60FAAAAAElFTkSuQmCC Might be able to hack it further, but then would not be a perfectly conformant PNG and some viewers may not display it correctly. [Answer] ## Python and Matplotlib - 66 65 chars ``` from pylab import*;title('Hello world!');axis('off');savefig('X') ``` Bit of whitespace, but it has the text and nothing else. File is saved as `X.png`: ![enter image description here](https://i.stack.imgur.com/nMZWU.png) [Answer] ## Ghostscript command line incantation, 84 (i.e. Postscript) : ``` gs -sDEVICE=png16 -oa.png -c '/ 72 selectfont 9 9 moveto(Hello world!)show showpage' ``` Missing font message is intentional ;-). And proper (i.e. not hidden) name for our PNG file, too :-) [Answer] # Python with PIL 122 Chars ``` from PIL import Image,ImageDraw;d=Image.new("RGB",(70,9));i=ImageDraw.Draw(d);i.text((0,0),"Hello World!");d.save("a.png") ``` It could probably be much smaller but I haven't worked with PIL extensively and made this in 5 minutes. Output: ![enter image description here](https://i.stack.imgur.com/pzhov.png) [Answer] # Bash + DOT, ~~46~~ 41 ``` dot -Tpng<<<'graph{label="Hello World!"}' ``` This outputs a png into the standard output. It is saving a file, but I don't think that was a requirement. Outout: ![Hello World!](https://i.stack.imgur.com/tlSql.png) [Answer] # Python, with ~~118~~ ~~115~~ ~~117~~ ~~116~~ 114 chars Here's a full criteria passing with white text on alpha background at ~~116~~ 114 chars!: ``` from PIL import Image,ImageDraw as D m=Image.new("LA",(99,9)) D.Draw(m).text((9,0),'Hello World!') m.save('r.png') ``` (You can replace newlines with semicolons - count is the same regardless.) [Answer] # PureBasic - 128 chars ``` UsePNGImageEncoder() CreateImage(0,99,24) StartDrawing(ImageOutput(0)) DrawText(0,0,"Hello World!") SaveImage(0,"a.png",4673104) ``` ![enter image description here](https://i.stack.imgur.com/TuVZu.png) Not the shortest here, but I have to support my favorite Basic language :) edit: just in case there is a complain about the black background, at 133 chars: ``` UsePNGImageEncoder() CreateImage(0,80,16) StartDrawing(ImageOutput(0)) DrawText(0,0,"Hello World!",0,-1) SaveImage(0,"a.png",4673104) ``` ![enter image description here](https://i.stack.imgur.com/NGwNt.png) [Answer] ## bash + netpbm: 31 chars ``` pbmtext "Hello world!"|pnmtopng ``` Will make: ![Hello world by netPBM](https://i.stack.imgur.com/urkVS.png) [Answer] # Rebol/View 45 ``` save/png %i to-image layout[h1"Hello World!"] ``` writes a png image file named i into current directory ![](https://i.stack.imgur.com/j9rGh.png) [Answer] # Internet 11 Internet is an API! [ow.ly/thgUJ](http://ow.ly/thgUJ) -> <http://dummyimage.com/99x9/f/0.png&text=Hello+world!> ]
[Question] [ Write a program which runs forever and allocates more and more memory on the heap the longer it runs, at least until you reach the limit of the operating system on the amount of memory that can be allocated. Many kernels won't actually reserve memory you allocate until you use it for something, so if your program is in C or some other low level language you'll have to make sure you write something to each page. If you're using an interpreted language, you're probably not going to have to worry about this. Shortest code wins. [Answer] # Funge-98 ([`cfunge`](https://launchpad.net/cfunge)), 1 byte ``` 9 ``` I would have posted this earlier, but decided to test it, and it took a while to get my computer back to a usable state. `cfunge` stores the Funge stack on the operating system's heap (which is easily verifiable by running the program with a small memory limit, something that I should have done earlier!), so an infinitely growing stack (as with this program, which just pushes `9` repeatedly; Funge programs wrap from the end of a line back to the start by default) will allocate memory forever. This program likely also works in some Befunge-93 implementations. More interesting: ``` "NULL #(4 ``` This was my first idea, and is an infinite allocation that doesn't rely on the Funge stack (although it blows up the Funge stack too). To start with, the `"` command pushes a copy of the rest of the program to the stack (it's a string, and the program wraps round, so the close quote also serves as the open quote). Then the `N` reflects (it has no meaning by default), causing the program to run backwards. The `"` runs again, and pushes the program to the stack – the other way round this time, with the `N` at the top of the stack – then the program wraps around, loading a library with a 4-letter name (`4(`; the `NULL` library is part of `cfunge`'s standard library). `NULL` defines all uppercase letters to do reflect, so the `L` reflects, the `#` skips the library load on the way back, the `4` pushes junk we don't care about to the stack and the whole program repeats from the start. Given that loading a library multiple times has an effect, and requires the library's command list to be stored once for each copy of the library (this is implied by Funge-98's semantics), it leaks memory via non-stack storage (which is an alternative method of defining "heap", relative to the language rather than the OS). [Answer] ## Brainfuck, 5 bytes ``` +[>+] ``` This requires an interpreter that has no limit on the length of the tape. [Answer] # Bash + coreutils, 5 or # Ruby, 5 ``` `yes` ``` `yes` produces endless output. Putting `yes` in backticks tells the shell to capture all output and then execute that output as a command. Bash will continue allocating memory for this unending string until the heap runs out. Of course the resulting output would end up being an invalid command, but we should run out of memory before that happens. Thanks to @GB for pointing out this is a polyglot in ruby too. [Answer] # Python, 16 bytes Keeps nesting `a` until an error is reached: ``` a=0 while 1:a=a, ``` The first few iterations (as tuples) look like this: ``` 0 (0,) ((0,),) (((0,),),) ``` and so on and so forth. [Answer] ## ><> (Fish), 1 byte ``` 0 ``` [Try it here!](https://fishlanguage.com/playground/oQ5qkLuN8MgLfR5L5) `0` can actually be substituted for any hexadecimal number 1-f. **Explanation** `0` in ><> simply makes a 1x1 codebox for the fish to swim in. It constantly adds a `0` onto the stack, swims right, which loops backaround to `0`, adding it to the stack again. This will go on forever. [Answer] ## Perl, 12 bytes ``` {$"x=9;redo} ``` In perl, the `x` operator, with a string on the left and a number on the right, produces a repeated string. So `"abc" x 3` evaluates to `"abcabcabc"`. The `x=` operator mutates the left argument, replacing contents of the variable on its left with the result of repeating it's contents as many times as its right hand side indicates. Perl has a number of a number of strangely named built in variables, one of which is `$"`, whose *initial* value is a single space. The `redo` operator jumps to the beginning of the enclosing `{}`. The first time the `x=` operator is done, it changes the value of `$"` from `" "`" to `" "`, which is 9 spaces. The second time the `x=` operator is done, it changes the value of `$"` to `" "`, which is 81 spaces. The third time, `$"` becomes a 729 byte long string of spaces. I think you can see where this is going :). [Answer] ## Java 101 bytes ``` class A{public void finalize(){new A();new A();}public static void main(String[]a){for(new A();;);}} ``` Catching main Program in a endless Loop after creating and throwing away a object. Garbage collection does the job of leaking by creating 2 objects for each deleted ones [Answer] # sed, 5 bytes **Golfed** ``` H;G;D ``` **Usage (any input will do)** ``` sed 'H;G;D' <<<"" ``` **Explained** ``` #Append a newline to the contents of the hold space, #and then append the contents of the pattern space to that of the hold space. H #Append a newline to the contents of the pattern space, #and then append the contents of the hold space to that of the pattern space. G #Delete text in the pattern space up to the first newline, #and restart cycle with the resultant pattern space. D ``` **Screenshot** [![enter image description here](https://i.stack.imgur.com/hRBzu.gif)](https://i.stack.imgur.com/hRBzu.gif) [Try It Online !](https://tio.run/nexus/bash#@1@cmqKg7mHtbu2irmBjY6Ok9P8/AA) [Answer] # Haskell, ~~23~~ 19 bytes ``` main=print$sum[0..] ``` Print the sum of an infinite list [Answer] ## ///, 7 bytes ``` /a/aa/a ``` Constantly replace `a` with `aa`, ad nauseum. [Answer] # C++ (using g++ compiler), ~~27~~ ~~23~~ 15 bytes *Thanks to Neop for helping me to remove 4 bytes* This solution does not really leak any memory because it allocates everything on the stack and thus causes a stack overflow. It is simply infinitely recursive. Each recursion causes some memory to be allocated until the stack overflows. ``` main(){main();} ``` ## Alternative solution This solution actually leaks memory. ``` main(){for(;;new int);} ``` ## Valgrind output This is the Valgrind output after terminating the program several seconds into the run time. You can see that it is certainly leaking memory. ``` ==2582== LEAK SUMMARY: ==2582== definitely lost: 15,104,008 bytes in 3,776,002 blocks ==2582== indirectly lost: 0 bytes in 0 blocks ==2582== possibly lost: 16 bytes in 4 blocks ==2582== still reachable: 4 bytes in 1 blocks ==2582== suppressed: 0 bytes in 0 blocks ``` [Answer] # JAVA, ~~81~~ ~~79~~ 78 bytes # JAVA (HotSpot) ~~71~~ 70 bytes Shorter than other Java answers at the time I posted (81, later 79 bytes): ``` class A{public static void main(String[]a){String x="1";for(;;)x+=x.intern();}} ``` As suggested by @Olivier Grégoire, a further byte can be saved: ``` class A{public static void main(String[]a){for(String x="1";;)x+=x.intern();}} ``` Placing `x+=x.intern()` as the for loop increment would not help anything, because a semicolon is still required to end the for statement. As suggested by @ETHproductions, just using `x+=x` works too: ``` class A{public static void main(String[]a){String x="1";for(;;)x+=x;}} ``` Which can also benefit from @Olivier Grégoire's tip: ``` class A{public static void main(String[]a){for(String x="1";;)x+=x;}} ``` My only misgivings about that is that it is not guaranteed to allocate data *on the heap*, as an efficient JVM can easily realize that `x` never escapes the local function. Using `intern()` avoids this concern because interned strings ultimately end up stored in a static field. However, HotSpot does generate an `OutOfMemoryError` for that code, so I guess it's alright. Update: @Olivier Gregoire also pointed out that the `x+=x` code can run into `StringIndexOutOfBoundsException` rather than `OOM` when a lot of memory is available. This is because Java uses the 32-bit `int` type to index arrays (and Strings are just arrays of `char`). This doesn't affect the `x+=x.intern()` solution as the memory required for the latter is quadratic in the length of the string, and should thus scale up to on the order of 2^62 allocated bytes. [Answer] # [Perl 6](https://perl6.org), 13 bytes ``` @= eager 0..* ``` ## Explanation: `@ =` store the result into an unnamed array `eager` make the following list eager `0 .. *` infinite range starting at zero [Answer] # Python 3, 16 bytes ``` i=9 while 1:i*=i ``` This comes from the fact that there is no limit to integer size in Python 3; instead, integers can take up as much memory as the system can handle (if something about my understanding of this is wrong, do correct me). [Answer] ## Rust, 46 bytes ``` fn main(){loop{std::mem::forget(Box::new(1))}} ``` Notice something interesting about this Rust program, leaking heap allocations until out of memory? That's right, no unsafe block. Rust guarantees memory safety in safe code (no reading of uninitialized data, read after free, double free etc.), but memory leaks are considered perfectly safe. There's even an explicit function to make the compiler forget about RAII cleanup of out of scope variables, which I use here. [Answer] # TI-83 Hex Assembly, 7 bytes ``` PROGRAM:M :AsmPrgm :EF6A4E :C3959D :C9 ``` Creates appvars indefinitely until an `ERR:MEMORY` is thrown by the OS. Run with `Asm(prgmM)`. I count each pair of hex digits as one byte. [Answer] # Python, 8 bytes ``` 2**9**99 ``` The [OP](https://codegolf.stackexchange.com/questions/101709/shortest-program-that-continuously-allocates-memory?noredirect=1#comment247805_101709) has allowed the technicality of a program that doesn't technically run "forever", but allocates more memory than any computer could possibly handle. This isn't quite a googolplex (that would be `10**10**100`, 11 bytes), but naively, log base 2 of the number is ``` >>> 9**99. 2.9512665430652752e+94 ``` i.e., 10^94 bits to represent it. [WolframAlpha](http://www.wolframalpha.com/input/?dataset=&i=2.9512665430652752e%2B94+bits) puts that as 10^76 larger than the deep web (keep in mind that there are about 10^80 [atoms in the universe](http://www.wolframalpha.com/input/?dataset=&i=atoms+in+the+universe)). Why 2 instead of 9 you ask? It doesn't make much of a difference (using 9 would only increase the number of bits by a factor of `log2(9) = 3.2`, which doesn't even change the exponent). But on the other hand, the program runs much faster with 2, since the calculation is simpler. This means it fills up memory immediately, as opposed to the 9 version, which takes a little longer due to the calculations required. Not necessary, but nice if you want to "test" this (which I did do). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~3~~ 2 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 byte thanks to Dennis (`W` wraps) ``` Wß ``` A link (i.e. function or method), which also works as a full program, that recursively wraps its input into a list. The input starts as zero so the first pass creates the list `[0]` The second pass then makes this `[[0]]` The third pass then makes this `[[[0]]]` and so on... --- Previous 3 byter, which leaks much faster: ``` ;Ẇß ``` recursively concatenates all non-empty contiguous sublists of its input to its input. `[0]` -> `[0,[0]]` -> `[0,[0],[0],[[0]],[0,[0]]]` and so on... [Answer] # Java 7, 106 bytes ``` class A{public void finalize(){for(;;)Thread.yield();}public static void main(String[]a){for(;;)new A();}} ``` ### Less Golfed ``` class A{ @Override public void finalize(){ for(;;) { Thread.yield(); } } public static void main(String[]a){ for(;;){ new A(); } } } ``` The `finalize` method is called on an object by the garbage collector when garbage collection determines that there are no more references to the object. I have simply redefined this method to loop forever so the garbage collector never actually frees the memory. In the `main` loop I create new objects which will never be cleaned up so eventually this will use up all the available memory. # Java 7 (fun alternative), 216 bytes ``` import sun.misc.*;class A{public static void main(String[]a)throws Exception{java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe");f.setAccessible(1>0);for(;;)((Unsafe)f.get(null)).allocateMemory(9);}} ``` ### Less Golfed ``` import sun.misc.*; class A{ public static void main(String[]a)throws Exception{ java.lang.reflect.Field f=Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); Unsafe u = (Unsafe)f.get(null); for(;;) { u.allocateMemory(9); } } } ``` This is a fun one more than anything else. This answer makes use of the `Unsafe` Sun library which is an undocumented internal API. You may need to change your compiler settings to allow restricted APIs. `Unsafe.allocateMemory` allocates a specified amount of bytes (without any boundary checking) which is not on the heap and **not** under java's garbage collector management so this memory will stick around until you call `Unsafe.freeMemory` or until the jvm runs out of memory. [Answer] # Haskell, 24 bytes ``` f x=f$x*x main=pure$!f 9 ``` The main problem in Haskell is to beat the laziness. `main` needs to have some `IO` type, so simply calling `main=f 9` would not work. Using `main=pure(f 9)` lifts the type of `f 9` to an `IO` type. However using constructs like `main=pure 9` does not do anything, the `9` is returned or displayed nowhere but simply discarded, so there is no need to evaluate the argument of `pure`, hence `main=pure(f 9)` does not cause any memory to be allocated as `f` is not called. To enforce evaluation, the `$!` operator exists. It simply applies a function to an argument but evaluates the argument first. So using `main=pure$!f 9` evaluates `f` and hence continuously allocates more memory. [Answer] ## dc, 7 bytes ``` [ddx]dx ``` `[ddx]` pushes a string containing "ddx" to the stack. `dx` duplicates it then executes it as code (leaving one copy on the stack). When executed, it makes two duplicates then executes one, leaving one more copy on the stack each time. [Answer] ## Haskell (using ghc 8.0.1), 11 bytes ``` m@main=m>>m ``` Non-tail recursion. `main` calls itself and then itself again. [Answer] # C (linux), 23 bytes ``` main(){while(sbrk(9));} ``` [`sbrk()`](https://en.wikipedia.org/wiki/Sbrk) increments the top of the data segment by the given number of bytes, thus effectively increasing the amount of memory allocated to the program - at least as reported in the `VIRT` field of `top` output. This only works on Linux - the macOS implementation is apparently an emulation that only allows allocation of up to 4MB. --- So a slightly more general answer: # C, 25 bytes ``` main(){while(malloc(9));} ``` I watched it on the macOS Activity Monitor. It went all the way up to about 48GB, then eventually the process received a SIGKILL signal. FWIW my macbook pro has 16GB. Most of the memory used was reported as compressed. Note that the question effectively requires each allocation to be written to, which doesn't happen explicitly here. However it is important to note that for every `malloc(9)` call, it is not just the 9 user requested bytes that are allocated. For each block allocated there will be a malloc header that is also allocated from somewhere on the heap, which is necessarily written to by the `malloc()` internals. [Answer] # Perl, 4 bytes ``` do$0 ``` Executes itself, in the current interpreter. When finished, execution returns to the calling script, which requires a call stack. [Answer] # Racket, 13 bytes ``` (let l()(l)1) ``` I'm not entirely certain if my answer falls under this question. Please let me know if I should remove this answer. [Answer] # JavaScript ~~22~~ ~~21~~ ~~17~~ ~~16~~ 15 Bytes ``` for(a=0;;)a=[a] ``` Saved 4 bytes by wrapping the list in another list as in @Jonathan Allan's Jelly answer. Saved 1 byte thanks to @ETHProductions ### Alternative solution 15 Bytes (only works with proper tail calls) ``` f=a=>f([a]);f() ``` [Answer] # Ruby, 11 bytes ``` loop{$*<<9} ``` Keeps pushing `9` onto `$*`, which is an array initially holding the command line arguments to the Ruby process. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 2 bytes ``` [A ``` [Try it online!](http://05ab1e.tryitonline.net/#code=W0E&input=) Will just keep pushing `abcdefghijklmnopqrstuvwyxz` onto the stack for eternity. **All possible 2-byte solutions:** ``` [ # Infinite loop. A # Push alphabet. 0 # Push 0. 1 # Push 1. 2 # Push 2. 3 # Push 3. 4 # Push 4. 5 # Push 5. 6 # Push 6. 7 # Push 7. 8 # Push 8. 9 # Push 9. T # Push 10. X # Push 1. Y # Push 2. ® # Push -1. ¶ # Push \n. º # Push len(stack) > 0, so 0 once then 1 for eternity. ð # Push a space. õ # Push an empty string. ¾ # Push 0. ¯ # Push []. M # Push -inf. ) # Wrap current stack in an array. ``` [Answer] ## Python, 35 bytes ``` def f(a=[]):a.append(a) while 1:f() ``` `a` is never released and just gets bigger until you hit a `MemoryError` You can view the execution on [Python Tutor](http://pythontutor.com/visualize.html#code=def%20f(a%3D%5B%5D%29%3Aa.append(a%29%0Awhile%201%3Af(%29%0A&cumulative=false&curInstr=17&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=2&rawInputLstJSON=%5B%5D&textReferences=false). [Answer] ## TI-BASIC, 8 ``` :Lbl A :While 1 :Goto A ``` (all 1-byte tokens, and two newlines) This continuously leaks memory because structured control flow such as `While` anticipated being closed by an `End` and pushes something on the stack (not the OS stack, a separate stack in heap memory) to keep track of that. But here we're using `Goto` to leave the loop (so no `End` is executed to remove the thing from the stack), the `While` is seen again, the thing gets pushed again, etc. So it just keeps pushing them until you get `ERR:MEMORY` ]
[Question] [ # Winner: [professorfish's bash answer](https://codegolf.stackexchange.com/questions/32151/convert-1-2-3-4-5-6-7-8-and-9-to-one-two-three-etc/32232#32232)! An entire 9 bytes! Wow! You may continue to submit your answer, however you can no longer win. Original post kept for posterity: --- Your goal is to convert a **whole** number between 1-9 into the word it represents. * You will not need to worry about decimals * The user will input a number. Assume that they will never enter anything 10 or higher * The user must type the number at some point, **however** the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point * It is not case sensitive (ie, "one", "One", "oNe", "OnE", etc are all acceptable) * HTTP/etc requests are allowed, **however** any code executed by the server the request is made to counts towards the byte count of your final code (e.g. if I had a C++ program make a HTTP request, the PHP code used in the HTTP request counts) * Anything that can compile and run is acceptable --- * This contest **has ended** on June 27th, 2014 (7 days from posting). * This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code wins [Answer] ## Python 2, 64 ``` print' ottffssennwhoiieiieoruvxvgn ere ehe e nt'[input()::9] ``` This is what the string looks like with some extra whitespace (try reading vertically): ``` o t t f f s s e n n w h o i i e i i e o r u v x v g n e r e e h e e n t ``` As explained in the comments below, `[input()::9]` starts at the given index and selects every ninth subsequent character. [Answer] # Bash (with bsdgames), 9 ``` number -l ``` Reads from standard input. I don't know why there's a utility for this, but whatever. [Answer] # Common Lisp - 22 bytes Here's a general one (not just for one-ten): ``` (format nil"~R"(read)) ``` Oh, you want ordinals (first, second, ... three-hundredth...)? Ok! ``` (format nil"~:R"(read)) ``` [Answer] # BASH 51 So I made another one using my second idea plus some help from others: ``` set one two three four five six seven eight nine $X ``` Where 'X' is the number you want. --- # BASH 48 (67) **67 with `\n` line breaks** I'm not sure if this totally counts, because it's reading from a file, but: `sed -n Xp a` Where "X" is the input and where `a` is a file with: ``` one two three four five six seven eight nine ``` The file is 36 chars, and the bash command is 13. How it works: > > Each line in the file is numbered, starting with 1. So 'one' is on the 1st line, 'two' on the 2nd. The command, `sed -n 'Xp' a` says, "Please print what's listed on line 'X' of file 'a'" `sed` is a Unix stream editor. `-n` means be silent, or only essentially ignore everything else. `Xp` means print what's on line 'X'. > > > [Answer] ### C# - 127 ( 86 / 46) If you only take the executable part... ``` Console.Write(((HourOfDay)Console.Read()-48)); ``` and if `HourOfDay` would have been part of the the System namespace you would need 46 chars. Unfortunately it sits in `System.DirectoryServices.ActiveDirectory` which makes it 86...the other noise spoils it. This is compileable and runnable from the commandline (127 chars): ``` using System;class P{static void Main(){Console.Write((System.DirectoryServices.ActiveDirectory.HourOfDay)Console.Read()-48);}} ``` if saved to a file called cg2.cs ``` csc cg2.cs /r:System.DirectoryServices.dll && cg2 ``` **How does this work?** [`HourOfDay`](http://msdn.microsoft.com/en-US/library/system.directoryservices.activedirectory.hourofday(v=vs.110).aspx) is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the [name of the value](http://msdn.microsoft.com/en-us/library/system.enum.getname(v=vs.110).aspx). You can cast an int to an enum. [Console.Read()](http://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx) reads a character from the input stream represented as an integer. typing '1' gives [49](http://en.wikipedia.org/wiki/UTF-8#Codepage_layout), substract 48 to get 1, cast/box to `HourOfDay` to return 'One'. [Take a look at the Powershell version of this same trick](https://codegolf.stackexchange.com/a/32181/9393) [Answer] # Befunge 98, ~~116~~ ~~105~~ 103 bytes ``` &1- v vvvvvvvvvj< """"""""" etnxereoe nheivuewn igvsiorto nie"ffh"" "es ""t "" " >>>>>>>>>4k,@ ``` Befunge was not made for this... Explanation: ``` &1- ;Grab the input number (`n`) and subtract 1 from it &1- v ;Start moving downwards < ;Start moving leftwards j ;Jump `n - 1` characters to the left. vvvvvvvvvj ;Redirect each of the possible locations to jump to, sending the IP down. " ;If `n` was 1, push `o, n, e` onto the stack (`o` is at the bottom) e n o " " ;If `n` was 2, push `t, w, o` onto the stack o w t " * * * " ;If `n` was 9, push `n, i, n, e` onto the stack e n i n " >>>>>>>>> ;Collect all the different possible positions the IP could be in, and send it right >>>>>>>>>4k, ;Print the top 5 chars. If there are less than 5, the rest are null characters. This is allowed @ ;End of program ``` [Answer] # Javascript 68 Atob / btoa can be a poor's man compressing tool ~~(but if you want to try this in console, you cannot copy from the formatted text you see at once. Go to 'edit' and copy from the source panel)~~ Markdown editor does not like some of the characters in this answer: some characters get lost at saving. Still, I think it's an editor problem, not mine. The lost characters are perfectly valid 8 bit unicode chars. (Or else I'm wrong, if this issue was already debated in meta, let me know) Here is the version with offending characters escaped, each sequence \xNN should count 1 ``` alert(btoa("×C§{Dð£Dá­ç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[prompt()]) ``` **Simple Test** In firefox console: ``` [0,1,2,3,4,5,6,7,8,9] .map(x=>x +',' btoa("×C§{Dð£Dá­ç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[x]) ``` [Answer] # Javascript 73 ``` alert('0one0two0three0four0five0six0seven0eight0nine'.split(0)[prompt()]) ``` # 69 ``` alert(btoa("ôéÞõ5õ1ëxO_¢êý|Þöȱõ'xß^hSôا{Ý").split(9)[prompt()]) ``` [Answer] # Perl, 55 ``` $_=(nine,eight,seven,six,five,four,three,two,one)[-$_] ``` It is run with option `-p` (+1 byte), e.g.: ``` perl -pe '$_=(nine,eight,seven,six,five,four,three,two,one)[-$_]' ``` Input is expected in STDIN and output is written to STDOUT. The code just generates an array and selects the right element. Option `-p` takes care of reading the input line into `$_` and prints the result in `$_`. **Variations:** * With trailing new line (+3): ``` $_=(nine,eight,seven,six,five,four,three,two,one)[-$_].$/ ``` or (same byte count): ``` s/./(nine,eight,seven,six,five,four,three,two,one)[-$&]/e ``` **Update:** * Using bare words instead of `qw[...]` (thanks Zaid). * Negative index saves a byte (thanks aragaer). [Answer] ## Oracle SQL - 46 ``` select to_char(to_date(&1,'j'),'jsp')from dual ``` [Demonstration](http://www.sqlfiddle.com/#!4/d41d8/31776) This does include a [standard loophole](http://meta.codegolf.stackexchange.com/a/1078/3419), I admit, but the SQL is shorter than Golfscript; I couldn't resist! It works by (ab)using Oracle's [datetime format models](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements004.htm#i34924). `TO_DATE(n, 'j')` converts a number into a [Julian day](http://en.wikipedia.org/wiki/Julian_day), the number of days since January 1, 4712 BC. `TO_CHAR(<date>, 'jsp')` converts this back into the integer (though as a string). The `sp`, is a [format element suffix](http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements004.htm#SQLRF51083) that spells the number. This'll actually work with quite a lot of numbers. The `&1` is a substitution variable that'll only work with clients that accept it, for instance SQL\*Plus. [Answer] # CJam, ~~45~~ 43 bytes ``` "^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256bKb'ef+'j/li= ``` The above uses ^ and M- notation, since some characters are unprintable. At the cost of 9 more bytes, unprintable characters can be avoided: ``` " one two three four five six seven eight nine"S/li= ``` [Try it online.](http://cjam.aditsu.net/ "CJam interpreter") ### How it works ``` " Convert the string into an integer by considering it a base-256 number. "; "^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256b " Convert the integer from above into an array by considering it a base-20 number. "; Kb " Add the ASCII character code of “e” to all elements of that array. This casts to char. "; 'ef+ " So far, we've pushed the string “jonejtwojthreejfourjfivejsixjsevenjeightjnine”. "; " Split the the above string where the character “j” occurs. "; 'j/ " Read an integer from STDIN and push the corresponding substring. "; li= ``` ### Example ``` $ base64 -d > convert.cjam <<< IgGMOPiMFVMfl3LyoDHzA0j82AhFLPGF8TQiMjU2YktiJ2VmKydqL2xpPQ== $ wc -c convert.cjam 43 convert.cjam LANG=en_US cjam convert.cjam <<< 5 five ``` [Answer] # GolfScript, 51 bytes ``` ~' one two three four five six seven eight nine'n/= ``` It's a simple lookup table. The input is evaluated (`~`), an array of the values is created, and the index is found. [Try it here](http://golfscript.apphb.com/?c=OycxJwp%2BJwpvbmUKdHdvCnRocmVlCmZvdXIKZml2ZQpzaXgKc2V2ZW4KZWlnaHQKbmluZSduLz0%3D) [Answer] # bash say (OS X): ~~3~~ 8 "Your goal is to convert a whole number between 1-9 into the word it represents" Last time I checked, spoken words are words as well. Previous attempt (accepts no input) ~~`say 4`~~ Edit, must be able to read input: ``` say|read ``` Type any number and the word comes out. I know the end date is due, but in my opinion I should have won the contest. Example audio file: [four.aiff](https://www.dropbox.com/s/dut3a1d36jyt97w/four.aiff) [Answer] # Perl, 60 bytes ``` $_=(ZOneTwoThreeFourFiveSixSevenEightNine=~/.[a-z]*/g)[$_] ``` Requires the `-p` switch (two bytes). ### Example ``` $ perl -p convert.pl <<< 5 Five ``` ### How it works * `-p` reads from STDIN and saves the result in `$_`. * `=~/.[a-z]*/g` splits the preceding bareword into substrings of one (uppercase) letter followed by any number of lowercase letters. * `(…)` collects the substrings into an array. * `[$_]` retrieves the substring corresponding to the user input. * `$_=…` saves the result in `$_`. * `-p` prints the value of `$_`. [Answer] # Bash + coreutils, 64 # Non-competitive compression concept ``` xxd -p<<<TàPnàõ:àsÀ~®@ãCN|tr 0-9a-d \\ng-inor-x|sed -n $1p ``` Some of the exotic characters here may not render well, so this script may be reconstructed from its base64 representation: ``` base64 -d <<< eHhkIC1wPDw8VOCLUIJu4PWWDzrgc8B+rkDjEoBDTnx0ciAwLTlhLWQgXFxuZy1pbm9yLXh8c2VkIC1uICQxcA== ``` ### Example output ``` $ ./n.sh 1 one $ ./n.sh 9 nine $ ``` ### Explanation It occurred to me that the string `one two three four five six seven eight nine` contains only the letters `efghinorstuvwx` and a space separator - 15 character values in total. Thus each character can potentially be represented in 4 bits, or 2 characters per 1 byte. We can use the hex representation of a byte as an easy way to split each byte into two hex digits. We can then transform the hex digits back to the letters we require using `tr` or similar. As luck would have it, `rstuvwx` are consecutive, so may be expressed as `r-x` to `tr`. The encoding is arranged such that `e` and `f` are left as-is, and that the words are line-break separated, so we can use `sed` to ouptut just the line we need. This decoding process ends up using a fair amount of extra space, so makes this answer non-competitive as a shell-script-style answer, but may be a useful concept in other languages. [Answer] # Python 2.x - ~~65~~ 64 Not as good as @grc 's answer, but certainly more legible :-) ``` 'one two three four five six seven eight nine'.split()[input()-1] ``` One less char, thanks to @flornquake ``` 'nine eight seven six five four three two one'.split()[-input()] ``` [Answer] ## DOS Batch - 162 Chars (incl' line breaks) This answer was inspired by @grc's Python answer, although I did have something similar in mind. ``` @setlocal enabledelayedexpansion @set s="ottffssennwhoiieiieoruvxvgn ere ehe e nt @set /a c=%1 @set z=!s:~%c%,1! @if _%z%==_ exit /b @echo %z% @%0 %c%+9 ``` Usage: [Filename] [number] For example, if the code is in a file called speak.bat, and you want to see the number "five", you would run it as: `speak 5` Also, the output is top-to-bottom, not left-to-right! So instead of > > five > > > you will see > > f > > i > > v > > e > > > [Answer] # (pure) Bash, 64 Takes input as its first argument, assuming valid input. ``` v=(o one two three four five six seven eight nine) echo ${v[$1]} ``` Creates an array `v`, then accesses the element specified on the input. Since arrays are zero-indexed, I had to add a 0th element as a placeholder. Alternatively (thnx @DennisWilliamson for pointing this out): ``` v=(one two three four five six seven eight nine) echo ${v[$1-1]} ``` [Answer] ## Java 7 - 185 ``` class Num{ public static void main(String[] args) { System.out.print("ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".split(",")[(new java.util.Scanner(System.in)).nextInt()-1]); }} ``` [Answer] # C 111 ``` #include <stdio.h> int main(){printf("%.5s","one two threefour five six seveneightnine"+5*(getchar()-'1'));} ``` The length here is carefully engineered so I can interpret it as binary and convert *that* to decimal. At only 7 characters, I'm confident I have a winner! [Answer] ## VBScript 98 80 75 ``` msgbox split(" one two three four five six seven eight nine")(inputbox("")) ``` [Answer] # J - ~~68 or 60~~ 57 or 53 bytes Interactive version (stdin): ``` >one`two`three`four`five`six`seven`eight`nine{~<:".1!:1]1 ``` Function version: ``` f=:one`two`three`four`five`six`seven`eight`nine>@{~<: ``` Explanation: ``` f=:one`two`three`four`five`six`seven`eight`nine>@{~<: <: Decrease by one {~ Get the correct string >@ Unbox ``` `".(1!:1)1` reads a string and converts it to integer [Answer] # Perl 36 (58 standalone) ``` use Number::Spell;say spell_number<> ``` Or, without additional modules: ``` say qw(one two three four five six seven eight nine)[<>-1] ``` [Answer] **In AppleScript ; 123 chars.** ``` {"one","two","three","four","five","six","seven","eight","nine"}'s item((display dialog""default answer"")'s text returned) ``` This script takes the input in a dialog. Then it gives the output in AppleScript’s *result*. *Example :* * Input : `6` * Output : `"six"` Here is a nicer version : ``` set l to {"one","two","three","four","five","six","seven","eight","nine"} set n to text returned of (display dialog "?" default answer "") display dialog (l's item n) buttons ("OK") default button 1 ``` This version displays the output in a nice dialog. *Example :* * Input : `9` * Output : `nine` *[ Answer edited ; slightly improved the dialog for the input ; still 124 chars. Answer edited again ; now 1 char less ! ]* [Answer] ## Powershell - 91 74 ``` [Enum]::ToObject([System.DirectoryServices.ActiveDirectory.HourOfDay],[Console]::Read()-48) ``` Found out how to cast to remove the Enum and ToObject call: ``` [System.DirectoryServices.ActiveDirectory.HourOfDay]([Console]::Read()-48) ``` **How does this work?** HourOfDay is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the name of the constant value. You can cast an int to an enum. [Console.Read()](http://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx) reads a character from the input stream represented as an integer. typing '1' gives 49, substract 48 to get 1, cast to HourOfDay to return 'One'. Because powershell does a ToString on all objects being written to the output stream and doesn't need the fluff to turn this into an executable this all that is needed besides powershell... [Answer] # CJam - 50 This is a plain ASCII solution that uses HTTP requests (this is allowed in the question): ``` "aj21.com/"r+g ``` On the server there are 9 plain-text files named 1, 2, ..., 9, each containing the corresponding word. Total size: 14 + 3 ("one") + 3 ("two") + 5 + 4 + 4 + 3 + 5 + 5 + 4 = 50. It can be golfed more by using a shorter domain. The online interpreter doesn't support HTTP requests, so the program needs to be run using the [java interpreter](http://sf.net/p/cjam). [Answer] # Batch - 86 Far shorter than the other batch answer, and actually surprisingly competitive. ``` for /f "tokens=%1" %%1 in ("one two three four five six seven eight nine") do echo>%%1 ``` Used as `filename.bat number`, and the output is in the form of a file with the name of the correct number. [Answer] # Ruby 64 ``` p %w?one two three four five six seven eight nine?[$*[0].to_i-1] ``` [Answer] ## BASH 9 shameless Linux-replica of [cousincoicane's answer](https://codegolf.stackexchange.com/a/32298/13171) ``` spd-say 1 ``` speaks out one [Answer] # GolfScript, 50 bytes I wanted to see if I could beat [Quincunx's 51-byte self-contained GolfScript solution](https://codegolf.stackexchange.com/questions/32151/convert-1-2-3-4-5-6-7-8-and-9-to-one-two-three-etc/32154#32154). Turns out that, with enough tricks, yes, I can — by one byte. Since one of the tricks I'm using is the use of bytes outside the printable ASCII range, the resulting program is cannot be directly pasted here. Instead, I'm providing a hex dump of it; users on Unixish systems can use `xxd -r` to reconstruct the actual 50-byte GolfScript program from the hex dump: ``` 0000000: 7e6e 270b 97eb 442f e166 9894 9f00 c63c ~n'...D/.f.....< 0000010: 8128 73a3 9b55 5065 a9fb f06a 2727 ff16 .(s..UPe...j''.. 0000020: 277b 6261 7365 7d2f 2b6e 2f3d 7b39 392b '{base}/+n/={99+ 0000030: 7d25 }% ``` The basic trick used to generate this program is simple: I compress the long string literal that makes up most of Quincunx's code by subtracting 99 (the ASCII code of the letter `c`) from the character values, interpreting the resulting values as a number in base 22 (enough to encode the letters up to `x`) and then re-encode the resulting number in base 255 to produce the unprintable byte string that makes up most of the first half of my program. The rest of the program then reverses this process, decoding the string back into something printable. (Since the lowest letter actually present in the number names is `e`, I could've shortened the byte string further by subtracting 101 from the ASCII codes and using base 20. However, subtracting 101 would've mapped the letter `o` to a newline, which I'm using as the number delimiter because it's conveniently available as the built-in constant `n` in GolfScript. Working around that would cost me more than the one byte that using a lower base would save. Using the offset 99 leaves the newline corresponding to the letter `m`, which is conveniently absent from the number names.) Here's a de-golfed version of the program: ``` ~ # eval the input, turning it into a number n # push a newline onto the stack; we'll need it later # this is the byte string encoding the number names: "\x0B\x97\xEBD/\xE1f\x98\x94\x9F\x00\xC6<\x81(s\xA3\x9BUPe\xA9\xFB\xF0j" # convert the encoded string from base 255 to base 22 # (and, incidentally, from a string to an array): "\xFF\x16" {base}/ + # prepend the newline pushed earlier to the array, re-stringifying it n/ # split the resulting string at newlines = # pick the substring corresponding to the input number {99+}% # add 99 to the character values in the chosen substring ``` ]
[Question] [ On some terminals, pressing backspace generates the control code `^H` to delete the previous character. This gave rise to a snarky idiom where [edits are feigned for comedic effect](http://www.catb.org/~esr/jargon/html/writing-style.html): > > Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate > HQ. > > > Given a string with one or more `^H`'s, output the result of backspacing on each `^H`. The input will use only printable characters (ASCII 32-126), and `^` will only appear as `^H`. Backspaces will never happen on empty text. You may not assume that the output environment supports control codes, in particular the backspace code `\x08`. ``` >> Horse^H^H^H^H^HCow Cow >> Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ. Be nice to this gentleman, he's visiting from corporate HQ. >> 123^H45^H^H^H78^H 17 >> Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma Digital Trauma ``` ## Leaderboard Here's a by-language leaderboard, courtesy of [Martin Büttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner). 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"https://api.stackexchange.com/2.2/questions/52946/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=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);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#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=45497;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*((?:[^,\s]|\s+[^-,\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] # GNU sed, 11 bytes ``` :;s/.^H//;t ``` ### Test output: ``` $ echo "Horse^H^H^H^H^HCow Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ. 123^H45^H^H^H78^H Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma" | sed ':;s/.^H//;t' Cow Be nice to this gentleman, he's visiting from corporate HQ. 17 Digital Trauma $ ``` [Answer] # Pyth, 11 bytes ``` .U+PbZcz"^H ``` [Demonstration.](https://pyth.herokuapp.com/?code=.U%2BPbZcz%22%5EH&input=123%5EH45%5EH%5EH%5EH78%5EH&debug=0) ``` .U+PbZcz"^H Implicit: z = input() cz"^H z.split("^H") .U reduce, with the first element of the list as the initial value. Pb Remove the last character of what we have so far. + Z And add on the next segment. Print implicitly. ``` [Answer] # Gema, 6 bytes ``` ?#\^H= ``` Sample run: ``` bash-4.3$ gema -p '?#\^H=' <<< 'pizza is alright^H^H^H^H^H^Hwesome' pizza is awesome ``` CW, because the fool vs. gentleman example takes far too long. (Killed after a day. Maybe a glitch in the interpreter? All other examples here are processed in fractions of seconds.) Gema's recursive pattern not seems to be affected by the recursion level, but the amount of non-matching text increases processing time exponentially. [Answer] # C, 52 bytes ``` j;f(char*s){for(j=0;*s=s[j];s[j]==94?s--,j+=3:s++);} ``` We define a function `f` that takes a pointer to the string as input. After the function call, that pointer will contain a modified string. A simple test: ``` int main(int argc, char** argv) { char buf[300] = "Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma"; f(buf); printf(buf); return 0; } ``` The above prints: ``` Digital Trauma ``` [Answer] # Haskell, 47 bytes ``` h(a,_:_:b)=f$init a++b;h(x,_)=x f=h.span(/='^') ``` Defines a function `f :: String -> String`. How it works: ``` f "ab^Hc^Hd" === h ("ab", "^Hc^Hd") (find ^H) === f ("a" ++ "c^Hd") (backspace) === f "ac^Hd" (join) === h ("ac", "^Hd") (find ^H) === f ("a", "d") (backspace) === f "ad" (join) === h ("ad", "") (find ^H) === "ad" (no ^H: base case) ``` [Answer] # CJam, ~~14~~ 13 bytes ``` q"^H"/{W\ts}* ``` **How it works** ``` q e# Read the entire input "^H"/ e# Split it on occurrences of string "^H" { }* e# Reduce on the split array W\t e# This is the tricky part. We know that if there are two parts that we e# are reducing on, they must be separated by "^H". Which in turn means e# that from the first part, last characters needs to be deleted e# So we simply put the second part in place of the last character of the e# first part. s e# Doing the above makes it a mixed array of character and string. e# So we convert it to a single string, ready to be served as first part e# in next reduce iteration ``` *UPDATE: 1 byte saved thanks to jimmy23013* [Try it online here](http://cjam.aditsu.net/#code=q%22%5EH%22%2F%7BW%5Cts%7D*&input=Digital%20Trauma%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EHMaria%20Tidal%20Tug%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EHDigital%20Trauma) [Answer] # Retina, 13 bytes [Retina](https://github.com/mbuettner/retina) ``` +`.\^H(.*) $1 ``` The two lines should go to their own files but you can run the code as one file with the `-s` flag. At each step we delete the first match for `.\^H` in the string. We repeat this (with the `+` modifier) until no deletion happens. [Answer] # JavaScript (*ES6*), 39 bytes ``` f=s=>(t=s.replace(/.\^H/,''))!=s?f(t):t // TEST Out=x=>O.innerHTML+=x+'\n' Test=_=>(Out(I.value + "\n-> " + f(I.value)),I.value='') ;["Horse^H^H^H^H^HCow" ,"Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ." ,"123^H45^H^H^H78^H" ,"Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma"] .forEach(t => Out(t + "\n-> " + f(t))) ``` ``` #I { width:400px } ``` ``` <pre id=O></pre> <input id=I><button onclick='Test()'>-></button> ``` [Answer] # Perl, ~~20~~ ~~16~~ 15 bytes (14 characters code + 1 character command line option.) ``` s/.\^H//&&redo ``` Sample run: ``` bash-4.3$ perl -pe 's/.\^H//&&redo' <<< "Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ." Be nice to this gentleman, he's visiting from corporate HQ. ``` [Answer] # Julia, ~~58~~ ~~42~~ 41 bytes Saved 16 bytes thanks to manatwork and 1 thanks to Glen O! ``` f(s)='^'∈s?f(replace(s,r".\^H","",1)):s ``` This creates a recursive function that accepts a string and returns a string. This replaces one occurrence of `^H` at a time with an empty string while the input contains `^`. Examples: ``` julia> f("123^H45^H^H^H78^H") "17" julia> f("pizza is alright^H^H^H^H^H^Hwesome") "pizza is awesome" ``` [Answer] # REGXY, 10 bytes Uses [REGXY](http://esolangs.org/wiki/REGXY), a regex substitution based language. Replaces any character followed by ^H with nothing. The second line then executes which is just a pointer to the previous line, repeating the substitution until it fails to match. ``` /.\^H// // ``` This compiles and executes correctly with the sample interpreter in the link above, but the solution is perhaps a bit cheeky as it relies on an assumption in the vagueness of the language specification. The spec states that the first token on each line (before the /) acts as a label, but the assumption is that a null label-pointer will point back to the first command in the file with a null label (or in other words, that 'null' is a valid label). A less cheeky solution would be: ``` a/.\^H// b//a ``` Which amounts to 13 bytes. [Answer] # Python 3, 53 bytes ``` o="" for x in input().split("^H"):o=o[:-1]+x print(o) ``` But personally I like this wordier version better: ``` H=input().split("^H") print(eval("("*~-len(H)+")[:-1]+".join(map(repr,H)))) ``` The interesting thing is that ``` 'B''a''c''k''h''a''n''d''e''d'[:-1][:-1][:-1][:-1][:-1][:-1] ``` actually works and gives `'Back'`, so I tried to map `^H -> [:-1]` and any other char `c -> 'c'` then `eval`, but unfortunately you can't have any strings afterwards without a `+`, so this fails: ``` 'B''a''c''k''h''a''n''d''e''d'[:-1][:-1][:-1][:-1][:-1][:-1]'s''p''a''c''e''s' ``` [Answer] # Haskell, ~~52~~ 47 bytes ``` import Data.Lists foldl1((++).init).splitOn"^H" ``` Usage example: ``` > map (foldl1((++).init).splitOn"^H") ["Horse^H^H^H^H^HCow", "123^H45^H^H^H78^H", "Digital Trauma^H^H^H^H^H^H^H^H^H^H^H^H^H^HMaria Tidal Tug^H^H^H^H^H^H^H^H^H^H^H^H^H^H^HDigital Trauma"] ["Cow","17","Digital Trauma"] ``` How it works: ``` splitOn"^H" -- split on substring "^H", e.g "Horse^H^H^H^H^HCow" -> ["Horse","","","","","Cow"] . -- then foldl1( ) -- fold from left by init -- first dropping the last char from the left argument (++). -- second concatenating left and right argument ``` [Answer] # Ruby, ~~27~~ ~~24~~ 20 bytes (19 characters code + 1 character command line option.) ``` $_=$`+$'while/.\^H/ ``` Thanks to: * [Ventero](https://codegolf.stackexchange.com/users/84/ventero) for suggesting to use the global variables (-4 characters) Sample run: ``` bash-4.3$ ruby -pe '$_=$`+$'"'"'while/.\^H/' <<< "Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ." Be nice to this gentleman, he's visiting from corporate HQ. ``` [Answer] # [Vim](https://www.vim.org/), 12 bytes ``` qqt^3xh@qq@q ``` [Try it online!](https://tio.run/##JcIxCoAwDAXQq/zNRVy8QHHq6gUKItEG2sa0oXj7Osh7fQxVC@sbnarTMTZC4ZNgAovccImk4H83FUuUjzIj0tTQubFxuXFVyTilPlIPI/h9@QA "V (vim) – Try It Online") Makes use of the fact that "`^` will only appear as `^H`". ### Explanation ``` qqt^3xh@qq@q qq @qq@q Define an indefinitely looping recursive macro and immediately call it t^ Move to just before the next ^ character in the line 3x Delete 3 characters (the one to be deleted, ^, and H) h Move left 1 step (to be in position for the next search) ``` [Answer] # [V (vim)](https://github.com/DJMcMayhem/V), ~~16~~ 14 bytes ``` qq:s/.^H @qq@q ``` [Try it online!](https://tio.run/##JcIxCoAwDAXQ3VP8zUV0dypOXb2AUCRqQBvThl4/DvJec1ed6zRusQuqQd0XQuadYAK7uOIQubf4OynbTU/KAy7qKxpXNs4njiIPdimvlGSEuI4f "V (vim) – Try It Online") similar to sed, but uses Vim's recursion. [Answer] # Pyth - 19 bytes Reduce works really, really well with this but it only does one char at a time so I had to spend almost as many chars as the actual algo to do a replace `^H` with linebreak. Looking for a better way to do that. ``` u?+GHnHbPGjbcz"^H"k ``` [Try it online here](http://pyth.herokuapp.com/?code=u%3F%2BGHnHbPGjbcz%22%5EH%22k&input=Be%20nice%20to%20this%20fool%5EH%5EH%5EH%5EHgentleman%2C%20he%27s%20visiting%20from%20corporate%20HQ.&debug=1). [Answer] # Python 2, 50 It's a bit odd having a second `lambda` in there, but seems to be the best Python so far. ``` lambda s:reduce(lambda a,b:a[:-1]+b,s.split('^H')) ``` [Answer] # Julia, ~~41~~ 39 bytes ``` s->foldl((t,v)->chop(t)v,split(s,"^H")) ``` What it's doing is using ^H as a delimiter, and then removing the last character on each string then concatenating the next string before removing the last character again. Unlike the other Julia answer, this is not a recursive function. Note: I've removed the function name from the definition. Originally, it said `f(s)=` rather than `s->`, and you used it as `f("AAA^HB^H^H")`... but I'm saving two bytes by letting it be "anonymous", and use itself as its name. You use it like this: ``` (s->foldl((t,v)->chop(t)v,split(s,"^H")))("AAA^HB^H^H") ``` (you can also assign a variable to it as `f=s->foldl((t,v)->chop(t)v,split(s,"^H"))`, then `f("AAA^HB^H^H")` will work) [Answer] # [TeaScript](http://github.com/vihanb/TeaScript), 7 bytes [Not competing] **Not competing** as TeaScript was made after this challenge was posted. This is here as reference. ``` xW/.\^H ``` This uses the new TeaScript 3, and recursive replaces to remove the characters [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 81 bytes ``` >,[[>+>+<<-]-[>-<---]>---------[>>+<<[-]]>>-[+<[-]<<<,[-]>>]<[<<+>>-]<,]<[<]>[.>] ``` [Try it online!](https://tio.run/##fUyrDsMwEPuV8uT2BZbRQElZ2ekqXTe1Ou0BouX7swYMDGw2sGVbXovHc6uXW2vMqkxMgJgoBSJilA@UvVIxI0VTdwDyIaRBgXTkhty9UU@01s6xx8vvw1y8PnwZf3PyEj7Mce3ruv@bLuP37Rs "brainfuck – Try It Online") [Answer] # K5, 64 bytes K isn't really designed for this kind of work... ``` {[s]$[2>#s;s;`=t:*&{"^H"~2#x_s}'1+!-2+#s;s;,/2#2!|(0,t,3+t)_s]}/ ``` [Answer] # golflua, 36 bytes ``` \f(s)@o!=s o=s;s=s:g(".^H","",1)$~s$ ``` Sample run: ``` Lua 5.2.2 Copyright (C) 1994-2013 Lua.org, PUC-Rio > \f(s)@o!=s o=s;s=s:g(".^H","",1)$~s$ > w(f("Be nice to this fool^H^H^H^Hgentleman, he's visiting from corporate HQ.")) Be nice to this gentleman, he's visiting from corporate HQ. ``` [Answer] # Javascript, 62 bytes Not the shortest one, but works fine. ``` t=prompt();while(t.match(R=/.\^H/))t=t.replace(R,'');alert(t); ``` This probably can be shortened a lot! [Answer] # R, ~~54~~ 52 bytes ``` f=function(s)ifelse(s==(r=sub(".\\^H","",s)),r,f(r)) ``` Same basic idea as [my Julia answer](https://codegolf.stackexchange.com/a/52959/20469). This creates a recursive function that accepts a string and returns a string. If the input is equal to itself with a single occurrence of `^H` removed, return it, otherwise call the function again. You can [try it online](http://www.r-fiddle.org/#/fiddle?id=FJNnw6Xp)! [Answer] # ECMAScript 6, 57 bytes ``` s=>{while(~s.indexOf`^H`)s=s.replace(/.\^H/,'');return s} ``` This is ~~probably golfable, just gotta think of a way~~ probably not [Answer] # Java, ~~78~~ 77 bytes ``` String f(String a){while(!a.equals(a=a.replaceFirst(".\\^H","")));return a;} ``` [Answer] # (Visual)FoxPro any version 80 bytes ``` PARA t DO WHILE AT('^H',t)>0 t = STRT(t,SUBS(t,AT('^H',t)-1,3)) ENDDO RETU t ``` Repeating string translation to empty by finding ^H and backing up one character. [Answer] # rs, 8 bytes Technically, this doesn't count, as it depends on a feature I added after this question was posted. However, I think it's pretty neat. ``` +?1.\^H/ ``` [Live demo and test cases](http://kirbyfan64.github.io/rs/index.html?script=%2B%3F1.%5C%5EH%2F&input=Horse%5EH%5EH%5EH%5EH%5EHCow%0ABe%20nice%20to%20this%20fool%5EH%5EH%5EH%5EHgentleman%2C%20he%27s%20visiting%20from%20corporate%20HQ.%0A123%5EH45%5EH%5EH%5EH78%5EH%0ADigital%20Trauma%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EHMaria%20Tidal%20Tug%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EH%5EHDigital%20Trauma). [Answer] # Vim, ~~38~~ 35 bytes Saved 3 bytes thanks to Leo! ``` qa:%s/\([^H]\|\^\@<!.\)\^H//g @aq@a ``` [Try it online!](https://tio.run/##K/v/vzDRSrVYP0YjOs4jNqYmJi7GwUZRL0YzJs5DXz@dyyGx0CHx/3@P/KLi1DgPGHTOLwcA "V (vim) – Try It Online") See [Razetime's answer](https://codegolf.stackexchange.com/a/223119/95792) for a shorter and smarter version of this. ``` qa:%s/\([^H]\|\^\@<!.\)\^H//g @aq@a qa Start recording a macro a :%s/ Substitute in entire file \([^H]\|\^\@<!H\) Regex for the character to be deleted [^H] A character that isn't H \| or H an H \^\@<! that doesn't have a ^ before it \^H All of that followed by ^H // Replace with empty string g Global flag so it replaces multiple times Enter the command @a Recursively call macro a q Stop recording @a Run the macro ``` ``` ]
[Question] [ So, last week I posted a challenge to play [Duck, Duck, Goose](https://codegolf.stackexchange.com/questions/157897/duck-duck-goose). This lead to a number of Minnesotans commenting about their regional ['Gray duck' variation](https://en.wikipedia.org/wiki/Duck,_duck,_goose#Duck,_Duck,_Gray_Duck). So here's the rules: Using this list of colours: ``` Red Orange Yellow Green Blue Indigo Violet Gray ``` Write a program to follow these rules: 1. Select one of these colours, and prepend it to the word 'duck' and print the result to a new line. 2. If the colour was not 'Gray', repeat step 1. 3. If the colour was 'Gray', end your program. Rules which must be followed: * The program should not consistently print the same number of lines. * It can begin on 'Gray duck', but should not do consistently. * There should be exactly one duck on each line and no empty lines are output. * There should be at least one space between a colour and a duck. * White space before and after the significant output does not matter. * The case of the output doesn't matter. * Colours can be repeated. * The output doesn't have to contain every colour every time, but it must be possible that your code will output every colour. * No colours outside the above array can be included. * Either grey or gray are acceptable in your answer. * Colours should not consistently be in the same order. * Aim for the shortest program. Smallest number of bytes wins. Example output: ``` Green duck Orange duck Yellow duck Indigo duck Yellow duck Gray duck ``` Thanks to @Mike Hill for first alerting me to this variation. [Answer] ## LuaLaTeX, 220 211 characters command: ``` lualatex -interaction nonstopmode ``` Not the shortest, but the fanciest. Based on [@skillmon's solution](https://codegolf.stackexchange.com/a/159706/79196) [![enter image description here](https://i.stack.imgur.com/p4dBo.png)](https://i.stack.imgur.com/p4dBo.png) ``` \RequirePackage{tikzducks}\newcount\b\let~\def~\0{red}~\1{orange}~\2{yellow}~\3{green}~\4{blue}~\5{cyan}~\6{violet}~\7{gray}\loop\b\uniformdeviate8\tikz\duck[body=\csname\the\b\endcsname]; \ifnum\b<7\repeat\stop ``` [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 124 bytes ``` 00 C0 AD 12 D0 85 02 A2 17 8E 18 D0 A5 02 F0 03 0A 90 02 49 1D 85 02 A8 CA 10 02 A2 2F BD 42 C0 D0 F6 88 D0 F3 86 FB E8 BD 42 C0 F0 06 20 16 E7 E8 D0 F5 AA BD 73 C0 F0 06 20 16 E7 E8 D0 F5 A6 FB D0 C9 60 00 C7 52 45 59 00 D2 45 44 00 CF 52 41 4E 47 45 00 D9 45 4C 4C 4F 57 00 C7 52 45 45 4E 00 C2 4C 55 45 00 C9 4E 44 49 47 4F 00 D6 49 4F 4C 45 54 00 20 44 55 43 4B 0D 00 ``` **[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%22duck.prg%22:%22data:;base64,AMCtEtCFAqIXjhjQpQLwAwqQAkkdhQKoyhACoi+9QsDQ9ojQ84b76L1CwPAGIBbn6ND1qr1zwPAGIBbn6ND1pvvQyWAAx1JFWQDSRUQAz1JBTkdFANlFTExPVwDHUkVFTgDCTFVFAMlORElHTwDWSU9MRVQAIERVQ0sNAA==%22%7D,%22vice%22:%7B%22-autostart%22:%22duck.prg%22%7D%7D)** -- Usage: `SYS49152`. [![screenshot](https://i.stack.imgur.com/Ibyb1.png)](https://i.stack.imgur.com/Ibyb1.png) --- ### Explanation (commented disassembly): ``` 00 C0 .WORD $C000 ; load address .C:c000 AD 12 D0 LDA $D012 ; current rasterline as seed .C:c003 85 02 STA $02 ; to "random" value .C:c005 A2 17 LDX #$17 ; cfg for upper/lower, also use as .C:c007 8E 18 D0 STX $D018 ; initial index into colors array .C:c00a .loop: .C:c00a A5 02 LDA $02 ; load current random val .C:c00c F0 03 BEQ .doEor ; zero -> feedback .C:c00e 0A ASL A ; shift left .C:c00f 90 02 BCC .noEor ; bit was shifted out -> no feedback .C:c011 .doEor: .C:c011 49 1D EOR #$1D .C:c013 .noEor: .C:c013 85 02 STA $02 ; store new random val .C:c015 A8 TAY ; use as counter for next color string .C:c016 .findloop: .C:c016 CA DEX ; next char pos in colors (backwards) .C:c017 10 02 BPL .xok ; if negative ... .C:c019 A2 2F LDX #$2F ; load length of colors - 1 .C:c01b .xok: .C:c01b BD 42 C0 LDA .colors,X ; load character from colors .C:c01e D0 F6 BNE .findloop ; not zero, try next character .C:c020 88 DEY ; decrement random counter .C:c021 D0 F3 BNE .findloop ; not zero, continue searching .C:c023 86 FB STX $FB ; save character position .C:c025 E8 INX ; increment to start of color .C:c026 .outloop: .C:c026 BD 42 C0 LDA .colors,X ; output loop for color string .C:c029 F0 06 BEQ .duckout .C:c02b 20 16 E7 JSR $E716 .C:c02e E8 INX .C:c02f D0 F5 BNE .outloop .C:c031 .duckout: .C:c031 AA TAX ; A is now 0, use as char pos for duck .C:c032 .duckoutloop: .C:c032 BD 73 C0 LDA .duck,X ; output loop for duck string .C:c035 F0 06 BEQ .outdone .C:c037 20 16 E7 JSR $E716 .C:c03a E8 INX .C:c03b D0 F5 BNE .duckoutloop .C:c03d .outdone: .C:c03d A6 FB LDX $FB ; load saved character position .C:c03f D0 C9 BNE .loop ; not zero -> continue main loop .C:c041 60 RTS ; zero was start of "Grey" -> done .C:c042 .colors: .C:c042 00 c7 52 45 .BYTE 0, "Gre" .C:c046 59 00 d2 45 .BYTE "y", 0, "Re" .C:c04a 44 00 cf 52 .BYTE "d", 0, "Or" .C:c04e 41 4e 47 45 .BYTE "ange" .C:c052 00 d9 45 4c .BYTE 0, "Yel" .C:c056 4c 4f 57 00 .BYTE "low", 0 .C:c05a c7 52 45 45 .BYTE "Gree" .C:c05e 4e 00 c2 4c .BYTE "n", 0, "Bl" .C:c062 55 45 00 c9 .BYTE "ue", 0, "I" .C:c066 4e 44 49 47 .BYTE "ndig" .C:c06a 4f 00 d6 49 .BYTE "o", 0, "Vi" .C:c06e 4f 4c 45 54 .BYTE "olet" .C:c072 00 .BYTE 0 .C:c073 .duck: .C:c073 20 44 55 43 .BYTE " duc" .C:c077 4b 0d 00 .BYTE "k", $d, 0 ``` [Answer] ## [Perl 5](https://www.perl.org/), 79 bytes ``` say$_=(Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet)[rand 8]." duck"until/y/ ``` [Try it online!](https://tio.run/##K0gtyjH9/784sVIl3lbDvSi1UicoNUXHvygxLz1VJzI1Jye/XAconJqn45RTmqrjmZeSmZ6vE5aZn5NaohkNVJaiYBGrp6SQUpqcrVSaV5KZo1@p////v/yCksz8vOL/ur6megaGBgA "Perl 5 – Try It Online") [Answer] # [Taxi](https://bigzaphod.github.io/Taxi/), 1995 bytes ``` Go to Heisenberg's:w 1 r 3 r 1 l.[a]Pickup a passenger going to Divide and Conquer.8 is waiting at Starchild Numerology.8 is waiting at Starchild Numerology.Go to Starchild Numerology:n 1 l 3 l 1 l 3 l.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Multiplication Station.Go to Divide and Conquer:w 1 r 3 r 1 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 What's The Difference.Pickup a passenger going to Trunkers.Go to Zoom Zoom:n.Go to Trunkers:w 3 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:w 2 r 1 l.Pickup a passenger going to Multiplication Station.1 is waiting at Starchild Numerology.Go to Starchild Numerology:e 1 r 1 l 3 l.Pickup a passenger going to Addition Alley.Go to Multiplication Station:w 1 r 2 r 1 r 4 l.Pickup a passenger going to Addition Alley.Go to Addition Alley:n 2 l 1 r 3 l 1 l.Pickup a passenger going to The Underground.'Red duck\n' is waiting at Writer's Depot.'Orange duck\n' is waiting at Writer's Depot.'Yellow duck\n' is waiting at Writer's Depot.'Green duck\n' is waiting at Writer's Depot.'Blue duck\n' is waiting at Writer's Depot.'Indigo duck\n' is waiting at Writer's Depot.'Violet duck\n' is waiting at Writer's Depot.'Grey duck' is waiting at Writer's Depot.Go to Writer's Depot:n 1 l 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 3 r 1 l 1 r.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Writer's Depot:s 2 r 1 l 2 l.Switch to plan "b".[c]Go to Narrow Path Park:n 4 l.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Writer's Depot:s 1 r 1 l 2 l.Switch to plan "a" if no one is waiting.[d]Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 2 r.Go to Writer's Depot:n 1 l.Switch to plan "e" if no one is waiting.Switch to plan "d".[e]Go to Heisenberg's:n 3 r 3 r.Switch to plan "a". ``` [Try it online!](https://tio.run/##pVXBbtswDP0VIhffDCTpocita4Fuh7VB063YshwUi7EJq5JHy8vy9Zlsy0XiOo6bHWwh1DP5yEcyVvyl/f7egDXwGSlHvUaOg3y2hTEwTN0zBhUuxWpOUVpkICATuYPFyBAb0nH55R39IYkgtIRbo38XyOE1UA5bQbaECAsLKzhKSEl4KF6RjTLxbhioJtd1NdMlOUdSNWf4QZZ98K@FspQpioQlo0sC5enpvPd1VDGGSX32RrjdRcpo9C79rxlWyZTP5ExCL4mwQQ7PCTo@mw0y6gh7v3jmQqfIuQ/505jX6jVr8moALpvpRdFrN513zufE99MFdR//Z69gJcuQPrmRkqrQN0ph47OblRfdiw1Xl3g@NrqenlTyc9PX/YK6Cn/T0s0sm0LLMHhCCbKI0l86aBXshckiO1XuMDM2DB5ZOF8DwT9QKbMdCL5nRD0Q@0kVQzl80ZJiMxD8nYxCO5zwroKeAfrmPjL6JVRtyXXvlnwQzK6Gc2ET9@LUu2ubnUO/dqsF4ufyWOe6m8PFlmyUlPeZEhpG0QhoA9qA2yMHmXyogzpzzJvJrXZSO@x6FC6j1clszk3F3OQWHjcbelsfBxY/t1d@cZxgN@5hJ04UZSl71VoUWu9gkRLmh2q1zdW8ck9nvOODJ/i0cdJVFVcdf811f0w79BejcL//Bw "Taxi – Try It Online") I think it's worth noting that 47% of this code is just picking a random integer from 1 to 8. Also, Taxi is so verbose that it is way shorter to hard code the `duck\n` after each color rather than concatenating it later. Here's the un-golfed version: ``` Go to Heisenberg's: west 1st right 3rd right 1st left. [Pick up a random INT 1-8 going to The Underground] [a] Pickup a passenger going to Divide and Conquer. 8 is waiting at Starchild Numerology. 8 is waiting at Starchild Numerology. Go to Starchild Numerology: north 1st left 3rd left 1st left 3rd left. Pickup a passenger going to Divide and Conquer. Pickup a passenger going to Multiplication Station. Go to Divide and Conquer: west 1st right 3rd right 1st right 2nd right 1st right. Pickup a passenger going to Cyclone. Go to Cyclone: east 1st left 1st left 2nd left. Pickup a passenger going to What's The Difference. Pickup a passenger going to Trunkers. Go to Zoom Zoom: north. Go to Trunkers: west 3rd left. Pickup a passenger going to What's The Difference. Go to What's The Difference: west 2nd right 1st left. Pickup a passenger going to Multiplication Station. 1 is waiting at Starchild Numerology. Go to Starchild Numerology: east 1st right 1st left 3rd left. Pickup a passenger going to Addition Alley. Go to Multiplication Station: west 1st right 2nd right 1st right 4th left. Pickup a passenger going to Addition Alley. Go to Addition Alley: north 2nd left 1st right 3rd left 1st left. Pickup a passenger going to The Underground. [Use the random INT to select a color] 'Red duck\n' is waiting at Writer's Depot. 'Orange duck\n' is waiting at Writer's Depot. 'Yellow duck\n' is waiting at Writer's Depot. 'Green duck\n' is waiting at Writer's Depot. 'Blue duck\n' is waiting at Writer's Depot. 'Indigo duck\n' is waiting at Writer's Depot. 'Violet duck\n' is waiting at Writer's Depot. 'Grey duck' is waiting at Writer's Depot. Go to Writer's Depot: north 1st left 1st left. [b] Pickup a passenger going to Narrow Path Park. Go to Narrow Path Park: north 3rd right 1st left 1st right. Go to The Underground: east 1st right. Switch to plan "c" if no one is waiting. Pickup a passenger going to The Underground. Go to Writer's Depot: south 2nd right 1st left 2nd left. Switch to plan "b". [Output the selected color] [c] Go to Narrow Path Park: north 4th left. Pickup a passenger going to Post Office. Go to Post Office: east 1st right 4th right 1st left. [If the color was grey, exit by error] Go to Writer's Depot: south 1st right 1st left 2nd left. Switch to plan "a" if no one is waiting. [Get rid of the rest of the colors] [You could throw them off a bridge but you won't get paid] [d] Pickup a passenger going to Sunny Skies Park. Go to Sunny Skies Park: north 2nd right. Go to Writer's Depot: north 1st left. Switch to plan "e" if no one is waiting. Switch to plan "d". [Start over from the beginning] [e] Go to Heisenberg's: north 3rd right 3rd right. Switch to plan "a". ``` [Answer] # [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 133 bytes ``` v->{for(int x=9;x>0;)System.out.println("Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet".split(",")[x+=Math.random()*8-x]+" duck");} ``` [Try it online!](https://tio.run/##HY69asMwFIV3P8XFk5XIomODaw/tUDqEQgOBEjKosuzIkSUhXbkOwc/uqpkOfOeHM/CJl9ZJM7TX3apGZz3CkCCLqDTrohGorGGbKhOahwB7rgzcMwAXf7QSEJBjksmqFsbkFQf0yvSnM3DfB/KIArxZE@Io/csx5RrooF6nsrl31hfKIMz1rpqbp4ocbgHlyGxE5tIMalPk717e6Jds6afnppf0W2ptf2nC0tBXHSX9MK3qLT0qqyXmLDitsMhpTk7ztt5zvLDUbO1YkM1zOZ@3ObRRXHNSLWv1uNcxLoR0WJioNflnS7asfw "Java (OpenJDK 9) – Try It Online") ## Explanations ``` v->{ // Void-accepting void lambda function for(int x=9;x>0;) // Loop until x is zero System.out.println( // Print... "Grey,Red,Orange, // colors, "Grey" first Yellow,Green,Blue, // more colors Indigo,Violet" // more colors .split(",") // as an array [x+=Math.random()*8-x] // pick one randomly, use implicit double to int cast with "x+=<double>-x" trick +" duck"); // Oh, and append " duck" to the color. } ``` [Answer] # [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, 133 bytes ``` f={s="";v=s;while{v!="grey"}do{v=["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Grey"]select random 7;s=s+v+" duck\n"};s} ``` **Call with:** ``` hint call f ``` **Example output:** [![](https://i.stack.imgur.com/bnkbn.jpg)](https://i.stack.imgur.com/bnkbn.jpg) At first I somehow misread the challenge as if the goal was to just output a varying amount of lines, not necessarily ending at the "Grey duck" -line. Following that incorrect interpretation produced a slightly more interesting piece of code: ``` f={s="";c=[1];c set[random 9,0];{s=s+(["Red","Orange","Yellow","Green","Blue","Indigo","Violet","Grey"]select random 7)+" duck\n"}count c;s} ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~93 91 90 89 87 86~~ 85 bytes Thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) for saving 2 bytes, [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) 1 byte and [Asone Tuhid](https://codegolf.stackexchange.com/users/77598/asone-tuhid) 1 byte! ``` puts %w(Red Orange Yellow Green Blue Indigo Violet Grey)[$.=rand(8)]+" duck"while$.<7 ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFhBtVwjKDVFwb8oMS89VSEyNScnv1zBvSg1NU/BKac0VcEzLyUzPV8hLDM/J7UEJFGpGa2iZwtUnqJhoRmrraSQUpqcrVSekZmTqqJnY/7/PwA "Ruby – Try It Online") [Answer] # pdfTeX, 231 220 219 209 207 bytes ``` \newcount\b\let~\def~\0{Red}~\1{Orange}~\2{Yellow}~\3{Green}~\4{Blue}~\5{Indigo}~\6{Violet}~\7{Gray}~\9{ }\newlinechar`z\loop\b\pdfuniformdeviate8\message{z\csname\the\b\endcsname\9duck}\ifnum\b<7\repeat\bye ``` # LuaTeX, 216 ~~206~~ 204 bytes ``` \newcount\b\let~\def~\0{Red}~\1{Orange}~\2{Yellow}~\3{Green}~\4{Blue}~\5{Indigo}~\6{Violet}~\7{Gray}~\9{ }\newlinechar`z\loop\b\uniformdeviate8\message{z\csname\the\b\endcsname\9duck}\ifnum\b<7\repeat\bye ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~42~~ 40 bytes Saved 2 bytes thanks to *Erik the Outgolfer* ``` [“ëßigo°¯†¾›ÈŠÛˆ¨‡—°Íolet“#7ÝΩ©è'Ðœðý,®# ``` [Try it online!](https://tio.run/##AVMArP8wNWFiMWX//1vigJzDq8OfaWdvwrDCr@KAoMK@4oC6w4jFoMOby4bCqOKAoeKAlMKww41vbGV04oCcIzfDnc6pwqnDqCfDkMWTw7DDvSzCriP//w "05AB1E – Try It Online") [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 68 bytes ``` "Grey"," Red Orange Yellow Green Blue Indigo Violet"ṇṛS," duck"ẉS¬?↰ ``` [Try it online!](https://tio.run/##SypKTM6ozMlPN/r/X8m9KLVSSUeJKyg1hcu/KDEvPZUrMjUnJ7@cCyiTmsfllFOayuWZl5KZns8Vlpmfk1qi9HBn@8Ods4N1lBRSSpOzlR7u6gw@tMb@UduG//8B "Brachylog – Try It Online") [Answer] # [Ruby](https://www.ruby-lang.org/), ~~84~~ 81 bytes Thanks to Dom Hastings for -3 bytes. ``` puts$_=%w[Red Orange Yellow Green Blue Indigo Violet Grey].sample+" duck"until/y/ ``` [Try it online!](https://tio.run/##KypNqvz/v6C0pFgl3la1PDooNUXBvygxLz1VITI1Jye/XMG9KDU1T8EppzRVwTMvJTM9XyEsMz8ntQQkURmrV5yYW5CTqq2kkFKanK1UmleSmaNfqf//PwA "Ruby – Try It Online") [Answer] # Bash + GNU utilities, 72 ``` shuf -e {Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey}\ Duck|sed /y/q ``` [Try it online](https://tio.run/##S0oszvj/vzijNE1BN1WhOig1Rce/KDEvPVUnMjUnJ79cx70oNTVPxymnNFXHMy8lMz1fJywzPye1BCRRWRuj4FKanF1TnJqioF@pX/j/PwA). [Answer] # PHP, 89 bytes ``` do echo[Grey,Red,Orange,Yellow,Green,Blue,Indigo,Violet][$i=rand()%8]," Duck ";while($i); ``` Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/d46be81de712f91a00fdaf2eb781d265af8bf13b). [Answer] # [><>](https://esolangs.org/wiki/Fish), 107 bytes ``` x<>" duck"a> x<^"deR" x<^"egnarO" x<^"wolleY" x<^"neerG" x<^"eulB" x<^"ogidnI" x<^"teloiV" x"Grey duck"r>o| ``` [Try it online!](https://tio.run/##S8sszvj/v8LGTkkhpTQ5WynRjqvCJk4pJTVICcxITc9LLPKHsMvzc3JSIyHsvNTUIneoktIcJwgrPz0zJc8Twi5JzcnPDAOyldyLUishhhfZ5df8/w8A "><> – Try It Online") [Answer] # JavaScript, 104 bytes ``` f=_=>`grey,red,orange,yellow,green,blue,indigo,violet`.split`,`[n=Math.random()*8|0]+` duck ${n?f():``}` ``` [Try it online](https://tio.run/##DctBCsIwEADAu6/w4CHRtXgUofoCXyDixmYbY@NuSdJKUd8eex2YpxlNaqLv85bFUmmEkwSqgjilSlvf6iO6SBNEsiDRsCOYKAR5w8zEcA8DgWfrncDo55qxSn3wGQEvXJ9NflRzs/JSer3/7q4bXNqh6RarD59apQ@IPyxaaV3@) [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~114~~ 112 bytes ``` do disp([strsplit('Red Orange Yellow Green Blue Indigo Violet'){i=randi(7)},' duck'])until i>6 disp('Grey duck') ``` [Try it online!](https://tio.run/##JYy9CgIxDIB3nyJbWnDWSQcXcRIcBBGH4xKOYGiONvU4xGevh87fj/Xevbg1MiApY7gXz2VU8YAXJjjnLg0MN1a1CY6ZOcFBK8MpkQwGVzFlx/iW3WKShG38rBGo9k98xJpcFGS/Wf3euPTzn8XWvg "Octave – Try It Online") There are a bunch of different options that are all between 112 and 118 bytes... Some initialize an index in the start and decrements it by a random number for each loop, and waits until it's **0**. Others use `printf` instead of `disp` to avoid some brackets and so on. [Answer] # [PHP](http://php.net/), ~~133~~ ~~125~~ ~~111~~ ~~108~~ ~~97~~ 92 bytes ``` <?for(;$b=[Red,Orange,Yellow,Green,Blue,Indigo,Violet][rand(0,7)];)echo"$b duck "?>Grey duck ``` [Try it online!](https://tio.run/##K8go@P/fxj4tv0jDWiXJNjooNUXHvygxLz1VJzI1Jye/XMe9KDU1T8cppzRVxzMvJTM9XycsMz8ntSQ2GqgsRcNAx1wz1lozNTkjX0klSSGlNDmbS8neDqirEsz5//9ffkFJZn5e8X/dFIXijPyikvj8gtS8@JLEdNv8PAA) -8 bytes thanks to [@Olivier Grégoire](https://codegolf.stackexchange.com/users/16236/olivier-gr%C3%A9goire) -3 bytes thanks to [@manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) -11 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) [Answer] # [Python 2](https://docs.python.org/2/), ~~138~~ ~~133~~ ~~120~~ ~~117~~ 116 bytes ``` import os while id:id=ord(os.urandom(1))%8;print"Grey Red Orange Yellow Green Blue Indigo Violet".split()[id],'duck' ``` [Try it online!](https://tio.run/##DcmxCsIwEADQ3a84CtIEpKCTKC4u4iQ4CCIO4h3t4TUXLgmlXx@7vhfnPGjY1cpjVMugaTUNLASMB8aTGjpNXbFPQB3d1vv1/hiNQ24uRjPcCeG2ZE/wJBGdYGEKcJZCcA3IvcKDVSg3XYrC2fkX43vTYvn@2lr/ "Python 2 – Try It Online") Much better with some ideas from @EriktheOutgolfer. Thanks! -3 more with thanks to @ovs -1 with thanks to @Rod for a cool new trick learned :-) [Answer] # Python 3, 130, 128, 127, 126, 125 bytes ``` from random import* d,c=1,'Grey Red Orange Yellow Green Blue Indigo Violet'.split() while d!=c[0]:d=choice(c);print(d,'duck') ``` -1 by @ElPedro! -1 by me -1 by @Bubbler! [Try it online!](https://repl.it/repls/WeakParallelDivisor) [Answer] ## bash, 96 bytes ``` a=(Grey Red Orange Yellow Green Blue Indigo Violet);for((i=1;i;));{ echo ${a[i=RANDOM%8]} duck;} ``` Thanks to @DigitalTrauma. [Answer] # [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 114 bytes ``` {srand();for(split("Red9Orange9Yellow9Green9Blue9Indigo9Violet9Grey",A,9);r<8;print A[r]" duck")r=int(8*rand()+1)} ``` [Try it online!](https://tio.run/##SyzP/v@/urgoMS9FQ9M6Lb9Io7ggJ7NEQykoNcXSHyicnmoZmZqTk19u6V6Umppn6ZRTmmrpmZeSmZ5vGZaZn5NaApKoVNJx1LHUtC6ysbAuKMrMK1FwjC6KVVJIKU3OVtIssgWKaFhoQWzRNtSs/f@fCwA "AWK – Try It Online") **Explanation** ``` {srand(); # Seed rand to obtain different sequence each run for( split("Red9Orange9Yellow9Green9Blue9Indigo9Violet9Grey", A,9); # Split on 9 to avoid using '"'s r<8; print A[r]" duck") # Print the colored ducks r=int(8*rand()+1) # AWK uses 1-indexing not 0-indexing when splitting strings into arrays } ``` Note that this requires "some" input. The input can be empty. To avoid the need for input prepend the first line with `BEGIN` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 94 bytes ``` for(;$r-ne'Grey'){$r=-split"Red Orange Yellow Green Blue Indigo Violet Grey"|Random;"$r Duck"} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/Py2/SMNapUg3L1XdvSi1Ul2zWqXIVre4ICezRCkoNYXLvygxLz2VKxKoOL@cC6gkNY/LKac0lcszLyUzPZ8rLDM/J7UEJFGpVBOUmJeSn2utpFKk4FKanK1U@/8/AA "PowerShell – Try It Online") Loops until `$r` is equal to `Grey`. Inside the loop, `-split`s the literal string on newlines, chooses a `Random` one thereof, then prints out the color plus `Duck` (technically, it's left on the pipeline and pipeline cleanup on the next loop iteration causes a `Write-Output` to happen). Note that it's theoretically possible for `Grey` to never be chosen, and the loop to continue infinitely, but this almost never (in the probability sense) will happen. [Answer] # [R](https://www.r-project.org/), 101 bytes ``` cat(paste(c(sample(scan(,""),rexp(1),T),"gray"),"duck\n")) Red Orange Yellow Green Blue Indigo Violet ``` [Try it online!](https://tio.run/##DcixCgIxDADQPZ@RKYUu/oKL3CSICIJLaEM5jGlJe9z59dU3Pp8z8aDGfQgl6vxpKtQTG0XEEF2ORqcQ7yFicf7@C/OW3i/DEOAmGa7OVgSeolp3uLiIwVk3gcXyWio81qoy5vwB "R – Try It Online") Heavily inspired by [@user2390246's answer](https://codegolf.stackexchange.com/a/157920/67312) to the related challenge. We need two sources of randomness: Changing the order of the colors and sampling the non-gray duck colors. The `sample` will take a random sample of random size given by an exponential distribution with rate parameter `1`, truncated to an integer. Using an exponential distrubtion unfortunately means that there is a probability of `exp(-8)` or around `0.0003354` that the sample will be at least `8`, so we have to sample with `replace=T`. [Answer] ## [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~69~~ 68 bytes *Thanks to Leo for saving 1 byte.* ``` .^/y/{K`Red¶Orange¶Yellow¶Green¶Blue¶Indigo¶Violet¶Grey " duck¶">?G` ``` [Try it online!](https://tio.run/##K0otycxLNPz/Xy9Ov1K/2jshKDXl0Db/osS89NRD2yJTc3Lyyw9tcy9KTc07tM0ppxQo6JmXkpmef2hbWGZ@TmoJWLKSS0khpTQ5@9A2JTt794T//wE "Retina – Try It Online") ### Explanation ``` ./y/^{K`Red¶Orange¶Yellow¶Green¶Blue¶Indigo¶Violet¶Grey ``` `.` suppresses implicit output at the end of the program (otherwise, we'd get two grey ducks). `/y/^{` wraps the entire program in a loop which continues as long as the working string doesn't contain a `y`. The rest of that line sets the working string to a linefeed-separated list of all the colours. ``` " duck¶">G?` ``` We grep a random line from the working string (and therefore a random colour). And we print the result with a trailing `duck` and a linefeed. [Answer] # [MATL](https://github.com/lmendo/MATL), ~~68~~ 64 bytes ``` `'DYCIXMSQ(qm#Q$4{#is,Gh1(=lAjUSId;&'F2Y232hZaYb8YrX)' duck'h7Mq ``` [Try it online!](https://tio.run/##y00syfn/P0HdJdLZM8I3OFCjMFc5UMWkWjmzWMc9w1DDNscxKzTYM8VaTd3NKNLI2CgjKjEyySKyKEJTXSGlNDlbPcPct/D/fwA) # Explanation ``` ` % Do...while 'DYCI···Id;&' % Push this string (to be decompressed by base conversion) F % Push false 2Y2 % Push string 'abc...xyz' 32 % Push 32 (ASCII for space) h % Concatenate horizontally. Gives 'abc...xyz ' Za % Base-convert from alphabet of all printable ASCII % characters except single quote (represented by input % false) to alphabet 'abc...xyz '. Produces the string % 'grey red ··· violet' Yb % Split on space. Gives a cell array of strings 8Yr % Random integer from 1 to 8, say k X) % Get the content of the k-th cell ' duck' % Push this string h % Concatenate horizontally 7M % Push k again q % Subtract 1 % Implicit end. Run a new iteration if top of the stack % is non-zero % Implicit display ``` [Answer] # [Python 2](https://docs.python.org/2/), 98 bytes **Look ma no imports!** ``` v=0 while 1:x=id(v)%97%8;print"GVIYORGBrinererleodladeuyliln ee egog n towe"[x::8],"duck";v=1/x,v ``` (Prints extra spaces between the colours and `duck` as allowed in the question) **[Try it online!](https://tio.run/##K6gsycjPM/r/v8zWgKs8IzMnVcHQqsI2M0WjTFPV0lzVwrqgKDOvRMk9zDPSP8jdCchJLUotyknNT8lJTEktrczJzMlTSE1VSE3PT1fIU1AoyS9PVYqusLKyiNVRSilNzlayLrM11K/QKfv/HwA "Python 2 – Try It Online")** A pretty poor pseudo-random number generator seeded with the object id of **0** (but it seems to fit the spec) which repeatedly yields an integer, `x`, in **[0,7]** which is used to slice a list of characters from that index in steps of **8** to get the colour name which is printed along with `duck` as a tuple, forcing a space in-between. When `x` becomes zero `Grey` is printed and the evaluation of the next input to the modulo based random number generator errors attempting to divide by zero (`v=1/x,v` tries to make a new tuple with the first element `1/x` = `1/0`) --- Same way is 100 in Python 3 with ``` v=0 while 1:x=id(v)%17%8;print("GVIYORGBrinererleodladeuyliln ee egog n towe"[x::8],"duck");v=1/x,v ``` [Answer] # [Java (JDK 10)](http://jdk.java.net/), 287 bytes ``` Random r=new Random();int i;String c;do{i=r.nextInt(8);switch(i){case 0:c="Red";break;case 1:c="Orange";break;case 2:c="Yellow";break;case 3:c="Green";break;case 4:c="Blue";break;case 5:c="Indigo";break;case 6:c="Violet";break;default:c="Gray";}System.out.println(c+" duck");}while(i!=7) ``` [Try it online!](https://tio.run/##Vc9NS8QwEAbgs/srxp5axOK3YujFi@xBhF0QZPGQTcbutGlSkunWpfS319bioafhfeYDppBHeVnocqCqdp6hGHPaMJl0I612lVgpI0OAN0kWutVZ3ewNKQgseSxHRxqqsRVv2ZPNd18gfR4S6IZ5HXxmsYU5xIkgy0BiHgYltOso86nFH15bjp8SEVpidYgp6ZQMCFfPKos2qCOx9yhL8YfXE757aXNc@M3kn2iMaxd@O/mrR7QLvpv4xTTLI/eTrq2m3C38YfIPcgb53zV@y8bwfF2eItFvT4GxSl3DaT2@yMbG6iIC3agySkTfHshgTOfZYzKIvh9@AQ "Java (JDK 10) – Try It Online") My very first codegolf! Obviously not competitive, just happy to have learned enough Java (currently in CS200) to be able to participate. [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2), 41 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` (’Red ṆỴ »Ẹ Ɓ# Ñɦ ƲỤ ṡʂ Ɓ~’OɼD‘ _*‘+£`Ɓ~Q ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWN101HjXMDEpNUXi4s-3h7i0Kh3Y_3LVD4VijssLhiSeXKRzb9HD3EqDcwlNNQME6oFr_k3tcHjXMUIjXApLahxYnAIUDlxQnJRdDjYQZDQA) #### Explanation ``` ( # While loop ’...’ # (condition) Push compressed string of colours O # Split it on spaces ɼ # Pick a random item from this list D # Duplicate the item ‘ _*‘+ # Append compressed string " duck" £ # Pop and print with a newline `Ɓ~ # Push compressed string "Grey" Q # Check for inequality # (body) Do nothing ``` [Answer] # [Kotlin](https://kotlinlang.org), 122 bytes ``` while({x:Any->println("$x duck");x!="Grey"}("Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey".split(",").shuffled()[0])){} ``` [Try it online!](https://tio.run/##HYu9CsIwFEb3PkUMDgnE4lxR0EWcBAVBxCHYmzb0elvS9I/SZ4/BD850zlfVHi0F0xH7akui1067gkXa7O6dpULOCYszQiZLkvQamdnPYSgtgpjH7EjT5tDE0CMJvh5Z3n0qLnfjas/PDia@CH6DXF2dpgLUExDrQUUDpE7YgbpQbotaPWyN4NX/krYNWi@44jJty84YhFzI1/Yt5byEJfwA "Kotlin – Try It Online") [Answer] # MS-SQL, 158 bytes ``` DECLARE @ VARCHAR(6)a:SELECT @=value FROM STRING_SPLIT('Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey',',')ORDER BY NEWID()PRINT @+' duck'IF @<>'Grey'GOTO a ``` Based largely on [Razvan's excellent answer](https://codegolf.stackexchange.com/a/159627/70172), but using the `STRING_SPLIT` function that is specific to MS-SQL 2016 and later. Also uses a `GOTO` instead of a `WHILE` loop. Formatted: ``` DECLARE @ VARCHAR(6) a: SELECT @=value FROM STRING_SPLIT('Red,Orange,Yellow,Green,Blue,Indigo,Violet,Grey',',') ORDER BY NEWID() PRINT @+' duck' IF @<>'Grey'GOTO a ``` ]
[Question] [ Given a number *n* (0 <= *n* <= 2642245), check if *n* and *n*3 have the same set of digits, and output a truthy or falsey value accordingly. For example, let's check the number 100. 1003 is 1000000. The set of digits in 100 is {0, 1}. The set of digits in 1000000 is {0, 1}. Therefore, 100 should give a truthy value. ### Test cases ``` 0 -> True 1 -> True 10 -> True 107624 -> True 251894 -> True 251895 -> False 102343 -> False ``` Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest bytes wins. [OEIS A029795](http://oeis.org/A029795) [Answer] # Python 3, ~~36~~ 32 bytes ``` lambda x:{*str(x)}=={*str(x**3)} ``` I think this only works in Python 3.5 and later. Four bytes have gone, thanks to Copper. [Answer] # [05AB1E](http://github.com/Adriandmen/05AB1E), 6 bytes 05AB1E uses [CP-1252](http://www.cp1252.com) encoding. ``` 3mê¹êQ ``` [Try it online!](http://05ab1e.tryitonline.net/#code=M23DqsK5w6pR&input=MjUxODk0) **Explanation** ``` 3m # input^3 ê # sorted with duplicates removed Q # is equal to ¹ê # input sorted with duplicates removed ``` [Answer] # C, 73 bytes ``` k;b(i){k=0;while(i)k|=1<<i%10,i/=10;return k;}f(n){return b(n)-b(n*n*n);} ``` Creates the set via bits. Returns `0` for same set, anything else for different sets. Ungolfed: ``` k; b(i){ k=0; while(i) k|=1<<i%10, i/=10; return k; } f(n){ return b(n)-b(n*n*n); } ``` [Answer] # Perl, 31 + 2 (`-pl` flag) = ~~25~~ ~~21~~ ~~18~~ ~~34~~ 33 bytes ``` $_=($==$_**3)!~/[^$_]/*!/[^$=]/ ``` Using: ``` perl -ple '$_=($==$_**3)!~/[^$_]/*!/[^$=]/' <<< 251894 ``` Output: `1\n` or `0\n`. Thanx to @Dada for 3 bytes, Gabriel Benamy for 1 byte, & @Zaid for bug reports. [Answer] # Mathematica, 34 bytes ``` f=Union@*IntegerDigits;f@#==f[#^3]& ``` Direct implementation (unnamed function of one integer argument). [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ,3*\D‘ṬE ``` [Try it online!](http://jelly.tryitonline.net/#code=LDMqXETigJjhuaxF&input=&args=MTA2MjM5) or [verify all test cases](http://jelly.tryitonline.net/#code=LDMqXETigJjhuaxFCsW8w4figqxH&input=&args=MTAwLCAwLCAxLCAxMCwgMTA3NjI0LCAyNTE4OTQsIDI1MTg5NSwgMTAyMzQzLCAxMDYyMzksIDIxMDM4NjksIDE2NTY0). ### How it works ``` ,3*\D‘ṬE Main link. Argument: n ,3 Pair; yield [n, 3]. *\ Cumulative reduce by exponentation. Yields [n, n³]. D Decimal; yield the digit arrays of n and n³. ‘ Increment, mapping 0 ... 9 to 1 ... 10. Ṭ Untruth (vectorizes); map digit array [a, b, c, ...] to the smallest of zeroes with ones at indices a, b, c, ... E Test the results for equality. ``` [Answer] ## CJam, 8 bytes ``` l_~3#s^! ``` [Test suite.](http://cjam.tryitonline.net/#code=cU4vezpMOwoKTF9-MyNzXiEKCl1ufS8&input=MAoxCjEwCjEwNzYyNAoyNTE4OTQKMjUxODk1CjEwMjM0Mw) ### Explanation ``` l e# Read input. _~ e# Duplicate and evaluate. 3# e# Raise to third power. s e# Convert back to string. ^ e# Symmetric set difference. Gives an empty list iff the two sets e# are equal. ! e# Logical NOT. ``` [Answer] ## Haskell, 47 bytes ``` n%p=[c|c<-['0'..],elem c$show$n^p] f n=n%1==n%3 ``` Very slow. Test with `c<-['0'..'9']`. Tests every character for inclusion in the string representation of `n`, and makes a list of those included. Does likewise for `n^3` and checks if the lists are equal. [Answer] # JavaScript ES6, ~~55~~ 51 bytes Thanks to Downgoat for 3 bytes! You can save a byte by converting to ES7 and using `n**3` instead of `n*n*n`. ``` n=>(f=s=>[...new Set(s+[])].sort()+[])(n)==f(n*n*n) ``` Simple enough. [Answer] # C#, ~~241~~ ~~208~~ ~~205~~ ~~201~~ ~~193~~ ~~233~~ ~~222~~ ~~220~~ ~~212~~ ~~203~~ ~~177~~ 159 bytes (109 alternate) ``` I=>{x=s=>{var a=new int[10];foreach(var h in s+"")a[h-'0']++;return a;};var i=x(I);var j=x(I*I*I);for(var k=0;k<10;)if(i[k]>0^j[k++]>0)return 0>1;return 1>0;}; ``` The lambda's must specifically use the `ulong` type: ``` System.Func<ulong, bool> b; // = I=>{...}; System.Func<ulong, int[]> x; // inner lambda ``` Thanks to @Corak and @Dennis\_E for saving some bytes, and @TimmyD for finding a problem with my original solution. Thanks to @SaxxonPike for pointing out the ulong/long/decimal/etc problem (which actually also saved me some bytes). --- There is also a **109 byte** solution using HashSets, similar to the Java answers here, but I'm going to stick to my original solution for my score. ``` using System.Collections.Generic;I=>{return new HashSet<char>(I+"").SetEquals(new HashSet<char>(I*I*I+""));}; ``` [Answer] # Java 8, 154 characters ``` a->java.util.Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new java.math.BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray()); ``` Called like this: ``` interface Y { boolean n(int x); } static Y y = a->java.util.Arrays.equals((a+"").chars().distinct().sorted().toArray(),(new java.math.BigInteger(a+"").pow(3)+"").chars().distinct().sorted().toArray()); public static void main(String[] args) { System.out.println(y.n(0)); System.out.println(y.n(1)); System.out.println(y.n(10)); System.out.println(y.n(107624)); System.out.println(y.n(251894)); System.out.println(y.n(251895)); System.out.println(y.n(102343)); } ``` Outputs: ``` true true true true true false false ``` A very Java 8-y answer, using a lambda as well as streams including some fancy number-to-string conversions. Unfortunately we need to use `BigInteger.pow(3)` instead of `Math.pow(a,3)` due to Math.pow using non-precise doubles, which return incorrect values with large numbers (starting with `2103869`). [Answer] # BASH, ~~69~~, 59 bytes *UPDATE* Another nice way to do this in bash is to use *tr* (62 bytes, but can probably be squeezed a bit more) ``` T() { m=`bc<<<$1^3`;[ -z "`tr -d $m <<<$1;tr -d $1 <<<$m`" ];} ``` *EDIT:* Some more optimizations (Thx ! @manatwork) **Golfed** ``` T() { S(){ fold -1|sort -u;};bc<<<$1^3|S|diff - <(S<<<$1);} ``` **Test** ``` TEST() { T $1 >/dev/null; echo $? } TEST 0 0 TEST 1 0 TEST 11 1 TEST 10 0 TEST 107624 0 TEST 251894 0 TEST 251895 1 TEST 102343 1 TEST 106239 1 ``` 0 - for success (exit code) 1 - for failure (exit code) [Answer] # x86-64 machine code function, 40 bytes. # Or 37 bytes if 0 vs. non-zero is allowed as "truthy", like strcmp. Thanks to Karl Napf's C answer for the bitmap idea, which x86 can do very efficiently with [BTS](http://www.felixcloutier.com/x86/BTS.html). Function signature: `_Bool cube_digits_same(uint64_t n);`, using the x86-64 System V ABI. (`n` in RDI, boolean return value (0 or 1) in AL). `_Bool` is defined by ISO C11, and is typically used by `#include <stdbool.h>` to define `bool` with the same semantics as C++ `bool`. Potential savings: * 3 bytes: Returning the inverse condition (non-zero if there's a difference). Or from inline asm: returning a flag condition (which is possible with gcc6) * 1 byte: If we could clobber EBX (doing so would give this function a non-standard calling convention). (could do that from inline asm) * 1 byte: the RET instruction (from inline asm) All of these are possible if this was an inline-asm fragment instead of a function, which would make it **35 bytes for inline-asm**. ``` 0000000000000000 <cube_digits_same>: 0: 89 f8 mov eax,edi 2: 48 f7 e7 mul rdi # can't avoid a REX prefix: 2642245^2 doesn't fit in 32 bits 5: 48 f7 e7 mul rdi # rax = n^3, rdx=0 8: 44 8d 52 0a lea r10d,[rdx+0xa] # EBX would save a REX prefix, but it's call-preserved in this ABI. c: 8d 4a 02 lea ecx,[rdx+0x2] 000000000000000f <cube_digits_same.repeat>: f: 31 f6 xor esi,esi 0000000000000011 <cube_digits_same.cube_digits>: 11: 31 d2 xor edx,edx 13: 49 f7 f2 div r10 ; rax = quotient. rdx=LSB digit 16: 0f ab d6 bts esi,edx ; esi |= 1<<edx 19: 48 85 c0 test rax,rax ; Can't skip the REX: (2^16 * 10)^3 / 10 has all-zero in the low 32. 1c: 75 f3 jne 11 <cube_digits_same.cube_digits> ; 1st iter: 2nd iter: both: 1e: 96 xchg esi,eax ; eax=n^3 bitmap eax=n bitmap esi=0 1f: 97 xchg edi,eax ; edi=n^3 bitmap, eax=n edi=n bmp, eax=n^3 bmp 20: e2 ed loop f <cube_digits_same.repeat> 22: 39 f8 cmp eax,edi 24: 0f 94 d0 sete al ;; The ABI says it's legal to leave garbage in the high bytes of RAX for narrow return values ;; so leaving the high 2 bits of the bitmap in AH is fine. 27: c3 ret 0x28: end of function. ``` LOOP seems like the smallest way to repeat once. I also looked at just repeating the loop (without REX prefixes, and a different bitmap register), but that's slightly larger. I also tried using PUSH RSI, and using `test spl, 0xf` / `jz` to loop once (since the ABI requires that RSP is 16B aligned before CALL, so one push aligns it, and another misaligns it again). There's no `test r32, imm8` encoding, so the smallest way was with a 4B TEST instruction (including a REX prefix) to test just the low byte of RSP against an imm8. Same size as LEA + LOOP, but with extra PUSH/POP instructions required. Tested for all n in the test range, vs. steadybox's C implementation (since it uses a different algorithm). In the two cases of different results that I looked at, my code was correct and steadybox's was wrong. I think my code is correct for all n. ``` _Bool cube_digits_same(unsigned long long n); #include <stdio.h> #include <stdbool.h> int main() { for(unsigned n=0 ; n<= 2642245 ; n++) { bool c = f(n); bool asm_result = cube_digits_same(n); if (c!=asm_result) printf("%u problem: c=%d asm=%d\n", n, (int)c, (int)asm_result); } } ``` The only lines printed have c=1 asm=0: false-positives for the C algorithm. Also tested against a `uint64_t` version of Karl's C implementation of the same algorithm, and the results match for all inputs. [Answer] # [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319) ``` ⍕≡⍕∪(⍕*∘3) ``` `⍕≡` is the argument's text representation identical to `⍕∪` the union of the argument's text representation and `(⍕*∘3)` the text representation of the cubed argument? [TryAPL online!](http://tryapl.org/?a=%u2395pp%u219017%20%u22C4%20f%u2190%u2355%u2261%u2355%u222A%28%u2355*%u22183%29%20%u22C4%20f%A80%201%2010%20107624%20251894%20251895%20102343&run) **Note:** For large numbers, set `⎕PP←34 ⋄ ⎕FR←1287` (34 significant digits, 128 bit floats) [Answer] # Clojure, 35 bytes ``` #(=(set(str %))(set(str(* % % %)))) ``` [Answer] # Haskell, ~~54~~ 52 bytes Thanks @Laikoni for saving two bytes. ``` (%)=all.flip elem k n|[a,b]<-show<$>[n,n^3]=b%a&&a%b ``` [Answer] # Java 7, ~~185~~ 178 characters ``` import java.util.*; boolean a(int n){return new HashSet(Arrays.asList((n+"").split(""))).equals(new HashSet(Arrays.asList((new java.math.BigInteger(n+"").pow(3)+"").split(""))));} ``` Call as: ``` public static void main(String [] args) { System.out.println(0 + " -> " + a(0)); System.out.println(1 + " -> " + a(1)); System.out.println(10 + " -> " + a(10)); System.out.println(107624 + " -> " + a(107624)); System.out.println(2103869 + " -> " + a(2103869)); System.out.println(251894 + " -> " + a(251894)); System.out.println(251895 + " -> " + a(251895)); System.out.println(102343 + " -> " + a(102343)); System.out.println(106239 + " -> " + a(106239)); } ``` Output: ``` 0 -> true 1 -> true 10 -> true 107624 -> true 2103869 -> true 251894 -> true 251895 -> false 102343 -> false 106239 -> false ``` *(I'm never sure if I have to count imports and method definitions as well... I've seen either way. The code itself would be only 141 bytes long though.)* [Answer] # R, ~~65~~ ~~79~~ 70 bytes Takes `n` from stdin, splits `n` and `n^3` into single digits, and compares the two sets. Uses the `gmp` package to handle large integers (thanks to Billywob for pointing out that shortcoming). Now uses `substring` to cut up `n` and `n^3`, thanks to @MickyT for the suggestion. (Previous versions used `scan` and `gsub` in a hacky way.) ``` s=substring setequal(s(n<-gmp::as.bigz(scan()),p<-1:1e2,p),s(n^3,p,p)) ``` [Answer] # [Jelly](http://github.com/DennisMitchell/jelly), 8 bytes ``` *3ṢQ⁼ṢQ$ ``` [Try it online!](http://jelly.tryitonline.net/#code=KjPhuaJR4oG84bmiUSQ&input=&args=MTAw) Explanation: ``` $ # As a monadic (single argument) link: ⁼ # Return true if the following are equal ṢQ # The unique sorted elements of 'n' ṢQ # and The unique sorted elements *3 # of 'n^3' ``` [Answer] # Pyth, 10 bytes Because we don't have enough variety with Pyth answers, let's add not one, but two more! Both are 10 bytes, and have been tested with `106239` as a sample input (which some other answers failed). ``` !s.++Q,`** ``` Explanation: ``` !s.++Q,`**QQQQ Implicit input filling **QQQ Q ^ 3 ` repr(Q^3) , Q [repr(Q^3),Q] +Q [Q,repr(Q^3),Q] .+ Deltas ([Digits in Q but not in Q^3, digits in Q^3 but not in Q]) !s Are both empty? ``` [Try the first answer using an online test suite.](http://pyth.herokuapp.com/?code=%21s.%2B%2BQ%2C%60%2a%2a&test_suite=1&test_suite_input=106239%0A0%0A1%0A10%0A107624%0A251894%0A251895%0A102343&debug=0) Second answer: ``` qFmS{`d,** ``` Explanation: ``` qFmS{`d,**QQQQ Implicit input filling **QQQ Q ^ 3 , Q [Q^3, Q] m map over each element d of [Q^3, Q]: `d the element's string representation { with duplicates removed S and sorted qF Fold over equality (are the two the same?) ``` [Try the second answer using an online test suite.](http://pyth.herokuapp.com/?code=qFmS%7B%60d%2C%2a%2a&test_suite=1&test_suite_input=106239%0A0%0A1%0A10%0A107624%0A251894%0A251895%0A102343&debug=0) [Answer] # Kotlin: 46/88/96 bytes The question doesn't specify from where the input comes from, so here's the usual 3 input sources. --- ### Function: 46 bytes ``` fun f(i:Long)="$i".toSet()=="${i*i*i}".toSet() ``` --- [Answer] ## JavaScript (ES6), 44 bytes ``` g=n=>n<1?0:g(n/10)|1<<n%10 n=>g(n)==g(n*n*n) ``` Port of @KarlNapf's excellent C answer. ES7 saves a byte via `n**3`. Only works up to 208063 due to JavaScript's limited numeric precision; if you only need it to work up to 1290, you can save another byte. [Answer] # [Perl 6](https://perl6.org), 22 bytes ``` {!(.comb⊖$_³.comb)} ``` ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 !( .comb # get a list of the graphemes ( digits ) ⊖ # Symmetric Set difference $_³.comb # cube and get a list of the graphemes ) } ``` The [Symmetric Set difference 「⊖」 operator](https://docs.perl6.org/routine/(%5E)) returns an empty [Set](https://docs.perl6.org/type/Set) if both sides are equivalent Sets (automatically turns a list into a Set). At that point the only thing left to do is invert it logically. [Answer] # C++, 82 bytes ``` t(int a){int b=a*a*a,c,d;while(a|b)c|=1<<a%10,a/=10,d|=1<<b%10,b/=10;return c==d;} ``` The function t(a) returns the answer. Uses an int as a set. Printed nicely: ``` t(int a) { int b = a*a*a, c, d; while(a|b) c|=1 << a%10, a/=10, d|=1 << b%10, b/=10; return c==d; } ``` [Answer] # C++14, 93 bytes ``` int b(auto i){int k=0;while(i)k|=1<<i%10,i/=10;return k;}int f(auto n){return b(n)-b(n*n*n);} ``` Port of my [C answer](https://codegolf.stackexchange.com/a/99836/53667), works for big numbers (call with `L` suffix). [Answer] # Ruby, 48 bytes ``` ->n{(f=->x{x.to_s.chars.uniq.sort})[n]==f[n**3]} ``` [Answer] ## Haskell, 47 bytes ``` import Data.Set s=fromList.show f n=s n==s(n^3) ``` Usage example: `f 102343` -> `False`. Uses sets from the `Data.Set` module. The helper function `s` turns a number into its string representation and than makes a set out of the characters. [Answer] # [Brachylog](http://github.com/JCumin/Brachylog), 11 bytes ``` doI,?:3^doI ``` [Try it online!](http://brachylog.tryitonline.net/#code=ZG9JLD86M15kb0k&input=MTAyMzQz) Thanks to @DestructibleWatermelon for pointing out a problem with my original answer. ### Explanation ``` (?)doI, I is the Input sorted with no duplicates ?:3^ Compute Input^3 doI Input^3 sorted with no duplicates is I ``` [Answer] ## PowerShell v2+, ~~94~~ 93 bytes ``` filter f($n){-join("$n"[0..99]|sort|select -u)} (f($x=$args[0]))-eq(f("[bigint]$x*$x*$x"|iex)) ``` *(Newline for clarity, not included in bytecount)* The first line defines `f` as a `filter` (similar-ish enough to a function for our purposes here to not go into specifics) that takes input `$n` and does the following: ``` filter f($n){-join("$n"[0..99]|sort|select -u)} f($n) # Input "$n" # Cast as string [0..99] # Index as char-array |sort # Sorted alphabetically |select -u # Only select the -Unique elements -join( ) # Join those back together into a string # Implicit return ``` The second line takes the input `$args`, performs `f` on it, and checks whether it's `-eq`ual to `f` performed on `$x` cubed. Note the explicit `[bigint]` cast, required else we'll get the result back in scientific notation, which will obviously not work. The Boolean result is left on the pipeline, and output is implicit. ``` PS C:\Tools\Scripts\golfing> 0,1,10,107624,251894,251895,102343,106239,2103869|%{"$_ --> "+(.\do-n-n3-same-digits.ps1 $_)} 0 --> True 1 --> True 10 --> True 107624 --> True 251894 --> True 251895 --> False 102343 --> False 106239 --> False 2103869 --> True ``` *Saved a byte thanks to @ConnorLSW* [Answer] # Groovy, 35 ~~51~~ chars/bytes I was sad not to see Groovy included, so here's my original 51-byte attempt: `def x(def n){"$n".toSet()=="${n.power(3)}".toSet()}` Rewritten as a 35-byte anonymous closure and with `**` for exponentiation, thanks to manatwork: `{"$it".toSet()=="${it**3}".toSet()}` Some test cases for the original function: ``` println x(0) println x(1) println x(10) println x(107624) println x(251894) println x(251895) println x(102343) ``` A named closure `c` could be called like this: `println c.call(107624)`. The anonymous 35-byte closure could be called like this: `println ({"$it".toSet()=="${it**3}".toSet()}(107624))` Outputs: ``` true true true true true false false ``` Please note: I learned that something like code golf exists just now, so hopefully I got this right! ]
[Question] [ # Introduction One day, you were showing your kid how to draw on a computer. You type `mspaint.exe` in the run bar. To your horror, it says "No items match your search". You must create a simple version of paint so your kid can draw! # Challenge You must create a simple drawing program. To do this, open a white display window (larger than 99x99 pixels). Anytime the mouse is pressed down, change the pixel that the mouse is on to black. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins! [Answer] # 8086 machine code, ~~32 31 28~~ 26 bytes ``` 00000000 b8 0f 00 cd 10 b8 02 10 ba 18 01 cd 10 b8 03 00 |................| 00000010 cd 33 4b b8 01 0c eb f3 3f 00 |.3K.....?.| 0000001a ``` Assumes the presence of a VGA graphics card, and any Microsoft-compatible mouse driver. -2 bytes thanks to @berendi! [![screenshot](https://i.stack.imgur.com/kUTpB.png)](https://i.stack.imgur.com/kUTpB.png) ### How it works: ``` | org 0x100 | use16 b8 0f 00 | mov ax, 0x000f ; set screen mode: 640x350 monochrome cd 10 | int 0x10 ; call video bios b8 02 10 | mov ax, 0x1002 ; set palette ba 18 01 | mov dx, palette ; pointer to palette data cd 10 | @@: int 0x10 ; call video bios b8 03 00 | mov ax, 0x0003 ; get mouse position in (CX, DX) and button status in BL cd 33 | int 0x33 ; call mouse driver 4b | dec bx ; if no buttons pressed, --BX = 0xFFFF (invalid page) b8 01 0c | mov ax, 0x0c01 ; plot pixel with color AL at (CX, DX) in page BH eb f3 | jmp @b ; repeat 3f 00 | palette db 0x3f, 0x00 ; palette in 2:2:2 rgb. color 0 = white, 1 = black. | ; this should be a 17-byte struct, but we only care about the first two colors here ``` That's all there is to it. No magic involved, just a few function calls. [Answer] # Scratch, 10 Scratch bytes ![](https://i.stack.imgur.com/kHyQ7.png) Scratch was practically designed for things like this. [Try it online!](https://scratch.mit.edu/projects/156553434) [Answer] # HTML + JavaScript (ES6), 66 64 62 bytes **HTML** ``` <canvas id=c> ``` **JavaScript** ``` onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1) ``` Saved 2 bytes thanks to Gustavo Rodrigues and 2 bytes from Shaggy. ``` onclick=e=>c.getContext`2d`.fillRect(e.x,e.y,1,1) ``` ``` /* This css isn't needed for the program to work. */ *{margin: 0} #c{border:1px solid black} ``` ``` <canvas id=c> ``` [Answer] ## C + Win32, ~~209~~ ~~200~~ ~~195~~ ~~178~~ 159 bytes * 2022 Update: Saved 19 bytes by removing `#include <windows.h>`. ``` short m[9];main(h){for(h=CreateWindowExA(0,"EDIT","",1<<28,0,0,199,199,0);GetMessageA(m,h,0,0);m[4]^513?DispatchMessageA(m):SetPixel(GetDC(h),m[12],m[13],0));} ``` Thanks, Cody and Quentin! I was hoping to get rid of the `#include <windows.h>` but this leads to all sort of errors. At least it is working correctly with multiple monitors... Saved 17 bytes thanks to inspiration by [@c--](https://codegolf.stackexchange.com/users/112488/c)!!! [![enter image description here](https://i.stack.imgur.com/uPW7I.png)](https://i.stack.imgur.com/uPW7I.png) [Answer] # Processing, ~~98~~ 79 bytes *19 bytes saved thanks to @dzaima* ``` void setup(){background(-1);}void draw(){if(mousePressed)point(mouseX,mouseY);} ``` ### Explanation (outdated) ``` void setup() { size(100,100); // size of the sketch background(-1); // set the background to white // 1 byte shorter than background(255); } void draw(){} // required for mousePressed to work void mousePressed() { // function that is called whenever the mouse is pressed point(mouseX, mouseY); // draw a point at the mouse's coordinates // the colour is set to black as default } ``` [![clicketty click](https://i.stack.imgur.com/nTojI.png)](https://i.stack.imgur.com/nTojI.png) [Answer] # JavaScript ES6, 126 bytes Tested in chrome. ``` onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>` ``` ### Try it online! ``` onclick=e=>document.body.outerHTML+=`<a style=position:fixed;top:${e.y}px;left:${e.x}px;width:1px;height:1px;background:#000>` ``` [Answer] ## Haskell, ~~189~~ ~~184~~ ~~170~~ 169 bytes ``` import Graphics.Gloss.Interface.Pure.Game main=play FullScreen white 9[]Pictures(#)(\_->id) EventKey(MouseButton LeftButton)Down _(x,y)#l=Translate x y(Circle 1):l _#l=l ``` This uses the `Gloss` library (v1.11). It opens a full screen window and paints black pixels (in fact circles with radius 1) by pressing the left mouse button. Press `ESC` to exit. How it works: ``` play -- handles the whole event handling, screen update, etc. process FullScreen -- use a full screen window white -- use a white background 9 -- 9 simulation steps per second (see simulation handler below) [] -- the initial world state, an emtpy list of circles Pictures -- a function to turn the world state into a picture. -- The world state is a list of translated circles and -- "Pictures" turns this list into a single picture (#) -- event handler, see below (\_->id) -- simulation step handler. Ignore time tick and return the -- world state unchanged. More readable: "\tick world -> world" EventKey ... # l=... -- if the left mouse button is pressed, add a circle with -- radius 1 translated to the current position of the mouse -- to the world state _#l=l -- on all other events do nothing ``` Edit: @ceased to turn counterclockwis told me about the newst version of gloss which saves 5 bytes when using full screen windows. Thanks! [Answer] # SmileBASIC 2, ~~52~~ 51 bytes This one runs in SmileBASIC's daddy, Petit Computer (and is ~~one~~ two byte shorter.) ``` PNLTYPE"OFF GPAGE 1GCLS 15@A GPSET TCHX,TCHY GOTO@A ``` Explanation: ``` PNLTYPE"OFF 'turn off keyboard GPAGE 1 'set graphics to lower screen GCLS 15 'clear with color 15 (white) @A 'loop begin GPSET TCHX,TCHY 'set black pixel at draw location GOTO@A 'loop ``` [Answer] # Javascript + jQuery 138 bytes ``` d=$(document.body).click((e)=>d.append("<div style='background:black;width:5;height:5;position:fixed;top:"+e.pageY+";left:"+e.pageX+"'>")) ``` [Check it out online!](http://neil.computer/golf/paint.php) Adding click and drag support would be simple, you'd set a variable, however, per the instructions and to shorten code, it is not supported, "Anytime the mouse is pressed down, change the pixel that the mouse is on to black". I interpretted the instruction as a `click` event. [Answer] # SpecBAS - ~~61~~ 59 bytes ``` 1 CLS 15 2 IF MOUSEBTN=1 THEN PLOT MOUSEx,MOUSEy 3 GO TO 2 ``` Black is already the default pen colour, but the background is usually a nasty shade of grey, so `CLS 15` sets it to bright white. [![enter image description here](https://i.stack.imgur.com/hZAKn.png)](https://i.stack.imgur.com/hZAKn.png) [Answer] # SmileBASIC, ~~70~~ ~~58~~ 53 Bytes ``` XSCREEN 4GCLS-1@L TOUCH OUT,X,Y GPSET X,Y+240,0GOTO@L ``` Explained: ``` XSCREEN 4 'display one graphics page on both screens GCLS -1 'fill screen with white @L 'loop TOUCH OUT,X,Y 'get touch location GPSET X,Y+240,0 'draw black pixel at touch position, offset by the height of the top screen. GOTO @L 'loop ``` [Answer] # Clojure, ~~91~~ 71 bytes -20 bytes thanks to @cfrick for pointing out that I can use `use` to shrink my importing. ``` (use 'quil.core)(defsketch P :mouse-dragged #(point(mouse-x)(mouse-y))) ``` Uses the [Quil](http://quil.info/) library. Draws a dot whenever the mouse is dragged. Basically the Processing answer, since Quil is a Processing wrapper for Clojure. ``` (q/defsketch P ; Start a new drawing :mouse-dragged ; Attach a mouse drag listener ; that draws a point at the current mouse location #(q/point (q/mouse-x) (q/mouse-y))) ``` [![enter image description here](https://i.stack.imgur.com/yE3Kg.png)](https://i.stack.imgur.com/yE3Kg.png) [Answer] # Excel VBA, 62 Bytes Anonymous VBE immediate window function that allows the user to draw on the any sheet by simply selecting it ``` Cells.RowHeight=48:Do:DoEvents:Selection.Interior.Color=0:Loop ``` # Sample Output [![enter image description here](https://i.stack.imgur.com/UiljF.png)](https://i.stack.imgur.com/UiljF.png) [Answer] # Tcl/Tk, 45 ~~46~~ ~~51~~ ~~57~~ ``` gri [can .c] bind . <1> {.c cr o %x %y %x %y} ``` [![pentagram](https://i.stack.imgur.com/ZpfCZ.png)](https://i.stack.imgur.com/ZpfCZ.png) [Answer] # Java 7, 353 bytes ``` import java.awt.*;import java.awt.event.*;class M{static int x,y;public static void main(String[]a){Frame f=new Frame(){public void paint(Graphics g){g.drawLine(x,y,x,y);}};f.addMouseListener(new MouseAdapter(){public void mousePressed(MouseEvent e){x=e.getX();y=e.getY();f.repaint(x,y,1,1);}});f.setBackground(Color.WHITE);f.resize(500,500);f.show();}} ``` Ungolfed: ``` import java.awt.*; import java.awt.event.*; class M { //store the last point static int x, y; public static void main(String[] a) { Frame f = new Frame() { @Override public void paint(Graphics g) { g.drawLine(x, y, x, y); } } f.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); //repaint only the "new pixel" f.repaint(x, y, 1, 1); } }); //default background is grey f.setBackground(Color.WHITE); f.resize(500, 500); f.show(); } } ``` [Answer] # TI-Basic, 1 byte ``` Pt-Change( ``` I'm sure that most of you with TI calcs thought of the `Pen` command, but it turns out that it's not tokenized so it would make most sense to count that as 3 bytes. You can read about the interactive version of `Pt-Change(` at <http://tibasicdev.wikidot.com/pt-change> [Answer] # Python2 *and* Python3, 82 bytes (or 77?) ``` from turtle import *;up();onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop() ``` Using the Turtle module, this isn't too bad :) Ungolfed: ``` import turtle turtle.up() def fun(x, y): turtle.goto(x,y) turtle.dot(1) turtle.onscreenclick(fun) turtle.mainloop() ``` If it's OK to have lines between the dots, you can actually save 5 bytes: ``` from turtle import *;onscreenclick(lambda x,y: goto(x,y)or dot(1));mainloop() ``` [Answer] ## HTML + Javascript, ~~152~~ 148 bytes ``` <body onclick="document.body.innerHTML+='<x style=position:fixed;width:1;height:1;left:'+event.clientX+';top:'+event.clientY+';background:#000;>'"/> ``` [Answer] # [Turing](http://compsci.ca/holtsoft/), 77 bytes ``` var x,y,b:int loop mousewhere(x,y,b)if b=1then drawdot(x,y,1)end if end loop ``` Ungolfed: ``` var x,y,b : int loop mousewhere(x,y,b) % Set (x,y) to mouse co-ords, and b to 1 or 0 indicating if the button is pressed if b=1 then drawdot(x,y,1) % Draw a black pixel at (x,y) end if end loop ``` [Answer] # HTML + CSS + JavaScript (ES6), 8 + 31 + 64 = 103 bytes Fun with CSS `box-shadow`! ``` s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0` ``` ``` *{margin:0;width:1px;height:1px ``` ``` <p id=p> ``` # HTML + CSS + JavaScript (ES6), 8 + 22 + 69 = 99 bytes This one attempts to offset the default `margin` of the `<body>` element, but it may be different across browsers and user agent stylesheets. Tested successfully in Chrome. ``` s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x-8}px ${e.y-16}px 0` ``` ``` *{width:1px;height:1px ``` ``` <p id=p> ``` # HTML + CSS + JavaScript (ES6), 8 + 18 + 69 = 95 bytes Pixels in this one may appear bigger as they are drawn at half-pixel coordinates. ``` s='0 0 0',onclick=e=>p.style.boxShadow=s+=`,${e.x}px ${e.y}px 0 .5px` ``` ``` *{margin:0;width:0 ``` ``` <p id=p> ``` [Answer] # Lua (love2d Framework), 180 bytes golfed version ``` l=love v,g,m,p=255,l.graphics,l.mouse,{}d=m.isDown function l.draw()g.setBackgroundColor(v,v,v)if d(1)or d(2)then p[#p+1],p[#p+2]=m.getPosition()end g.setColor(0,0,0)g.points(p)end ``` ungolfed ``` l=love v,g,m,p=255,l.graphics,l.mouse,{} d=m.isDown function l.draw() g.setBackgroundColor(v,v,v) if d(1)or d(2)then p[#p+1],p[#p+2]=m.getPosition() end g.setColor(0,0,0) g.points(p) end ``` quite easy how it works. First a few initialisations to make things shorter. After it it will check the mous is clicked and saves the points to the array. After that it draws the points.Also it sets the color to white& black cause default is the other way around :) And here comes the picture: [![enter image description here](https://i.stack.imgur.com/RY7h7.png)](https://i.stack.imgur.com/RY7h7.png) [Answer] ## Processing, 65 bytes ``` void draw(){if(mousePressed)line(mouseX,mouseY,pmouseX,pmouseY);} ``` [![minimal draw](https://i.stack.imgur.com/h4lIH.png)](https://i.stack.imgur.com/h4lIH.png) [Answer] # glslsandbox 232 bytes Old post but found this interesting. Since processing already been done I decided to do something different. This draws whether the mouse is pressed or not, so not what pydude asked for but almost. ``` #ifdef GL_ES precision lowp float; #endif uniform float time;uniform vec2 mouse,resolution;uniform sampler2D t;void main(){vec2 f=gl_FragCoord.xy,r=resolution;gl_FragColor=vec4(time<2.||length(f-mouse*r)>2.&&texture2D(t,f/r).x>.1);} ``` [Try it on glslsandbox](http://glslsandbox.com/e#43844.0) [Answer] **Processing, 93 bytes, 91 bytes if spaces don't count** ``` void setup(){size(100,100);background(-1);}void draw(){if(mousePressed) point(mouseX,mouseY);} ``` [Answer] ## UCBlogo with wxWidgets, 65 bytes ``` setbg 7 setpc 0 ht pu make "buttonact[setpos clickpos pd fd 1 pu] ``` Explanation (the code assigned to the variable `buttonact` is executed on each button click): ``` SetBackground 7 ; white SetPenColor 0 ; black HideTurtle PenUp make "buttonact [ SetPos ClickPos PenDown Forward 1 PenUp ] ``` At least, I think this works. It should according to the [documentation](https://people.eecs.berkeley.edu/~bh/usermanual), but apparently the `buttonact` variable only works in a wxWidgets build and I'm struggling to build UCBLogo with wxWidgets on a modern Linux (waddyamean you can't cast a pointer to `int` and back?). ## UCBlogo without wxWidgets, 73 bytes To see the intended effect, you can run this longer version with an infinite loop. ``` setbg 7 setpc 0 ht pu while[1=1][setpos mousepos if[button?][pd] fd 1 pu] ``` But this crashes `ucblogo` on my machine... Looks like a race condition. ## UCBlogo, actually working on my machine, 80 bytes ``` setbg 7 setpc 0 ht pu while[1=1][setpos mousepos if[button?][pd] fd 1 pu wait 1] ``` [Answer] # [APL (dzaima/APL)](https://github.com/dzaima/APL), 37 bytes ``` P5.draw←{P5.Lm.p:P5.G.pt P5.mx P5.my} ``` [Try it online!](https://tio.run/##SyzI0U2pSszMTfz/P8BUL6UosfxR24RqINMnV6/ACki76xWUKADp3AowWVn7/z8A "APL (dzaima/APL) – Try It Online") Machine code is OP. ]
[Question] [ *Inspired by [a question](https://stackoverflow.com/q/43640022/2586922) over at Stack Overflow. The title here is entirely my fault.* --- ## The challenge Given a list of positive integers containing at least two entries, replace each number by the minimum of all entries excluding itself. ## Test cases ``` [4 3 2 5] -> [2 2 3 2] [4 2 2 5] -> [2 2 2 2] [6 3 5 5 8] -> [3 5 3 3 3] [7 1] -> [1 7] [9 9] -> [9 9] [9 8 9] -> [8 9 8] ``` ## Rules The algorithm should theoretically work for any input size (greater than one) and values (positive integers). It's accepted if the program is limited by time, memory or data types and so only works for numbers up to a given value, or for input size up to a given value. [Programs or functions](http://meta.codegolf.stackexchange.com/a/2422/36398) are allowed, in any [programming language](http://meta.codegolf.stackexchange.com/a/2073/36398). [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. Input can be taken by any [reasonable means](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods); and with any format. Same for output. Input and output formats may be different. Shortest code in bytes wins. [Answer] # [Python 2](https://docs.python.org/2/), 41 bytes ``` lambda l:[sorted(l)[x==min(l)]for x in l] ``` [Try it online!](https://tio.run/nexus/python2#LcxNCoAgEAXgdZ1ilgaz6b8ET2IujBIEszAX3d7GiIE335vFGLEkp4910@C4vM8Q9425Sj5CHNaTlDkDPGA9OJWy437HXKXssMUGe4Wk5tdAt55mIo9YU844fznRVrwsrmB9BMPynyqlFw "Python 2 – TIO Nexus") For each element `x` we check whether `x==min(l)`. If not, this is `False`, which is treated as `0` when used as a list index into `sorted(l)`, giving the smallest element. Otherwise, it's `True` aka `1`, giving the second-smallest element, since that element itself is smallest and should be ignored. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ ~~6~~ 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` ~~JḟЀ`ị⁸Ṃ€~~ ~~ṙJṖ€Ṃ€~~ ṙJṖ«/ argument: 1D array (z) J [1,2,3,...,len(z)] ṙ rotate z by each of the above amount (current array is 2D) Ṗ remove the last array «/ reduce by [impliclitly vectorized] minimum ``` [Try it online!](https://tio.run/nexus/jelly#@/9w50yvhzunHVqt/////2gTHSMgNI0FAA "Jelly – TIO Nexus") [Verify all of them at once!](https://tio.run/nexus/jelly#@/9w50yvhzunHVqtz3W4/VHTmv///0dHm@gY6xjpmMbqAFlGUJYZUMwUCC2AbHMdQyBpqWMJJi2AdCwA "Jelly – TIO Nexus") (slightly modified) I'm pretty sure Dennis can out-golf this. ## How it works The algorithm is rather convoluted. Let us observe what this does to `[4,2,2,5]`. Firstly, we use `J` to obtain `[1,2,3,4]`. Note that Jelly uses 1-indexing. Then, we see `ṙ`. It takes two arguments: an array and an integer. It rotates the array to the left by an amount specified by the integer. Here, `ṙ` would see `[4,2,2,5]` on its left and `[1,2,3,4]` on its right (more about how this works can be found in the [tutorial](https://github.com/DennisMitchell/jelly/wiki/Tutorial#42monadic-chains)). In Jelly, commands implicitly vectorize. Therefore, this command will be performed over each individual element on the right, which is why we would create a 2D array: Therefore, `[4,2,2,5]ṙ[1,2,3,4]` becomes `[[4,2,2,5]ṙ1,[4,2,2,5]ṙ2,[4,2,2,5]ṙ3,[4,2,2,5]ṙ4]`, which becomes: ``` [[2,2,5,4], [2,5,4,2], [5,4,2,2], [4,2,2,5]] ``` Notice that the original elements are on the last row, since in that row we rotated to the left by an amount equal to the length of the array, which is why we use `Ṗ` next to remove that row, so that the columns are the collections of the elements of the array which are not at the current index: ``` [[2,2,5,4], [2,5,4,2], [5,4,2,2]] ``` The following operation, `«/`, is also quite convoluted. Firstly, `«` returns the minimum of the two numbers it sees on its left and on its right. For example, `5«3` returns `3`. Now, if the two arguments are arrays, then it would vectorize as I have said above. What this means it that `[1,5,2,3]«[4,1,5,2]` would become `[1«4,5«1,2«5,3«2]` which is `[1,1,2,2]`. Now, `/` is `reduce`, which means that we do the operation over each row until the end. For example, `[1,2,3,4]+/` would become `((1+2)+3)+4`, which is the sum of the array `[1,2,3,4]`. So, if we apply `«/` to the 2D array we just obtained, we would get: ``` ([2,2,5,4]«[2,5,4,2])«[5,4,2,2] ``` which, because of the vectorization, would be equivalent to: ``` [2«2«5,2«5«4,5«4«2,4«2«2] ``` which computes the minimum of every array without the element at the index. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 [bytes](https://github.com/DennisMitchell/jelly) ### Now possible in 3 [bytes](https://github.com/DennisMitchell/jelly), since [2017-08-13](https://github.com/DennisMitchell/jellylanguage/commit/c41aa1416ad7d6c8543120031d11f947028f9833): ``` Ṃ-Ƥ - map minimum over overlapping outfixes of length one less than the input ``` [Try it online!](https://tio.run/##y0rNyan8///hzibdY0v@//8fbaJjrGOkYxoLAA) --- ### Original, 5 [bytes](https://github.com/DennisMitchell/jelly) ``` =Ṃ‘ịṢ ``` **[Try it online!](https://tio.run/nexus/jelly#@2/7cGfTo4YZD3d3P9y56P///9EmOsY6RjqmsQA "Jelly – TIO Nexus")** #### How? ``` =Ṃ‘ịṢ - Main link: list a e.g. [4,3,2,5] Ṃ - minimum of a 2 = - equals? (vectorises) [0,0,1,0] ‘ - increment [1,1,2,1] Ṣ - sort a [2,3,4,5] ị - index into [2,2,3,2] ``` [Answer] # [Haskell](https://www.haskell.org/), ~~42~~ ~~41~~ 39 bytes EDIT: * -1 byte thanks to nimi! * -2 bytes. One thanks to xnor! And one by myself. `f` takes a list of integers (or any `Ord` type) and returns a list. ``` f(x:y)=minimum y:(fst<$>zip(f$y++[x])y) ``` [Try it online!](https://tio.run/nexus/haskell#LYqxDsIgGIR3n8KBAVIksVptie3u7NgwEIX2TwQboLH48oiNueS7L5czEmwLNign7wHN9glWeWbkhP34ejPNsFPywfktOLDDruuv@TsoJwhh6zdpvPBIWgMWzGy2kWPtwwV1H5iwRrEo@kWQSFLqj/RAS1qJTbbyb6e8VTl19jPdZza0WVn/@gs "Haskell – TIO Nexus") `f` recurses while rotating the list. `x` is the first list element and `y` the remainder. Since the recursion is infinite, the result list needs to be cut off: `fst<$>zip...y` is a shorter way of saying `take(length y)...`. [Answer] # Octave, 26 bytes ``` @(x)sort(x)((x==min(x))+1) ``` A similar approach as used in [this answer](https://codegolf.stackexchange.com/a/117777/31516), which happens to be the same as [this](https://codegolf.stackexchange.com/a/117779/31516). I'm not really a fan of just porting other answers, which is why I'd like to note that I had a similar idea before I saw the other ones. **Explanation:** Jonathan Allan has already provided a good explanation for the Jelly-code, so this covers the Octave-bit, and why it works (and wouldn't work in MATLAB). ``` @(x) % An unnamed anonymous function taking a vector x as input sort(x) % Gives a sorted version of x (x==min(x)) % Checks if each element is equal to the minimum value ((x==min(x))+1) % Adds 1 to the boolean vector, to use as indices @(x)sort(x)((x==min(x))+1) % Complete function ``` This doesn't work in MATLAB, since inline assignments and direct indexing doesn't work. `sort(x)(1)` gives an error in MATLAB, not the first element in the sorted vector. [Answer] ## Haskell, 41 bytes ``` a#(b:c)=minimum(a++c):(b:a)#c a#b=b ([]#) ``` Usage example: `([]#) [4,3,2,5]`-> `[2,2,3,2]`. [Try it online!](https://tio.run/nexus/haskell#@5@orJFklaxpm5uZl5lbmquRqK2drGkFFEvUVE7mSlROsk3iSrPViI5V1vyfm5iZp2CrUFCUmVeioKKQphBtomOsY6RjGvsfAA "Haskell – TIO Nexus") Start with an empty accumulator `a` and run down the input list. The next element in the output list is the minimum of the accumulator `a` and all but the first element of the input list (->`c`) followed by a recursive call with the first element `b` added to the accumulator and `c`. Stop when you reach the end of the input list. [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), ~~13~~ 12 bytes ``` l+₁:?⊇ᶠ⁽⌋ᵐb↔ ``` [Try it online!](https://tio.run/nexus/brachylog2#@5@j/aip0cr@UVf7w20LHjXufdTT/XDrhKRHbVP@/4820zHWMQVCi9j/UQA "Brachylog – TIO Nexus") *Saved one byte thanks to @ais523.* ### Explanation ``` l+₁:? The list [length(Input) + 1, Input] ⊇ᶠ⁽ Find the length(Input) + 1 first subsets of the Input ⌋ᵐ Get the min of each subset b↔ Remove the first element and reverse ``` We exploit the fact that `⊇` unifies subsets from biggest to smallest. For example for `[1,2,3]`, the subsets we get are in this order: `[1,2,3], [1,2], [1,3], [2,3], [1], [2], [3], []`. We can see that the subsets `[1,2], [1,3], [2,3]` are the ones we want the minimum from, but are in the reverse order compared to the input list (hence the `↔`). We can select those subsets only by finding the first `length(Input) + 1` subsets, which will contain all of them + the entire list first. We discard that entire list with `b`. [Answer] ## JavaScript (ES6), ~~50~~ 46 bytes ``` a=>a.map((_,i)=>Math.min(...a.filter(_=>i--))) ``` Edit: Saved 4 bytes thanks to @Arnauld. [Answer] # R, ~~46~~ 31 bytes ``` l=scan();sort(l)[(min(l)==l)+1] ``` implements [Stewie Griffin's solution](https://codegolf.stackexchange.com/a/117781/67312) in R, alas, my original idea is 50% longer! still reads the list from stdin, but now returns a much more readable numeric vector. [Try it online!](https://tio.run/nexus/r#@59jW5ycmKehaV2cX1SikaMZrZGbmQekbW1zNLUNY/@bKRgrmAKhxX8A) ### old implementation: ``` l=scan();Map(function(x)min(l[-x]),match(l,l)) ``` reads in the list from stdin. A negative index `l[-x]` excludes the element from the list, and `match(l,l)` returns the index of the first occurrence of each element of the list. Returns a list. [Answer] # [Actually](https://github.com/Mego/Seriously), 13 bytes ``` ;;S╝m╗⌠╜=╛E⌡M ``` Uses the same technique that [xnor also discovered](https://codegolf.stackexchange.com/a/117779/45941). [Try it online!](https://tio.run/nexus/actually#@29tHfxo6tzcR1OnP@pZ8GjqHNtHU2e7PupZ6Pv/f7SJjoIRGJnGAgA "Actually – TIO Nexus") Explanation: ``` ;;S╝m╗⌠╜=╛E⌡M ;; make two extra copies of input list S╝ sort one and save it in register 1 m╗ save the minimum of the other in register 0 ⌠╜=╛E⌡M for each value in list: ╜=╛E return the minimum element of the input list if the value is not equal to the minimum, else return the second-smallest element ``` [Answer] # [Uiua](https://www.uiua.org/), 8 bytes ``` /↧÷⊞≠.⍏. ``` Vyxal port is 10 bytes: ``` ⊏⊃'=/↧'⊏⍏. ``` [Try these online!](https://www.uiua.org/pad?src=ZiDihpAg4oqP4oqDJz0v4oanJ-KKj-KNjy4KZyDihpAgL-KGp8O34oqe4omgLuKNjy4K4oqDZiBnIFs0IDMgMiA1XQriioNmIGcgWzQgMiAyIDVd) ``` /↧÷⊞≠.⍏. input: a positive integer vector ⊞≠.⍏ a matrix of the size of the input where the diagonal is 0s and the rest are 1s ÷ . divide each number in the input by each row of the above matrix, giving infinities where division by 0 occurs /↧ minimum of each column ⊏⊃'=/↧'⊏⍏. ⊃ . fork on two functions with two copies of input vectors as arguments: '=/↧ for each element, 1 if it is the minimum, 0 otherwise '⊏⍏ input sorted ⊏ select 0th or 1st item from the sorted list ``` Alternative 8: ``` ⊏=0⊃⍏⊏⍏. ``` [Try it online!](https://www.uiua.org/pad?src=ZiDihpAg4oqPPTDiioPijY_iio_ijY8uCmcg4oaQIC_ihqfDt-KKnuKJoC7ijY8uCuKKg2YgZyBbNCAzIDIgNV0K4oqDZiBnIFs0IDIgMiA1XQ==) ``` ⊏=0⊃⍏⊏⍏. ⊃⍏⊏⍏. take the input array and push (rank, sorted) ⍏ ⍏ rank: lowest number is replaced with 0, next lowest 1, ... ⊏⍏. sorted: lowest number is placed first, next 2nd, ... =0 for each element, 1 if rank is 0, 0 otherwise ⊏ select 1st in the sorted array if rank 0, 0th otherwise ``` [Answer] # Python 2, 51 bytes I know there's already a better Python solution, but I still want to post mine. ``` lambda L:[min(L[:i]+L[i+1:])for i in range(len(L))] ``` [**Try it online**](https://tio.run/nexus/python2#ZY9BDoMgEEX3nmLCCiJdgKJI0p7AG1AWNtWWRKkxNj2@HWhj0pRZDP/9GfIhhGS2hAIkKAd4DicAK1EictGS/5ZMVoUjCku7rxVlEQvNGkTa2fcE1IgbaH5xBBHr3UgYJb6bEUw3HM/b2E2XawetsZMPtLXGu7y1PhfGseGxgAcfYOnCradjjwOMue1192MPwsyLDysM1If5uVLGNlvygkuu4u@wf24VMoWlY3YuYiaeknGN/Q0) [Answer] ## Mathematica 34 Bytes ``` Min[#~Drop~{i}]~Table~{i,Tr[1^#]}& ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 68 59 bytes ``` ($a=$args)|%{$b+=@((($c=$a|sort)[0],$c[1])[$_-eq$c[0]])};$b ``` [Try it online!](https://tio.run/nexus/powershell#@6@hkmirkliUXqxZo1qtkqRt66ChoaGSDBSrKc4vKtGMNojVUUmONozVjFaJ100tBLINYmM1a61Vkv7//2/23/i/KRBafM3L101OTM5IBQA "PowerShell – TIO Nexus") I'm pretty confident it can be shortened, I will continue to look at it [Answer] ## C, 85 bytes ``` i,j,m;f(d,o,n)int*d,*o;{for(i=n;i--;)for(m=d[!i],j=n;j;o[i]=m=--j^i&&d[j]<m?d[j]:m);} ``` First argument is the input integer array. The second argument is the output integer array. The third argument is the element count for both arrays. See it [work online](https://ideone.com/oEtVbb). [Answer] # [Perl 6](https://perl6.org), ~~26 24~~ 19 bytes ## 26 ``` {.map: (.Bag∖*).min.key} ``` Note that is `∖` U+2216 not `\` U+5C [Try it](https://tio.run/nexus/perl6#ZY5LTsMwFEXnXsVVB9Shqaum9EfUCjFDYsisySAkBlnkYzUOoooyZwVshhlLYSPh2WorEPbonvPetZta4nUh0pAVB1ykVSax6VtRJPoaXNwmz9/vH5eeKFQpXuSh62nqxsjaYINclbLm3tenqHWuDB@Ot0Ob0qp45JMoG01suitNyBp65YG2QqbzpMTIVYTsqdof28ZbcESq1I3xEck3LVMjM3hoGaBq2I9xpz0fJ@1j0Dom7lVthJb7vLNN7WngFx@wrt9dYYYA8xh0aA67gCKhmJEK/qvAqQWNzOmu4qOycWYvySWmbue8N8WS8Brrv9gCi1dn4TBF6v0B "Perl 6 – TIO Nexus") ``` {.map: (.Bag⊖*).min.key} ``` [Try it](https://tio.run/nexus/perl6#ZY5LTsMwFEXnXsVVB9Shqaum9EfUCjFDYsisySAkBlnkYzUOooqyARbAZpixFDYSnq22AmGP7jnvXbupJV4XIg1ZccBFWmUSm74VRaKvwcVt8vz9/nHpiUKV4kUeup6mboysDTbIVSlr7n19ilrnyvDheDu0Ka2KRz6JstHEprvShKyhVx5oK2Q6T0qMXEXInqr9sW28BUekSt0YH5F80zI1MoOHlgGqhv0Yd9rzcdI@Bq1j4l7VRmi5zzvb1J4GfvEB6/rdFWYIMI9Bh@awCygSihmp4L8KnFrQyJzuKj4qG2f2klxi6nbOe1MsCa@x/ostsHh1Fg5TpN4f "Perl 6 – TIO Nexus") ## 24 ``` {(.min X%$_)X||.sort[1]} ``` [Try it](https://tio.run/nexus/perl6#ZY7NSsNAFIX38xSHUu2EplOS/hNa3AouXRSSIJqMMJA/MhNR0jyZO18s3gltVZy7Ouc799xptMTbWiQByz9wm5SpxL5vuchVgePN@Mk5nk5Cl7UJvbjrKXNnpDbYI1OF1Nz5@hS6ypThk9lhYlVS5i98HqXTuVX3hQlYQzceaStgVfZcYDpUBOy1rM9tswM4IlVUjXERyfdKJkamcNAyQGnYb/EBiweljePiknExan@AqGSddbauvQR@@SPW9eESC/hYxaBHOYQ@SbJiRsj/j/wBrSmyotnGZ2Tlwg7BDbxh57rnYUP2Dru/tjWsvb2CwSZJvd8 "Perl 6 – TIO Nexus") ## 19 ``` {.sort[.min X==$_]} ``` [Try it](https://tio.run/nexus/perl6#ZY7PSsNAGMTv@xRDEbuh6Zam/wkpXgWPHoQkiE1WWEg2IbsRJeTJvPli8dvQVsX9TjO/mWFbI/G2FVnIyg/cZlUuEQ2dMFVjY1EqjacounlO@4HwnZXGIkKhtDTc@/oUpi6U5dP5cepUVpUnvkjy2cKpe21D1tL8I7VCVhcvGrNxImSvVXNemx/BkShdt9ZHIt9rmVmZw0PHAGXgfsRHLB6UsZ6PS8bHpPsBopZN0bu57hL45U9YP8RrrBBgk4Ie5RAHJMlKGaHgPwpGtKXIhm6fnpGTK3cEd1iOnWtviR3ZBxz@2s5w9v4KRpsk7X4D "Perl 6 – TIO Nexus") --- ## 26 ``` { # bare block lambda with implicit parameter 「$_」 .map: # for each of the values in the input (implicit method call on 「$_」) ( .Bag # turn the block's input into a Bag ∖ # set-difference 「∖」 U+2216 aka 「(-)」 # ⊖ # symmetric-set-difference 「⊖」 U+2296 aka 「(^)」 * # turn expression into a WhateverCode lambda (this is the parameter) ).min.key # get the minimum pair from the Bag, and return its key } ``` I used the "fancy" unicode [operators](https://docs.perl6.org/language/setbagmix) rather than the ascii equivalents because they would have required a space before them so that they wouldn't be parsed as part of the `.Bag` method call. ## 24 ``` { (.min X% $_) # the minimum cross modulus-ed with the input X|| # cross or-ed .sort[1] # with the second minimum } ``` ## 19 ``` { .sort\ # sort the values [ # index into that .min X== $_ # the minimum cross compared with the input ] } ``` --- (The 24 and 19 byte golfs were inspired by a [Jelly](https://codegolf.stackexchange.com/questions/117774/moving-modest-minimum/117777#117777) implementation) [Answer] ## Clojure, ~~36~~ ~~81~~ ~~62~~ 71 bytes Newest (shouldn't really submit these in a hurry): ``` #(for[c[(zipmap(range)%)]i(sort(keys c))](apply min(vals(dissoc c i)))) ``` [Try it online](https://tio.run/nexus/clojure#dYxBCsMgFET3nmKgFP7fpk3pXcSFGC2fGhUNgeTy1q5L3ywf8zotPiDgQiFX7TSdUlZbqNr08nxlI9Ry3ejtjwbHbMiWEg@skmi3sdEirWUHB@EvSlGpkraYQKOzj7TWd9wwYTYKPww3/XWP8ZvHnsYw9/4B). Aaaand this one has a bug (62 bytes), zipmap produces an unordered map so this won't produce the correct sequence on larger inputs. ``` #(for[c[(zipmap(range)%)][i v]c](apply min(vals(dissoc c i)))) ``` `v` is not actually used for anything but this is shorter than `i (keys c)`. Previous at 81 bytes: [Try it online](https://tio.run/nexus/clojure#dYxBCsMgEEX3nuJDKYzbNCm9yzALMbEMGCNahPby1q5L3l8@3u@0bgEBFwpHYc/00by7TMWl52avVljRxAu5nOMbuyZqLlZatdbDw0PtD2MoF02vmEAjb@ORecYNExYx@GO46dTdR7eMPUSs7f0L). ``` #(let[r(range(count %))](for[i r](apply min(for[j r :when(not= i j)](nth % j))))) ``` [Try it online](https://tio.run/nexus/clojure#dU1LCsIwFNznFANSeNlWKyJ4kpBF0MSmpC/hkSqePoZuxZnNMB@m0cMHBBwo@WqExPHT0z1vXDFobSlkMRFiyZWSPlgj79YCwfU9eybO9YaIpXe5zhi62qEUFYlcE4NWV179xJgTjhgxWYUf9Gz8m537buq8WKt1a18). Oh damn the original (36 bytes) does not work when the minimum number is repeated, `[4 2 2 5]` results in `[2 4 4 2]` as both `2`s are removed :( ``` #(for[i %](apply min(remove #{i}%))) ``` `#{i}` is the set which contains only `i`, it returns truthy for `i` and falsy for others, meaning that the minimum is calculated from all other numbers within the input list. [Try it online](https://tio.run/nexus/clojure#dYtNCoAgFAb3nuIDEZ7b/ugu4iJIQVATCSGis9vbRzPLYTrtzsNDkj@qCVCWtlLihRQyVZeO5iDv8CjNCEGlhnzGDEpbafwZM2HEgNkKfOA2/LaFv5ldrdW69xc). [Answer] # Pyth, ~~8~~ 7 bytes ``` mh.-SQ] ``` *-1 Byte thanks to @isaacg* [Try it!](https://pyth.herokuapp.com/?code=mh.-SQ%5D&input=%5B9%2C+8%2C+9%5D&test_suite=1&test_suite_input=%5B4%2C3%2C2%2C5%5D%0A%5B4%2C2%2C2%2C5%5D%0A%5B6%2C3%2C5%2C5%2C8%5D%0A%5B7%2C1%5D%0A%5B9%2C9%5D%0A%5B9%2C8%2C9%5D&debug=0) [Answer] # [Factor](https://factorcode.org/), 38 bytes ``` [ all-rotations [ rest infimum ] map ] ``` [Try it online!](https://tio.run/##bczfCoIwFAbw@z3F1wMoqFlW0G100010JV4MmSDotO0IhfjsazP8A7UPxvbxO6fgOTXKPO7X2@UILZ6dkLnQy8sXL1Jco1WC6N2qUhJOjPUM9vTYIkKIGIP7buCdXRnauHqYUfgfhSu0syOxTeLYhFwVjZnYHsF3z3pXYOsJHGx@wFjOIFnIBJKxHtjATApeVZ5qiFPZSI0USmhCKYuy7mpkqHmLzLjbNx8 "Factor – Try It Online") Get all the rotations of the input, then get the smallest element in each rotation minus the first element. Like this: \$\begin{matrix} 4 & 3 & 2 & 5 \\ \end{matrix} \rightarrow\$ \$\require{enclose}\begin{matrix}\enclose{horizontalstrike}{4} & 3 & \color{red}{2} & 5 \\ \enclose{horizontalstrike}{3} & \color{red}{2} & 5 & 4 \\ \enclose{horizontalstrike}{2} & 5 & 4 & \color{red}{3} \\ \enclose{horizontalstrike}{5} & 4 & 3 & \color{red}{2} \\ \end{matrix} \rightarrow\$ \$\begin{matrix} 2 & 2 & 3 & 2 \\ \end{matrix}\$ [Answer] # [J](https://www.jsoftware.com), 7 bytes ``` 1<./\.] ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsdzQRk8_Ri8WwrvZp8mVmpyRr2AEhMZArGulkKZgAmaaImSMEDJGCBljBVMgBkGwnBlYwFTBAiJrqGAOETdXMISIWAIhWATEgAhZAFkWMEEgB-KqBQsgNAA) J's outfix adverb `\.` is made for this. It applies a verb (in this case min) to every outfix of a list of a specified size (in this case 1). Outfix being the inverse operation of "window" functions which exist in most languages -- a list composed of the original list without a window as that window moves across the list. [Answer] # PHP, 72 Bytes ``` <?$k=$g=$_GET;sort($k);foreach($g as&$v)$v=$k[$v==$k[0]?:0];print_r($g); ``` [Online Version](http://sandbox.onlinephpfunctions.com/code/360e9ea9c9cb808cb2c458e83bf1e1c8d67732b3) [Answer] # PHP, 47 bytes ``` while(++$i<$argc)echo@min([z,$i=>z]+$argv),' '; ``` [Answer] # Scala, 37 bytes ``` l.indices map(i=>l diff Seq(l(i))min) ``` `l` is any collection of Int. Test cases: ``` scala> val l = List(4,3,2,5) l: List[Int] = List(4, 3, 2, 5) scala> l.indices map(i=>l diff Seq(l(i))min) res0: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 2, 3, 2) scala> val l = List(4,2,2,5) l: List[Int] = List(4, 2, 2, 5) scala> l.indices map(i=>l diff Seq(l(i))min) res1: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 2, 2, 2) scala> val l = List(6,3,5,5,8) l: List[Int] = List(6, 3, 5, 5, 8) scala> l.indices map(i=>l diff Seq(l(i))min) res2: scala.collection.immutable.IndexedSeq[Int] = Vector(3, 5, 3, 3, 3) scala> val l = List(7,1) l: List[Int] = List(7, 1) scala> l.indices map(i=>l diff Seq(l(i))min) res3: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 7) scala> val l = List(9,9) l: List[Int] = List(9, 9) scala> l.indices map(i=>l diff Seq(l(i))min) res4: scala.collection.immutable.IndexedSeq[Int] = Vector(9, 9) scala> val l = List(9,8,9) l: List[Int] = List(9, 8, 9) scala> l.indices map(i=>l diff Seq(l(i))min) res5: scala.collection.immutable.IndexedSeq[Int] = Vector(8, 9, 8) ``` This can probably still be golfed, I couldn't find a shorter way to remove an element from a list than `l diff Seq(l(i))` [Answer] # C#, 36 Bytes ``` i.Select((x,a)=>i.Where((y,b)=>b!=a).Min()) ``` Takes the elements (i) and looks in the elements without the current item for the minimal value. It's kind of sad, that some other attempts don't work, as we work with primitive types, and therefore don't have lists with references to compare the items from. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` {sWQè ``` Port of [*@xnor*'s Python 2 answer](https://codegolf.stackexchange.com/a/117779/52210). [Try it online](https://tio.run/##MzBNTDJM/f@/ujg88PCK//@jTXQMdYx1zGIB) or [verify all test cases](https://tio.run/##MzBNTDJM/W/u5nl4gr2SwqO2SQpK9v@ri8MDD6/4r/M/2kTHWMdIxzSWC8gygrLMgGKmQGgBZJvrGAJJSx1LMGkBpk10DIEqzGIB). **Explanation:** ``` { # Sort the (implicit) input-list # i.e. [4,1,3,6] → [1,3,4,6] s # Swap, so the (implicit) input-list is at the top of the stack again W # Get the minimum without popping from the list # i.e. [4,1,3,6] → 1 Q # Check for each element if they are equal to this value (1/0 as truthy/falsey) # i.e. [4,1,3,6] and 1 → [0,1,0,0] è # Use these 0s and 1s to index in the sorted list # i.e. [1,3,4,6] and [0,1,0,0] → [1,3,1,1] ``` [Answer] # [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 7 bytes Port of xnor's Python 2 answer. Requires `⎕IO←0`: ``` ∧⊇⍨⊢=⌊/ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91LH/U1f6od8WjrkW2j3q69P@nAcUf9fZBlHQ1H1pv/KhtIpAXHOQMJEM8PIP/pymYKBgrGCmYcoFYRlCWGVDMFAgtgGxzBUMgaalgCSYtFCwB "APL (Dyalog Extended) – Try It Online") Explanation: ``` ∧⊇⍨⊢=⌊/ ⍝ Monadic function train ⌊/ ⍝ The minimum element of the input ⊢= ⍝ Element-wise compare the input to the above ⍝ Results in a boolean vector, let's call it "X" ∧ ⍝ Sort the input ⊇⍨ ⍝ Index into sorted input by X ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~49~~ 38 bytes -11 bytes thanks to mazzy ``` ($a=$args)|%{($c=$a|sort)[$_-eq$c[0]]} ``` [Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9X0Ml0VYlsSi9WLNGtVpDJRnIqSnOLyrRjFaJ100tVEmONoiNrf1fy8WlpKKhBtRkomCsYKRgqqmEEDBCFTADqjAFQguEkLmCIYJjqWCJzLFA5hoaAM0yAWoGqf8PAA "PowerShell – Try It Online") Improvement of [Sinusoid's lovely answer](https://codegolf.stackexchange.com/a/117815/78849). Saves 10 bytes by using explicit output instead of building an array. Indexes into the sorted array to either spot 0 (i.e. smallest value) or spot 1 if the conditional is true. [Answer] # [Husk](https://github.com/barbuz/Husk), 6 bytes ``` mo▼`-¹ ``` [Try it online!](https://tio.run/##yygtzv7/Pzf/0bQ9CbqHdv7//z/aRMdYx0jHNBYA "Husk – Try It Online") [Answer] # [K (ngn/k)](https://bitbucket.org/ngn/k), 12 bytes ``` {(&/x_)'!#x} ``` [Try it online!](https://tio.run/##y9bNS8/7/z/NqlpDTb8iXlNdUbmi9n@auoaJgrGCkYKptQmQBNFmQL4pEFpYmysYWlsqWAKxhYKl5n8A "K (ngn/k) – Try It Online") Uses `list _ int` to remove individual values from the input, then takes the minimum of the remaining values. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes ``` s∇g=İ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJz4oiHZz3EsCIsIiIsIls0LDEsMyw2XSJd) ## How? ``` s∇g=İ s # Sort the input ∇ # Push this two values down so that there are two copies of the input on top g # Get the minimum of the input = # For each in the input, is it equal to that? İ # Index this into the sorted list ``` ]
[Question] [ A [polyglot](/questions/tagged/polyglot "show questions tagged 'polyglot'") is a program that can be run in 2 or more different programming languages. What general tips do you have for making polyglots, or choosing languages that are easy to write polyglots for a specific task? Please post the tips that could be applied in most situations. I.e. they shouldn't work only in polyglots of two specific languages. (You could simply post an answer to a polyglot question if you have a too specific tip.) But you can introduce features of a language that makes it easy to work with many languages, or easy to be added to any existing polyglots. Please post one tip per answer. And feel free to suggest edit if a language-specific tip also applies to another language. [Answer] # Use two-dimensional languages Unlike one-dimensional languages, which generally parse the entire source code and will produce syntax errors or unwanted runtime effects on things they don't understand (thus forcing you to hide other languages' code from them), two-dimensional languages tend to only parse code in the path of execution, meaning that the entire rest of the program is ignored. There's also a lot more room to split execution paths away from each other in two dimensions; you can send the instruction pointer turning in an unusual direction, like down or even left (wrapping round to the right hand side of the program), to get it out of your way very quickly. The techniques useful in one-dimensional languages also generalise to two-dimensional languages (e.g. you can skip over code with `;;` in Befunge-98, in addition to just sending the IP in a weird direction), making this mostly just a strict gain compared to a one-dimensional solution. As a bonus, several two-dimensional languages have an entry point other than the top-left of the program, meaning that you don't need to go to any effort to split them away from other languages; they'll split themselves off from the group naturally. [Answer] # Exploit comment symbols A simple way to create a two-language polyglot is to have the code divided in two parts as follows: 1. The first part does the actual work in language A, is harmless in language B (no errors), and ends in a language-A comment symbol, which hides the second part to language A. 2. The second part does the actual work in language B. Thus * Language A sees the first part, which does the job, and then a comment. * Language B sees a useless first part and then the second part, which does the job. The only difficult part here is finding a set of statements (first part) that do the job in language A while not giving errors in language B. Some suggestions for this: * Most stack-based languages allow displaying only the top of the stack at the end of the program (sometimes this is even default, as in 05AB1E). * Some languages ignore undefined statements (for example Golfscript). A simple example that uses these guidelines can be found [here](https://codegolf.stackexchange.com/questions/98776/palindrome-polyglot/98781#98781). Languages A and B are [MATL](https://github.com/lmendo/MATL) and [05AB1E](https://github.com/Adriandmen/05AB1E) respectively. [Answer] # Know your Trues and Falses Each language sees "true" and "false" in a slightly different way. If they have similar syntax, you can exploit this by adding a decision that the languages will handle differently. [One example](https://codegolf.stackexchange.com/a/97812/60919) from the Trick or Treat thread uses `''`, an empty string. In Lua, this evaluates to truthy, but falsy in Python, so the following: ``` print(''and'trick'or'treat') ``` ..will print a different string in each language. All it takes is finding a value like this. For example, you could use `'0'`, which evaluates to `false` in PHP but `true` in Python. [Answer] ## Blockquotes in at least one language Here's an example that works both in Python and C++ ``` #include <iostream> /* """ */ int main() { std::cout << "Hello World!\n"; } /* """ print("Hello World!") # */ ``` [Luis Mendo](https://codegolf.stackexchange.com/a/101161) pitched what I think is by far the easiest solution, which is to use comments. You look for one language that has block commenting and another language where regular syntax in the first is commenting syntax in the second. Even easier is two languages with different block commenting styles that are interchangeably correct syntax, but I couldn't be bothered to check. Check it out in [Python 3.5](https://repl.it/E8GQ/0) and [C++](https://repl.it/E8GS/0) [Answer] # Divide and conquer When you're writing a polyglot in a large number of languages, you won't necessarily be able to separate all the language's control flows from each other immediately. Thus, you'll need to "true polyglot" some of the languages for some length of time, allowing the same code to run in each of them. There are two main rules to bear in mind while you're doing this: * **The control flow in any two languages should either be very similar, or very different**. Trying to handle a large number of interleaved control flows is a recipe for getting confused and makes your program hard to modify. Instead, you should limit the amount of work you have to do by ensuring that all the programs that are in the same place are there for the same reason and can happily be run in parallel for as long as you need them to be. Meanwhile, if a language is very different from the others, you want its execution to move to a very different location as soon as possible, so that you don't have to try to make your code conform to two different syntactic models at once. * **Look for opportunities to split one language, or a group of similar languages, away from each other. Work from larger groups down to smaller groups.** Once you have a group of similar languages all at a certain point in the program, you'll need to split them up at some point. At the start of the program, you might well, say, want to split the languages that use `#` as a comment marker away from languages that use some other comment marker. Later on, perhaps you have a point where all languages use `f(x)` syntax for function calls, separate commands with semicolons, and have similar syntactic similarities. At that point, you could use something much more language-specific to split them, e.g. the fact that Ruby and Perl don't process escape sequences in `''` strings, but Python and JavaScript do. In general, the logical flow of your program should end up as a tree, repeatedly splitting into groups of languages that are more similar than each other. This puts most of the difficulty in writing the polyglot right at the start, before the first split. As the control flow branches out more and more, and the languages that are running at any given point get more and more similar, your task gets easier because you can use more advanced syntax without causing the languages involved to syntax-error. A good example is the set {JavaScript, Ruby, Perl, Python 3}; all these languages accept function calls with parentheses and can separate statements with semicolons. They also all support an `eval` statement, which effectively allows you to do flow control in a portable way. (Perl is the best of these languages to split off from the group early, because it has a different syntax for variables from the others.) [Answer] # Variable or code inside string literals Double-quoted string literals are mostly harmless in many languages. But in some languages they could also contain code. In Bash, you can use ``...`` (it doesn't end the program): ``` "`echo Hello world! >/proc/$$/fd/1`" ``` In Tcl, you can use `[...]`: ``` "[puts {hello world!};exit]" ``` In PHP, you can use `${...}` (this generates an error in Bash so it must appear after the Bash code): ``` "${die(print(Hello.chr(32).world.chr(33)))}"; ``` In Ruby, you can use `#{...}`: ``` "#{puts 'Hello world!';exit}" ``` There might be also others. These grammars aren't compatible. That means you can put all the code of these languages in one string in a harmless location. And it will just ignore the unrecognized code in other languages and interpret them as string content. In many cases, you could also easily comment out a double quote character there and make a more traditional polyglot. [Answer] # Hide code inside string literals In most languages, a string literal on its own either does nothing, or does something that can be easily reversed (such as pushing the string onto the stack). String literal syntax is also relatively nonstandardised, especially for the alternative syntaxes that many languages use to handle strings with embedded newlines; for example, Python has `""" ... """`, Perl has `q( ... )`, and Lua has `[[ ... ]]`. There are two main uses of these. One is to allow you to interleave sections intended for different languages via starting a string at the end of one language's first section and resuming it at the start of the second: it should be fairly easy to avoid accidentally closing the string due to the variety of string delimiters among different languages. The other is that many string delimiters happen to be meaningful as a command in other languages (often more so than comment markers), so you can do something like `x = [[4] ]`, which is a harmless assignment in languages which use JSON notation for lists, but which starts a string in Lua (and thus allows you to split the Lua code from the rest, given that it effectively "jumps" to the next `]]`). [Answer] # Variable Aliasing This is probably one of the simplest yet (IMO) most important tricks to use, especially since it can reach so many languages. Example: ``` print=alert;print("Hello World!") ``` This will work in not only Javascript, but also Python, Ruby, etc. More examples later when I think of some others. Of course, comment suggestions/post edits are welcome. [Answer] ## `#`-based comments *This tip is a subset of [Exploit comment symbols](https://codegolf.stackexchange.com/a/101161/21487) and [Blockquotes in at least one language](https://codegolf.stackexchange.com/a/101168/21487)* When creating polyglots with many languages, especially production-ready languages as opposed to esolangs, it can be useful to look at the languages which use `#` in block or single-line comments. * There are many languages with block comment syntaxes starting with `#`, and there's a lot of variety in the chars following the `#`. * Most of these languages also allow a single `#` as a line comment, which means that something which might start a block comment in one language is just an ordinary comment in another, making it easy to fit in. Here's a quick summary list of languages which use `#` in a block comment (not exhaustive): ``` Language Start End Single-line #? Notes ------------------------------------------------------------------------------------------ Agena #/ /# ✓ AutoIt #cs #ce Brat #* *# ✓ C #if 0 #endif Not actually a comment CoffeeScript ### ### ✓ Needs to be on separate line Common Lisp #| |# Julia #= =# ✓ Lily #[ ]# ✓ Objeck #~ ~# ✓ Perl 6 #`{ }# ✓ Any bracketing chars will do Picolisp #{ }# ✓ Scheme #| |# ``` For more examples, see [Rosetta Code](https://www.rosettacode.org/wiki/Comments). Here's a quick and easy example, as a demonstration: ``` #| ### #`[ print("Julia") #= |# (format t "Common Lisp") #| ### alert("CoffeeScript") ### ]# say "Perl 6" #`[ ... # ]# # ### # |# ; =# ``` [Answer] # Ending the program You can end the program abruptly in one language so that it will ignore the code in another language. So basically this format can be used ``` code_in_language1 end_program_in_language1 code_for_language2 end_program_in_language2 ... ``` where `end_program_in_languageN` is the command for ending the program. For example, in my answer in [What will you bring for Thanksgiving?](https://codegolf.stackexchange.com/questions/100470/what-will-you-bring-for-thanksgiving/100483#100483), I ended the program in Dip, and then I wrote code for another language, V, so that the Dip interpreter would ignore it. ``` "turkey"e#"corn"??"gravy"p&Ssalad "turkey"e#"corn"??"gravy" p& # print stack and exit program (Dip) Ssalad # Now that the program ended in Dip, # I can write V code that would otherwise # have caused errors in Dip ``` But then, not all languages have a command that can end the program just like that. However, if such a language has the feature, it should be used wisely. As @LuisMendo suggested, you can create an error (if it is allowed) to end the program if the language does not already have an "end program" builtin. [Answer] ## Arithmetic operator discrepancies For similar languages or simple polyglots, sometimes it's useful to look for differences in how the languages perform arithmetic. This is because most (non-esoteric) languages have infix arithmetic operators and arithmetic can be a quick and easy way to introduce a difference. For example: * `^` is bitwise XOR in some languages and exponentiation in others * `/` is integer division in some languages and floating point division in others + For the integer division languages, `-1/2` is `-1` in some languages (round down) and `0` in others (round to zero) * `-1%2` is `-1` in some languages and `1` in others * `--x` is a no-op in some languages (double negation) and pre-decrement in others * `1/0` gives infinity in some languages and errors out in others * `1<<64` gives 0 in some languages (overflow) and `36893488147419103232` in others [Answer] # Use Brainfuck Pretty much all BF implementations cast out chars that aren't `+-<>[].,`, which just so happens to work in our favor! BF is probably one of the easiest languages to work into a polyglot because of this feature, **as long as you write the BF part first.** Once you have your BF code written out, it's just a matter of modeling whatever other code you have *around* the BF structure. Here's a really simple example: ``` .+[.+] ``` This pretty much increments and charcode-outputs "forever" (depending on runtime settings). Now if you wanted to write a random piece of code, say, in JS, you could do: ``` x=>"asdf".repeat(+x)[x*Math.random()*2+1|0] ``` Notice how the JS is molded around the BF. Be sure to know that this works best if you are really set on starting with BF; it's decently harder to start with another language and try to incorporate BF. [Answer] # Use languages in which most characters don't matter This is a generalization of [Mama Fun Roll's point about BF](https://codegolf.stackexchange.com/a/101171/16766). An esolang that ignores most characters is very useful in polyglots. Also useful: an esolang in which a large set of characters are interchangeable. Some examples: * [Whitespace](http://esolangs.org/wiki/Whitespace) ignores everything that isn't space, tab, or newline. * [Brain-Flak](http://esolangs.org/wiki/Brain-Flak) basically ignores everything besides `()[]{}<>`. (`@` sometimes causes an error when the interpreter tries to parse it as the start of a debug flag.) * [oOo CODE](http://esolangs.org/wiki/OOo_CODE) ignores everything except letters. Furthermore, all lowercase letters are interchangeable, as are all uppercase letters. * [Wierd](http://esolangs.org/wiki/Wierd) only distinguishes between whitespace and non-whitespace characters. * In [Wordy](http://esolangs.org/wiki/Wordy), some punctuation characters are ignored, and all letters are interchangeable. * Both [Parenthetic](http://esolangs.org/wiki/Parenthetic) and [Parenthesis Hell](http://esolangs.org/wiki/Parenthesis_Hell) ignore everything except parentheses. [Answer] # Be Aware of Nested Block Comments Sometimes multiple languages will use the same syntax for block comments, which is more often than not a deal breaker for creating a polyglot with the two languages. Very occasionally however, one of the languages will allow nested block comments, which can be abused to create separate code paths. For example, consider this polyglot: ``` #[#[]#print("Lily")#]#echo"Nim" ``` Nim and Lily both use `#[` and `]#` to begin and end block comments, but only Nim allows nested block comments. Lily considers the second `#[` as part of the singular block comment and the first `]#` as terminating the block comment. (The `#` following Lily’s print statement is a line comment that hides Nim’s code.) Nim alternatively, sees the `#[]#` as a nested (albeit empty) block comment and `print("Lily")#` as the outer block comment. [Answer] # Call nonexistent functions, then exit while evaluating their arguments Many programming languages are capable of parsing an arbitrary identifier followed by a pair of parentheses with an expressions inside: ``` identifier(1 + 1) ``` Sometimes, the form of the identifier in question might be fixed, due to being needed to give code to a different language you're using. That might at first seem to cause trouble, if the identifier doesn't correspond to a function that the language actually has. However, many programming languages will evaluate a function's arguments before they check to see if the function itself actually exists (e.g. Lua), and so you can use this sort of construct anyway; all you need is to exit the program somewhere inside the function's arguments. Here's an example, a dc/Lua polyglot: ``` c2pq(1 + #os.exit(print(3))) ``` `c2pq` is a dc program to print 2 and exit; Lua sees this as the name of a function, but Lua can be prevented from erroring via placing an exit command in its argument. The big advantage of this construction is that unlike an assignment (`c2pq =`), it's not automatically incompatible with languages in which variable names start with a sigil; function name syntax is much more consistent across languages than variable name syntax is. [Answer] Not sure if this counts, but... # Use a shebang line to turn everything into a valid `perl` program According to [this answer](https://askubuntu.com/a/850575) and the Perl documentation, if you pass any file that starts with a shebang line to `perl`, it invokes the appropriate program to run it. For instance, this ``` #!/usr/bin/python for i in range(6): print i**2 ``` gets executed by the Python interpreter if you call `perl filename.py`. ]
[Question] [ > > **Note: The survey for community favorite will be released soon** > > > In this KoTH, the aim is to be the last bot alive. Coins will be placed in random areas, and your bot must get the coins first. If a bot runs into another bot, the bot with more coins wins, and the other bot dies. More details below. ## Coin types There will be 2 types of coins: gold and silver. Gold adds 5 coins to the bot's strength, and silver adds 2. Once a coin is collected, another coin is placed at another spot on the board. At any given time, there is one gold coin and four silver coins in the arena. ## Bot collisions In the event of two bots trying to occupy the same space, the one with more coins will stay, and the one with less will...not. The winning bot will gain **85%** of opponents coins (Rounded up). If they are tied, both die. If three or more try to occupy the same space, the most powerful wins, and gets 85% of all the other bot's coins. In the event that the most powerful bot is a tie, **all** of the bots die who tried to enter the space. ## Arena The arena's side length is calculated with `4 + botCount`. When placing bots in the beginning of the game, random places are chosen. The system ensures that no bots start in the same space, or next to each other. Coins generate randomly, excluding a 3 by 3 square centered on each bot. If a bot is found outside of the arena, it dies instantly. The arena starts at (0,0), or Northwest, in the upper left corner, and the location of a bot is always an integer. ## Your bot Your bot should be a function, in any object oriented language that has arrays, integers, strings, and functions. Note that all submissions will be converted to Javascript, to make things simple. To store information between moves, use `botNotes.storeData(key, value)` and `botNotes.getData(key, value)`. You may not store or access data any way, other than that which is provided through the parameters and `botNotes`. You should create a function that, when called, returns a string `north`, `east`, `south`, `west`, or `none`. There will be 3 arguments for the function: * An object with four integers (`locationX`, `locationY`, `coins`, `arenaLength`), your current location, your coins, and the length of the arena * A multidimensional array with the X and Y coordinates of other bots, and their coin count, ex-`[[0,5,4],[4,7,1],[7,4,12]]` * An array with the coin locations listed (Gold is always first) This is a king of the hill challenge, [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) prohibited. Your function will be run several thousand times, each time allowed one "Move". Note that if the game exceeds **20,000 moves**, the bot with the most coins wins. This will be done 8,000 times, to remove randomness. **Chatroom:** <https://chat.stackexchange.com/rooms/81347/gold-collectors-koth> **Prizes:** **First Place:** 100-point bounty **Community Favorite:** 15-point accepted answer **Winners:** **First Place:** TBTPTGCBCBA **Second Place:** Big King Little Hill **Third Place:** Potentially Victorious **Fourth Place:** Polite Near-Sighted Drunk Bot **Fifth Place:** Safety Coin [Answer] ## BaitBot - JavaScript Node.JS Why bother chasing or running if you can never catch? Instead, BaitBot finds the nearest coin and waits for a weaker bot to also approach it. When they're both adjacent, baitBot goes for the coin assuming the weaker bot will as well. If baitBot is waiting and a stronger bot approaches, he just grabs the coin and skedaddles. [Try Me!](https://tio.run/##pVVbb9owFH7nV5ynkmguhZS2UwV96C7SpF0eVmmroqhywgGMUnuyTemE@O3s2AlJCLSatheM7XP9vs8nC/7ETabFL3sq1QS32@lSZlYoCSkX9lbZ4BEZKDtHbRhkSkgTwroDkKOFidDojQ2MIe5KJbHLusiNpcWopZ3TukK/lUrTNiHPKsNEGMtlhncq4EVQAI12qSUEX7id93hqAh73EziFR@zlKuPO72cIb6BxP2jd34chhdocy3SLdoUoA84gDV9PmNJyLFFKy2ECPlnwDKV9L3Tdy9lZn3CRisGAReycDWn34fuPr/5STIP9/sdjGOw8/bUv5Ga/8/Wu3sGmNMTcYGU9auG0Lq3PD60Hrdj3tXXUtK4yDovT4tfH2dn3N204cCJSkQv7@4BYyuhFREjyOEpKx44D66OQE5DINQnGKw04HcxIZxKfLVgFwpbCy3JlyOqdMxoXquwZElhAzKYE5U1LW6fNfRqGhFWnTUEjZkjQVFyQVePqNU4K5TcAOnQdveTqX8nLrods1a7Fy3rVd/SSb/FIN00aPk1hhV2NFeq8JsONAewaOrJzjbwkgsFiSZTNNE9rikoi7wq7cTlCelORW6Q34jjaU8kI@uF/c7iXlGKOIWrprx5ZcfPNNskvROmx@OaKXgnX4orGISylFXkTBa6dPnluVAUX3XrAShwKE/MXCNxAH05ODmZVozQGuzlRdF7G7uUoZ3buAoT/1uwxD4K3s@lsn7gm8TyodEEtrCvpXtNMg0pRfuef4TVcUZUaJf/si7qGt5uOi1F0/8C1dt@K@NzNw4TFbjIOIvpzxYbsMkm8rYtEsZvWcJEwiCMapeUaufWSwdCtF@U95e5TjIzqV7lT/CyoP2OuB9aog@3lCcPtHw) ``` function baitBot(me, others, coins) { let directions = ['none','east','south','west','north'] function distanceTo(a) { return (Math.abs(a[0] - me.locationX) + Math.abs(a[1] - me.locationY)) } function distanceBetween(a, b){ return (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1])) } function adjacentDir(a) { //0 = no, 1,2,3,4 = ESWN if(distanceTo(a) == 1) { if(a[0] > me.locationX){ return 1} else if(a[0] < me.locationX) {return 3} else if(a[1] > me.locationY) {return 2} else{ return 4} } else {return 0} } function edibility(a) { return me.coins - a[2] } //Find nearest coin and get next to it let closestCoin = coins.sort((a,b) => distanceTo(a) - distanceTo(b))[0] if(distanceTo(closestCoin) > 1) { if(closestCoin[0] > me.locationX){ return 'east'} else if(closestCoin[0] < me.locationX){ return 'west'} else if(closestCoin[1] < me.locationY){ return 'north'} else if(closestCoin[1] > me.locationY){ return 'south'} } //If we're next to a coin and there's a threat close, just grab it let nearestThreat = others.filter(a => edibility(a) < 0).sort((a,b) => distanceBetween(a, closestCoin) - distanceBetween(b, closestCoin))[0] if(nearestThreat && distanceBetween(nearestThreat, closestCoin) <= 2) { return directions[adjacentDir(closestCoin)] } //Otherwise, wait until there's a target also next to the coin. If none are close, just take it let targets = others.filter(a => edibility(a) > 0 && distanceBetween(closestCoin, a) <= 3) targets.sort((a,b) => distanceBetween(a, closestCoin) - distanceBetween(b, closestCoin)) if(targets.length > 0 && distanceBetween(targets[0], closestCoin) > 1){ return directions[0] } return directions[adjacentDir(closestCoin)] } ``` [Answer] # Big King Little Hill | JavaScript ``` function BigKingLittleHill(me, enemies, coins) { // Is a move safe to execute? function isItSafe(x){ let loc = [x[0] + me.locationX,x[1] + me.locationY]; return loc[0] >= 0 && loc[0] < me.arenaLength && loc[1] >= 0 && loc[1] < me.arenaLength && enemies .filter(enemy => me.coins <= enemy[2]) .filter(enemy => getDist(enemy,loc) == 1).length === 0; } // Dumb conversion of relative coord to direction string function coordToString(coord){ if (coord[0] == 0 && coord[1] == 0) return 'none'; if (Math.abs(coord[0]) > Math.abs(coord[1])) return coord[0] < 0 ? 'west' : 'east'; return coord[1] < 0 ? 'north' : 'south'; } // Calculate a square's zone of control function getZOC(x) { let n = 0; for(let i = 0; i < me.arenaLength;i++){ for(let j = 0; j < me.arenaLength;j++){ if (doesAControlB(x, [i,j])) n++; } } return n; } function doesAControlB(a, b) { return getEnemyDist(b) > getDist(a, b); } // Distance to nearest enemy function getEnemyDist(x) { return enemies.filter(enemy => enemy[2] >= me.coins/50).map(enemy => getWeightedDist(enemy, x)).reduce((accumulator, current) => Math.min(accumulator, current)); } // Weights distance by whether enemy is weaker or stronger function getWeightedDist(enemy, pos) { return getDist(enemy, pos) + (enemy[2] < me.coins ? 1 : 0); } function getDist(a, b){ return (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1])) } //check whether there are coins in our Zone of Control, if yes move towards the closest one let loc = [me.locationX,me.locationY]; let sortedCoins = coins.sort((a,b) => getDist(loc,a) - getDist(loc,b)); for (let coin of sortedCoins) { if (doesAControlB(loc,coin)){ return coordToString([coin[0] - loc[0],coin[1] - loc[1]]); } } //sort moves by how they increase our Zone of Control northZOC = [[0,-1], getZOC([loc[0],loc[1]-1])]; southZOC = [[0,1], getZOC([loc[0],loc[1]+1])]; westZOC = [[-1,0], getZOC([loc[0]-1,loc[1]])]; eastZOC = [[1,0], getZOC([loc[0]+1,loc[1]])]; noneZOC = [[0,0], getZOC([loc[0],loc[1]])]; let moves = [northZOC,southZOC,westZOC,eastZOC,noneZOC].sort((a,b) => b[1] - a[1]); //check whether these moves are safe and make the highest priority safe move for (let move of moves) { if (isItSafe(move[0])) { return coordToString(move[0]); } } //no moves are safe (uh oh!), return the highest priority return coordToString(moves[0][0]) } ``` [Try it online!](https://tio.run/##jVZRb9s2EH6WfsXtpZZgxrGWpcWSOMWaDlixDnvogG01/CDLZ4upTGYklTgL8tuzO1KSZccG9pDQPH3Hu/v43Um3@X1uCyPv3InSC3x5WdaqcFIr@CBXv0q1@iydq/AXWVXJGgWgwrVEK6DQUtkUnuI4iqPTU/hkIYe1vkew@RLBacANFrXD93HUnSntJ/eFHieb9CmOoqhCB5UuYALTzXQ8gyGscUSGnNF/ic0027P9PbtkP4OuNopd2et6AmN486bdXrFDblDln1GtXMkOzdNsF5wdBTdl8i6KRktZOTQJGx9hcs0uvny4mnjk4/T7WXoEu0L3UVoXDIKipjCZQJaOKh@PNpQQFfXcEvmxXs@JXXWPxjJnegkGK6qeqC20NgvmdiENBkqtM3RLPY495g/9xdsTv/NkyyWEHXM0aVgIhiwYUmh4HSitcHDZOP2Wu3KUz23nncI17BmzWZr2LqaLc0Vh3sPgAa0bwAUMMKcffPAOMOuAShtXeqTVNf3yxEQNMzd5VdTEBJLS7D813drAwr@UKnNEjDmjqx4RxPzX329IasDls9QUBK6jpTYJG6Q30LIvg0s5HAaJttDbAL19Db1toZ6thUb7001I5kOyETCV4pbYATUceu1SPf6vYUC1JXZ5756QC5iHChoHKutn1pJX1ZzvopWYh/rjAIKUyJqrwnejQsrZuqDXXZa2xzVctaGaLnil6Vbz3ExtL5yej9PROr/bUf6fKFelw0WvA2CTpiODi7rAJMmLol7zlWpDE6U2xKpL2dfLay3VYcROkSGGpZZoip0/wkOJrkQTEqWpAw@Yf6O9NtwvWq3Q7FJwKNE7bfeJf/V4CElHxtV2LryHjDQ83ubZj7W9q97h2y7LuW9OYO4bbQg9exbsodeeQ1MUJRbfunr5H3WHwTCeQdL4qA18bXqkEZUAEuoj2jCunX7IzcKyLxSVtiwSwsf94bwzlffHMeMs9S0ubnzQSQg@YhtdsZin/TlIriJPqZC@Ye6vlFoNfK@xP@fbOzXcxOsGY2@Gp@nT/vzpZuCUAYHV8IrwHoHO8BqYcXimtGGVA3t2LKup1A/MDglJFYYmGB4iNY787KKJw4RNx@Ikm4l2Bk2buCEaPUmZOD/itg5H8cMGz1O0hZ9kYvwKT8a2HsbzsG3xh@DDXTgP/W0242PZBDBfUyCI4G3loq1INKmKJgXRnD3bE8U8XAJLm2/goKCJ7hCIZe2/LXK1gDX1s5dsSY3Lkr0zUhvpHgOEPXqC8kKnu/IHbaXUfY6wnfuNHsFRGbWgrVROT5XeTy6pS9Dld6loX6aHkoyPR7AUgqPEzy8@cySCn7rmu4BzAV33@Z1vtgs4E9B7KV1Alj3HfEAzw/2tnosfxNlM0PrOr@/EuV/P/DqL295r0fAjiYC0ACzN6VsBb3mlSOdhZR9671pd8UhYJf/rkzF9@Q8 "JavaScript (Node.js) – Try It Online") Big King Little Hill makes decisions based on “zones of control”. It will only pursue coins that are in its zone of control meaning it can reach the coin before any other bot can. When there are no coins in its zone of control it instead moves to maximize the size of its zone of control. Big King Little Hill calculates the zone of control of each of its 5 possible moves and favors the moves that maximize the size of its zone of control. In this way, Big King Little Hill eventually reaches a local maximum (little hill) of control and waits for a coin to be generated within its zone. Additionally, Big King Little Hill rejects any move that could result in its death unless there are no alternatives. Big King Little Hill is a pessimist (it prefers the term realist) because it does not bother to contest any coin it isn't assured to get. It is also a pacifist in that it does not pursue weaker bots in any sense (although it might step on one if they get in the way). Lastly, Big King Little Hill is a coward that will not jeopardize its own life for any reward unless it absolutely has to. [Answer] # First Gen Learning Algorithm | [JavaScript (Node.js)](https://nodejs.org) ``` function run() { return ['north','east','south','west'][(Math.random()*4)|0]; } ``` [Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/rTQvuSQzP09DU6Gai7MotaS0KE8hWj0vv6gkQ11HPTWxuARIFeeXgrnlqUBubLSGb2JJhl5RYl5Kfq6GppaJZo1BrDVX7f//AA "JavaScript (Node.js) – Try It Online") Have you ever seen those timelapses of learning algorithms learning to play a game? They often move almost randomly in the first few generations... [Answer] # Potentially Victorious | JavaScript Preferred color for this bot is `#1600a6`. ``` function (me, others, coins) { let huntingTimer = botNotes.getData("huntingTimer"); let huntedIndex = botNotes.getData("huntedIndex"); if(!huntingTimer) huntingTimer = 0; else if(huntingTimer >0) huntingTimer--; else if(huntingTimer == -1) huntingTimer = Math.ceil(20*(1+Math.log2(me.coins/25))); else huntingTimer++; function distanceFromMe(X, Y) { return Math.abs(me.locationX - X) + Math.abs(me.locationY - Y); } function U(x, y) { function distance(X, Y) { return Math.abs(X-x) + Math.abs(Y-y); } function gravitation(k, X, Y) { return - k / ( distance(X, Y) + .2 ); } function exponential(k, q, X, Y) { return - 5*k * Math.exp(- q * distance(X,Y)); } // No going away from the arena. if(!((0 <= x) && (x < me.arenaLength) && (0 <= y) && (y < me.arenaLength))) { return Infinity; } let reachability = [1, 1, 1, 1, 1]; let distances = coins.map(c => distanceFromMe(c[0], c[1])); for(let i = 0; i < others.length; i++) { for(let coin = 0; coin < 5; coin++) reachability[coin] += (Math.abs(others[i][0] - coins[coin][0]) + Math.abs(others[i][1] - coins[coin][1])) < distances[coin]; } let potential = gravitation(40, coins[0][0], coins[0][1]) / (reachability[0]); // Gold // Silver for(let i = 1; i < 5; i++) { potential += gravitation(10, coins[i][0], coins[i][1]) / (reachability[i]); } others.sort((a, b) => b[2] - a[2]); // Other bots for(let i = 0; i < others.length; i++) { if( ((Math.abs(me.locationX - others[i][0]) + Math.abs(me.locationY - others[i][1])) < 3) && (huntingTimer == 0) && (me.coins > 25) && (me.coins < (others[0][2]*.9)) && (others[i][2] < me.coins-5) && (others[i][2] >= 10) ) { huntingTimer = -10; huntedIndex = i; } if((huntingTimer < 0) && (huntedIndex == i)) potential += exponential(30, 1, others[i][0], others[i][1]); if(others[i][2] >= me.coins) { // Otherwise, they could eat us, and we will avoid them. potential += exponential(-1400, 3, others[i][0], others[i][1]); } } return potential; } // All possible squares we can move to, with their names. let movements = [ [ "north", U(me.locationX, me.locationY - 1)], [ "south", U(me.locationX, me.locationY + 1)], [ "east", U(me.locationX + 1, me.locationY)], [ "west", U(me.locationX - 1, me.locationY)], [ "none", U(me.locationX, me.locationY)] ]; botNotes.storeData("huntingTimer", huntingTimer); botNotes.storeData("huntedIndex", huntedIndex); // Sort them according to the potential U and go wherever the potential is lowest. movements.sort((a, b) => a[1] - b[1]); return movements[0][0]; } ``` *(Apologies for sloppy formatting, the 4 spaces indentation for this site doesn't go well with my custom of using tabs.)* ## Rough explanation I hereby resign at the attempt to update the explanation of the formulae. The coefficients are constantly changing and it's kinda hard to keep the explanation up to date. So I will just explain the general principle. Each coin and each bot generates a force field with some potential. I just add the potentials from everything together and the bot then goes wherever the potential is the lowest. (Obviously this idea is stolen from physics.) I use two kinds of potentials. First one is a pseudo-gravitational one (which acts at any range), with $$U = - \frac{k}{r + \frac 1 5} \cdot \frac{1}{1 + n}.$$ The *k* is a "strength" of the field, and, with this choice of sign, the potential is attractive. The *r* here (and everywhere else) is the distance in the taxicab metric, *r = |x₁ - x₂| + |y₁ - y₂|*. I use *k = 40* for gold coins and *k = 10* for silver coins. *n* is the number of bots who are nearer to the particular coin than we are. Otherwise, we absolutely ignore the other bots (if we get in the way of a stronger bot, we run away, but that's it). I value gold coins for more than they are worth because otherwise the bots that go primarily after the gold all the time beat me. The second potential is an exponentially decaying one (which effectively acts only at very small distances). This is generated by the other, mainly the more powerful, bots. These produce a field with $$ U = -5 \times 1400 e^{-3r}. $$ This force is prohibitively strong at range 0-1, but decays to almost nothing at the larger distances. (Distance + 1 means cutting the force in 1/20.) We generally don't attack the other bots intentionally (of course if they get in our way and we step on them, it's their fault), but there is a possibility to do that. If some harsh conditions are fulfilled, we may enter the *hunting mode*, being focused on a single bot. To enter the hunting mode: 1. We must have at least 25 coins. (We need to get some coins first.) 2. They must have at most *(our coins - 5)* coins, and at least 10 coins. (We don't want to be hunting someone who grabs one coin and is suddenly more powerful, and we don't want to be pursuing zero-coin bots either.) 3. We must lag behind the currently leading bot by at least 1/10 of his coins. (You need to be lucky to hunt something, so there is no need to give away a good position just for trying our luck.) 4. We must not be on a *hunting cooldown* (see below). If all these are satisfied, the hunting mode is activated. For the next 10 rounds, the hunted bot only emits the potential $$ U = -150 e^{-r}. $$ After these 10 rounds elapse, we enter the hunting cooldown, during which we may not enter hunting mode again. (That is to prevent us from endlessly and fruitlessly chasing one bot while all other happily grab coins.) The hunting cooldown is 20 rounds when we have 25 coins, and increases by 20 coins per each doubling of that. (In other words, the cooldown is `20(1 + log2(c / 25))`.) (We use that because in the endgame, all the huntable bots are most likely dead, and so any hunt will be most likely in vain. Because of that, we want to limit the wasted time. But sometimes, a lucky late-game eating can change everything, so we keep the possibility.) Finally, the whole arena is placed into an infinite potential well which prevents the bot from escaping. [Answer] # The Bot That Plays The Game Cautiously But Can Be Aggressive | JavaScript **Preferred color:** `#F24100` **Note:** Although this bot has taken 1st place, it is due to teaming up with "Feudal Noble" at the end and eating him for more coins. Otherwise this bot would have been 3rd. If you are interested in bots that are more powerful individually, checkout [Potentially Victorious](https://codegolf.stackexchange.com/a/170268/81663) and [Big King Little Hill](https://codegolf.stackexchange.com/a/170450/81663). ``` function (me, monsters, coins) { var i, monstersCount = monsters.length, phaseSize = Math.round((me.arenaLength - 4) / 4), center = (me.arenaLength - 1) / 2, centerSize = me.arenaLength / 4, centerMin = center - centerSize, centerMax = center + centerSize, centerMonsters = 0, centerMonstersAvg = null, end = 2e4, apocalypse = end - ((me.arenaLength * 2) + 20), mode = null; var getDistance = function (x1, y1, x2, y2) { return (Math.abs(x1 - x2) + Math.abs(y1 - y2)) + 1; }; var isAtCenter = function (x, y) { return (x > centerMin && x < centerMax && y > centerMin && y < centerMax); }; var round = botNotes.getData('round'); if (round === null || !round) round = 0; round++; botNotes.storeData('round', round); var isApocalypse = (round >= apocalypse && round <= end); if (isApocalypse) { mode = botNotes.getData('mode'); if (mode === null || !mode) mode = 1; } for (i = 0; i < monstersCount; i++) if (isAtCenter(monsters[i][0], monsters[i][1])) centerMonsters++; var lc = botNotes.getData('lc'); if (lc === null || !lc) lc = []; if (lc.length >= 20) lc.shift(); lc.push(centerMonsters); botNotes.storeData('lc', lc); if (lc.length >= 20) { centerMonstersAvg = 0; for (i = 0; i < lc.length; i++) centerMonstersAvg += lc[i]; centerMonstersAvg = centerMonstersAvg / lc.length; } var getScore = function (x, y) { var score = 0, i, chaseFactor = 0.75, coinFactor = 1; if (monstersCount < phaseSize) { chaseFactor = 0; coinFactor = 0.25; } else if (monstersCount < phaseSize * 2) { chaseFactor = 0; coinFactor = 0.5; } else if (monstersCount < phaseSize * 3) { chaseFactor = 0.5; coinFactor = 0.75; } if (isApocalypse) { if (mode === 1) { var centerDistance = getDistance(x, y, center, center); if (centerDistance <= 3) { mode = 2; } else { score += 5000 / (centerDistance / 10); } } if (mode === 2) chaseFactor = 1000; } for (i = 0; i < monstersCount; i++) { var monsterCoins = monsters[i][2], monsterDistance = getDistance(x, y, monsters[i][0], monsters[i][1]); if (me.coins > monsterCoins && monsterDistance <= 3) { score += (Math.min(5, monsterCoins) * chaseFactor) / monsterDistance; } else if (me.coins <= monsterCoins && monsterDistance <= 3) { score -= (monsterDistance === 3 ? 50 : 10000); } } for (i = 0; i < coins.length; i++) { var coinDistance = getDistance(x, y, coins[i][0], coins[i][1]), coinDistanceCenter = getDistance(center, center, coins[i][0], coins[i][1]), coinValue = (i === 0 ? 250 : 100), coinCloserMonsters = 0; for (var j = 0; j < monstersCount; j++) { var coinMonsterDistance = getDistance(monsters[j][0], monsters[j][1], coins[i][0], coins[i][1]); monsterCoins = monsters[j][2]; if ( (coinMonsterDistance < coinDistance && monsterCoins >= me.coins / 2) || (coinMonsterDistance <= coinDistance && monsterCoins >= me.coins) ) { coinCloserMonsters++; } } var coinMonsterFactor = (100 - ((100 / monstersCount) * coinCloserMonsters)) / 100; if (coinMonsterFactor < 1) coinMonsterFactor *= coinFactor; if (coinMonsterFactor >= 1) coinMonsterFactor *= 15; score += ((coinValue * coinMonsterFactor) / coinDistance) + (centerMonstersAvg === null || centerMonstersAvg > 1.75 ? -1 * (50 / coinDistanceCenter) : 200 / coinDistanceCenter); } return score + Math.random(); }; var possibleMoves = [{x: 0, y: 0, c: 'none'}]; if (me.locationX > 0) possibleMoves.push({x: -1, y: 0, c: 'west'}); if (me.locationY > 0) possibleMoves.push({x: -0, y: -1, c: 'north'}); if (me.locationX < me.arenaLength - 1) possibleMoves.push({x: 1, y: 0, c: 'east'}); if (me.locationY < me.arenaLength - 1) possibleMoves.push({x: 0, y: 1, c: 'south'}); var topCommand, topScore = null; for (i = 0; i < possibleMoves.length; i++) { var score = getScore(me.locationX + possibleMoves[i].x, me.locationY + possibleMoves[i].y); if (topScore === null || score > topScore) { topScore = score; topCommand = possibleMoves[i].c; } } if (isApocalypse) botNotes.storeData('mode', mode); return topCommand; } ``` This bot (aka "TBTPTGCBCBA") tries to make the best decision possible by generating a score for each possible move and selects the move with higher score for each turn. The scoring system has many details which are evolved since the start of the challenge. They can be described generally like this: * The closer the coins are to a possible move, the more score that move gets. If a coin has no other possible contestants, the score goes even higher. If a coin has other possible contestants, the score goes lower. * If another bot is close to a possible move and has less coins, depending on the phase of the game, it could mean more score for that move. So it is casual for "TBTPTGCBCBA" to eat a few of other bots in each game. * If another bot is close to a possible move with equal or more points, that move gets enough negative score to make sure death is avoided. Of course there could be some cases that all possible moves are bad and death can't be avoided, but that is very rare. * There is a mechanism to keep track of number of bots in middle of the board for last 20 turns. If average is low enough, all moves towards coins in the middle get more score and if the average is high, then all moves towards coins in the middle get lower score. This mechanism allows to avoid conflicts with "Feudal Noble". Since the "Feudal Noble" is always in the middle (unless it is being chased), the average number of bots in the middle goes up and "TBTPTGCBCBA" understands to avoid middle if there is a better option outside of middle area. If "Feudal Noble" dies, the average goes down and "TBTPTGCBCBA" understands that it can use the middle. * There are some factors that dynamically change based on the phase of the game (detected from number of bots alive), these factors affect the scoring in each of above items. * This bot has a special ability. Over time it grows tired of the selfishness of "Feudal Noble" and the oppression of peasants. At the right moment, it will rise to end the unpleasant Feudalism system. A successful attempt not only helps poor peasants, but also provides a higher win chance due to the coins taken from the "Feudal Noble". [Answer] # Safety coin | JavaScript ``` SafetyCoin=(myself,others,coins)=>{ x=myself.locationX; y=myself.locationY; power=myself.coins; arenaSize=myself.arenaLength; dist=0; optimalCoin=7; optimalDist=11*arenaSize; for(i=0;i<coins.length;i++){ enemyDist=3*arenaSize; dist=Math.abs(x-coins[i][0])+Math.abs(y-coins[i][1]) for(j=0;j<others.length;j++){ if(i==0){ if(others[j][2]+5>=power){ enemyDist=Math.min(enemyDist,Math.abs(others[j][0]-coins[i][0])+Math.abs(others[j][1]-coins[i][1])) } } else{ if(others[j][2]+2>=power){ enemyDist=Math.min(enemyDist,Math.abs(others[j][0]-coins[i][0])+Math.abs(others[j][1]-coins[i][1])) } } } if(enemyDist>dist){ if(i==0){ if(dist/5<optimalDist){ optimalDist=dist/5; optimalCoin=i; } } else{ if(dist/2<optimalDist){ optimalDist=dist/2; optimalCoin=i; } } } } if(optimalCoin==7){ safeDir=15; if(x==0){safeDir-=8;} if(x==arenaSize-1){safeDir-=2;} if(y==0){safeDir-=1;} if(y==arenaSize-1){safeDir-=4;} for(i=0;i<others.length;i++){ if(others[i][2]>=power){ if(Math.abs(x-others[i][0])+Math.abs(y-others[i][1])==2){ if(x-others[i][0]>0){safeDir-=8;} if(x-others[i][0]<0){safeDir-=2;} if(y-others[i][1]>0){safeDir-=1;} if(y-others[i][1]<0){safeDir-=4;} } } } directions=["north","east","south","west"]; if(safeDir!=0){ tmp=""; tmp+="0".repeat(Math.max(Math.sqrt(arenaSize)/2|0,y-(arenaSize/2|0))); tmp+="2".repeat(Math.max(Math.sqrt(arenaSize)/2|0,(arenaSize/2|0)-y)); tmp+="1".repeat(Math.max(Math.sqrt(arenaSize)/2|0,(arenaSize/2|0)-x)); tmp+="3".repeat(Math.max(Math.sqrt(arenaSize)/2|0,x-(arenaSize/2|0))); rnd=tmp[Math.random()*tmp.length|0]; while(!(2**rnd&safeDir)){rnd=tmp[Math.random()*tmp.length|0];} return directions[rnd]; } return "none";//the only safe move is not to play :P } distX=coins[optimalCoin][0]-x; distY=coins[optimalCoin][1]-y; if(Math.abs(distX)>Math.abs(distY)){ if(distX>0){return "east";} else{return "west";} } else{ if(distY>0){return "south";} else{return "north";} } } ``` This bot heads straight towards a weighted valued coin (value/distance) which it can not die from reaching at the same time or after another bot. If there is no valid coin with this property ~~it sits where it is~~ the bot now moves in a random safe direction(safety means that if a bot moves towards it, safety coin cannot collide. This allows the bot to swap places with another bot if immediately next to it), weighted towards the center of the arena. [Answer] # The GUT, JavaScript ``` function gut(me, others, coins) { // Prepare values for the calculation var x = me.locationX; var y = me.locationY; var cMe = me.coins+1; var arenaLen = me.arenaLength; var objects = []; // Add bots to objects for (var i = 0; i < others.length; i++) { objects.push([others[i][0],others[i][1],others[i][2]/cMe]); } // Add coins to objects for (var j = 0; j < coins.length; j++) { var coinVal = 0; if (j == 0) { // Gold has a higher coin value coinVal = -10; } else { // Silver has a lower coin value coinVal = -5; } objects.push([coins[j][0],coins[j][1],coinVal/cMe]); } // Perform the calculation // x acceleration var x_acceleration = 0; for (var k=0; k < objects.length; k++) { var kval = objects[k][2]; var xval = objects[k][0]; x_acceleration += 200*kval/cMe*(x-xval)*Math.exp(Math.pow(kval,2)-50*Math.pow(x-xval,2)); } // y acceleration var y_acceleration = 0; for (var l=0; l < objects.length; l++) { var kval = objects[l][2]; var yval = objects[l][1]; y_acceleration += 200*kval/cMe*(y-yval)*Math.exp(Math.pow(kval,2)-50*Math.pow(y-yval,2)); } // Compare the values if (Math.abs(y_acceleration)>Math.abs(x_acceleration)) { if (y_acceleration < 0) { // Don't fall off the edge if (y>0) { return "north"; } else { return "none"; } } else { if (y<arenaLen-1) { return "south"; } else { return "none"; } } } else if (Math.abs(y_acceleration)<Math.abs(x_acceleration)) { if (x_acceleration < 0) { if (x>0) { return "west"; } else { return "none"; } } else { if (x<arenaLen-1) { return "east"; } else { return "none"; } } } else { return "none"; } } ``` With [Potentially Victorious](https://codegolf.stackexchange.com/a/170268/30525) we've got two fields: the bot field and the coin field. However, nature isn't that complicated. It's time to unify the two fields to produce the ***Grand Unified Theory***. Firstly, we need to work out what the potential of the field is. Assuming our own bot doesn't influence the field in any way, we can write this as: $$V = \sum\_\limits{n} k\_n\left(e^{k\_n^2-100(x-x\_n)^2}+e^{k\_n^2-100(y-y\_n)^2}\right)$$ Where \$k\_n\$ is the "relative property" of the object and \$(x\_n, y\_n)\$ are the coordinates of each object. The relative property of the object is calculated like so: $$k = \frac{c\_{\text{object}}}{c\_{\text{me}}}$$ Where \$c\$ is the coin value. (The coin value is positive for bots and negative for coins). And \$c\_{\text{me}} = c\_{\text{self}} + 1\$ where \$c\_{\text{self}}\$ is my own coin value (with 1 correction to prevent a division by zero). **Let's just call this correction part of [Modified Betanian Dynamics (MOBD)](https://en.wikipedia.org/wiki/Modified_Newtonian_dynamics).** We can also find the kinetic energy as: $$T = \frac{1}{2}c\_{\text{me}}(\dot{x}^2 + \dot{y}^2)$$ We can now calculate the action: $$\begin{align}\text{Action} &= \int^b\_a (T-V)dt\\&=\int^b\_a \left(\frac{1}{2}c\_{\text{me}}(\dot{x}^2 + \dot{y}^2) - \sum\_\limits{n} k\_n\left(e^{k\_n^2-100(x-x\_n)^2}+e^{k\_n^2-100(y-y\_n)^2}\right)\right) dt\end{align}$$ And so the Lagrangian of our bot in the coin-bot field is: $$\mathcal{L} = \frac{1}{2}c\_{\text{me}}(\dot{x}^2 + \dot{y}^2) - \sum\_\limits{n} k\_n\left(e^{k\_n^2-100(x-x\_n)^2}+e^{k\_n^2-100(y-y\_n)^2}\right)$$ We now need to solve the Euler-Lagrange equations: $$\frac{d}{dt} \frac{\partial \mathcal{L}}{\partial \dot{x}} = \frac{\partial \mathcal{L}}{\partial x}$$ and: $$\frac{d}{dt} \frac{\partial \mathcal{L}}{\partial \dot{y}} = \frac{\partial \mathcal{L}}{\partial y}$$ So: $$\frac{d}{dt} \frac{\partial \mathcal{L}}{\partial \dot{x}} = \frac{d}{dt} \left[c\_{\text{me}}\dot{x}\right] = c\_{\text{me}}\ddot{x}$$ $$\frac{\partial \mathcal{L}}{\partial x} = \sum\limits\_n 200 k\_n \left(x - x\_n\right) e^{k\_n^2 - 100(x-x\_n)^2}$$ $$\Rightarrow \ddot{x} = \sum\limits\_n \frac{200k\_n}{c\_{\text{me}}} \left(x - x\_n\right) e^{k\_n^2 - 100(x-x\_n)^2}$$ And also: $$\frac{d}{dt} \frac{\partial \mathcal{L}}{\partial \dot{y}} = \frac{d}{dt} \left[c\_{\text{me}}\dot{y}\right] = c\_{\text{me}}\ddot{y}$$ $$\frac{\partial \mathcal{L}}{\partial y} = \sum\limits\_n 200 k\_n \left(y - y\_n\right) e^{k\_n^2 - 100(y-y\_n)^2}$$ $$\Rightarrow \ddot{y} = \sum\limits\_n \frac{200k\_n}{c\_{\text{me}}} \left(y - y\_n\right) e^{k\_n^2 - 100(y-y\_n)^2}$$ Now we don't need to go any further: we just look at the direction of the overall acceleration: $$\text{output} = \begin{cases}\text{north} &\text{if }\ddot{y}<0 \text{ and } |\ddot{y}|>|\ddot{x}| \\ & \\ \text{south} &\text{if }\ddot{y}>0 \text{ and } |\ddot{y}|>|\ddot{x}| \\ & \\ \text{west} &\text{if }\ddot{x}<0 \text{ and } |\ddot{x}|>|\ddot{y}| \\ & \\ \text{east} &\text{if }\ddot{x}>0 \text{ and } |\ddot{x}|>|\ddot{y}| \\ & \\ \text{none} &\text{if }|\ddot{y}|=|\ddot{x}|\end{cases}$$ And just like that, we've unified the coins and the bots. Where's my Nobel Prize? [Answer] # Goldilocks, [JavaScript (Node.js)](https://nodejs.org) ``` function goldilocks(me, others, coins) { let target = coins[0]; // Gold let x = target[0] - me.locationX; let y = target[1] - me.locationY; mymove = 'none' if (Math.abs(x) <= Math.abs(y) && x != 0) mymove = x < 0 ? 'west' : 'east' else if (y != 0) mymove = y < 0 ? 'north' : 'south' return mymove } ``` [Try it online!](https://tio.run/##bZFNb8IwDIbv/ArvQlvJg5aVMRXQjrts901VhUIJbVmbTElgVIjf3jml42PayYn9vK9jZ8N2TKeq@DL3Qq5406y3IjWFFJDJclWUMv3UbsURpMm50gipLIT24NADKLkBw1RGYX7Kx34yheEQXkjbAXuqnSAqwj1UfECmzLZ4n3ZMfWGCP8zHtEdQVVdyx4lyhBTcoUyxBveNmXzAltrdezCbw/lae9DvU@O7OfgesVf6PczAh2dwvrk2DkTgcEYHgnipeeta/6erf3VCKpO3Qi23dLKvU9xslejg3rHZMUUjLORyQ8rDedoIAoTzXO2tXVoEEwSmuGCvXGQmj@Dp2LMep5UvmFLkE8c@jjFMMA5xggHFCYYYjJKkZa0TeV/oB4RxghCPEIIujmx8RAhtHHd16u2TRyqFlqXde@be/LwdA6@egjetPK/5AQ "JavaScript (Node.js) – Try It Online") Just locks on to the gold coin's location and moves towards it every time. (Thanks to @Mayube's 'B33-L1N3' bot for the original code this used, though barely any of it remains.) [Answer] # The AntiCapitalist | Javascript Has no incentive to go after coins, but tries to place himself exactly between the two richest bots with the same amount of money, in the hope they will hunt him and eventually catch him at the same time, taking two capitalists with him when he dies. Does not actively resist getting coins, so he might become a more juicy target. ``` function antiCapitalist(me, capitalists, coins){ function acquireTargets(capitalists){ capitalists.sort((a, b) => a[2] < b[2]); let previousCapitalist; for(let i in capitalists){ let capitalist = capitalists[i]; if(capitalist[2] === 0){ return false; } if(previousCapitalist && capitalist[2] === previousCapitalist[2]){ return [previousCapitalist, capitalist]; } previousCapitalist = capitalist; } return false; } function move(){ const targets = acquireTargets(capitalists); if(!targets){ return 'none'; } const coordinates = [Math.floor((targets[0][0] + targets[1][0]) / 2), Math.floor((targets[0][1] + targets[1][1]) / 2)]; if(me.locationX !== coordinates[0]){ return me.locationX < coordinates[0] ? 'east' : 'west'; } else if(me.locationX !== coordinates[1]){ return me.locationY < coordinates[1] ? 'south' : 'north'; } else { return 'none'; } } return move(); } ``` [Answer] # Third Gen Learning Algorithm | [JavaScript (Node.js)](https://nodejs.org) ``` function run(me) { options = []; if (me.locationX > 0) options.push('west'); if (me.locationY > 0) options.push('north'); if (me.locationX < me.arenaLength) options.push('east'); if (me.locationY < me.arenaLength) options.push('south'); return options[Math.floor(Math.random() * options.length)]; } ``` [Try it online!](https://tio.run/##hZC9DsIwDITn9im8NUGiYufnDZgpqhiiNqVBxa6cBAbEs4eUvwGK2Gzfd3eSD@qkbMWmd1OkWofQeKycIQT2KI5awiVNqB8uFpZQ7uZpYhqISt5RpYZ7ASuYSXhCee9tK7Kzti6T3/B2DEZi147RBSwgroo1qo2pXfvp1OpXzR@jJf@oTBPWzjO@9HKtXJs3HRGL@8gKazoKCZN3RKdxHyPjL64h3AA "JavaScript (Node.js) – Try It Online") After a few generations of learning, this bot has learned that leaving the arena = bad [Answer] # B33-L1N3 | [JavaScript (Node.js)](https://nodejs.org) ``` function(me, others, coins) { // Do nothing if there aren't any coins if (coins.length == 0) return 'none'; // Sort by distance using Pythagoras' Theorem coins = coins.sort((a, b) => (a[0] ** 2 + a[1] ** 2) - (b[0] ** 2 + b[1] ** 2)); // Closest coin let target = coins[0]; let x = target[0]; let y = target[1]; // Util function for movement function move(pos, type) { let moveTypes = { X: ['east', 'west'], Y: ['south', 'north'] }; if (pos > me['location'+type]) return moveTypes[type][0]; else return moveTypes[type][1]; } // Move the shortest distance first if (x < y && x != me.locationX) return move(x, 'X'); else if (y != me.locationY) return move(y, 'Y'); } ``` [Try it online!](https://tio.run/##dVJNT@swEDynv2K44ARC@TgC4QLXJz0JkFpFPbhh2wQldmVvoRHqby/rGMLTkzjZmh3vzM76Vb9pX7lmw2fGvtDhsNqaihtr0o5yWK7J@RyVbYzP8DFJzs/xYGGk0Jg1mhUCg6AdGcXQpo/cSSKldLhOWzJrrlEUuMjgiLfOQBlrSN0M/R6tYyx7vDSetakIWx96/@251mvrtFd4qsk66iZJSxwFUMRz6uV1muocywzFHVJdXixwcoIrnEKXl/Ge4Qzp8p/Kcqxk0cR9az352DzKsHZrOb505O1NxHcCxdoP1v9gl4INHZ@5afGdJlbWobNv1JHhSTLCAUo3ViLmfkNDwkPDgD8JEub8wOwapSLtWeVQ72JTLXLMA@jtluuAGomhVgvsxdGQvTTFHToqVWsrHcTUadBYjDsYNcoBj9Mk1Hr6jRFmS/ZxvD9SC8uHr0U6RDfub9U4z/EH7HAr4RwfS2pHhbiZfpuZZXH2nXifqbCEQTi86f@jzr@ovVDngbo/HD4B "JavaScript (Node.js) – Try It Online") Makes a **beeline** for the closest coin [Answer] # Livin' on the Edge, JavaScript ``` function LivinOnTheEdge (myself, others, coins) { x = myself.locationX; y = myself.locationY; xymax = myself.arenaLength - 1; if (x < xymax && y == 0) { return 'east'; } else if (y < xymax && x == xymax) { return 'south'; } else if (x > 0 && y == xymax) { return 'west'; } else { return 'north'; } } ``` This one heard the edge of the arena is a dangerous place to be. Knowing no fear, it tirelessly circles the board clockwise, only inches away from the certain death that awaits behind the border, hoping no other bot will dare to move so closely to the edge's vicinity. [Answer] # Damacy, [JavaScript (Node.js)](https://nodejs.org) ``` function damacy(me, others, coin) { let xdist = t => Math.abs(t[0] - me.locationX) let ydist = t => Math.abs(t[1] - me.locationY) function distanceCompare(a, b, aWt, bWt) { aWt = aWt || 1 bWt = bWt || 1 return (xdist(a) + ydist(a)) / aWt - (xdist(b) + ydist(b)) / bWt } function hasThreat(loc) { let threat = others.filter(b => b[0] == loc[0] && b[1] == loc[1] && b[2] >= me.coins) return (threat.length > 0) } function inArena(loc) { // probably unnecessary for this bot return loc[0] >= 0 && loc[1] >= 0 && loc[0] < me.arenaLength && loc[1] < me.arenaLength } function sortedCoins() { coinsWithValues = coin.map((coords, i) => coords.concat((i == 0) ? 5 : 2)) coinsWithValues.sort((a, b) => distanceCompare(a, b, a[2], b[2])) return coinsWithValues.map(c => c.slice(0, 2)) } othersPrev = botNotes.getData('kata_others_pos') botNotes.storeData('kata_others_pos', others) if (othersPrev) { for(let i = 0; i < others.length; i++) { let bot = others[i] let matchingBots = othersPrev.filter(function (b) { let diff = Math.abs(b[0] - bot[0]) + Math.abs(b[1] - bot[1]) if (diff >= 2) return false // bot can't have jumped return [0, 2, 5].includes(bot[2] - b[2]) }) if (matchingBots.length > 0) { let botPrev = matchingBots.shift() // remove matched bot so it doesn't get matched again later othersPrev = othersPrev.filter(b => b[0] != botPrev[0] || b[1] != botPrev[1]) bot[0] = Math.min(Math.max(bot[0] + bot[0] - botPrev[0], 0), me.arenaLength-1) bot[1] = Math.min(Math.max(bot[1] + bot[1] - botPrev[1], 0), me.arenaLength-1) } } } let eatables = others.filter(b => b[2] < me.coins && b[2] > 0) let targets if (eatables.length > 0) { targets = eatables.sort(distanceCompare) } else { targets = sortedCoins() } let done, newLoc, dir while (!done && targets.length > 0) { t = targets.shift() if ((xdist(t) <= ydist(t) || ydist(t) == 0) && xdist(t) != 0) { let xmove = Math.sign(t[0] - me.locationX) dir = xmove < 0 ? 'west' : 'east' newLoc = [me.locationX + xmove, me.locationY] if (!hasThreat(newLoc) && inArena(newLoc)) done = 1 } if (!done) { let ymove = Math.sign(t[1] - me.locationY) dir = ['north', 'none', 'south'][ymove + 1] newLoc = [me.locationX, me.locationY + ymove] if (!hasThreat(newLoc) && inArena(newLoc)) done = 1 } } if (!done) dir = 'none' return dir } ``` [Try it online!](https://tio.run/##rVZLb9tGEL7rV4wv0RJey6JiN4FrOWjTY1L0UNQtCMJYkiuJLskVuCs7QqLf7s7sgw9Fbi81YHG5O49vvpmd4aN4Ejpvy625aFQhX15WuyY3pWqgELXI96yWHJTZyFZzyFXZRPB1AlBJA1@KUhtYAv7fwWdhNjORaWaSeQoXUMtZpXJBlv6MvML@FYX4SOEvUuhxoJJocvlR1VvRSiY4ZBzEvcHnvXFwgN7RMv1@@wax3crsVjbcaqXZtQ0wC52JCM4dKFxGcGnVL8Jp1p9m9hQtoZHDENtG6N83rRSGIfYAhUI1dhfdO@pmq7IysmUZRZ4RQ8sloAqt3rzBnbjbif3OIoW7JbFCpOtoBN9Zn1WyWZsN3ME8OgZWNj@1shEeFsDlJWxblYms2sOuaWQutRbtHlaqRaylhkyZoQuPDRHMCY4HNnzF01uCJ8jPJ4eklzw@OsanVWtk8ZFCY4E3G@h9aTZ/iGonNZJHO7NabBnLlWoLrMAyIgbdGzLTYMEwVhJ38wg@wDXcwCKKTpmbkUtmq8faeKWskHdu2Y9GlB8bI1C5hTLTVZlLNufeMYXpkv5bK5@oAJX5VRnUWUvzizCCTf/G3wcn87BVekpqnZQ2qpWn5cJFJPlyBax3QxRauJhPRvWHlMD8R3zchgp0xYJb5@eBcFeq6Lmr06RMJ4OjWph8Uzbrn5XRnQz5C/Xc5ZNuSzDqdItytUKd7ppnri@gN1zQ1RqcxOEkTqPOCEVojWDVLfrtLiUrUWlJhU0B5KKZGryOTxIed/VWFpMj6YQSxOE6nZVNXu0KiX7R4cJ6pnR7hUMUCCD/QwKG1@0oVrTkkz1S0JtyZVgPHbG2slaI0YrJwkLXCkqkS0lNIawD7Xgq1qLEqyiQ6c7GqLS@T0jfYM6WARa9YQe0NA92h1y7rIR01WXD3EJ8Yf7oPMhcDMxypIIf3fSLeGw2ft1sHMzGQ7Pxf5g9TMLvYeIHCzZD7GxSv9ZvF74h2Vvct1fXN227Fi0Sr/29CuZOZNwLoqNOyPaVo24SGoGkEj3WHPW@YRiFanDYNvL5k8o5XiDK@vOmrCSwMzoj5N7MKWg0Wf3psPIoIj/ScFreLv1MwzUWRbd2HRQddJJny2Gh24Fva9dnU5fr5rVhT38IH0Wdyi2OjQ8wfZbaTLFDT6XAhZdz4aJoMrSChWFV@ei7IB1czbN@9joTFn2Ye36rL0XL39J/BhwmHTOW2HGY@xNhnvxE6cNMpg0mdYMdGheNpKdWO9xIE2ftHOL0XwMeB0pfHqT3/wXsg@5DnvToHeYJnftuSbV3mLw8iRZhPajsEaW@dlhvIObQYbVv9mbdwDucoP2dvYH3hwnZ8DNMtJYrbMXX/CrlyRWPOd725B3H1SJNrSxZQtu99Fvq2hwS7N6xf9KMTn7gcEXPa3@OvufeRhimhBqD8oP3pv/8YMWurvch7WFEJLEH9pa/HwND9jj@dLP5O1NIgX0unM0DsjfBzxOtKsrqmnUf00QmHxDCRwFH0cs/ "JavaScript (Node.js) – Try It Online") One last katamari-based bot for today, this time with a little bit of memory. Thanks to [@BetaDecay](https://codegolf.stackexchange.com/questions/170229/gold-collector-koth/170269#comment411210_170276) for the name suggestion - definitely a more fun name than my `simplePredictorKatamari`. Tries to figure out how bots have moved in the last turn, and based on that, predicts where they'll try to move at the end of this turn (assuming they continue to move in the same direction). *(Thanks to @fəˈnɛtɪk, for noticing that I was calling the wrong function name in botNotes, and to @OMᗺ for noticing a bug in the base code.)* [Answer] # Proton | JavaScript ``` Proton=(myself,others,coins)=>{ x=myself.locationX; y=myself.locationY; power=myself.coins; arenaSize=myself.arenaLength; forceX=0; forceY=0; prevState=botNotes.getData("proton_velocity"); if(prevState){ velocity=prevState[0]; direction=prevState[1]; } else{ velocity=0; direction=0; } for(i=0;i<coins.length;i++){ if(Math.abs(x-coins[i][0])+Math.abs(y-coins[i][1])==1){ velocity=0; direction=0; botNotes.storeData("proton_velocity",[velocity,direction]); if(x-coins[i][0]==1){return "west";} if(coins[i][0]-x==1){return "east";} if(y-coins[i][1]==1){return "north";} if(coins[i][1]-y==1){return "south";} } else{ dist=Math.sqrt(Math.pow(x-coins[i][0],2)+Math.pow(y-coins[i][1],2)); if(i==0){ forceX+=(x-coins[i][0])*5/Math.pow(dist,3); forceY+=(y-coins[i][1])*5/Math.pow(dist,3); } else{ forceX+=(x-coins[i][0])*2/Math.pow(dist,3); forceY+=(y-coins[i][1])*2/Math.pow(dist,3); } } } for(i=0;i<others.length;i++){ if(Math.abs(x-others[i][0])+Math.abs(y-others[i][1])==1&&power>others[i][2]){ velocity=0; direction=0; botNotes.storeData("proton_velocity",[velocity,direction]); if(x-others[i][0]==1){return "west";} if(others[i][0]-x==1){return "east";} if(y-others[i][1]==1){return "north";} if(others[i][1]-y==1){return "south";} } else{ dist=Math.sqrt(Math.pow(x-others[i][0],2)+Math.pow(y-others[i][1],2)); forceX+=(x-others[i][0])*others[i][2]/Math.pow(dist,3); forceY+=(y-others[i][1])*others[i][2]/Math.pow(dist,3); } } vX=velocity*Math.cos(direction)+10*forceX/Math.max(1,power); vY=velocity*Math.sin(direction)+10*forceY/Math.max(1,power); velocity=Math.sqrt(vX*vX+vY*vY); if(velocity==0){return "none"} retval="none"; if(Math.abs(vX)>Math.abs(vY)){ if(vX>0){ if(x<arenaSize-1){retval="east";} else{vX=-vX;retval="west";} } else{ if(x>0){retval="west";} else{vX=-vX;retval="east";} } } else{ if(vY>0){ if(y<arenaSize-1){retval="south";} else{vY=-vY;retval="north";} } else{ if(y>0){retval="north";} else{vY=-vY;retval="south";} } } direction=Math.atan2(-vY,vX); botNotes.storeData("proton_velocity",[velocity,direction]); return retval; } ``` All coins (including those held by other bots) emit a repulsive force towards Protonbot. Based on this force, it builds up velocity and bounces off of walls (turns around immediately upon hitting a boundary). If it ends up next to a bot or coin it can consume, the Strong nuclear force takes over and it moves to consume it, dropping all velocity when it does so. [Answer] ## Not so Blindly | JavaScript (Node.js) **Important Note:** This approach is not entirely mine and has been answered in a [similar question](https://codegolf.stackexchange.com/a/167590/78039). Make sure to vote that answer as well. Haev you ever heard about A\* pathfinding algorithm? here it is. It creates the best path from one point to the less valuable coin (as everyone is going for the most valuable, no one is going for the less) and tries to not collide with any other user. Expects parameters as follow: ``` AI({locationX: 3, locationY: 1, arenaLength: [5,5]}, [[2,1],[2,2], ...],[[1,2],[3,1], ...]) ``` --- Maybe I do one that goes hunting other bots --- ``` function AI(me, others, coins){ var h = (a,b) => Math.abs(a[0] -b[0]) + Math.abs(a[1] -b[1]) var s = JSON.stringify; var p = JSON.parse; var walls = others.slice(0,2).map(s); var start = [me.locationX, me.locationY]; var goal = coins.pop(); var is_closed = {}; is_closed[s(start)] = 0; var open = [s(start)]; var came_from = {}; var gs = {}; gs[s(start)] = 0; var fs = {}; fs[s(start)] = h(start, goal); var cur; while (open.length) { var best; var bestf = Infinity; for (var i = 0; i < open.length; ++i) { if (fs[open[i]] < bestf) { bestf = fs[open[i]]; best = i; } } cur = p(open.splice(best, 1)[0]); is_closed[s(cur)] = 1; if (s(cur) == s(goal)) break; for (var d of [[0, 1], [0, -1], [1, 0], [-1, 0]]) { var next = [cur[0] + d[0], cur[1] + d[1]]; if (next[0] < 0 || next[0] >= me.arenaLength[0] || next[1] < 0 || next[1] >= me.arenaLength[1]) { continue; } if (is_closed[s(next)]) continue; if (open.indexOf(s(next)) == -1) open.push(s(next)); var is_wall = walls.indexOf(s(next)) > -1; var g = gs[s(cur)] + 1 + 10000 * is_wall; if (gs[s(next)] != undefined && g > gs[s(next)]) continue; came_from[s(next)] = cur; gs[s(next)] = g; fs[s(next)] = g + h(next, goal); } } var path = [cur]; while (came_from[s(cur)] != undefined) { cur = came_from[s(cur)]; path.push(cur); } var c = path[path.length - 1]; var n = path[path.length - 2]; if(n){ if (n[0] < c[0]) { return "west"; } else if (n[0] > c[0]) { return "east"; } else if (n[1] < c[1]) { return "north"; } else { return "south"; } }else{ return "none"; } } ``` [Answer] # Coward | Python 2 ``` import random def move(me, others, coins): target = (me.locationX, me.locationY) # Identify the dangerous opponents. threats = [i for i, value in enumerate(others[2]) if value >= me.coins] # If no one scary is nearby, find a nearby coin. safe = True for x, y in self.coins: distance = abs(me.locationX - x) + abs(me.locationY - y) safe = True for i in threats: if abs(others[0][i] - x) + abs(others[1][i] - y) <= distance: safe = False break if safe: target = (x, y) break # Otherwise, just try not to die. if not safe: certain = [] possible = [] for x, y in [ (me.locationX, me.locationY), (me.locationX + 1, me.locationY), (me.locationX - 1, me.locationY), (me.locationX, me.locationY + 1), (me.locationX, me.locationY - 1), ]: # Don't jump off the board. if x < 0 or y < 0 or x == me.arenaLength or y == me.arenaLength: continue # Check if we can get away safely. for i in threats: if abs(others[0][i] - x) + abs(others[1][i] - y) <= 1: break else: certain.append((x, y)) # Check if we can take a spot someone is leaving. for i in threats: if others[0][i] = x and others[1][i] == y: for i in threats: if abs(others[0][i] - x) + abs(others[1][i] - y) == 1: break else: possible.append((x, y)) if certain: target = random.choice(certain) elif possible: target = random.choice(possible) # Otherwise, we're doomed, so stay still and pray. directions = [] x, y = target if x < me.locationX: directions.append('west') if x > me.locationX: directions.append('east') if y < me.locationY: directions.append('north') if y > me.locationY: directions.append('south') if not directions: directions.append('none') return random.choice(directions) ``` Avoid bots with more money if at all possible. Otherwise, grab money that's lying around. [Answer] # Wild Goose Chase Bot, Javascript *A bot that's really good at dodging other bots, but very bad at getting coins.* --- Algorithm: 1. If there are no adjacent bots, return none 2. Otherwise: 1. Return none with a random chance 1/500 chance (this is intended to prevent stalemates). 2. Determine which spaces are safe to move to (ie inside the arena and not occupied by another bot) 3. Return one at random --- Code: ``` function wildGooseChase(me, others, coins){ x = me.locationX; y = me.locationY; dirs = {}; dirs[(x+1)+" "+y] = "east"; dirs[(x-1)+" "+y] = "west"; dirs[x+" "+(y+1)] = "south"; dirs[x+" "+(y-1)] = "north"; mov = {}; mov["east"] = [x+1,y]; mov["west"] = [x-1,y]; mov["north"] = [x,y-1]; mov["south"] = [x,y+1]; possibleDirs = ["east","west","north","south"]; for (i = 0; i < others.length; i++){ if (others[i][0]+" "+others[i][1] in dirs){ possibleDirs.splice(possibleDirs.indexOf(dirs[others[i][0]+" "+others[i][1]]),1); } } if (possibleDirs.length == 4 || Math.floor(Math.random() * 500) == 0){ return "none" } for (i = 0; i < possibleDirs.length; i++){ if (mov[possibleDirs[i]][0] == me.arenaLength || mov[possibleDirs[i]][0] < 0 || mov[possibleDirs[i]][1] == me.arenaLength || mov[possibleDirs[i]][1] < 0){ var index = possibleDirs.indexOf(possibleDirs[i]); if (index != -1) { possibleDirs.splice(index, 1); i--; } } } if (possibleDirs.length == 0){ return "none"; } return possibleDirs[Math.floor(Math.random() * possibleDirs.length)]; } ``` [Try it Online!](https://tio.run/##vZZRb9owEMefyae48bIwTJdspCvN@rRJe9m0100oD4EYyBRs5Dht0cZn7@5sKEkJUcrotGokPtv3u7/vzvkV38b5VKUrPRAy4Q8Ps0JMdSoF3KVZ8kXKnH9axDl3l5yB1AuucgZTmYq899vp3MMNLPlFJqcxrfkROp11dehn6DidJFU5Dv/ehPZ57N73/V6/C93@OkJDl8e57u6Ng4rxjpeM98bgrnG9Meay0IsD62BrFVIZq9NZytsdAT6OrUeag2t8to5248aZHR@Ux@1O1sBw/0eDBdgZ@mjoOPhvJfM8nWT8sw1965DZ/dl2O7ZbTYQzqcBNca4XQgoft2JfZFzM9QKH@n1SvJPOwLWmcRqNvchEvB/wI0gFkBhmdoXjIl9l6ZS7lbFUJPz@@8w1@jVuHPWY38OwOxsH/xxDUtnKosLNDQzhzx/4FuvFxSyTUrnmUcUikUu3B28g8LwezfMMpOK6UIJOS/Cu3fupGDV@qpLQWZQnITIFQU4wG2PFRfzV4iHZsckfwQMS7dgU/zn7@WY/ewq3sQIjNEZUq/6T1UZmE5dd9eoGMKXB7FV7pGYaA3s@uHIwMA@bVqdVcwohLcI03g5W8BrOtcZBD5N787DkVH2PfeIaAgaPLeI62LaUa49BSdpr39s4xkAVFDnO27cgJMTJr3jKhYZVFq8xO0NIJI7rRSrmjk1Ymj8O2IeIwXjI3tPPiL2jH5959POBXUYR7i1ymVGzmrvH253tdqgs@bc@QUtAI5gyJv/itYa5tO9VhiE6PIMn0yhKnsx71dPleTxRh9o70ua97GjIgvM4oo5Yiohey34uT/eDSSI4ltxEarytJoWGyRp4MuchQL6QRZaUU6Y5N0eNudmEVkeGHJm8Qw2IhhEgxBN5i2BbLhTiqeABu6KkRUFGLQSp8YpOi9Wq4nTCEaPs1KjfrITXoEQF19QY5ol3Gi6JRBqUcIkOsM3sCm7PfVAHHhuic58FETaeg4C8lm0nPA3bcO6xTRSEva3ePfZBoxhhQ2LjqyPYoxfExs8FQ2Ngp1IJrhh@/OHVQCFoeQhfnytey1wJq6flU8CnUxvF66htG3uaKM3KtqWmejyV2nC0prZ50kw9ak09@jfqoxlyUJUtMmTUOkOuXpLalGdFdcXzdC5oQpJycPcXRe@MEVGHOv00lmmSZPhNUCglC/zyS6j36IXi3Fx5LRIoaN1Qqje/uYbo/4A@oF4e/0jVngF/@D/wzVV@Hvo9938Tv8U3wfO0fyH6mSxUFf45NXyWeGxePTeqh78) Note to Redwolf Programs: This bot has the potential to cause very long rounds. I have taken some liberties to prevent stalemates, but have not tested if they are actually effective. If this bot becomes a problem during testing, please feel free to disqualify it. [Answer] # KatamariWithValues, [JavaScript (Node.js)](https://nodejs.org), ``` function katamariWithValues(me, others, coin) { let xdist = t => Math.abs(t[0] - me.locationX) let ydist = t => Math.abs(t[1] - me.locationY) function distanceCompare(a, b, aWt = 1, bWt = 1) { return (xdist(a) + ydist(a)) / aWt - (xdist(b) + ydist(b)) / bWt } function hasThreat(loc) { let threat = others.filter(b => b[0] == loc[0] && b[1] == loc[1] && b[2] >= me.coins) return (threat.length > 0) } function inArena(loc) { // probably unnecessary for this bot return loc[0] >= 0 && loc[1] >= 0 && loc[0] < me.arenaLength && loc[1] < me.arenaLength } function sortedCoins() { coinsWithValues = coin.map((coords, i) => coords.concat((i == 0) ? 5 : 2)) coinsWithValues.sort((a, b) => distanceCompare(a, b, a[2], b[2])) return coinsWithValues.map(c => c.slice(0, 2)) } let eatables = others.filter(b => b[2] < me.coins && b[2] > 0) let targets if (eatables.length > 0) { targets = eatables.sort(distanceCompare) } else { targets = sortedCoins() } let done, newLoc, dir while (!done && targets.length > 0) { t = targets.shift() if ((xdist(t) <= ydist(t) || ydist(t) == 0) && xdist(t) != 0) { let xmove = Math.sign(t[0] - me.locationX) dir = xmove < 0 ? 'west' : 'east' newLoc = [me.locationX + xmove, me.locationY] if (!hasThreat(newLoc) && inArena(newLoc)) done = 1 } if (!done) { let ymove = Math.sign(t[1] - me.locationY) dir = ['north', 'none', 'south'][ymove + 1] newLoc = [me.locationX, me.locationY + ymove] if (!hasThreat(newLoc) && inArena(newLoc)) done = 1 } } if (!done) dir = 'none' return dir } ``` [Try it online!](https://tio.run/##rVVNbxoxEL3zKyaX4FUcAhSaCoVEVa7prWparVaRdzHspouNbJMUNfx2OmMbFijpqZGitT1f7z2Ph2fxImxhqoW7VHoiN5vpUhWu0gp@CifmwlSPlSu/iXopLZtLDtqV0lgOha5UAr9bALV08GtSWQdjwP9b@CJc2RG5ZS7tZnAJc9mpdSEo6/ckBqzeCegdBfyggB0mChKqkPd6vhBGMsEh5yAeKVMP12ERYAEY6ZZGAfPgmEjgIpTFZQJXPuxya80ba@6tmAuTrPerl8J@LY0UjiG6bREi4/wplg7idKZV7aRhOXHLSYPxGDCEVufneNLbnfTiST@D2zHxJlltcgA/ZO/UUs1cCbfQTY6BVeqzkUpEWABXV7AwOhd5vYKlUrKQ1gqzgqk2iLWykGu3XyJiQwRdghOB7W/RekPwBNV5CEgaz2PTMT6rjZOTe6LGtrp5ok1voXh00pmLBWOF1maCPVYlpGDYoTIKW4KxirTrJnAHQxhBP0lOpetQSeb7w@d4p3FQd@7VTw4kP05GoAoPpWPrqpCsy2PhdSv2M94Qyu15nGyCflTJp27uPFym7yFhZtJZ3FVTYNt0@7cehYuOWGjn5MkeUdw2iayt/Cvy4EL2aUy0wjeu5OuDLjiqZvD8taxqCeyMbIQ8pjkFjR50tNqymjoWZCVG8Z25BG7G8aHh@u2tWYdrxQI7z7NxkzvOmbl@kVjFTwxbzdR7M4b@ED66hpAb7OU7aL9K69rYNm0pcBH9Al10Tfez4DzwofxgHGUxhiidNQMhpPDot48xHm3BgNeWxpM/8IrHNGQ4pLk6QfPkZGxopm2Fl1q2OeBCSfpavcSDLA3ZLqCX/ZPwIVEahxT3/whH0g3lVoM@YCZzfILUeuvW5kUYRPWk82d0@r2DOqJpv4Pqd/5hjeAaX3UziEbwad2iHOFNPgnjpUq7fMgHGU8H/Jr38HvNB7zXzzLvS5kwd@P9gcMQ50Ta5yhh@NLcSD9yGNB3GO1Yu4s5cFBZXZOUM3byR5To8D1I/KBkkmz@AA "JavaScript (Node.js) – Try It Online") *(Thanks to @OMᗺ for pointing out a bug in the original code this was based on.)* Tries to grow by "eating" bots with less coins than itself. If that's not possible (no such bot exists), then seeks out the nearest coin. This version has small tweaks to (a) give higher preference to gold coins than to silver coins - with the risk that seeking a more distant gold coin may end up costing the bot's life or lead to chasing after fool's gold (b) skip bots with 0 coins - no need to waste time chasing after those. [Answer] # Polite Near-Sighted Drunk Bot | JavaScript ``` function politeNearSightedDrunkBot(me, others, coins) { let directions = ['none','east','south','west','north'] let drunkennessCoefficient = .2 let nearSightedness = me.arenaLength - others.length + 2 //drawCircle(me.locationX, me.locationY, nearSightedness*squareSize) function randomInt(a) { return Math.floor(Math.random() * a); } function getRandomDirection() { return ['east', 'west', 'north', 'south'][randomInt(4)] } function distanceTo(a) { return (Math.abs(a[0] - me.locationX) + Math.abs(a[1] - me.locationY)) } function distanceBetween(a, b){ return (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1])) } function isTargetSafe(a) { for (let i = 0; i < others.length; i++) { if (others[i][2] >= me.coins && distanceBetween(a, others[i]) <= distanceTo(a)) { return false //unnecessary loop, but I don't want to split out into a function } } return true } function amISafe() { for (let i = 0; i < others.length; i++) { if (others[i][2] >= me.coins && distanceTo(others[i]) == 1) { /*let num = botNotes.getData('turnsSpentAdjacentToEnemy') if (!num) { console.log('politeNearSightedDrunkBot: Woops!') botNotes.storeData('turnsSpentAdjacentToEnemy', 1) } else if (num == 1) { console.log('politeNearSightedDrunkBot: \'Scuse me...') botNotes.storeData('turnsSpentAdjacentToEnemy', 2) } else if (num == 2) { console.log('politeNearSightedDrunkBot: D\'ye mind?') botNotes.storeData('turnsSpentAdjacentToEnemy', 3) } else if (num == 3) { console.log('politeNearSightedDrunkBot: Bugger off!') }*/ return false } } return true } function getSafeDirections() { let candidates = {'none': true, 'east': true, 'south': true, 'west': true, 'north': true} if (me.locationY == 0) { candidates['north'] = false } else if (me.locationY == me.arenaLength - 1) { candidates['south'] = false } if (me.locationX == 0) { candidates['west'] = false } else if (me.locationX == me.arenaLength - 1) { candidates['east'] = false } if (!amISafe()) { candidates['none'] = false }/* else { botNotes.storeData('turnsSpentAdjacentToEnemy', 0) }*/ if (candidates['north'] && !isTargetSafe([me.locationX, me.locationY-1])) { candidates['north'] = false } if (candidates['south'] && !isTargetSafe([me.locationX, me.locationY+1])) { candidates['south'] = false } if (candidates['west'] && !isTargetSafe([me.locationX-1, me.locationY])) { candidates['west'] = false } if (candidates['east'] && !isTargetSafe([me.locationX+1, me.locationY])) { candidates['east'] = false } if (candidates['none']) { } return candidates } function getSafeCoins() { let safestCoins = [] let coinSizes = [5, 2, 2, 2, 2] for (let i = 0; i < coins.length; i++) { let distanceToThisCoin = distanceTo(coins[i]) if (distanceToThisCoin < nearSightedness && isTargetSafe(coins[i])) { safestCoins.push([coins[i][0], coins[i][1], coinSizes[i], distanceToThisCoin]) //alert('Coin at (' + coins[i][0] + ', ' + coins[i][1] + ') is safe!') } } if (safestCoins.length == 0) { //alert('No safe coins!') } return safestCoins } function getAdditiveBestDirectionToTargets(targets) { let candidates = {'east': 0, 'south': 0, 'west': 0, 'north': 0} for (let i = 0; i < targets.length; i++) { if (targets[i][0] < me.locationX) { candidates['west'] = candidates['west'] + targets[i][2]/targets[i][3] } else if (targets[i][0] > me.locationX) { candidates['east'] = candidates['east'] + targets[i][2]/targets[i][3] } if (targets[i][1] > me.locationY) { candidates['south'] = candidates['south'] + targets[i][2]/targets[i][3] } else if (targets[i][1] < me.locationY) { candidates['north'] = candidates['north'] + targets[i][2]/targets[i][3] } } for (let key in candidates) { //alert(key + ': ' + candidates[key]) } return candidates } let targetCoins = getSafeCoins() let safeDirections = getSafeDirections() let chosenDir = null if (targetCoins.length > 0) { //alert('Coins found! Exactly ' + targetCoins.length) let weightedDirections = getAdditiveBestDirectionToTargets(targetCoins) let bestOptionWeight = 0 let choices = [] for (let key in safeDirections) { if (safeDirections[key] && key != 'none') { if (weightedDirections[key] == bestOptionWeight) { choices.push(key) } else if (weightedDirections[key] > bestOptionWeight) { choices = [key] bestOptionWeight = weightedDirections[key] } } } if (choices.length > 0) { //alert('Picking from choices, ' + choices.length + ' options and best weight is ' + bestOptionWeight) chosenDir = choices[randomInt(choices.length)] } else { //alert('No safe choices!') } } else { let lastDir = botNotes.getData('direction') || 'none' if (safeDirections[lastDir] && Math.random() >= drunkennessCoefficient) { chosenDir = lastDir } } if (!chosenDir) { //alert('indecisive!') let choices = [] for (key in safeDirections) { if (safeDirections[key]) { choices.push(key) } } if (choices.length > 0) { chosenDir = choices[randomInt(choices.length)] } else { chosenDir = getRandomDirection() } } botNotes.storeData('direction', chosenDir) //alert('Moving ' + chosenDir) return chosenDir } ``` Staggers around picking up nearby coins, but randomly switches directions every so often. Does what he can to avoid bumping into anyone, but he gets... belligerent... when aggravated. Tends to sober up as the competition goes on. May need some debugging, when the controller is fully done I'll work on it. [Answer] # Weighted Motion | JavaScript ``` WeightedMotion=(myself,others,coins)=>{ x=myself.locationX; y=myself.locationY; power=myself.coins; arenaSize=myself.arenaLength; dirX=0; dirY=0; for(i=0;i<coins.length;i++){ if(i==0){ dirX+=5/(x-coins[i][0]); dirY+=5/(y-coins[i][1]); } else{ dirX+=2/(x-coins[i][0]); dirY+=2/(y-coins[i][1]); } } for(i=0; i<others.length;i++){ dirX+=(power-others[i][2])/(2*(x-others[i][0])); dirY+=(power-others[i][2])/(2*(y-others[i][1])); } if(Math.abs(dirX)>Math.abs(dirY)){ if(dirX>0){ if(x>0){return "west";} else{ if(dirY>0){if(y>0)return "north";} else if(dirY<0){if(y<arenaSize-1)return "south";} } } else if(x<arenaSize-1){return "east";} else{ if(dirY>0){if(y>0)return "north";} else if(dirY<0){if(y<arenaSize-1)return "south";} } } else{ if(dirY>0){ if(y>0){return "north";} else{ if(dirX>0){if(x>0)return "west";} else if(dirX<0){if(x<arenaSize-1)return "east";} } } else if(y<arenaSize-1){return "south";} else{ if(dirX>0){if(x>0)return "west";} else if(dirX<0){if(x<arenaSize-1){return "east";} } } return "none"; } ``` Moves in the direction it has assigned the highest value while avoiding running off the edge of the board. Value is calculated as such: * Coin = power of coin / distance to coin * Bot = Difference in power of bots / 2 \* distance to bot [Answer] ## Blindy | [JavaScript (Node.js)](https://nodejs.org/en/) This definitely wont win but at least participate. First try at KoH challenge. It sorts the coins and goes to the closest one. He doesn't look for players so he doesn't care if he collide with other. ``` function(myself, others, coins){ mx = myself.locationX my = myself.locationY l="west" r="east" u="north" d="south" n="none" if(coins.length == 0) return n var closestCoin = coins.sort(a=>Math.sqrt(Math.pow(mx-a[0],2) + Math.pow(my-a[1],2))).pop() cx = closestCoin[0] cy = closestCoin[1] return mx>cx?l:mx<cx?r:my>cy?u:my<cy?d:n } ``` [Answer] # Feudal Noble | JavaScript **Preferred color:** `#268299` ``` function (noble, peasants, coins) { var center = (noble.arenaLength - 1) / 2, centerSize = noble.arenaLength / 4, peasantsCount = peasants.length, centerMin = center - centerSize, centerMax = center + centerSize, apocalypse = 2e4 - ((noble.arenaLength * 2) + 20), inDanger = false; var round = botNotes.getData('round'); if (round === null || !round) round = 0; round++; botNotes.storeData('round', round); var getDistance = function (x1, y1, x2, y2) { return (Math.abs(x1 - x2) + Math.abs(y1 - y2)) + 1; }; var isAtCenter = function (x, y) { return (x > centerMin && x < centerMax && y > centerMin && y < centerMax); }; var getScore = function (x, y) { var score = 0, i, centerFactor = 10; for (i = 0; i < peasantsCount; i++) { var peasantCoins = peasants[i][2], peasantDistance = getDistance(x, y, peasants[i][0], peasants[i][1]); if (noble.coins > peasantCoins && isAtCenter(x, y)) { score += Math.min(100, peasantCoins) / peasantDistance; } else if (noble.coins <= peasantCoins && peasantDistance <= 3) { score -= (peasantDistance === 3 ? 50 : 2000); inDanger = true; } } for (i = 0; i < coins.length; i++) { if (isAtCenter(coins[i][0], coins[i][1])) { var coinDistance = getDistance(x, y, coins[i][0], coins[i][1]), coinValue = (i === 0 ? 500 : 200), coinCloserPeasants = 1; for (var j = 0; j < peasantsCount; j++) { var coinPeasantDistance = getDistance(peasants[j][0], peasants[j][1], coins[i][0], coins[i][1]); if (coinPeasantDistance <= coinDistance && peasants[j][2] >= noble.coins) coinCloserPeasants++; } score += (coinValue / coinCloserPeasants) / (coinDistance / 3); } } if (round >= apocalypse) centerFactor = 1000; score -= getDistance(x, y, center, center) * centerFactor; return score; }; var possibleMoves = [{x: 0, y: 0, c: 'none'}]; if (noble.locationX > 0) possibleMoves.push({x: -1, y: 0, c: 'west'}); if (noble.locationY > 0) possibleMoves.push({x: -0, y: -1, c: 'north'}); if (noble.locationX < noble.arenaLength - 1) possibleMoves.push({x: 1, y: 0, c: 'east'}); if (noble.locationY < noble.arenaLength - 1) possibleMoves.push({x: 0, y: 1, c: 'south'}); var topCommand, topScore = null; for (var i = 0; i < possibleMoves.length; i++) { var score = getScore(noble.locationX + possibleMoves[i].x, noble.locationY + possibleMoves[i].y); if (topScore === null || score > topScore) { topScore = score; topCommand = possibleMoves[i].c; } } if (round >= apocalypse) { var dg = botNotes.getData('dg'); if (dg === null || !dg) dg = []; if (dg.length >= 20) dg.shift(); dg.push(inDanger); botNotes.storeData('dg', dg); if (dg.length >= 20) { var itsTime = true; for (i = 0; i < dg.length; i++) if (!dg[i]) itsTime = false; if (itsTime) return 'none'; } } return topCommand; } ``` This feudal noble stays at the center of the field and claims it as his own palace. Collects anything at the center for himself, but anything in farms far away should be brought to him by peasants. Of course if an angry powerful peasant appears at the palace, noble might run away to save his life, but he comes back as soon as it is safe! As the time goes on, peasants get stronger and stronger. Professional fighters and powerful heros start to rise from the peasantry. Power of the noble keeps decaying. He tries to keep his wealth and his Feudalism system together as long as he can. But finally a time comes that he should accept his faith, he should accept that people don't want Feudalism anymore. That is the day that feudal noble gives up everything, doesn't run from powerful peasants anymore and gets killed by one of them. [Answer] # Quantum Gnat Bot | JavaScript ``` function quantumGnatBot(me, others, coins) { let quantumCoefficient = .2 let turn = botNotes.getData('turn') botNotes.storeData('turn', turn+1) botNotes.storeData('test', [2, 5, 7]) botNotes.getData('test') let dG = {'none': [0, 0, -2, -2], 'east': [1, 0, me.arenaLength-1, -2], 'south': [0, 1, -2, me.arenaLength-1], 'west': [-1, 0, 0, -2], 'north': [0, -1, -2, 0]} function randomInt(a) { return Math.floor(Math.random() * a); } function getRandomDirection() { return ['east', 'west', 'north', 'south'][randomInt(4)] } function distanceBetween(a, b){ return (Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1])) } function isTargetSafe(a) { for (let i = 0; i < others.length; i++) { if (others[i][2] >= me.coins && distanceBetween(a, others[i]) <= 1) { return false } } return true } function isEnemySquare(a) { for (let i = 0; i < others.length; i++) { if (distanceBetween(a, others[i]) == 0) { return true } } return false } function getSafeDirections() { let candidates = {'none': true, 'east': true, 'south': true, 'west': true, 'north': true} for (let key in dG) { if (me.locationX == dG[key][2] || me.locationY == dG[key][3] || !isTargetSafe([me.locationX+dG[key][0], me.locationY+dG[key][1]])) { candidates[key] = false } } //alert('Safe: ' + candidates['north'] + ', ' + candidates['east'] + ', ' + candidates['south'] + ', ' + candidates['west']) return candidates } function getThreatDirections() { let candidates = {'none': false, 'east': false, 'south': false, 'west': false, 'north': false} for (let key in dG) { if (isEnemySquare([me.locationX+dG[key][0], me.locationY+dG[key][1]])) { candidates[key] = true } } return candidates } function getTargetDirections() { let targetBot = null let candidates = {'none': false, 'east': false, 'south': false, 'west': false, 'north': false} for (let i = 0; i < others.length; i++) { if (distanceBetween([me.locationX, me.locationY], others[i]) > 2 && (!targetBot || targetBot[2] < others[i][2])) { targetBot = others[i] } } if (targetBot[0] < me.locationX) { candidates['west'] = true } else if (targetBot[0] > me.locationX) { candidates['east'] = true } if (targetBot[1] > me.locationY) { candidates['south'] = true } else if (targetBot[1] < me.locationY) { candidates['north'] = true } //alert('Chasing ' + targetBot[0] + ', ' + targetBot[1] + ' (' + targetBot[2] + ')') //alert('Path: ' + candidates['north'] + ', ' + candidates['east'] + ', ' + candidates['south'] + ', ' + candidates['west']) return candidates } let safeDirections = getSafeDirections() let threatDirections = getThreatDirections() let targetDirections = getTargetDirections() let chosenDir = null let choices = [] for (key in safeDirections) { if (safeDirections[key] && targetDirections[key]) { choices.push(key) } } if (choices.length == 0) { //alert('Best options are blocked...') for (key in safeDirections) { if (safeDirections[key]) { choices.push(key) } } } for (key in threatDirections) { if (threatDirections[key] && Math.random() < quantumCoefficient) { //alert('Chance for quantum swap!') choices.push(key) } } if (choices.length > 0) { chosenDir = choices[randomInt(choices.length)] } else { //alert('No options? Guess we spin the wheel.') chosenDir = getRandomDirection() } return chosenDir } ``` This annoying bot tries to buzz around the strongest bot without getting swatted and has a slight chance of phasing through those who try to hunt it. It has a tendency to draw the two most powerful bots into close proximity... ;) [Answer] # Retired ICE Agent, JavaScript **Preferred colour: `indianred`** ``` function(me, others, coins) { me.arenaLength = me.arenaLength - 1; // Calculate the average coin value of bots var avg = 2; for (var i = 0; i < others.length; i++) { avg += others[i][2]; } avg /= others.length; // Find nearest coins var min = []; var min_distance = 100000 for (var j = 0; j < coins.length; j++) { var distance = Math.sqrt(Math.pow(me.locationX - coins[j][0],2) + Math.pow(me.locationY - coins[j][1],2)); if (distance < min_distance) { min_distance = distance; min = coins[j]; } } if (me.coins <= avg || min_distance < 5) { // If own coinage is lower than the average or a coin is very close, find some coins // Move straight to the nearest coin if (me.locationY != min[1]) { if (me.locationY - min[1] > 0) { return "north"; } else { return "south"; } } else { if (me.locationX - min[0] > 0) { return "west"; } else { return "east"; } } } else { // You have enough money to eat most bots // Find the weakest bot var weakling = []; var weakling_money = 1000000; for (var k = 0; k < others.length; k++) { if (others[k][2] < weakling_money) { weakling_money = others[k][2]; weakling = others[k]; } } // Move to the weakest bot if (me.locationY != weakling[1]) { if (me.locationY - weakling[1] > 0) { return "north"; } else { return "south"; } } else { if (me.locationX - weakling[0] > 0) { return "west"; } else { return "east"; } } } } ``` Now retired, this ICE agent is bitter about humanity. As a result, Retired ICE now targets the weakest bot, while keeping its coin value above the average (as per ICE policy). [Answer] # Greedy-Pursuit | [Haskell](https://www.haskell.org/) **Preferred colour:** [`#62bda4`](https://duckduckgo.com/?q=color+picker+%2362bda4) ``` import Data.List f x y c _ bs _ | [bx,by,_]:_ <- sortByDist x y $ filter ((c>).last) bs = toDir (bx-x,by-y) f x y _ _ _ cs | [cx,cy,_]:_ <- sortByDist x y cs = toDir (cx-x,cy-y) f _ _ _ _ _ _ = "none" sortByDist x y = sortOn (\[bx,by,_]-> abs (bx-x) + abs (by-y)) toDir (dx,dy) | dx > 0 = "east" | dx < 0 = "west" | dy > 0 = "south" | dy < 0 = "north" | otherwise = "none" ``` [Try it online!](https://tio.run/##dZBBa4QwEIXv@RUP6UFpXLReSlk9FI8LPfRoRWLMotTVxWTZCP3vNnGzshTKXDKPN9@8Scvkt@j7ZelO53FSyJliu0MnFSFHaMzgqFBLVAT4QVFrWs@0Kt8q7ENIM/E@58a9Wp9w7HolJvg@z4Jdz6QK7GwKNeadkWsd2vlwDhy8WovLG5xryv@F8wcOtxzuONVDpfCGcRAeIeTPeLryPgb4X9sRYQZm4q2xAjy7xmIDQtyqRtPGrLH5Go0Mkd0hzGXeXdvftKvYtPnuk@NFtZvojIPJ4cRRtWK6dlJswZcT6wbTnS/qU02Hwf4pXpAgxiuKIqEJjcrSvGIa0bgsl18 "Haskell – Try It Online")\* Pretty simple strategy, picks the first decision from: * if there are bots with less coins: pick closest and move towards it * if there are coins: pick closest and move towards it * default: stay The bot only tries to catch other bots or coins without caring about potentially stronger bots that might try to catch it. \* I don't really know JavaScript but I did the thing with google (might be inaccurate): [Try it online!](https://tio.run/##jVRNj9owEL3nV4xQD/GuE74uK9gEFXGk6qGXrmiEHGOWtGCjxCyJ6P52OnacbFip7ZIDnq83b/wm@cleWMHz7KgDqTbieu3fQXY4qlzDgmkWLrNCe94WSqiAwxrSAtYewG9YpSVNK7pOJmt4DKDAinm1wGyb@gm22V6LHHyfxyTcs0ITUxuBVosM3WkZmPqgIg58bR9e1OC8pPyv4LyDww0OdzjrzhNBTyopep7nvSuPLN5XCf6PdoggBob0LC0C984wsMTzXKtNSTfYxvDblBDDwPQQOFmv8T3WvrNofVWTV6iT3rVOlyiRh3MqvRP5OStEh/hdH8lvT5LrTEnYgr9Vp5ymSheUq0wWBC5Y@8JyHCsCEwz3ijOT/X3qItX7yFMT4U3EYk095z4L9gt1i8D0CWsV/RSiGC6QC33KJaSrUYIj8Cm8khZNHY4sN@x9RlNyk88wOYUZBEOYoBFbw5wHiNAAnLG0rPhN4RemdyFK4WNgNUhQmvsb1zBBgToYHaEjcycxlKHx@Sb7MzX4c0vNsfXPNkCo/Z8T0o5TSx41ot@wcuLP3sT/92/SrMbsbTX@W1E1PdrF@UCJa1KvFbrqRcIL8joXJDZmyAzXqZY63Av5rHemH7Ft6iT3mtTX6VIJimCKxR731CDY1fkQQL2wnXqb6W7U8TQsncfev18DWeWpO9eSe6/Xfh8OLJPY5XjS33S@lOajAyMY42o9wGo1pmM6SBI8DemADpPE40oWai/wVXj2Yetfeu3b0pvAiEJrP6E9RtuSxvMQz7guki3tpOh5eKVtB9p2IECm1z8 "JavaScript (Node.js) – Try It Online") [Answer] # Coin Magnet | JavaScript ``` CoinMagnet=(myself,others,coins)=>{ x=myself.locationX; y=myself.locationY; power=myself.coins; arenaSize=myself.arenaLength; dirX=0; dirY=0; for(i=0;i<coins.length;i++){ if(i==0){ dirX+=(coins[i][0]-x)*3 dirY+=(coins[i][1]-y)*3 } dirX+=(coins[i][0]-x)*2 dirY+=(coins[i][1]-y)*2 } for(i=0;i<others.length;i++){ dirX+=Math.ceil(0.85*others[i][2])*(others[i][0]-x) dirX+=Math.ceil(0.85*others[i][2])*(others[i][1]-y) } if(Math.abs(dirX)>Math.abs(dirY)){ if(dirX>0){return "east";} else{return "west";} } else if(dirY!=0){ if(dirY>0){return "south";} else{return "north";} } return "none"; } ``` This bot is rather dumb, it heads in the direction of the most acquirable coins. This includes coins that it can not get because other bots have higher power than itself. [Answer] # ICE Agent | Javascript ``` function(me, others, coins) { me.arenaLength = me.arenaLength - 1; // Calculate the average coin value of bots var avg = 2; for (var i = 0; i < others.length; i++) { avg += others[i][2]; } avg /= others.length; // Find nearest coins var min = []; var min_distance = 100000 for (var j = 0; j < coins.length; j++) { var distance = Math.sqrt(Math.pow(me.locationX - coins[j][0],2) + Math.pow(me.locationY - coins[j][1],2)); if (distance < min_distance) { min_distance = distance; min = coins[j]; } } if (me.coins <= avg || min_distance < 5) { // If own coinage is lower than the average or a coin is very close, find some coins // Move straight to the nearest coin if (me.locationY != min[1]) { if (me.locationY - min[1] > 0) { return "north"; } else { return "south"; } } else { if (me.locationX - min[0] > 0) { return "west"; } else { return "east"; } } } else { // You have enough money to eat most bots // Check if already on border if (me.locationX == 0 || me.locationX == me.arenaLength || me.locationY == 0 || me.locationY == me.arenaLength) { // Move anticlockwise around the border if (me.locationX == 0 && me.locationY != 0 && me.locationY != me.arenaLength) { return "south"; } if (me.locationX == 0 && me.locationY == 0) { return "south"; } if (me.locationY == me.arenaLength && me.locationX != 0 && me.locationX != me.arenaLength) { return "east"; } if (me.locationX == 0 && me.locationY == me.arenaLength) { return "east"; } if (me.locationX == me.arenaLength && me.locationY != 0 && me.locationY != me.arenaLength) { return "north"; } if (me.locationX == me.arenaLength && me.locationY == me.arenaLength) { return "north"; } if (me.locationY == 0 && me.locationX != 0 && me.locationX != me.arenaLength) { return "west"; } if (me.locationX == me.arenaLength && me.locationY == 0) { return "west"; } } else { // Find the nearest border and move to it if (me.locationX <= me.arenaLength - me.locationX) { // Move to left border return "west"; } else { // Move to right border return "east"; } } } } ``` What's the point of a border if isn't being patrolled? ICE moves anticlockwise around the border, picking up any bots which stray into its path. Before it can do that, it needs to be able to eat other bots first. For that reason ICE, keeps its coins above the average of all of the bots. Guaranteed to steal kids from their parents™ [Answer] # X Marks The Spot | JavaScript ``` function(me, others, coins){ if (me.locationY != 0) { // If not on X axis if (others.every(other => other[1]==me.locationY-1)) { // If any in my way if (!others.every(other => other[0]==me.locationX-1)) { if (me.locationX != 0) { // If no one to my left and not on edge of board return "west" } else { return "none" } } else if (!others.some(other => other[0]==me.locationX+1)) { if (me.locationX != me.arenaLength-1) { // If no one to my right and not on edge of board return "east" } else { return "none" } } else { // I'm surrounded return "none" } } else { // No one in my way return "north" } } else { // If on the x axis if (!others.some(other => Math.abs(other[0]-me.locationX)==1 && other[1] == me.locationY)) { // If no one next to me move = ["east","west"][Math.floor(Math.random()*2)] // Prevent from falling off the board if (move == "east" && me.locationX == me.arenaLength-1) { return "west" } else if (move == "west" && me.locationX == 0) { return "east" } else { return move } } else { // I'm surrounded return "none" } } } ``` X marks the spot, so all the gold must be on the x axis, right? My bot makes a beeline for the y=0 line then stays there, moving about randomly. [Answer] # Firebird ``` function(me,others,coins) { var x = me.locationX; var y = me.locationY; var safe = [true, true, true, true]; var threats = []; var targets = []; var opps = []; var meTo = (loc) => (Math.abs(x - loc[0]) + Math.abs(y - loc[1])); var inSquare = (loc, r) => (Math.abs(loc[0] - x) <= r && Math.abs(loc[1] - y) <= r); var distance = (from, loc) => (Math.abs(from[0] - loc[0]) + Math.abs(from[1] - loc[1])); var attackRange = (from, check, r) => { for (var i = 0; i < check.length; i++) { if (distance(check[i], from) == (r || 1)) { return true; } } return false; }; var dirStr = (dir) => (['north','east','south','west'][dir]); var i, n, o, p; for (i = 0; i < others.length; i++) { o = others[i]; if (o[2] >= me.coins) { threats.push(o); } else { targets.push([o[0], o[1], Math.floor(o[2] * 0.55)]); } } for (i = 1; i < 5; i++) { targets.push([coins[i][0], coins[i][1], 2]); } targets.push([coins[0][0], coins[0][1], 5]); if (y === 0 || attackRange([x, y - 1], threats)) { safe[0] = false; } if (x == me.arenaLength - 1 || attackRange([x + 1, y], threats)) { safe[1] = false; } if (y == me.arenaLength - 1 || attackRange([x, y + 1], threats)) { safe[2] = false; } if (x === 0 || attackRange([x - 1, y], threats)) { safe[3] = false; } if (safe.includes(false)) { if (!(safe[0]) && safe[2]) { opps.push(2); } if (!(safe[1]) && safe[3]) { opps.push(3); } if (!(safe[2]) && safe[0]) { opps.push(0); } if (!(safe[3]) && safe[1]) { opps.push(1); } } else { targets.sort((a,b)=>(meTo(a) - meTo(b))); o = targets[0]; if (o[0] == x) { if (o[1] < y) { return 'north'; } else { return 'south'; } } else if (o[1] == y) { if (o[0] < x) { return 'west'; } else { return 'east'; } } else if (Math.abs(o[0] - x) < Math.abs(o[1] - y)) { if (o[1] < y) { return 'north'; } else { return 'south'; } } else if (Math.abs(o[0] - x) > Math.abs(o[1] - y)) { if (o[0] < x) { return 'west'; } else { return 'east'; } } } console.log(safe[opps[0]]); var lx, ly; for (i = 0; i < opps.length; i++) { if (opps[i] === 0) { lx = x; ly = y - 1; } if (opps[i] == 1) { lx = x + 1; ly = y; } if (opps[i] == 2) { lx = x; ly = y + 1; } if (opps[i] == 3) { lx = x - 1; ly = y; } if (attackRange([lx, ly], targets, 0)) { return dirStr(opps[i]); } } return dirStr(opps[0]); } ``` Completely revamped to be more deadly than before (: [Answer] # A-Path-y | JavaScript Preferred color for this bot is `#0077b3`. ``` run: function (me, others, coins) { var X_INDEX = 0; var Y_INDEX = 1; var COIN_INDEX = 2; var GOLD_POINTS = 5; var SILVER_POINTS = 2; var NORTH = 0; var SOUTH = 1; var WEST = 2; var EAST = 3; var IDLE = 4; var MOVE_COMMANDS_COUNT = IDLE+1; var MAP_TYPE_BLANK = 0; var MAP_TYPE_BOT = 1; var MAP_TYPE_GOLD_COIN = 2; var MAP_TYPE_SILVER_COIN = 3; var MIDGAME_THRESHOLD = 25; var PATH_FINDING_MAX_STEPS = 10000; var offsets = [[0,-1],[1,0],[0,1],[-1,0]]; function randInt(min,max) { return Math.floor(Math.random() * ((max - min) + 1)) + min; } /** * Find a path using a*, returns the direction to take from the starting position coupled with a metric describing the cost of the path */ function pathFind(startX,startY,targetX,targetY,map,mapSize) { var i; var j; // shuffleIndecies to make path selection slightly random var indecies = [0,1,2,3]; var shuffleIndecies = new Array(4); for (j=0;j<4;j++) { var randomIndex = randInt(0,3-j); shuffleIndecies[j] = indecies[randomIndex]; indecies[randomIndex] = indecies[0]; var lastElementIndex = 4-j-1; indecies[0] = indecies[lastElementIndex]; } // A* if (!(startX===targetX && startY===targetY)) { var tileX = new Array(PATH_FINDING_MAX_STEPS); var tileY = new Array(PATH_FINDING_MAX_STEPS); var fscore = new Array(PATH_FINDING_MAX_STEPS); var gscore = new Array(PATH_FINDING_MAX_STEPS); var openList = new Array(PATH_FINDING_MAX_STEPS); var tileParent = new Array(PATH_FINDING_MAX_STEPS); var tileIsClosed = new Array(mapSize); for (i = 0;i<PATH_FINDING_MAX_STEPS;i++) { tileX[i]=0; tileY[i]=0; fscore[i]=0; gscore[i]=0; openList[i]=0; tileParent[i]=0; } for (i = 0;i<mapSize;i++) { var newArray = new Array(mapSize); tileIsClosed[i] = newArray; for (j = 0;j<mapSize;j++) { tileIsClosed[i][j] = 0; } } var currentIndex = -1; var openListSize=1; var tileId=1; tileX[0]=targetX; tileY[0]=targetY; fscore[0]=1; gscore[0]=map[targetX][targetY].negativeWeight; do { var currentBestIndex=-1; var currentBestScore=2147483647; // Look for the lowest F cost square on the open list for (var ii=0;ii<openListSize;ii++) { if (fscore[openList[ii]]<currentBestScore) { currentBestScore=fscore[openList[ii]]; currentBestIndex=ii; } } if (currentBestIndex===-1) { break; } currentIndex=openList[currentBestIndex]; var currentTileX=tileX[currentIndex]; var currentTileY=tileY[currentIndex]; // found path if (startX===currentTileX && startY===currentTileY) { break; } // if not in closed list if (tileIsClosed[currentTileX][currentTileY]===0) { // Switch it to the closed list. tileIsClosed[currentTileX][currentTileY]=1; // remove from openlist openList[currentBestIndex]=openList[--openListSize]; // add neighbours to the open list if necessary for (j=0;j<4;j++) { i = shuffleIndecies[j]; var surroundingCurrentTileX=currentTileX+offsets[i][0]; var surroundingCurrentTileY=currentTileY+offsets[i][1]; if (surroundingCurrentTileX>=0 && surroundingCurrentTileX<mapSize && surroundingCurrentTileY>=0 && surroundingCurrentTileY<mapSize ) { tileX[tileId]=surroundingCurrentTileX; tileY[tileId]=surroundingCurrentTileY; var surroundingCurrentGscore=gscore[currentIndex] + map[surroundingCurrentTileX][surroundingCurrentTileY].negativeWeight; gscore[tileId]=surroundingCurrentGscore; fscore[tileId]=surroundingCurrentGscore+Math.abs( surroundingCurrentTileX-startX)+Math.abs( surroundingCurrentTileY-startY); tileParent[tileId]=currentIndex; openList[openListSize++]=tileId++; } } } else { // remove from openlist openList[currentBestIndex]=openList[--openListSize]; } } while(true); if (tileX[tileParent[currentIndex]]<startX) return {moveDirection:WEST, pathLength:currentIndex, pathScore:gscore[currentIndex]+currentIndex/4}; else if (tileX[tileParent[currentIndex]]>startX) return {moveDirection:EAST, pathLength:currentIndex, pathScore:gscore[currentIndex]+currentIndex/4}; else if (tileY[tileParent[currentIndex]]<startY) return {moveDirection:NORTH, pathLength:currentIndex, pathScore:gscore[currentIndex]+currentIndex/4}; else if (tileY[tileParent[currentIndex]]>startY) return {moveDirection:SOUTH, pathLength:currentIndex, pathScore:gscore[currentIndex]+currentIndex/4}; } console.log("Path finding failed"); return {moveDirection:IDLE, pathLength:0, pathScore:2147483647}; } function process(info,bots,coins) { var i; var j; var k; var x; var y; // initialise map var mapSize = info.arenaLength; var map = new Array(mapSize); for (i = 0;i < info.arenaLength;i++) { var newArray = new Array(info.arenaLength); map[i] = newArray; for (j = 0;j < mapSize;j++) { map[i][j] = {type:MAP_TYPE_BLANK, coins: 0 , negativeWeight:i===0||i===mapSize-1||j===0||j===mapSize-1?3:1}; } } // populate map with bots for (i = 0 ; i<bots.length;i++) { map[bots[i][X_INDEX]][bots[i][Y_INDEX]].type = MAP_TYPE_BOT; map[bots[i][X_INDEX]][bots[i][Y_INDEX]].coins = bots[i][COIN_INDEX]; for (j=-1;j<2;j++) { x = bots[i][X_INDEX] + j; if (x>=0 && x < mapSize) { for(k=-1;k<2;k++) { if (Math.abs((k+j)%2) === 1) { y = bots[i][Y_INDEX] + k; if (y>=0 && y< mapSize ) { // are we adjacent the bot or potentially will be? if (Math.abs(info.locationX-x)<=1 && Math.abs(info.locationY-y)<=1) { // make the cell significantly less attractive when the bot is stronger than us, or // make the cell slightly more attactive when the bot is weaker than us, or // not change if the bot has no coins map[x][y].negativeWeight+= bots[i][COIN_INDEX] >= info.coins?100000:(bots[i][COIN_INDEX]===0?0:-1); } // another bot is not a direct threat/target else { // make the cell moderately less attractive when the bot is stronger than us, or // make the cell slightly more attactive when the bot is weaker than us, or // not change if the bot has no coins map[x][y].negativeWeight+= bots[i][COIN_INDEX] >= info.coins?3:(bots[i][COIN_INDEX]===0?0:-1); } } } } } } } // populate map with coins for (i = 0 ; i<coins.length;i++) { map[coins[i][X_INDEX]][coins[i][Y_INDEX]].type = i === 0?MAP_TYPE_GOLD_COIN:MAP_TYPE_SILVER_COIN; map[coins[i][X_INDEX]][coins[i][Y_INDEX]].coins = i === 0?GOLD_POINTS:SILVER_POINTS; // check to see whether bots are adjacent to the coin for (j=-1;j<2;j++) { x = coins[i][X_INDEX] + j; if (x>=0 && x < mapSize) { for(k=-1;k<2;k++) { if ((k+j)%2 === 1) { y = coins[i][Y_INDEX] + k; if (y>=0 && y< mapSize ) { if (map[x][y].type === MAP_TYPE_BOT) { // this coin looks like a trap as a stronger bot is adjacent to it if (map[x][y].coins >= info.coins) { map[coins[i][X_INDEX]][coins[i][Y_INDEX]].negativeWeight+=100000; } else { // are we adjacent the coin? we might be able to kill another bot if it trys to get the coin if (Math.abs(info.locationX-coins[i][X_INDEX])<=1 && Math.abs(info.locationY-coins[i][Y_INDEX])<=1) { map[coins[i][X_INDEX]][coins[i][Y_INDEX]].negativeWeight+=-20; } // another bot is likely to get this coin... make it less attractive else { map[coins[i][X_INDEX]][coins[i][Y_INDEX]].negativeWeight=+100; } } } } } } } } // add the coin attractiveness, more for gold coins map[coins[i][X_INDEX]][coins[i][Y_INDEX]].negativeWeight += i === 0?-20:-10; } var pathBest = {moveDirection:IDLE, pathLength: 2147483647, pathScore: 2147483647}; if (info.coins > MIDGAME_THRESHOLD) { var viableCoinCount =0; var viableCoins = new Array(5); // find coins that are reachable before any other bot outer1: for (j = 0 ; j<coins.length;j++) { var contention = 0; var myDistanceToCoin = Math.abs(info.locationX-coins[j][X_INDEX]) + Math.abs(info.locationY-coins[j][Y_INDEX]); for (i = 0 ; i<bots.length;i++) { var dist = Math.abs(bots[i][X_INDEX]-coins[j][X_INDEX]) + Math.abs(bots[i][Y_INDEX]-coins[j][Y_INDEX]); if (dist < myDistanceToCoin) { continue outer1; } } viableCoins[viableCoinCount++] = j; } // no coins are reachable before another bot so find the cell that is furthest away from any bot and head there if (viableCoinCount ===0) { var mostIsolatedCellX = mapSize/2; var mostIsolatedCellY = mapSize/2; var mostIsolatedCellMinBotDistance = 0; for (x=5;x<mapSize-5;x++) { for (y=5;y<mapSize-5;y++) { if (x!= info.locationX && y!=info.locationY) { // ignore coin attractiveness map[x][y].negativeWeight = map[x][y].negativeWeight<-4?map[x][y].negativeWeight:1; var currentCellMinBotDistance = 2147483647; for (i = 0 ; i<bots.length;i++) { var dist = Math.abs(bots[i][X_INDEX]-x) + Math.abs(bots[i][Y_INDEX]-y) + Math.abs(info.locationX-x) + Math.abs(info.locationY-y); if (dist < currentCellMinBotDistance ) { { currentCellMinBotDistance = dist; if (currentCellMinBotDistance>mostIsolatedCellMinBotDistance) { mostIsolatedCellMinBotDistance = currentCellMinBotDistance; mostIsolatedCellX=x; mostIsolatedCellY=y; } } } } } } } // attempt to find path to most isolated cell pathBest = pathFind(info.locationX, info.locationY, mostIsolatedCellX,mostIsolatedCellY, map, mapSize); } // attempt to find paths to each viable coin, keeping the best result for (i = 0 ; i<viableCoinCount;i++) { var path = pathFind(info.locationX, info.locationY, coins[viableCoins[i]][X_INDEX],coins[viableCoins[i]][Y_INDEX], map, mapSize); if (path.pathScore < pathBest.pathScore) { pathBest = path; } } } else { // attempt to find paths to each coin, keeping the best result for (i = 0 ; i<coins.length;i++) { var path = pathFind(info.locationX, info.locationY, coins[i][X_INDEX],coins[i][Y_INDEX], map, mapSize); if (path.pathScore < pathBest.pathScore) { pathBest = path; } } } var move = IDLE; if (pathBest.pathLength === 2147483647) { outer: for (i=0;i<MOVE_COMMANDS_COUNT;i++) { switch (i) { case NORTH: if (info.locationY-1 < 0) { continue; } move = i; break outer; case SOUTH: if (info.locationY+1 === info.arenaLength) { continue; } move = i; break outer; case WEST: if (info.locationX-1 < 0) { continue; } move = i; break outer; case EAST: if (info.locationX+1 === info.arenaLength) { continue; } move = i; break outer; case IDLE: move = i; break; default: } } } else { move = pathBest.moveDirection; } switch (move) { case NORTH: return "north"; case SOUTH: return "south"; case EAST: return "east"; case WEST: return "west"; default: return "none"; } } return process(me, others, coins); } ``` This bot uses path finding coupled with a map of cell desirabilities to avoid bots that could kill us, go for coins that are close, not traps and are least risky. It does not seem to be a contender for the winning place, but it does hold its own and will be alive at the end of the match if it survives the initial melee. Bot now has mid-to-late game strategy that ignores coins it cannot reach before other bots and if cannot go to any coin then moves to the closest cell that is furthest away from all other bots that are stronger than itself. It now has a chance of winning. *Note* sorry for the crappy code, I have automatically converted it from Java ]
[Question] [ Your task is to improvise a hardware random-number generator with whatever hardware you have lieing around. ## Challenge Write a program with the following properties: 1. It prints either `0` or `1` (and nothing else). 2. The output depends on a physical process and not just the internal state of the computer. 3. There is no relation between outputs of subsequent runs (one minute apart). 4. The output is not predictable with any realistic effort. 5. The probability of the output being `0` is between 0.2 and 0.8. 6. It runs in less than a minute with a reasonably high probability. You must explain why your program has these properties, if it is not obvious. ## Clarifications and Restrictions The following may seem like an awful lot of restrictions for a popularity contest, but ultimatively it’s all to ensure that the program remains within the spirit of the question, somewhat works and to avoid solutions which are popular due to being a total overkill but are ultimatively rather boring. * The system time does not count as a physical process. * You may use any consumer-grade hardware you like from 8-inch floopy-disk drives to a [USB rocket launcher](http://www.thinkgeek.com/product/8a0f/) to headphones – unless it is intended for random-number generation. A piece of hardware is *consumer-grade,* if it is mass-produced and costs less than 1000 $/€/£, so you cannot use radio telescopes, the CERN, MRIs or your home-built particle detector. * You can only make the most basic assumptions on the state and alignment of the hardware such as being switched on (if it has a power switch) and being properly installed and functional. For example you can assume a CD drive to be generally capable of reading a disk and not to be jammed, but you cannot assume it to be open or closed or to contain a disk. In another example you cannot assume two pieces of hardware to be aligned to allow for a special interaction, but you can assume them to be in the same room. * You may leave the hardware in any state you like, unless you break it. * You can and must assume the hardware to be in a natural environment, but nothing more. For example you can assume that the hardware is not positioned in a in tank of liquid helium nor in an extremely sound- and lightproof room nor in space. However, you cannot assume any sound- and lightsources to be present except those that are only avoidable with radical efforts. * Your program must run on a standard desktop computer with a non-esoteric operating system of your choice. You may employ any software that is not specifically designed for random-number generation. * You cannot assume Internet access. * You can neither assume humans to be present nor absent, but you can assume that nobody intentionally interfers with your program, e.g., by manually stopping a fan or running a program that does nothing but switching off the microphone as often as possible. * You can only make the most basic assumptions about the software settings. For example, you can assume drivers to be installed and activated but you must be prepared for the sound to be muted. * You may leave the software settings in any state you like. ## Bonus A special bounty was awarded to a particularly short solution. This was rather by numbers of instructions and similar than by characters. The winners were (tied according to my criteria): * [This answer](https://codegolf.stackexchange.com/a/38149/11354) by Franki. * [This answer](https://codegolf.stackexchange.com/a/38069/11354) by Tejas Kale. I could only award one answer and Tejas Kale’s answer won by lot. [Answer] ## Shell Reads a single sample from the microphone stream and prints its least-significant bit, which should be dominated by noise. **EDIT:** Changed to unmute the microphone ... and everything else too! ``` # Warning - unmutes EVERYTHING! for DEV in `amixer | grep Simple | sed -e "s/.*'\(.*\)'.*/\\1/" -e "s/ /~/g"` do amixer -q -- sset "`echo $DEV | sed 's/~/ /g'`" unmute 100% 2>/dev/null done echo $(( `od -N1 -d < /dev/dsp | head -n1 | sed 's/.* //'` & 1 )) ``` [Answer] # Bash ``` echo $[`ping -qc1 127.1|sed 's/[^1-9]/+/g'`0&1] ``` Gathers entropy from the response time of a single ping to localhost. Note that the response time appears exactly thrice in the output of `ping -qc1`: ``` PING 127.1 (127.0.0.1) 56(84) bytes of data. --- 127.1 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.044/0.044/0.044/0.000 ms ``` All other numbers and constant and – more importantly – independent from the response time. `sed 's/[^1-9]/+/g'` converts every zero and non-digit into plus signs, and `echo $[...0&1]` prints the parity of the resulting sum. [Answer] # JavaScript + HTML5 DeviceMotion ``` var hash = function(x) { var h = 0 for (var i = 0; i < x.length; i++) { h += x.charCodeAt(i) h ^= h << 5 h ^= h >> 3 h ^= h << 13 h &= 0xffff } return h } var listener = function(e) { var accelerationString = JSON.stringify(e.acceleration) var hashed = hash(accelerationString) alert(hashed % 2) window.removeEventListener("devicemotion", listener, true) } window.addEventListener("devicemotion", listener, true); ``` JSFiddle [here](http://jsfiddle.net/d3gxez10/11/). Uses the HTML5 DeviceMotion API on supported devices (mostly mobile devices). It turns the resulting `acceleration` object into JSON, hashes it, and takes the remainder modulo 2. Most of the code is the hash function (damn you JavaScript, and your total lack of a standard library). It could probably be shorter, but I'm a sucker for a good hash function. [Answer] # Python + Webcam Using code shamelessly stolen from [here](https://stackoverflow.com/questions/9711946/how-to-programmatically-capture-a-webcam-photo), takes a shapshot using your webcam, hashes the data, and prints the least significant bit. ``` #!/usr/bin/python import pygame.camera, hashlib pygame.camera.init() cam = pygame.camera.Camera(pygame.camera.list_cameras()[0]) cam.start() raw = cam.get_raw() cam.stop() pygame.camera.quit() h = hashlib.sha256() h.update(raw) print ord(h.digest()[-1]) % 2 ``` [Answer] ## Perl Checks your Harddrive's response time, by timing three operations: * Reading its own source * Deleting itself * Writing itself again Finally, the time taken is packed as a float, and the 11th most significant bit is used (second most significant bit of the mantissa). ``` use Time::HiRes qw(time); $t1 = time; open SELF, "<$0"; read SELF, $_, $^H; close SELF; unlink $0; open SELF, ">$0"; print SELF $_; close SELF; print 1&unpack(xB3, pack(f, time-$t1)) ``` [Answer] # Bash ``` echo $[`sensors|sed 's/[^1-9]/+/g'`0&1] ``` `sensors` prints the current system temperatures along with the fan speed. ``` acpitz-virtual-0 Adapter: Virtual device temp1: +52.0°C (crit = +98.0°C) thinkpad-isa-0000 Adapter: ISA adapter fan1: 3510 RPM coretemp-isa-0000 Adapter: ISA adapter Physical id 0: +54.0°C (high = +86.0°C, crit = +100.0°C) Core 0: +51.0°C (high = +86.0°C, crit = +100.0°C) Core 1: +46.0°C (high = +86.0°C, crit = +100.0°C) ``` `sed 's/[^1-9]/+/g'` converts every zero and non-digit into plus signs, and echo `$[...0&1]` prints the parity of the resulting sum. Regex and parity calculation borrowed from dennis's answer. [Answer] ## Bash ``` (echo -en "ibase=16;";(find /proc/[0-9]*/s* -type f -maxdepth 2 ; find /sys /proc/[^0-9]* -type f) 2>&1 | xargs -n1 sha256sum 2>&1 | sha256sum | tr abcdef ABCDEF | sed 's/ -/%2/' )| bc ``` Uses everything, just in case... Depends on * sensor readings of most hardware sensors (about all somehow expose their values somewhere in `/sys` or `/proc`) * number, memory layout and runtimes of all processes on the system (which may be considered "state of the system" but usually themselves depend on the timings of the hardware) * depending on the system, various values in `/proc/<pid>/s*` (e.g. sched/schedstat) depend on the speed of the hardware necessary to bring those processes alive. * things I might not have thought of that are available in those files too. Runtime on my system is ~10s, but may vary a lot. Especially don't run this as root, or at least modify it to exclude `/proc/kcore` (unless you are willing to spend a lot of time to include the entropy contained in there, which would probably really include everything) [Answer] # Shell + Wi-Fi ``` sudo airmon-ng start wlan0 > /dev/null && sudo dumpcap -a duration:30 -i mon0 -w out.cap > /dev/null && sha512sum out.cap | grep -c "^[0-7]" && sudo airmon-ng stop mon0 > /dev/null ``` Puts the wi-fi card into monitor mode, dumps 30 seconds worth of packets received (including unreadable encrypted data from neighbouring networks), takes the sha512 hash of the packet data, and returns 1 if the first letter of the hash is 0-7. Assumes that your wi-fi card is `wlan0`, and that you do not currently have a `mon0` device. If there are no nearby wi-fi devices, then the output will be predictable, as it will be the same every time. [Answer] Modern 8086 compatible processors manufactured by Intel contain an easily accessible peripheral that generates proper randomness. Driving that peripheral is done using the `rdrand` instruction which either generates a random bit pattern or sets the carry flag if the peripheral is unavailable or out of entropy. The following short program for 80386 Linux checks if the peripheral is available by means of the `cpuid` instruction and tries to generate a random number. If either the peripheral or a random number is not available, the program will terminate with a status of `1`. If a random number could be generated, either a `1` or a `0` is printed out and the program terminates with exit status `0`. Save as `rand.s` and assemble with ``` as --32 -o rand.o rand.s ld -melf_i386 -o rand rand.o ``` Here is the entire assembly: ``` .globl _start .type _start,@function _start: # check if the cpuid instruction is available by trying to # toggle the id flag in the eflags register pushfl mov (%esp),%eax btc $21,%eax # toggle id bit push %eax popfl # check if id bit was saved pushfl pop %eax # load new flags pop %ecx # load original flags xor %ecx,%eax # difference is in %eax bt $21,%eax # check if bit was flipped jnc .Lfailure # if we reach this part, we have a cpuid instruction # next, check if rdrand exists mov $1,%eax # load cpuid leaf 1 cpuid bt $30,%ecx # is rdrnd available? jnc .Lfailure # let's try to get some random data rdrand %ax # don't waste randomness; one bit would suffice jnc .Lfailure # no randomness available and $1,%eax # isolate one bit of randomness add $0x30,%al # 0x30 = '0' push %eax mov $4,%eax # prepare a write system call mov $1,%ebx mov %esp,%ecx # where we placed the data before mov %ebx,%edx # one byte int $0x80 # okay, we're done here. Let's exit mov %ebx,%eax # do an exit system call with status 0 xor %ebx,%ebx int $0x80 .Lfailure: mov $1,%eax # do an exit system call with status 1 mov %eax,%ebx int $0x80 .size _start,.-_start ``` And a dump of the resulting 77 bytes of machine code: ``` 08048098 <_start>: 8048098: 9c pushf 8048099: 8b 04 24 mov (%esp),%eax 804809c: 0f ba f8 15 btc $0x15,%eax 80480a0: 50 push %eax 80480a1: 9d popf 80480a2: 9c pushf 80480a3: 58 pop %eax 80480a4: 59 pop %ecx 80480a5: 31 c8 xor %ecx,%eax 80480a7: 0f ba e0 15 bt $0x15,%eax 80480ab: 73 2f jae 80480dc <_start+0x44> 80480ad: b8 01 00 00 00 mov $0x1,%eax 80480b2: 0f a2 cpuid 80480b4: 0f ba e1 1e bt $0x1e,%ecx 80480b8: 73 22 jae 80480dc <_start+0x44> 80480ba: 66 0f c7 f0 rdrand %ax 80480be: 73 1c jae 80480dc <_start+0x44> 80480c0: 83 e0 01 and $0x1,%eax 80480c3: 04 30 add $0x30,%al 80480c5: 50 push %eax 80480c6: b8 04 00 00 00 mov $0x4,%eax 80480cb: bb 01 00 00 00 mov $0x1,%ebx 80480d0: 89 e1 mov %esp,%ecx 80480d2: 89 da mov %ebx,%edx 80480d4: cd 80 int $0x80 80480d6: 89 d8 mov %ebx,%eax 80480d8: 31 db xor %ebx,%ebx 80480da: cd 80 int $0x80 80480dc: b8 01 00 00 00 mov $0x1,%eax 80480e1: 89 c3 mov %eax,%ebx 80480e3: cd 80 int $0x80 ``` [Answer] # bash Aiming for the most unnecessarily expensive random number gathering method. Time how long it takes to spawn emacs a million times, then use Dennis' trick to turn the time taken into a single Boolean (takes about 7 seconds on my machine). ``` $[`(time (seq 1000000 | xargs -P1000 emacs >/dev/null 2>&1)) |& sed 's/[^1-9]/+/g'`0&1] ``` [Answer] # Arduino Mega1280 edit: updated version that is robust against having anything plugged into the pins. The idea relies on the fact that the ATMega1280 uses a separate internal oscillator for the watchdog oscillator. I simply setup a watchdog interrupt which sets a flag, have a counter based on the system clock (on the Arduino this is a 16MHz external crystal), and allow clock jitter/variance do the work. ``` #include <avr/interrupt.h> int time; volatile bool wdt_ran; // watchdog interrupt handler ISR(WDT_vect, ISR_BLOCK) { wdt_ran = true; } void setup() { // setup watchdog interrupt cli(); MCUSR &= ~(1 << WDRF); WDTCSR |= (1<<WDCE) | (1<<WDE); WDTCSR = (1<<WDIE) | (1<<WDP2) | (1<<WDP1) | (1<<WDP0); sei(); // Open serial communications and wait for port to open: Serial.begin(57600); } void loop() { if(wdt_ran) { Serial.println(abs(time%2)); wdt_ran = false; } ++time; } ``` [Answer] # Javascript <http://jsfiddle.net/prankol57/9a6s0gmv/> Takes video input. You can see the screenshot that it used to calculate the random number. ``` var m = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); var constraints = { video: { mandatory: { maxWidth: 350, maxHeight: 350 } }, audio: false }; var video = document.querySelector("video"), canvas = document.createElement("canvas"); document.body.appendChild(canvas); canvas.width = 350; canvas.height = 350; function start() { m.call(navigator, constraints, function (stream) { video.src = window.URL.createObjectURL(stream); }, function() { alert("An error occured. Did you deny permission?"); }); } if (m) { start(); } else { alert('getUserMedia() is not supported in your browser'); } function getRandomData() { var ctx = canvas.getContext("2d"); ctx.drawImage(video, 0, 0); var data = ctx.getImageData(0, 0, 350, 350).data; var total = 0; for (var i = 0; i < data.length; ++i) { total += data[i]; total %= 2; } alert("The random number is " + total); } document.querySelector("button").onclick = getRandomData; ``` [Answer] # Shell on Linux Measure read speed of a hard drive + access time of a frequently updated directory on this disc which layout is unpredictable. ``` # Set this to the device node of whatever drive you want to measure DRIVE_DEVICE=sda # This must be a path that is # a) on device "/dev/$DRIVE_PATH" # b) frequently updated to add additional access time randomization due to # less-predictable disk layout due to less-predictable time, amount and # ordering uf updates, like logfile directories, maybe cache directories. FIND_PATH=/var/log # Better than using 'sync' - sync only the disk that we actually read from # also sync both internal drive and system buffers hdparm -f -F "/dev/$DRIVE_DEVICE" # Note: bash's built-in time command doesn't support formats :/ # Note: the result is only going to be as good as the system's time command, # which isn't necessarily equally good on other U*ICes t=$(command time -f '%e' -- find "$FIND_PATH" -printf '' 2>&1) echo $((${t#*.}&1)) ``` requires: ``` 1) read and execute access to every directory under "$FIND_PATH" 2) sending (flush) control commands to a hard drive via a device node. Requires root access per default, but can be delegated to a less privileged user either by using sudo on this script or by applying chgrp 'some_system_group' "$DRIVE_DEVICE" && chmod g+rx "$DRIVE_DEVICE" if this is acceptable on your system. ``` This approach has the advantage of not modifying any data on the system and not requiring perl over primo's one. [Answer] # Shell Tested on Linux, but maybe your U\*IX does have /proc/stat as well? This starts only a single additional process, reads only a single additional file (not even on disc) and is 37 characters short. It's also pretty fast. ``` t=1`sum /proc/stat`;echo $[${t% *}&1] ``` One may think that this is determined by all kernel and userland process states, but that is not the case, since /proc/stat also includes IO-wait time, time to sevice hardware interrupts, time spent in idle task and some other which all depend on external hardware input. [Answer] # Matlab The microphone solution: ``` recObj=audiorecorder;recordblocking(recObj,10);rem(sum(getaudiodata(recObj)<0),2) ``` Records 10 seconds of sound, finds the number of negative samples in the recording and outputs 0 if this number is even and 1 if it's odd. Thus 0 with 50% probability. The approach means that even small amounts of noice, unavoidable in a silent recording, will be enough to generate a random output. The following slightly longer code speeds up the number generator by using a shorter recording, compensated with a higher bitrate, which gives more noise. ``` recObj=audiorecorder(8000,16,1);recordblocking(recObj,0.1);rem(sum(getaudiodata(recObj)<0),2) ``` In a test under quiet conditions, I find that in 100 runs of the latter code, the code outputs zero 51 times. 100 runs under noisy conditions produced zero 40 times. Edit: Thanks to Emil for pointing out a flaw in the original code :-) [Answer] ## Bash (Thanks, Dennis.) ``` echo $[`w|sed 's/[^1-9]/+/g'`0&1] ``` [Answer] Takes the least significant bit of the computer's accelerometer (needs the `hdaps` Linux module): ``` #!/usr/bin/env python import re m = re.search('([-\d]+),([-\d]+)', open('/sys/devices/platform/hdaps/position', 'r').read()) print((int(m.group(1)) ^ int(m.group(2))) & 1) ``` This basically measures the noise of the sensor. [Answer] # SmileBASIC ``` XON MOTION 'enable motion sensor ACCEL OUT ,,Z 'get Z acceleration (up/down) PRINT Z<-1 'if Z is less than -1, output 1, otherwise 0. ``` Uses the 3DS's motion sensor. The Z axis of the accelerometer is usually around -1 (because of gravity), and due to random noise, it can sometimes be above or below that. Here's one that uses the microphone: ``` XON MIC 'enable microphone DIM REC%[0] 'make array MICSTART 0,3,1 'start recording. 0=8180Hz, 3=8 bit unsigned, 1=1 second WAIT 1 'delay (1 frame is enough since we only check the first sample) MICSAVE MIC 'save recording PRINT MIC[0]>0 'if the first sample isn't negative, output 1 ``` [Answer] # Bash I took Soham’s own suggestion (using `top`): ``` echo $[`top -bn1|sed 's/[^1-9]/+/g'`0&1] ``` Edit: It works the same way Soham's does. It turns all non numeric characters in the output of top into '+' and then evaulates the parity of the resulting string. the 'b' flag to top runs it in batch mode so that it reports all processes, not just the first screenful and 'n1' says to just run 1 iteration of top. ]
[Question] [ Given a non-negative number `n`, output the number of ways to express `n` as the sum of two squares of integers `n == a^2 + b^2` ([OEIS A004018](https://oeis.org/A004018)). Note that `a` and `b` can be positive, negative, or zero, and their order matters. Fewest bytes wins. For example, `n=25` gives `12` because `25` can be expressed as ``` (5)^2 + (0)^2 (4)^2 + (3)^2 (3)^2 + (4)^2 (0)^2 + (5)^2 (-3)^2 + (4)^2 (-4)^2 + (3)^2 (-5)^2 + (0)^2 (-4)^2 + (-3)^2 (-3)^2 + (-4)^2 (0)^2 + (-5)^2 (3)^2 + (-4)^2 (4)^2 + (-3)^2 ``` Here are the values up to `n=25`. Be careful that your code works for `n=0`. ``` 0 1 1 4 2 4 3 0 4 4 5 8 6 0 7 0 8 4 9 4 10 8 11 0 12 0 13 8 14 0 15 0 16 4 17 8 18 4 19 0 20 8 21 0 22 0 23 0 24 0 25 12 ``` Here are the values up to `n=100` as a list. ``` [1, 4, 4, 0, 4, 8, 0, 0, 4, 4, 8, 0, 0, 8, 0, 0, 4, 8, 4, 0, 8, 0, 0, 0, 0, 12, 8, 0, 0, 8, 0, 0, 4, 0, 8, 0, 4, 8, 0, 0, 8, 8, 0, 0, 0, 8, 0, 0, 0, 4, 12, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 8, 0, 0, 4, 16, 0, 0, 8, 0, 0, 0, 4, 8, 8, 0, 0, 0, 0, 0, 8, 4, 8, 0, 0, 16, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 8, 4, 0, 12] ``` Fun facts: The sequence contains terms that are arbitrarily high, and the limit of its running average is π. **Leaderboard:** ``` var QUESTION_ID=64812,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/64812/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i; ``` ``` body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px} ``` ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> ``` [Answer] ## Python (59 57 56 bytes) ``` lambda n:0**n+sum((-(n%(x-~x)<1))**x*4for x in range(n)) ``` [Online demo](http://ideone.com/nwd5fE) As with my CJam answer, this uses Möbius inversion and runs in pseudoquasilinear time. Thanks to [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000) for 2 bytes' savings, and [feersum](https://codegolf.stackexchange.com/users/30688/feersum) for 1. [Answer] # Python 2, 44 bytes ``` f=lambda n,x=1:+(x>n)or(n%x<1)-f(n,x+2)/4<<2 ``` This is almost the same as xsot's [solution](https://codegolf.stackexchange.com/a/65077/2537) (which is based on Peter Taylor's [solution](https://codegolf.stackexchange.com/a/65326/2537)), but saves 8 bytes by simplifying the way signs are handled. Note that for a full program, we can save 2 bytes in the function without incurring a cost outside the function: ``` f=lambda n,x=1:x>n or(n%x<1)-f(n,x+2)/4<<2 print+f(input()) ``` Two additional bytes for a full program this way: ``` n=input() f=lambda x:x>n or(n%x<1)-f(x+2)/4<<2 print+f(1) ``` For `n > 0` there is a very legible 40-byte solution: ``` f=lambda n,x=1:n/x and(n%x<1)*4-f(n,x+2) ``` [Answer] # Mathematica, 13 bytes If built-ins are allowed, this is how to do it in Mathematica. ``` 2~SquaresR~#& ``` --- For 0 < = n <= 100 ``` 2~SquaresR~# & /@ Range[0, 100] ``` > > {1, 4, 4, 0, 4, 8, 0, 0, 4, 4, 8, 0, 0, 8, 0, 0, 4, 8, 4, 0, 8, 0, 0, > 0, 0, 12, 8, 0, 0, 8, 0, 0, 4, 0, 8, 0, 4, 8, 0, 0, 8, 8, 0, 0, 0, 8, > 0, 0, 0, 4, 12, 0, 8, 8, 0, 0, 0, 0, 8, 0, 0, 8, 0, 0, 4, 16, 0, 0, > 8, 0, 0, 0, 4, 8, 8, 0, 0, 0, 0, 0, 8, 4, 8, 0, 0, 16, 0, 0, 0, 8, 8, > 0, 0, 0, 0, 0, 0, 8, 4, 0, 12} > > > [Answer] # Pyth, 13 bytes ``` /sM^^R2}_QQ2Q ``` [Test suite](https://pyth.herokuapp.com/?code=%2FsM%5E%5ER2%7D_QQ2Q&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10&debug=0) ``` /sM^^R2}_QQ2Q Q = eval(input()) }_QQ Inclusive range from -Q to Q (all possible a and b) ^R2 Map to their squares ^ 2 Form all pairs sM Sum pairs / Q Count occurances of Q ``` [Answer] ## J, 16 bytes ``` +/@,@:=+&*:/~@i: ``` This is a monadic verb (in other words, a unary function). [Try it online](https://tio.run/nexus/j#@5@mYGuloK3voONgZautpmWlX@eQafU/NTkjXyFNwcj0PwA "J – TIO Nexus") or [see it pass all test cases](https://tio.run/nexus/j#@5@mYGuloK3voONgZautpmWlX@eQafU/NTkjX0FDR08hTclAUyFTT8HI7D8A "J – TIO Nexus"). ## Explanation ``` +/@,@:=+&*:/~@i: Denote input by n i: The array of integers from -n to n /~@ Take outer product wrt the following function: + the sum of &*: squares of both inputs This results in a 2D array of a^2+b^2 for all a, b between -n and n = Replace by 1 those entries that are equal to n, and others by 0 ,@: Flatten the binary matrix +/@ Take its sum ``` [Answer] # Python 2, ~~69~~ ~~55~~ ~~53~~ 52 bytes ``` f=lambda n,x=1:+(x>n)or(2-x%4)*(n%x<1)+f(n,x+2)/4<<2 ``` This is a recursive function based off [Peter Taylor's excellent solution](https://codegolf.stackexchange.com/a/65326/45268). [Answer] # Julia, 40 bytes ``` n->n>0?4sum(i->(n-i^2)^.5%1==0,1:n^.5):1 ``` Ungolfed: ``` function f(n) if n==0 return 1 # Handle special case of n=0 else m=0 # Start the counter at zero for i=1:sqrt(n) # Loop over the values (i) whose squares are # less than n (except zero) k=sqrt(n-i^2) # Find k such that n=k^2+i^2 if k==floor(k) # if k is an integer, we've found a pair m+=4 # Add one for each of k^2+i^2, (-k)^2+(-i)^2, and the other two end end return m # Return the resulting count end end ``` Note that the loop doesn't include `i==0`, because when `n` is a square, it's already included by `i=sqrt(n)`, and there are only four, not eight, for that form (`0^2+k^2, 0^2+(-k)^2, k^2+0^2, (-k)^2+0^2`). [Answer] # CJam, ~~25~~ 23 bytes ``` Zri:R#Ym*{Rf-Yf#:+R=},, ``` This is a theoretical solution that requires **O(9n)** time and memory for input **n**. At the cost of one extra byte – for a total of **24 bytes** – we can reduce the complexity to **O(n2)**: ``` ri:R)Y*Ym*{Rf-Yf#:+R=},, ``` [Try it online!](http://cjam.tryitonline.net/#code=cmk6UikyKlltKntSZi1ZZiM6K1I9fSws&input=MjU) ### How it works Either ``` Z Push 3. ri:R Read an integer from STDIN and save it in R. # Compute 3**R. ``` or ``` ri:R Read an integer from STDIN and save it in R. )Y* Add 1 and multiply by 2. ``` Then ``` Ym* Take the second Cartesian power, i.e., compute all pairs. { }, Filter the pairs: Rf- Subtract R from each. Yf# Square the differences. :+ Add the squares. R= Compare with R. If = pushed 1, keep the pair. , Count the kept pairs. ``` [Answer] ## CJam (25 24 22 21 bytes) ``` {:X!X{X\2*)%!4*\-}/z} ``` [Online demo](http://cjam.aditsu.net/#code=17%2C%0A%0A%7B%3AX!X%7BX%5C2*)%25!4*%5C-%7D%2Fz%7D%0A%0A%25%60) This runs in pseudoquasilinear time\* and uses the statement from the OEIS that > > Moebius transform is period 4 sequence [ 4, 0, -4, 0, ...]. - Michael Somos, Sep 17 2007 > > > The input `0` is obviously a special case (Möbius tranforms and annihilators don't go well together), but ended up only costing one char. \* Pseudo- because it's quasilinear in the value of the input, not the size of the input; quasi because it does `Theta(n)` operations on integers of size on the order of `n`; a `b`-bit mod operation should take `b lg b` time, so overall this takes `Theta(n lg n lg lg n)` time. [Answer] ## Haskell, 42 bytes ``` f n|q<-[-n..n]=sum[1|a<-q,b<-q,a*a+b*b==n] ``` Usage exapmle: ``` *Main> map f [0..25] [1,4,4,0,4,8,0,0,4,4,8,0,0,8,0,0,4,8,4,0,8,0,0,0,0,12] *Main> ``` [Answer] # [Japt](https://github.com/ETHproductions/Japt), ~~42~~ ~~37~~ 33 bytes **Japt** is a shortened version of **Ja**vaScri**pt**. [Interpreter](https://codegolf.stackexchange.com/a/62685/42545) ``` V=Un oU+1;Vr@X+(Vf_p2 +Y*Y¥U)l ,0 ``` ### How it works ``` // Implicit: U = input number V=Un oU+1 // Set variable V to range(-U, U+1). Ends up like [-U,-U+1,...,U-1,U] Vr@ ,0 // Reduce each item Y in V with this function, starting at 0: X+( l // Return the previous value X + the length of: Vf_p2 // V filtered by items Z where Z*Z +Y*Y==U) // + Y*Y equals U. // This ends up as the combined length of all fitting pairs of squares. // Implicit: return last expression ``` Perhaps there's a better technique; suggestions are welcome. [Answer] ## Python 3, ~~68~~ ~~61~~ 60 bytes ``` lambda n:0**n+4*sum(i**.5%1+(n-i)**.5%1==0for i in range(n)) ``` Using two nested list comprehensions is too expensive. Instead, this checks if both coordinates on the circle of radius sqrt(n) are integers. *Peter Taylor has beaten this with a [Moebius-inversion based approach](https://codegolf.stackexchange.com/a/65326/39328).* [Answer] # Octave, 28 bytes ``` @(n)nnz((a=(-n:n).^2)'+a==n) ``` [Answer] # Julia, ~~89~~ ~~79~~ 63 bytes ``` g(x)=cos(π*x^.5)^2÷1 a(n)=(n==0)+4sum([g(i)g(n-i)for i=1:n]) ``` This is a named function `a` which accepts an integer and returns a float. It calls a helper function `g`. Ungolfed: ``` function g(x::Integer) floor(cos(π*sqrt(x))^2) end function a(n::Integer) (n == 0) + 4*sum([g(i)*g(n-i) for i=1:n]) end ``` The approach here uses a simplification of Wesley Ivan Hurt's formula listed on OEIS. The simplification was found by Glen O, the very same person who shaved 26 bytes off of this answer! [Answer] # Pyth, ~~16~~ 15 bytes ``` lfqQs^R2T^}_QQ2 ``` Try it online in the [Pyth Compiler](https://pyth.herokuapp.com/?code=lfqQs%5ER2T%5E%7D_QQ2&input=25&debug=0). ### How it works ``` lfqQs^R2T^}_QQ2 }_QQ Compute the inclusive range from -Q to Q (input). ^ 2 Take the second Cartesian power, i.e., compute all pairs. f Filter; for each T in the list of pairs: ^R2T Compute the squares of T's elements. s Add the squares. qQ Compare the sum with Q. If q returned True, keep T. l Count the kept pairs. ``` [Answer] ## TI-BASIC, 23 bytes ``` sum(seq(Σ(X²+Y²=Ans,X,-Ans,Ans),Y,-Ans,Ans ``` Pretty straightforward. `Σ(` is summation. Strangely, `sum(seq(sum(seq(` throws an `ERR:ILLEGAL NEST`, and so does `Σ(Σ(`, but `sum(seq(Σ(` is fine. I chose to put the `Σ(` on the inside to save a close-paren. [Answer] # JavaScript (ES6), ~~66~~ 60 bytes ``` n=>eval("for(r=0,a=~n;a++<n;)for(b=~n;b++<n;)r+=a*a+b*b==n") ``` 6 bytes saved thanks to [@edc65](https://codegolf.stackexchange.com/users/21348/edc65)! ## Explanation ``` n=>eval(` // use eval to allow for loops in an unparenthesised arrow function for(r=0, // r = number of pairs a=~n;a++<n; // a = first number to square ) for(b=~n;b++<n;) // b = second number to square r+=a*a+b*b==n // add one to the result if a^2 + b^2 == n // implicit: return r `) ``` ## Test ``` n = <input type="number" oninput='result.innerHTML=( n=>eval("for(r=0,a=~n;a++<n;)for(b=~n;b++<n;)r+=a*a+b*b==n") )(+this.value)' /><pre id="result"></pre> ``` [Answer] # Python 3, ~~93~~ ~~62~~ 69 bytes Itertools wasn't working so I used two ranges again, but moved the range out to save bytes. **Edit:** Previous code didn't actually work, since I defined range over n before I defined n. ``` lambda n:sum(i*i+j*j==n for i in range(-n,n+1)for j in range(-n,n+1)) ``` [Answer] ## APL, ~~23~~ ~~20~~ 19 bytes ``` {+/⍵=∊∘.+⍨×⍨0,,⍨⍳⍵} ``` Explanation: ``` {+/⍵=∊∘.+⍨×⍨0,,⍨⍳⍵} Monadic function: ⍳⍵ 1 2 3 ... ⍵ ,⍨ Duplicate 0, Concatenate to 0 ×⍨ Square everything ∘.+⍨ Make an addition table ∊ Flatten ⍵= 1s where equal to the input +/ Sum up the 1s ``` Other than the fact that APL doesn't have J's `i:` (numbers from -n to n) function, this works pretty much like the J answer. We can't use a train because getting the `-\⍳2×⍵` to not parse as `(-\) ⍳ (2×⍵)` would cost three bytes; similarly with other pair of atops. All those parentheses make the regular function shorter. Try it [here](http://tryapl.org/?a=%28%7B+/%u2375%3D%u220A%u2218.+%u2368%D7%u23680%2C%2C%u2368%u2373%u2375%7D%A80%2C%u2373100%29%u22611%204%204%200%204%208%200%200%204%204%208%200%200%208%200%200%204%208%204%200%208%200%200%200%200%2012%208%200%200%208%200%200%204%200%208%200%204%208%200%200%208%208%200%200%200%208%200%200%200%204%2012%200%208%208%200%200%200%200%208%200%200%208%200%200%204%2016%200%200%208%200%200%200%204%208%208%200%200%200%200%200%208%204%208%200%200%2016%200%200%200%208%208%200%200%200%200%200%200%208%204%200%2012&run). The output of `1` means all values match. [Answer] # Matlab 41 bytes Even smaller as the previous answers ``` @(n)nnz(~mod(sqrt(n-(1:n^.5).^2),1))*4+~n ``` Essentially Agawa001's answer with power and sqrt replaced [Answer] # [Candy](https://github.com/dale6john/candy), ~~17~~ 14 bytes Input pushed onto stack initially ~~`~TbAT1C(sWs+Aeh)Z`~~ `~T0C(sWs+Aeh)Z` ``` peekA # copy arg from stack to register A range2 # create double sided range on stack, -A, 1-A, ... A-1, A digit0 # prefix argument to 'cart', cart # cartesian product of current stack(0), and other stack(0) while # while stack not empty sqr # pop and square and push swap # swap two stack elements sqr # pop and square and push add # pop and pop and add and push pushA # push original argument equal # equality test 0/1 popAddZ # Z := Z + pop endwhile pushZ # push Z onto stack, will be output to stdout on termination ``` [Answer] # CJam, 28 ``` qi_mF{3a>},{~)\4%2-&}%4+:*1? ``` Not really short, but efficient. E.g. the result for 15625 is instantly 28. Uses the factorization-based formula from OEIS. [Try it online](http://cjam.aditsu.net/#code=qi_mF%7B3a%3E%7D%2C%7B~)%5C4%252-%26%7D%254%2B%3A*1%3F&input=15625) **Explanation:** ``` qi read input and convert to integer _ make a copy (will be used to handle the 0 case at the end) mF factorize into [prime exponent] pairs {…}, filter the array of pairs 3a> with the condition that the pair is greater than [3] which means the prime factor must be ⩾3 {…}% transform each pair as follows: ~ dump the prime factor and exponent onto the stack ) increment the exponent \ swap with the prime 4% get the remainder mod 4 (it will be 1 or 3) 2- subtract 2 (resulting in -1 or 1) & bitwise AND with the incremented exponent (see below) 4+ append a 4 to the array :* multiply all 1? if the input was 0, use 1, else use the above result ``` Some details about the calculation: * if the prime is 1 mod 4, the code calculates `(exponent + 1) & -1`, which is `exponent + 1` * if the prime is 3 mod 4, the code calculates `(exponent + 1) & 1`, which is 0 if the exponent is odd, and 1 if even All these values multiplied together and multiplied by 4 are exactly the OEIS formula. [Answer] # Python 2, 68 bytes ``` def x(n):r=range(-n,n+1);print sum(a*a+b*b==n for a in r for b in r) ``` Defines a function called `x()` that takes a number n. Try it online. <http://ideone.com/aRoxGF> [Answer] # Pyth, ~~41~~ ~~35~~ ~~33~~ ~~30~~ 27 bytes [Try it online.](https://pyth.herokuapp.com/?code=%3FQ*F%2B4m.%26tt%25ed4hhdr-PQ2%208%201&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A21%0A65%0A362880&debug=1) **Edit:** Thanks to [isaacg](http://chat.stackexchange.com/users/115644/isaacg), I got `m` and `*F` to work! YES! ``` ?Q*F+4m.&tt%ed4hhdr-PQ2 8 1 (implicit) Q = input() ?Q If Q != 0 m Map to d (exponent, prime) from ... r-PQ2 8 run-length-encoded(PQ with 2's removed) .& Bitwise and %ed4 d[-1] % 4 tt -2 hd with d[0] h +1 +4 Append 4 to the resulting array *F Then multiply it all together 1 Else 1 ``` **Edit:** Put the bitwise and back in for more byte savings! Also I removed all the "Formerly" stuff. It was starting to get cluttered. Thanks to [aditsu](https://codegolf.stackexchange.com/users/7416/aditsu) and his CJam solution, and to [maltysen](http://chat.stackexchange.com/users/138131/maltysen) and his tips (One day I will get `m*Fd` to work. One day...) ``` J4Vr-PQ2 8=J*J.&tt%eN4hhN;?QJ1 (implicit) Q=input() J4 J=4 -PQ2 Remove all 2's from the prime factorization of Q r 8 run-length encode (exponent, prime factor) V ; For N in range( the above ): =J*J J = J * ... tt%eN4 N[-1] mod 4 -2 hhN (exponent + 1) .& bitwise and ?QJ1 if Q != 0 print(J) else print(1) ``` Note that, * if the prime is 1 mod 4, we get `-1 & (exponent + 1)`, which is `exponent + 1` * but if the prime is 3 mod 4, we get `1 & (exponent + 1)`, which is `0` if the exponent is odd, and `1` if even Multiply it all together (times 4 at the beginning) and we get the number of sums of two squares that add up to our input. [Answer] # Python, 57 bytes Nice challenge. Unfortunately I'm not getting it shorter than this at the moment. ``` lambda n:0**n+sum(2-d%4for d in range(1,n+1)if d%2>n%d)*4 ``` [Answer] # PARI/GP, ~~34~~ 28 bytes Using generating functions: Saved 6 bytes thanks to [Mitch Schwartz](https://codegolf.stackexchange.com/users/2537/mitch-schwartz). ``` n->sum(i=-n,n,x^i^2)^2\x^n%x ``` --- Using built-ins, 33 bytes (saved 1 byte thanks to [Mitch Schwartz](https://codegolf.stackexchange.com/users/2537/mitch-schwartz).): ``` n->if(n,2*qfrep(matid(2),n)[n],1) ``` > > qfrep(q,B,{flag=0}): vector of (half) the number of vectors of norms from 1 to B for the integral and definite quadratic form q. If flag is 1, count vectors of even norm from 1 to 2B. > > > --- [Answer] ## Matlab, 72 bytes ``` n=input('');m=fix(sqrt(n));m=(-m:m).^2;disp(nnz(bsxfun(@plus,m,m')==n)) ``` [Answer] # Matlab, ~~63~~ 50 bytes ``` @(y)nnz(~mod(sqrt(y-power((1:sqrt(y)),2)),1))*4+~y ``` --- * This does beat the other same-entitled code, thus I put it :D. * The program finds the positive integer solutions then multiply by 4 to encompass negative ones. * It can perform all 25 first test cases ``` for i=1:25 ans(i) end 1 4 4 0 4 8 0 0 4 4 8 0 0 8 0 0 4 8 4 0 8 0 0 0 0 12 ``` [Answer] ## Python, ~~133~~ 129 bytes ``` from itertools import* n=input() l=[];s=0 for i in range(-n,n+1):l.append(i**2) for j in product(l,l): if sum(j)==n:s+=1 print s ``` This demonstrates the use of itertools cartesian product. [Try it online](http://ideone.com/iq0N9h) [Answer] # JavaScript, 89 bytes ``` n=prompt() p=Math.pow for (x=c=(+n?0:1);x<=n;x++)if(x&&p(n-p(x,2),.5)%1===0)c+=4 alert(c) ``` I know this isn't the shortest JavaScript answer even if I were to remove the i/o lines, but I do think it is the best performing JS answer giving me the result for a million within a few seconds (ten million took about a minute). ]
[Question] [ > > The contest is now over. [Coward](https://codegolf.stackexchange.com/questions/34833/save-the-last-bullet-for-yourself#35021) is the winner. > You can watch the last match [here](http://s3.amazonaws.com/codegolf_zombies/0.html). > > > Suddenly zombies appear! OH NOES! In this king-of-the-hill challenge, you must create a bot to survive the zombie apocalypse. Or at least, hold out for as long as possible. At the start of the game, 50 instances of each entry will be placed randomly in a large [toroidal](http://en.wikipedia.org/wiki/Torus#Topology) play area - that is, it appears to be square, but wraps around. The size of the play area will vary depending on the number of entries, but initially 6% of squares will be occupied. Each competitor starts with 3 bullets. At the beginning of each turn, a zombie will rise from the ground at a random location, destroying whatever was above it. Any player who is next to a zombie at the start of their turn will become a zombie. For each living player, their code will then be called. It will receive a [PlayerContext](https://github.com/jamespic/zombies/blob/master/src/main/java/zombie/PlayerContext.java) object, containing information on their current status, and their surroundings. Each player can see for 8 squares in any direction. The player must choose to either move (staying still is a valid movement), by returning a `Move`, or shoot a nearby person or zombie, by returning a `Shoot`. Your gun has a maximum range of 5 squares. Since you are within your gun's range you *can* shoot yourself, provided you have bullets left. If two players shoot each other, they both die. If two players attempt to move onto the same square, they will fail, and will both return to the square they started from. If there are still conflicts, this will be repeated until there are no conflicts, which may mean everyone is back where they started. If a player dies from a gunshot, their dead body will remain, and forms a permanent barrier. Any bullets they were carrying remain on their person, and can be scavenged by players in adjacent squares. If there are multiple players occupying the squares adjacent to a dead body, then the bullets will be shared between them, but any remainder will be lost. If a player becomes a zombie, then their bullets are lost. Zombies will mindlessly walk towards the nearest living player. Entries are scored on how long their longest-surviving player survives. ## Entries A control program is available at <https://github.com/jamespic/zombies>. Simply clone it, and run `mvn compile exec:java`. To be eligible, entries must be written in a JVM language, must be portable, and must be possible to build from Maven with no special set-up. This is to ensure that competitors do not need to install multiple run-time environments to test their bots against competitors. Sample entries are currently available in the following languages: * [Java 7](https://github.com/jamespic/zombies/blob/master/src/main/java/player/StandStill.java) - see also [a more complex example](https://github.com/jamespic/zombies/blob/master/src/main/java/player/Gunner.java), and [the code for zombies](https://github.com/jamespic/zombies/blob/master/src/main/java/zombie/Dead.java#L14) * [Scala 2.11.1](https://github.com/jamespic/zombies/blob/master/src/main/scala/example/ScalaExample.scala) * [Javascript (via Rhino)](https://github.com/jamespic/zombies/blob/master/src/main/resources/js-example.js) * [Python (via Jython 2.7 beta 2)](https://github.com/jamespic/zombies/blob/master/src/main/resources/py-example.py) * [Ruby (via JRuby 1.7.13)](https://github.com/jamespic/zombies/blob/master/src/main/resources/rb-example.rb) * [Clojure 1.5.1](https://github.com/jamespic/zombies/blob/master/src/main/resources/clj-example.clj) * [Frege](https://github.com/jamespic/zombies/blob/master/src/main/frege/PureFregeExample.fr) (a bit like Haskell - [here's another example](https://github.com/jamespic/zombies/blob/master/src/main/frege/IOFregeExample.fr)) If you would like to compete in a language that is not listed, you can post a comment requesting it, and I will investigate the possibility of integrating your chosen language into the control program. Or, if you are impatient, you can submit a pull request to the control program. Only one instance (in the Java sense of the word) will be created for each entry. This Java instance will be called multiple times per turn - once for each surviving player. ## API ``` package zombie // You implement this. Your entry should be in package `player` interface Player { Action doTurn(PlayerContext context) } // These already exist class PlayerContext { // A square array, showing the area around you, with you at the centre // playFields is indexed by x from West to East, then y from North to South PlayerId[][] getPlayField() int getBullets() // Current bullets available int getGameClock() // Current turn number PlayerId getId() // Id of the current player instance int getX() // Your current x co-ordinate int getY() // Your current y co-ordinate int getBoardSize() // The size of the current playing field Set<PlayerId> shootablePlayers() // A helper function that identifies players in range. } class PlayerId { String getName() // The name of the entrant that owns this player int getNumber() // A unique number, assigned to this player } // Don't implement this. Use either `Move` or `Shoot` interface Action {} enum Move implements Action { NORTHWEST, NORTH, NORTHEAST, EAST, STAY, WEST, SOUTHEAST, SOUTH, SOUTHWEST; static move randomMove(); } class Shoot implements Action { Shoot(PlayerId target); } ``` ## Additional Rules Each entry must have a unique name, in order to work correctly with the control program. Entries should not attempt to tamper with other entrants, or with the control program, or otherwise take advantage of the run-time environment to "break the fourth wall", and gain an advantage that would not be available in a "real" zombie apocalypse. Communication between players is allowed. The winner is the entrant whose bot has the highest score in a test I will run on the 3rd of August 2014. ## Final Results The final results are in! Coward is the winner! On 2nd August, I ran 19 rounds of the control program, and ranked each player according to their median score. The results were as follows: ``` Coward: 4298 Fox: 3214 Shotguneer: 2471 Cocoon: 1834 JohnNash: 1240 HuddleWolf: 1112 Sokie: 1090 SOS: 859 GordonFreeman: 657 Jack: 657 Waller: 366 SuperCoward: 269 MoveRandomly: 259 StandStill: 230 Vortigaunt: 226 ThePriest: 223 Bee: 61 HideyTwitchy: 52 ZombieHater: 31 Gunner: 20 ZombieRightsActivist: 16 SunTzu: 11 EmoWolfWithAGun: 0 ``` The last round is available to watch [here](http://s3.amazonaws.com/codegolf_zombies/0.html). ## Run-by-run results The individual results of each of the 19 runs were: ``` #Run at 03-Aug-2014 14:45:35# Bee: 21 Cocoon: 899 Coward: 4608 EmoWolfWithAGun: 0 Fox: 3993 GordonFreeman: 582 Gunner: 18 HideyTwitchy: 37 HuddleWolf: 2836 Jack: 839 JohnNash: 956 MoveRandomly: 310 SOS: 842 Shotguneer: 2943 Sokie: 937 StandStill: 250 SunTzu: 3 SuperCoward: 318 ThePriest: 224 Vortigaunt: 226 Waller: 258 ZombieHater: 41 ZombieRightsActivist: 10 #Run at 03-Aug-2014 14:56:48# Bee: 97 Cocoon: 3073 Coward: 5699 EmoWolfWithAGun: 0 Fox: 4305 GordonFreeman: 1252 Gunner: 24 HideyTwitchy: 25 HuddleWolf: 3192 Jack: 83 JohnNash: 1195 MoveRandomly: 219 SOS: 884 Shotguneer: 3751 Sokie: 1234 StandStill: 194 SunTzu: 69 SuperCoward: 277 ThePriest: 884 Vortigaunt: 564 Waller: 1281 ZombieHater: 10 ZombieRightsActivist: 2 #Run at 03-Aug-2014 15:01:37# Bee: 39 Cocoon: 2512 Coward: 2526 EmoWolfWithAGun: 0 Fox: 2687 GordonFreeman: 852 Gunner: 21 HideyTwitchy: 91 HuddleWolf: 1112 Jack: 1657 JohnNash: 944 MoveRandomly: 312 SOS: 660 Shotguneer: 1067 Sokie: 1356 StandStill: 169 SunTzu: 8 SuperCoward: 351 ThePriest: 223 Vortigaunt: 341 Waller: 166 ZombieHater: 25 ZombieRightsActivist: 47 #Run at 03-Aug-2014 15:08:27# Bee: 27 Cocoon: 2026 Coward: 3278 EmoWolfWithAGun: 0 Fox: 2677 GordonFreeman: 611 Gunner: 16 HideyTwitchy: 11 HuddleWolf: 1694 Jack: 600 JohnNash: 1194 MoveRandomly: 48 SOS: 751 Shotguneer: 5907 Sokie: 1233 StandStill: 62 SunTzu: 9 SuperCoward: 252 ThePriest: 173 Vortigaunt: 107 Waller: 276 ZombieHater: 53 ZombieRightsActivist: 38 #Run at 03-Aug-2014 15:14:01# Bee: 26 Cocoon: 1371 Coward: 5121 EmoWolfWithAGun: 0 Fox: 3878 GordonFreeman: 464 Gunner: 29 HideyTwitchy: 130 HuddleWolf: 955 Jack: 101 JohnNash: 698 MoveRandomly: 269 SOS: 1314 Shotguneer: 2444 Sokie: 3217 StandStill: 233 SunTzu: 10 SuperCoward: 269 ThePriest: 318 Vortigaunt: 266 Waller: 494 ZombieHater: 49 ZombieRightsActivist: 9 #Run at 03-Aug-2014 15:19:43# Bee: 25 Cocoon: 2098 Coward: 4855 EmoWolfWithAGun: 0 Fox: 4081 GordonFreeman: 227 Gunner: 43 HideyTwitchy: 28 HuddleWolf: 2149 Jack: 1887 JohnNash: 1457 MoveRandomly: 117 SOS: 1068 Shotguneer: 4272 Sokie: 636 StandStill: 53 SunTzu: 9 SuperCoward: 209 ThePriest: 220 Vortigaunt: 227 Waller: 366 ZombieHater: 19 ZombieRightsActivist: 49 #Run at 03-Aug-2014 15:24:03# Bee: 46 Cocoon: 682 Coward: 3588 EmoWolfWithAGun: 0 Fox: 4169 GordonFreeman: 764 Gunner: 13 HideyTwitchy: 21 HuddleWolf: 842 Jack: 1720 JohnNash: 1260 MoveRandomly: 259 SOS: 636 Shotguneer: 777 Sokie: 586 StandStill: 75 SunTzu: 6 SuperCoward: 390 ThePriest: 189 Vortigaunt: 208 Waller: 334 ZombieHater: 61 ZombieRightsActivist: 20 #Run at 03-Aug-2014 15:29:49# Bee: 90 Cocoon: 516 Coward: 4298 EmoWolfWithAGun: 0 Fox: 1076 GordonFreeman: 581 Gunner: 8 HideyTwitchy: 87 HuddleWolf: 4298 Jack: 4715 JohnNash: 727 MoveRandomly: 102 SOS: 859 Shotguneer: 2471 Sokie: 2471 StandStill: 427 SunTzu: 24 SuperCoward: 159 ThePriest: 359 Vortigaunt: 94 Waller: 398 ZombieHater: 54 ZombieRightsActivist: 21 #Run at 03-Aug-2014 15:36:50# Bee: 18 Cocoon: 3127 Coward: 3124 EmoWolfWithAGun: 0 Fox: 5094 GordonFreeman: 255 Gunner: 43 HideyTwitchy: 17 HuddleWolf: 1078 Jack: 272 JohnNash: 1270 MoveRandomly: 55 SOS: 723 Shotguneer: 3126 Sokie: 1388 StandStill: 179 SunTzu: 7 SuperCoward: 45 ThePriest: 519 Vortigaunt: 172 Waller: 200 ZombieHater: 45 ZombieRightsActivist: 8 #Run at 03-Aug-2014 15:40:59# Bee: 78 Cocoon: 1834 Coward: 4521 EmoWolfWithAGun: 0 Fox: 1852 GordonFreeman: 657 Gunner: 7 HideyTwitchy: 2 HuddleWolf: 969 Jack: 895 JohnNash: 1596 MoveRandomly: 277 SOS: 694 Shotguneer: 1397 Sokie: 844 StandStill: 325 SunTzu: 7 SuperCoward: 192 ThePriest: 148 Vortigaunt: 369 Waller: 232 ZombieHater: 16 ZombieRightsActivist: 17 #Run at 03-Aug-2014 15:44:22# Bee: 23 Cocoon: 2638 Coward: 2269 EmoWolfWithAGun: 0 Fox: 2067 GordonFreeman: 730 Gunner: 21 HideyTwitchy: 60 HuddleWolf: 763 Jack: 1469 JohnNash: 1494 MoveRandomly: 273 SOS: 3181 Shotguneer: 3181 Sokie: 653 StandStill: 450 SunTzu: 19 SuperCoward: 272 ThePriest: 215 Vortigaunt: 299 Waller: 510 ZombieHater: 62 ZombieRightsActivist: 16 #Run at 03-Aug-2014 15:48:03# Bee: 97 Cocoon: 2009 Coward: 2798 EmoWolfWithAGun: 0 Fox: 1907 GordonFreeman: 958 Gunner: 22 HideyTwitchy: 93 HuddleWolf: 925 Jack: 288 JohnNash: 476 MoveRandomly: 422 SOS: 3723 Shotguneer: 2076 Sokie: 1090 StandStill: 134 SunTzu: 92 SuperCoward: 141 ThePriest: 470 Vortigaunt: 216 Waller: 340 ZombieHater: 32 ZombieRightsActivist: 20 #Run at 03-Aug-2014 16:03:38# Bee: 121 Cocoon: 501 Coward: 9704 EmoWolfWithAGun: 0 Fox: 3592 GordonFreeman: 588 Gunner: 20 HideyTwitchy: 54 HuddleWolf: 749 Jack: 1245 JohnNash: 1345 MoveRandomly: 451 SOS: 835 Shotguneer: 1548 Sokie: 589 StandStill: 166 SunTzu: 11 SuperCoward: 158 ThePriest: 93 Vortigaunt: 246 Waller: 1350 ZombieHater: 18 ZombieRightsActivist: 11 #Run at 03-Aug-2014 16:10:24# Bee: 66 Cocoon: 1809 Coward: 3295 EmoWolfWithAGun: 0 Fox: 3214 GordonFreeman: 1182 Gunner: 15 HideyTwitchy: 52 HuddleWolf: 1514 Jack: 101 JohnNash: 745 MoveRandomly: 211 SOS: 862 Shotguneer: 6335 Sokie: 1504 StandStill: 384 SunTzu: 14 SuperCoward: 259 ThePriest: 244 Vortigaunt: 262 Waller: 1356 ZombieHater: 24 ZombieRightsActivist: 20 #Run at 03-Aug-2014 16:28:05# Bee: 61 Cocoon: 692 Coward: 11141 EmoWolfWithAGun: 0 Fox: 1955 GordonFreeman: 1234 Gunner: 42 HideyTwitchy: 24 HuddleWolf: 1862 Jack: 609 JohnNash: 1579 MoveRandomly: 167 SOS: 958 Shotguneer: 11141 Sokie: 284 StandStill: 422 SunTzu: 66 SuperCoward: 121 ThePriest: 207 Vortigaunt: 128 Waller: 259 ZombieHater: 22 ZombieRightsActivist: 7 #Run at 03-Aug-2014 16:32:10# Bee: 207 Cocoon: 4414 Coward: 2670 EmoWolfWithAGun: 0 Fox: 978 GordonFreeman: 620 Gunner: 19 HideyTwitchy: 135 HuddleWolf: 962 Jack: 657 JohnNash: 1200 MoveRandomly: 147 SOS: 687 Shotguneer: 2258 Sokie: 2433 StandStill: 249 SunTzu: 49 SuperCoward: 1056 ThePriest: 602 Vortigaunt: 326 Waller: 593 ZombieHater: 31 ZombieRightsActivist: 10 #Run at 03-Aug-2014 16:38:56# Bee: 265 Cocoon: 2231 Coward: 4228 EmoWolfWithAGun: 0 Fox: 4737 GordonFreeman: 532 Gunner: 9 HideyTwitchy: 75 HuddleWolf: 2375 Jack: 1237 JohnNash: 1249 MoveRandomly: 109 SOS: 860 Shotguneer: 6470 Sokie: 1096 StandStill: 126 SunTzu: 15 SuperCoward: 393 ThePriest: 133 Vortigaunt: 184 Waller: 257 ZombieHater: 32 ZombieRightsActivist: 12 #Run at 03-Aug-2014 16:52:16# Bee: 67 Cocoon: 1534 Coward: 9324 EmoWolfWithAGun: 0 Fox: 2458 GordonFreeman: 1019 Gunner: 24 HideyTwitchy: 72 HuddleWolf: 601 Jack: 399 JohnNash: 1366 MoveRandomly: 275 SOS: 506 Shotguneer: 1007 Sokie: 475 StandStill: 230 SunTzu: 135 SuperCoward: 361 ThePriest: 61 Vortigaunt: 112 Waller: 4106 ZombieHater: 12 ZombieRightsActivist: 22 #Run at 03-Aug-2014 17:03:04# Bee: 26 Cocoon: 1159 Coward: 7796 EmoWolfWithAGun: 0 Fox: 3948 GordonFreeman: 878 Gunner: 3 HideyTwitchy: 17 HuddleWolf: 1490 Jack: 513 JohnNash: 1240 MoveRandomly: 487 SOS: 1460 Shotguneer: 1481 Sokie: 832 StandStill: 457 SunTzu: 8 SuperCoward: 480 ThePriest: 527 Vortigaunt: 171 Waller: 3729 ZombieHater: 30 ZombieRightsActivist: 10 ``` [Answer] ## Emo Wolf With A Gun [He's back](https://codegolf.stackexchange.com/a/25357/21700). He hates zombies. He still hates Java. No copyright infringement intended. ``` package player; import zombie.*; public class EmoWolfWithAGun implements Player { @Override public Action doTurn(PlayerContext context) { PlayerId myself = context.getId(); return new Shoot(myself); } } ``` [Answer] # Coward The rules of cowardice. 1. If you cant run away, panic and shoot everything you don't know. 2. Run!!! 3. When running, you might aswell pick up some bullets. Deep down you know you cant run forever. 4. When running, seek other cowards. Misery loves company. And they might eat the other guy first. ``` package player; import java.lang.Math.*; import java.util.Set; import java.util.HashSet; import zombie.*; import static zombie.Constants.*; public class Coward implements Player { private static final Set<PlayerId> killed = new HashSet<>(); private static final Set<PlayerId> looted = new HashSet<>(); @Override public Action doTurn(PlayerContext context) { PlayerId[][] field = context.getPlayField(); // Panic and shoot if (context.getBullets() > 0) { int distEnemy = VISION_WIDTH; int distZombie = VISION_WIDTH; PlayerId targetEnemy = null; PlayerId targetZombie = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { PlayerId player = field[x][y]; if (player != null && !killed.contains(player)) { int dist = getDistance(x, y); if (player.getName().equals("Zombie")) { if( dist < distZombie ) { distZombie = dist; targetZombie = player; } } else if (isEnemy(player.getName()) && dist <= distEnemy ) { distEnemy = dist; targetEnemy = field[x][y]; } } } } if (targetZombie != null && distZombie <= 3) { killed.add(targetZombie); return new Shoot( targetZombie ); } else if (targetEnemy != null && distEnemy <= 5 ) { killed.add(targetEnemy); return new Shoot( targetEnemy ); } } // Looted? for( int xx = CENTRE_OF_VISION-VISION_RANGE+1; xx <= CENTRE_OF_VISION+VISION_RANGE-1; xx++ ) { for( int yy = CENTRE_OF_VISION-VISION_RANGE+1; yy <= CENTRE_OF_VISION+VISION_RANGE-1; yy++ ) { PlayerId player = field[xx][yy]; if( player != null && !player.getName().equals("Zombie") && !player.getName().equals("DeadBody")) { for( int x = -1; x <= 1; x++ ) { for( int y = -1; y <= 1; y++ ) { PlayerId loot = field[xx+x][yy+y]; if( loot != null && !looted.contains(loot) && loot.getName().equals("DeadBody")) { looted.add(loot); } } } } } } // Run away int bestScore = -10000000; Move bestMove = Move.randomMove(); for( int x = -1; x <= 1; x++ ) { for( int y = -1; y <= 1; y++ ) { PlayerId center = field[CENTRE_OF_VISION+x][CENTRE_OF_VISION+y]; if( center == null ) { int thisScore = 0; for( int xx = CENTRE_OF_VISION+x-VISION_RANGE+1; xx < CENTRE_OF_VISION+x+VISION_RANGE; xx++ ) { for( int yy = CENTRE_OF_VISION+y-VISION_RANGE+1; yy < CENTRE_OF_VISION+y+VISION_RANGE; yy++ ) { PlayerId player = field[xx][yy]; if( player != null) { int dist = getDistance(xx-x,yy-y); if( player.getName().equals("Coward")) { // Prefer lose groups thisScore += (int)Math.pow( 2, ( 6 - Math.abs( dist - 5 ))); // if( dist >= 3 && dist <= 6 ) { // thisScore += 32; // } else if( dist > 3 ) { // thisScore += 16; // } } else if( player.getName().equals("DeadBody")) { // Visit dead bodies on the route if( !looted.contains(player)) { thisScore += (32+VISION_RANGE-dist)*(VISION_RANGE-dist); } } else if( player.getName().equals("Zombie")) { // Avoid zombies if( dist <= 5 ) { thisScore -= (int)Math.pow( 10, ( 6 - dist )); } // if( dist <= 2 ) { // thisScore -= 10000; // } else if( dist <= 3 ) { // thisScore -= 1000; // } else if( dist <= 4 ) { // thisScore -= 100; // } } else if( isEnemy(player.getName())) { // Avoid strangers thisScore -= (int)Math.pow( 10, ( 9 - dist )); // if( dist == 7 ) { // thisScore -= 100; // } else if( dist <= 6 ) { // thisScore -= 1000; // } } } } } if( thisScore > bestScore ) { bestScore = thisScore; bestMove = Move.inDirection( x, y ); } } } } return bestMove; } private boolean isEnemy(String name) { switch (name) { case "Coward": case "DeadBody": case "GordonFreeman": case "EmoWolfWithAGun": case "HuddleWolf": case "ThePriest": case "Shotguneer": case "Vortigaunt": case "Fox": case "Cocoon": case "SuperCoward": case "SOS": case "JohnNash": case "MoveRandomly": return false; default: return true; } } private int getDistance(int x, int y) { return Math.max(Math.abs(CENTRE_OF_VISION - x), Math.abs(CENTRE_OF_VISION - y)); } } ``` [Answer] # Zombie Rights Activist The Zombie Rights movement quickly became popular at the offset of the apocalypse. The idea of killing every zombie in sight without remorse is absolutely cruel to them, so they shoot at other players who don't believe in the cause. Understanding the struggle, they will hug zombies if there are no enemies in sight. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class ZombieRightsActivist implements Player { @Override public Action doTurn(PlayerContext context) { if (context.getBullets() > 0) { for (PlayerId player: context.shootablePlayers()) { switch(player.getName()) { case "ZombieRightsActivist": case "DeadBody": case "Zombie": break; default: return new Shoot(player);//Kill the non-believers } } } double farthest=0; Move move=Move.randomMove(); for (int x = 0; x < VISION_WIDTH; x++) {//Find a lonely zombie and give it a hug for (int y = 0; y < VISION_WIDTH; y++) { PlayerId friend = context.getPlayField()[x][y]; if (friend!= null && (friend.getName().equals("Zombie"))) { double distance=sqrt(pow(x-context.getX(),2)+pow(y-context.getY(),2)); if (distance>farthest){ farthest = distance; move = Move.inDirection(x - CENTRE_OF_VISION, y -CENTRE_OF_VISION); } } } } return move; } } ``` [Answer] ## HuddleWolf - Java **[Rule 8](http://www.zombielandrules.com/): Travel in Groups** HuddleWolf takes the sixth rule of Zombieland to heart. It will chase down and huddle with any non-hostile object it sees. If HuddleWolf sees nobody to huddle with, he will venture northeastward in search of more populated areas. HuddleWolf also hates Zombies and will shoot on sight. HuddleWolf has realized Coward is a much better implementation of his original idea. He bows to Coward's supremacy and now actively prefers the company of Cowards to other nonhostiles. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class HuddleWolf implements Player { @Override public Action doTurn(PlayerContext context) { if (context.getBullets() > 0) { for (PlayerId player: context.shootablePlayers()) { if (isEnemy(player.getName())) { return new Shoot(player); } } } Move bestDirection = Move.NORTHEAST; int bestDistance = Integer.MAX_VALUE; bool foundACoward = false; for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { int distance = max(abs(x - CENTRE_OF_VISION), abs(y - CENTRE_OF_VISION)); PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && !(isEnemy(playerAtLocation.getName())) && !(playerAtLocation.equals(context.getId())) && distance < bestDistance && (!foundACoward || playerAtLocation.getName().equals("Coward"))) { if (playerAtLocation.getName().equals("Coward")) { foundACoward = true; } bestDistance = distance; bestDirection = Move.inDirection(x - CENTRE_OF_VISION, y -CENTRE_OF_VISION); } } } return bestDirection; } private boolean isEnemy(String name) { switch(name) { case "ZombieRightsActivist": case "ZombieHater": case "HideyTwitchy" : case "Gunner": case "Zombie" : return true; default: return false; } } } ``` [Answer] # Waller - Java The Waller loves walls, and seeks them out to hide from zombies. Ideally, the Waller would love to be encased in a wall and wait the apocalypse out. ## The Ideal Wall The ideal wall is where the Waller is completed surround by walls: ``` DDD DWD DDD ``` As the only way to die is to get shot or a zombie spawns underneath or neighboring you. It is the best odds possible for avoiding them. The ideal wall is hard to come by, but the Waller will find the best possible location and wait for zombies or other players to come to him to shoot and expand his wall. --- The algorithm is relatively simple 1. Is there a zombie about to bite? shoot them. 2. Find the best wall location (scored 0 - 8) in the field of view 3. Find the shortest path to that location and run to it! 4. Try increasing the wall 5. Wait... This is a work in progress, feel free to take anything I wrote to use for yourself. I wrote a simple [A\*](http://en.wikipedia.org/wiki/A*_search_algorithm) Algorithm to find the best path to a desired spot taking into consideration walls and other players. It gets recalculated each round as the walls may have changed between them. --- Changelog: * Tried to improve early game performance by waiting out and avoiding aggressive players for the first few turns before finding/building walls. * Added weights to path finding to take the best route in terms of distance and positional score. Will loot more often now and hopefully not run out of bullets. Improved opening game by running away from aggressive players. * Fixed issues with path finding ending on an occupied point * Further cleaned code. Added more walls to score a position than just neighboring walls. Expanded how far the Waller will extend his wall. * Cleaned code up a bit. Implemented shooting registry to avoid two Wallers shooting the same player during the same turn (inspired by Thaylon) * Added path finding between closest zombies and current Walelr. The Waller will only shoot a zombie if it can reach him in a certain number of moves. This hopefully will save some bullets when their is a wall blocking the zombie's path. --- Issues * The Waller may be in a good position, but sees a better wall location. They will mindless run through zombie-infested land to reach that new location. (I need to discourage this) * Early game is rough for the Waller, no good fortification are nearby and lots of aggressive players. (I need to improve early game performace) * No communication between Wallers in the same locations. Need to have they work together to built the best wall possible. --- Here is the code, I am not a java programmer (C#) so forgive my java errors. ``` package player; import java.lang.Math.*; import java.util.Set; import java.util.HashSet; import java.util.Hashtable; import java.util.ArrayList; import java.util.List; import java.util.LinkedList; import java.util.Collections; import java.util.Comparator; import zombie.*; import static zombie.Constants.*; public class Waller implements Player { private static final int MaximumDistanceToShootZombie = 2; private static final int PointsPerWall = 3; private static final int PointsPerLoot = 3; private static final int PointsPerZombie = -500; private static final int PointsPerAggressor = -500; private static final Set<PlayerId> shooting = new HashSet<PlayerId>(); private static final Set<PlayerId> dontLoot = new HashSet<PlayerId>(); private static final Set<Point> zombieLocations = new HashSet<Point>(); private Point CurrentLocation = new Point(CENTRE_OF_VISION, CENTRE_OF_VISION); private static int _lastGameTurn = -1; // DEBUG private static boolean _DEBUG = true; private static int agressiveKills; private static int zombieKills; private static int wallsBuilt; //////// private static class Point{ public int X; public int Y; public PlayerId Player; public int Distance; public Point(int x, int y) { X = x; Y = y; } public Point(int x, int y, PlayerId player) { X = x; Y = y; Player = player; } public boolean SameLocation(Point otherPoint) { return X == otherPoint.X && Y == otherPoint.Y; } public List<Point> getAdjacentPoints(PlayerId[][] field, int distance, boolean includeSelf) { List<Point> points = new ArrayList<Point>(); for(int x = X - distance; x <= X + distance; x++) { for(int y = Y - distance; y <= Y + distance; y++) { if(!includeSelf && x == X && y == Y) continue; Point pointToAdd = new Point(x, y); if(pointToAdd.isValid()) { pointToAdd.Player = field[x][y]; points.add(pointToAdd); } } } return points; } public int GetDistance(Point point) { return Math.max(Math.abs(X - point.X), Math.abs(Y - point.Y)); } private boolean isValid() { return X >= 0 && X < VISION_WIDTH && Y >= 0 && Y < VISION_WIDTH; } @Override public int hashCode() { return (X*100) + Y; } @Override public boolean equals(Object obj) { if (!(obj instanceof Point)) return false; if (obj == this) return true; return SameLocation((Point) obj); } @Override public String toString(){ return "("+X+","+Y+")"; } } @Override public Action doTurn(PlayerContext context) { int gameTurn = context.getGameClock(); if(gameTurn != _lastGameTurn){ _lastGameTurn = gameTurn; } PlayerId[][] field = context.getPlayField(); int bullets = context.getBullets(); // Mark all adjacent dead players as already been looted for(Point point : getSurrounding(field, CENTRE_OF_VISION, CENTRE_OF_VISION, 1)){ if(point.Player.getName().equals("DeadBody")) dontLoot.add(point.Player); } int x = context.getX(); int y = context.getY(); int boardSize = context.getBoardSize(); List<Point> newZombies = new ArrayList<Point>(); for(Point point : getSurrounding(field, CENTRE_OF_VISION, CENTRE_OF_VISION, VISION_RANGE)){ Point absolutePoint = GetNewTorusPoint(x + point.X - CENTRE_OF_VISION , y + point.Y - CENTRE_OF_VISION, boardSize); if(point.Player.getName().equals("DeadBody") && zombieLocations.contains(absolutePoint)) dontLoot.add(point.Player); // new zombie kill if(isZombie(point.Player)) newZombies.add(absolutePoint); } zombieLocations.clear(); zombieLocations.addAll(newZombies); Action action; // 1) Handle immediate threats to life, have to be dealt before anything else action = AssessThreats(field, bullets); if(action != null) return action; //2) Early turn avoidance if(gameTurn < 5) { action = EarlyTurn(field, bullets, context); if(action != null) return action; } int currentWallCount = countNumberOfSurroundingWalls(field, CENTRE_OF_VISION, CENTRE_OF_VISION); switch(currentWallCount) { case 8: action = ShootAgressivePlayers(field, bullets); if(action != null) return action; return Move.STAY; // no more moving case 7: action = ExpandWall(field, bullets, 1); if(action != null) return action; action = ShootAgressivePlayers(field, bullets); if(action != null) return action; case 6: case 5: case 4: // action = ExpandWall(field, bullets, 2); // if(action != null) return action; // break; case 2: case 1: default: break; } // 2) Score each possible square and find the best possible location(s) Set<Point> optimalLocations = scoreSquares(field); action = findShortestPath(field, CurrentLocation, optimalLocations); if(action != null) return action; action = ShootAgressivePlayers(field, bullets); if(action != null) return action; action = ExpandWall(field, bullets, 1); if(action != null) return action; // Stay still if nothing better to do return Move.STAY; } private Action EarlyTurn(PlayerId[][] field, int bullets, PlayerContext context) { Point bestPoint = CurrentLocation; double bestScore = 1000000; for(Point futurePoint : CurrentLocation.getAdjacentPoints(field, 1, true)) { double score = 0; for(Point adjacentPoint : futurePoint.getAdjacentPoints(field, VISION_RANGE, false)) { if(isAgressive(adjacentPoint.Player)){ int dist = futurePoint.GetDistance(adjacentPoint); if(dist > 6){ score += 1; } else { score += 10000; } } else if(isZombie(adjacentPoint.Player)) { int dist = futurePoint.GetDistance(adjacentPoint); if (dist <= 3) score += 10000; } else if(isWall(adjacentPoint.Player)) { score -= 2; } } if(score < bestScore) { bestScore = score; bestPoint = futurePoint; } } //if(_DEBUG) System.out.println("["+_lastGameTurn+"] Best Score: "+bestScore +" point: "+context.getX()+","+context.getY()); if(bestPoint == CurrentLocation) { Action action = ShootAgressivePlayers(field, bullets); if(action != null) return action; return Move.STAY; } if(bestScore >= 1000) { Action action = ShootAgressivePlayers(field, bullets); if(action != null) return action; } return Move.inDirection(bestPoint.X - CurrentLocation.X, bestPoint.Y - CurrentLocation.Y); } private Action ShootAgressivePlayers(PlayerId[][] field, int bullets) { if(bullets > 0) { for(Point point : getSurrounding(field, CENTRE_OF_VISION, CENTRE_OF_VISION, SHOOT_RANGE)) { PlayerId player = point.Player; if(isAgressive(player) && shouldShoot(player)) { if(_DEBUG) System.out.println("["+_lastGameTurn+"] Killing Aggressive: "+(++agressiveKills)); return new Shoot(player); } } } return null; } private Action ExpandWall(PlayerId[][] field, int bullets, int distance) { if(bullets > 0) { for(Point point : getSurrounding(field, CENTRE_OF_VISION, CENTRE_OF_VISION, distance)) { PlayerId player = point.Player; if(!isWall(player) && isEnemy(player) && !isZombie(player) && shouldShoot(player)) { if(_DEBUG) System.out.println("["+_lastGameTurn+"] Expanding Wall: "+(++wallsBuilt)+" Dist: "+CurrentLocation.GetDistance(point)); return new Shoot(player); } } } return null; } private boolean shouldShoot(PlayerId player) { boolean result = shooting.add(player); if(result && isZombie(player)){ dontLoot.add(player); } return result; } private boolean canShoot(PlayerId player) { return !shooting.contains(player); } private Action AssessThreats(PlayerId[][] field, int bullets){ // Find the most threatening zombie List<Point> bestZombies = new ArrayList<Point>(); int smallestDistance = MaximumDistanceToShootZombie+1; for(Point point : getSurrounding(field, CENTRE_OF_VISION, CENTRE_OF_VISION, MaximumDistanceToShootZombie)) { PlayerId zombie = point.Player; if(isZombie(zombie)) { LinkedList<Point> path = findShortestPath_astar(field, CurrentLocation, point, false, false); if(path.isEmpty()) continue; if(path.size() <= smallestDistance && canShoot(zombie)) { if(path.size() < smallestDistance) { smallestDistance = path.size(); bestZombies.clear(); } bestZombies.add(point); } } } // No zombies to worry about if(bestZombies.isEmpty()) return null; if(bestZombies.size() > 1) { if(_DEBUG) System.out.println("["+_lastGameTurn+"] Multiple Zombies in striking range, wait them out?"); return MoveToBestSpot(field); } Point zombie = bestZombies.get(0); // Do we have ammo? if(bullets > 0 && shouldShoot(zombie.Player)) { if(_DEBUG) System.out.println("["+_lastGameTurn+"] Shooting Zombie: "+(++zombieKills)); return new Shoot(zombie.Player); } if(_DEBUG) System.out.println("["+_lastGameTurn+"] No Bullets to Shoot Zombie! Should flee"); return MoveInDirection(field, CENTRE_OF_VISION - zombie.X, CENTRE_OF_VISION - zombie.Y); } private Action MoveToBestSpot(PlayerId[][] field) { int leastZombies = 100000; Point bestPoint = CurrentLocation; for(Point point : CurrentLocation.getAdjacentPoints(field, 1, false)) { if(point.Player == null) { int zombies = countNumberOfSurroundingZombies(field, point.X, point.Y); if(zombies < leastZombies) { leastZombies = zombies; bestPoint = point; } } } return Move.inDirection(bestPoint.X - CurrentLocation.X, bestPoint.Y - CurrentLocation.Y); } private Action MoveInDirection(PlayerId[][] field, int x, int y) { x = (int)Math.signum(x); y = (int)Math.signum(y); if(y == 0){ if(field[CENTRE_OF_VISION+x][CENTRE_OF_VISION] != null) return Move.inDirection(x,0); if(field[CENTRE_OF_VISION+x][CENTRE_OF_VISION-1] != null) return Move.inDirection(x,-1); if(field[CENTRE_OF_VISION+x][CENTRE_OF_VISION+1] != null) return Move.inDirection(x,1); } else if(x == 0){ if(field[CENTRE_OF_VISION][CENTRE_OF_VISION+y] != null) return Move.inDirection(0,y); if(field[CENTRE_OF_VISION-1][CENTRE_OF_VISION+y] != null) return Move.inDirection(-1,y); if(field[CENTRE_OF_VISION+1][CENTRE_OF_VISION+y] != null) return Move.inDirection(1,y); } else { if(field[CENTRE_OF_VISION+x][CENTRE_OF_VISION+y] != null) return Move.inDirection(x,y); if(field[CENTRE_OF_VISION+x][CENTRE_OF_VISION] != null) return Move.inDirection(x,0); if(field[CENTRE_OF_VISION][CENTRE_OF_VISION+y] != null) return Move.inDirection(0,y); } return Move.inDirection(0,0); } // Implementation of the A* path finding algorithm private LinkedList<Point> findShortestPath_astar(PlayerId[][] field, Point startingPoint, Point finalPoint, boolean includeWeights, boolean considerPlayersAsWalls) { LinkedList<Point> foundPath = new LinkedList<Point>(); Set<Point> openSet = new HashSet<Point>(); Set<Point> closedSet = new HashSet<Point>(); Hashtable<Point, Integer> gScores = new Hashtable<Point, Integer>(); Hashtable<Point, Point> cameFrom = new Hashtable<Point, Point>(); gScores.put(startingPoint, 0); openSet.add(startingPoint); Point currentPoint = startingPoint; while(!openSet.isEmpty()) { // Find minimum F score int minF = 10000000; for(Point point : openSet) { int g = gScores.get(point); int h = point.GetDistance(finalPoint); // Assumes nothing in the way int f = g + h; if(f < minF) { minF = f; currentPoint = point; } } // Found the final point if(currentPoint.SameLocation(finalPoint)) { Point curr = finalPoint; while(!curr.SameLocation(startingPoint)) { foundPath.addFirst(curr); curr = cameFrom.get(curr); } return foundPath; } openSet.remove(currentPoint); closedSet.add(currentPoint); // Add neighbouring squares for(Point pointToAdd : currentPoint.getAdjacentPoints(field, 1, false)){ if(closedSet.contains(pointToAdd) || isWall(pointToAdd.Player) || (considerPlayersAsWalls && pointToAdd.Player != null && !pointToAdd.SameLocation(finalPoint) )) continue; int gScore = gScores.get(currentPoint) + 1; // distance should always be one (may change depending on environment) // if(includeWeights){ // gScore += (int)-getScore(field,pointToAdd.X,pointToAdd.Y); // } boolean distIsBetter = false; if(!openSet.contains(pointToAdd)) { openSet.add(pointToAdd); distIsBetter = true; } else if(gScore < gScores.get(pointToAdd)){ distIsBetter = true; } if(distIsBetter) { gScores.put(pointToAdd, gScore); cameFrom.put(pointToAdd, currentPoint); } } } return foundPath; } private Action findShortestPath(PlayerId[][] field, Point startingPoint, Set<Point> finalPoints) { if(finalPoints.isEmpty()) return null; int smallestPath = 10000; Point pointToMoveTo = startingPoint; for(Point finalPoint : finalPoints) { if(finalPoint == startingPoint) return null; LinkedList<Point> path = findShortestPath_astar(field, startingPoint, finalPoint, true, true); // No path between the two points if(path.isEmpty()){ continue; } // Check if this is the smallest path if(path.size() < smallestPath) { smallestPath = path.size(); pointToMoveTo = path.getFirst(); } } if(pointToMoveTo == startingPoint) return null; double score = getScore(field, pointToMoveTo.X, pointToMoveTo.Y); if(score < -200) { if(_DEBUG) System.out.println("["+_lastGameTurn+"] Best Path leads to a bad spot: "+score); return null; } return Move.inDirection(pointToMoveTo.X - startingPoint.X, pointToMoveTo.Y - startingPoint.Y); } private Set<Point> scoreSquares(PlayerId[][] field) { double bestScore = getScore(field, CENTRE_OF_VISION, CENTRE_OF_VISION) + 1; // plus one to break ties, and would rather stay Set<Point> bestLocations = new HashSet<Point>(); if(bestScore >= 0) { bestLocations.add(CurrentLocation); } else { bestScore = 0; } for(int x = 0; x < VISION_WIDTH; x++){ for(int y = 0; y < VISION_WIDTH; y++){ if(x == CENTRE_OF_VISION && y == CENTRE_OF_VISION) continue; if(field[x][y] == null) { double score = getScore(field, x, y); if(score >= bestScore){ if(score > bestScore) { bestLocations.clear(); bestScore = score; } bestLocations.add(new Point(x, y)); } } } } return bestLocations; } private double getScore(PlayerId[][] field, int x, int y) { int walls = countNumberOfSurroundingWalls(field, x, y); double score = Math.pow(PointsPerWall, walls); int aggressors = countNumberOfSurroundingAggressions(field, x, y); score += aggressors * PointsPerAggressor; int zombies = countNumberOfSurroundingZombies(field, x, y); score += zombies * PointsPerZombie; int loots = countNumberOfSurroundingLoots(field, x, y); score += Math.pow(PointsPerLoot, loots); return score; } private int countNumberOfSurroundingZombies(PlayerId[][] field, int x, int y) { int zombies = 0; Point currentPoint = new Point(x,y); for(Point point : getSurrounding(field, x, y, MaximumDistanceToShootZombie+1)){ if(isZombie(point.Player)){ LinkedList<Point> path = findShortestPath_astar(field, currentPoint, point, false, false); if(path.isEmpty()) continue; if(path.size() < MaximumDistanceToShootZombie+1) zombies++; } } return zombies; } private int countNumberOfSurroundingLoots(PlayerId[][] field, int x, int y) { int loots = 0; for(Point point : getSurrounding(field, x, y, 1)){ PlayerId player = point.Player; if(isWall(player) && !dontLoot.contains(player)){ loots++; } } return loots; } private int countNumberOfSurroundingAggressions(PlayerId[][] field, int x, int y) { int aggressors = 0; for(Point point : getSurrounding(field, x, y, SHOOT_RANGE+1)){ if(isAgressive(point.Player)){ aggressors++; } } return aggressors; } private int countNumberOfSurroundingWalls(PlayerId[][] field, int x, int y) { int walls = 0; for(Point point : getSurrounding(field, x, y, 1)){ if(isWall(point.Player)){ walls++; } } return walls; } private static boolean isZombie(PlayerId player) { return player != null && player.getName().equals("Zombie"); } private static boolean isWall(PlayerId player) { return player != null && player.getName().equals("DeadBody"); } private static boolean isEnemy(PlayerId player) { if(player == null) return false; switch (player.getName()) { case "Waller": case "DeadBody": case "EmoWolfWithAGun": return false; default: return true; } } private static boolean isAgressive(PlayerId player) { if(player == null) return false; switch (player.getName()) { case "Waller": case "DeadBody": case "EmoWolfWithAGun": case "GordonFreeman": case "Vortigaunt": case "StandStill": case "MoveRandomly": case "Zombie": return false; default: return true; } } // Helper Functions private List<Point> getSurrounding(PlayerId[][] field, int x, int y, int maxDistance) { final Point currentPoint = new Point(x,y); List<Point> players = new ArrayList<Point>(); int minX = coercePoint(x - maxDistance); int maxX = coercePoint(x + maxDistance); int minY = coercePoint(y - maxDistance); int maxY = coercePoint(y + maxDistance); for(int i = minX; i <= maxX; i++){ for(int j = minY; j <= maxY; j++) { if(i == x && j == y) continue; if(field[i][j] != null) { Point point = new Point(i,j,field[i][j]); point.Distance = currentPoint.GetDistance(point); players.add(point); } } } Collections.sort(players, new Comparator<Point>() { public int compare(Point p1, Point p2) { return Integer.compare(p1.Distance, p2.Distance); }}); return players; } private static int coercePoint(int value) { if(value < 0) return 0; if(value >= VISION_WIDTH) return VISION_WIDTH-1; return value; } public static Point GetNewTorusPoint(int x, int y, int boardSize) { if(x >= boardSize) x = boardSize - x; if(y >= boardSize) y = boardSize - y; return new Point(x,y); } private static int getDistance(int x1, int y1, int x2, int y2) { return Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)); } } ``` [Answer] # Fox Fox needs a foxhole. Uses a good part of my Coward but follows a different strategy. If you choose to accept the (sub)mission, fox will choose to build a foxhole. ``` package player; import java.lang.Math.*; import java.util.Set; import java.util.HashSet; import zombie.*; import static zombie.Constants.*; public class Fox implements Player { private static int lastround = -1; private static final Set<PlayerId> killed = new HashSet<>(); private static final Set<PlayerId> looted = new HashSet<>(); @Override public Action doTurn(PlayerContext context) { PlayerId[][] field = context.getPlayField(); // Cleanup if (context.getGameClock() > lastround) { lastround = context.getGameClock(); killed.clear(); } // Snipe if (context.getBullets() > 0) { int distEnemy = 1; PlayerId targetEnemy = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { PlayerId player = field[x][y]; if (player != null && !killed.contains(player)) { int dist = getDistance(x, y); if (!player.getName().equals("Zombie") && isEnemy(player.getName()) && dist >= distEnemy ) { distEnemy = dist; targetEnemy = field[x][y]; } } } } if (targetEnemy != null) { killed.add(targetEnemy); return new Shoot( targetEnemy ); } } // Check Foxhole int foxhole = 0; PlayerId target = null; for( int x = -2; x <= 2; x++ ) { for( int y = -2; y <= 2; y++ ) { PlayerId player = field[CENTRE_OF_VISION+x][CENTRE_OF_VISION+y]; if (player != null && getDistance(CENTRE_OF_VISION+x,CENTRE_OF_VISION+y) == 2) { if (player.getName().equals("DeadBody") || player.getName().equals("Fox")) { foxhole++; } if( player.getName().equals("Zombie")) { target = player; } } } } if (context.getBullets() + foxhole >= 16) { if (target!=null) { return new Shoot( target ); } else { return Move.STAY; } } // Looted? for( int xx = CENTRE_OF_VISION-VISION_RANGE+1; xx <= CENTRE_OF_VISION+VISION_RANGE-1; xx++ ) { for( int yy = CENTRE_OF_VISION-VISION_RANGE+1; yy <= CENTRE_OF_VISION+VISION_RANGE-1; yy++ ) { PlayerId player = field[xx][yy]; if( player != null && !player.getName().equals("Zombie") && !player.getName().equals("DeadBody")) { for( int x = -1; x <= 1; x++ ) { for( int y = -1; y <= 1; y++ ) { PlayerId loot = field[xx+x][yy+y]; if( loot != null && !looted.contains(loot) && loot.getName().equals("DeadBody")) { looted.add(loot); } } } } } } // Collect bullets int bestScore = -10000000; Move bestMove = Move.randomMove(); for( int x = -1; x <= 1; x++ ) { for( int y = -1; y <= 1; y++ ) { PlayerId center = field[CENTRE_OF_VISION+x][CENTRE_OF_VISION+y]; if( center == null ) { int thisScore = 0; for( int xx = CENTRE_OF_VISION+x-VISION_RANGE+1; xx < CENTRE_OF_VISION+x+VISION_RANGE; xx++ ) { for( int yy = CENTRE_OF_VISION+y-VISION_RANGE+1; yy < CENTRE_OF_VISION+y+VISION_RANGE; yy++ ) { PlayerId player = field[xx][yy]; if( player != null) { int dist = getDistance(xx-x,yy-y); if( player.getName().equals("DeadBody")) { if( !looted.contains(player)) { thisScore += (32+VISION_RANGE-dist)*(VISION_RANGE-dist); } } else if( player.getName().equals("Zombie")) { if( dist <= 5 ) { thisScore -= (int)Math.pow( 10, ( 6 - dist )); } } } } } if( thisScore > bestScore ) { bestScore = thisScore; bestMove = Move.inDirection( x, y ); } } } } return bestMove; } private boolean isEnemy(String name) { switch (name) { case "Fox": case "Coward": case "DeadBody": case "GordonFreeman": case "EmoWolfWithAGun": case "HuddleWolf": case "ThePriest": case "Shotguneer": case "Vortigaunt": case "Cocoon": case "SuperCoward": case "SOS": case "JohnNash": case "MoveRandomly": return false; default: return true; } } private int getDistance(int x, int y) { return Math.max(Math.abs(CENTRE_OF_VISION - x), Math.abs(CENTRE_OF_VISION - y)); } } ``` [Answer] # Gordon Freeman [Gordon Freeman](http://en.wikipedia.org/wiki/Gordon_Freeman) hates zombies, so he'll never kill himself, but he has no qualms with scavenging for more ammo to shoot more zombies. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class GordonFreeman implements Player { @Override public Action doTurn(PlayerContext context){ int ammo = context.getBullets(); // if I have bullets, shoot some zombies if(ammo > 0){ for(PlayerId player: context.shootablePlayers()){ switch(player.getName()){ case "Zombie": return new Shoot(player); default: break; } } } // if no bullets, find a dead body and scavenge Move bestDirection = Move.STAY; int bestDistance = Integer.MAX_VALUE; for(int y = 1; y < VISION_WIDTH - 1; y++) { for(int x = 1; x < VISION_WIDTH - 1; x++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; // find a dead body if((playerAtLocation != null) && "DeadBody".equals(playerAtLocation.getName())){ // check adjacent squares for an empty square for(int yy=-1; yy <= +1; yy++){ for(int xx=-1; xx <= +1; xx++){ PlayerId playerNearby = context.getPlayField()[x + xx][y + yy]; if(playerNearby == null){ int distance = max(abs(xx + x - CENTRE_OF_VISION), abs(yy + y - CENTRE_OF_VISION)); if(distance < bestDistance){ bestDistance = distance; bestDirection = Move.inDirection(xx + x - CENTRE_OF_VISION, yy + y - CENTRE_OF_VISION); } } } } } } } return bestDirection; } } ``` [Answer] **The priest** If you have the faith, you don't need to run nor to shot. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class ThePriest implements Player { @Override public Action doTurn(PlayerContext context) { return Move.NORTH; } } ``` [Answer] # ZombieHater This submission hates zombies! It tries to shoot the nearest zombie while it has bullets, then collects more bullets to kill more zombies. **Edit:** ZombieHater now doesn't hesitate to kill other people to get more bullets. It also detects obstacles and tries to go around them. ``` package player; import java.awt.Point; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import zombie.*; import static zombie.Constants.*; public class ZombieHater implements Player { private static final Set<PlayerId> emptyDeadBodies = new HashSet<>(); private static final Map<PlayerId, Point> lastPos = new HashMap<>(); @Override public Action doTurn(PlayerContext context) { PlayerId[][] field = context.getPlayField(); Point myPos = new Point(context.getX(), context.getY()); PlayerId myId = context.getId(); // update dead bodies with the new empty ones addEmptyBodies(field); // shoot nearest zombie if possible if (context.getBullets() > 0) { PlayerId nearestZombie = getNearestEnemy(field); if (nearestZombie != null) { lastPos.remove(myId); return new Shoot(nearestZombie); } } // stuck, mostly because of dead body if (lastPos.containsKey(myId) && lastPos.get(myId).equals(myPos)) { return Move.randomMove(); } // walk towards dead bodies Point nearestDeadBody = getNearestDeadBody(field); if (nearestDeadBody != null) { Move move = Move.inDirection(nearestDeadBody.x - CENTRE_OF_VISION, nearestDeadBody.y - CENTRE_OF_VISION); lastPos.put(myId, myPos); return move; } lastPos.remove(myId); return Move.randomMove(); } // add surrounding dead bodies to empty bodies private void addEmptyBodies(PlayerId[][] field) { for (Move move : Move.values()) { PlayerId player = field[CENTRE_OF_VISION + move.x][CENTRE_OF_VISION + move.y]; if (player != null && "DeadBody".equals(player.getName())) { emptyDeadBodies.add(player); } } } // distance from centre, for example 5 if x=7 and y=3 private int distanceFromCentre(int x, int y) { int dx = Math.abs(CENTRE_OF_VISION - x); int dy = Math.abs(CENTRE_OF_VISION - y); return Math.max(dx, dy); } // return nearest enemy or null if none exists private PlayerId getNearestEnemy(PlayerId[][] field) { int minOffset = Integer.MAX_VALUE; PlayerId nearestEnemy = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { int offset = distanceFromCentre(x, y); PlayerId player = field[x][y]; if (player != null && isEnemy(player.getName()) && offset < minOffset) { minOffset = offset; nearestEnemy = field[x][y]; } } } return nearestEnemy; } // return nearest dead body or null if none exists private Point getNearestDeadBody(PlayerId[][] field) { int minOffset = Integer.MAX_VALUE; Point nearestDeadBody = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { int offset = distanceFromCentre(x, y); PlayerId player = field[x][y]; if (player != null && "DeadBody".equals(player.getName()) && offset < minOffset && !emptyDeadBodies.contains(player)) { minOffset = offset; nearestDeadBody = new Point(x, y); } } } return nearestDeadBody; } private boolean isEnemy(String name) { switch (name) { case "ZombieHater": case "DeadBody": case "EmoWolfWithGun": // don't bother shooting him return false; default: return true; } } } ``` [Answer] # The Vortigaunt Will always follow Doctor Gordon Freeman, or walk around aimlessly if he's not on the same dimension. ``` package player; import java.util.ArrayList; import zombie.*; public class Vortigaunt implements Player { class PlayerLocation { private int x; int y; PlayerId player; public PlayerLocation(int x, int y, PlayerId id) { this.x = x; this.y = y; this.player = id; } public int getX() { return x; } public int getY() { return y; } public PlayerId getPlayer() { return player; } } @Override public Action doTurn(PlayerContext context) { PlayerId[][] field = context.getPlayField(); PlayerLocation me = new PlayerLocation(context.getX(), context.getY(), context.getId()); ArrayList<PlayerLocation> freemans = findFreeman(field); PlayerLocation nearestFreeman = getNearestFreeman(freemans, me); if (nearestFreeman == null) { return Move.randomMove(); } else { return Move.inDirection(nearestFreeman.getX(), nearestFreeman.getY()); } } private PlayerLocation getNearestFreeman(ArrayList<PlayerLocation> freemans, PlayerLocation me) { double nearestDistance = Integer.MAX_VALUE; PlayerLocation nearestFreeman = null; for (PlayerLocation freeman : freemans) { int x = freeman.getX() - me.getX(); int y = freeman.getY() - me.getY(); double distance = (int)Math.sqrt((double)(x * x + y * y)); if (distance < nearestDistance) { nearestDistance = distance; nearestFreeman = freeman; } } return nearestFreeman; } private ArrayList<PlayerLocation> findFreeman(PlayerId[][] field) { ArrayList<PlayerLocation> freemans = new ArrayList<PlayerLocation>(); for (int x = field.length; x >= 0; x -= 1) { for (int y = field[x].length; y >= 0; y -= 1) { if (field[x][y].getName().equals("GordonFreeman")) { freemans.add(new PlayerLocation(x, y, field[x][y])); } } } return freemans; } } ``` [Answer] # Cocoon - Frege Such a shame. Half a dozen languages to choose from, and everyone just uses Java. Well, no sense in letting them go to waste, so here's a competitor in Frege. It uses Dijkstra's algorithm to find a secluded spot to wait out the apocalypse, goes foraging for bullets if it runs out, and shoots zombies if they get too close. ### Updated Cocoon now ignores routes that would take it within striking distance of zombies in its routing algorithm, and shoots zombies when they're within 2 squares, rather than 3 (to build a tighter cocoon). ``` module player.Cocoon where import zombie.FregeBindings import frege.data.TreeMap import Data.List(sortBy) import Data.Foldable(minimumBy, maximumBy) instance Ord PlayerId where a <=> b = case a.getName <=> b.getName of Eq -> a.getNumber <=> b.getNumber x -> x instance Show Action where show action = action.toString -- Dijkstras shortest path algorithm data DijkstraNode = Green {d :: Int, pos :: (Int, Int)} | Red {pos :: (Int, Int)} | Yellow {d :: Int, pos :: (Int, Int)} data DijkstraState = DijkstraState {board :: Tree (Int, Int) DijkstraNode, yellows :: TreeSet DijkstraNode} derive Eq DijkstraNode derive Ord DijkstraNode derive Show DijkstraNode derive Show DijkstraState updateState :: Int -> DijkstraState -> (Int, Int) -> DijkstraState updateState d (oldState@DijkstraState {board, yellows}) pos = case (lookup board pos) of Nothing -> oldState Just Green {d, pos} -> oldState Just Red {pos} -> let newYellow = Yellow d pos newYellows = insert yellows newYellow () newBoard = update board pos newYellow in DijkstraState {board = newBoard, yellows = newYellows} Just (oldYellow@Yellow {d = oldD, pos = oldPos}) | oldD <= d = oldState | true = let newYellow = Yellow d pos newYellows = insert (delete yellows oldYellow) newYellow () newBoard = insert board pos newYellow in DijkstraState {board = newBoard, yellows = newYellows} neighbours :: (Int, Int) -> [(Int, Int)] neighbours (x,y) = [(x1 + x, y1 + y) | x1 <- [-1 .. 1], y1 <- [-1 .. 1], x1 != 0 || y1 != 0] moveRegion = [(x, y) | x <- [-1 .. 1], y <- [-1 .. 1]] findMove :: DijkstraState -> Maybe Move findMove DijkstraState {board, yellows} | null yellows = Nothing | true = let tip@Yellow{d, pos} = head (keys yellows) rest = delete yellows tip newBoard = insert board pos (Green d pos) intermediateState = DijkstraState {board = newBoard, yellows = rest} neighbourhood = [node | pos <- moveRegion , node <- lookup board pos] in if tip.pos == (0, 0) then case minimum neighbourhood of _ | null neighbourhood = Nothing Green {d, pos = (x,y)} -> Just (Move.inDirection x y) _ -> Nothing else findMove (fold (updateState (d + 1)) intermediateState (neighbours pos)) insertRed :: Tree (Int, Int) DijkstraNode -> (Int, Int) -> Tree (Int, Int) DijkstraNode insertRed board pos = insert board pos (Red {pos}) removeZombieTerritory :: PlayerContext -> Tree (Int, Int) DijkstraNode -> Tree (Int, Int) DijkstraNode removeZombieTerritory ctx board = let zombies = [pos | pos@(x,y) <- v2, pid <- ctx.lookAround x y, pid.getName == "Zombie"] zombieTerritory = [(x + xx, y + yy) | (x,y) <- zombies, xx <- [-2..2], yy <- [-2..2]] in fold Tree.delete board zombieTerritory v = [-visionRange .. visionRange] v2 = sortBy (comparing dist) [(x,y) | x <- v, y <- v] shootable = sortBy (comparing dist) [(x, y) | x <- [-shootRange .. shootRange], y <- [-shootRange .. shootRange]] moveTo :: (Int, Int) -> PlayerContext -> Maybe Move moveTo pos ctx = let rawBoard = fold insertRed Tree.empty ([p | p@(x, y) <- v2, ctx.lookAround x y == Nothing] ++ [(0,0)]) board = removeZombieTerritory ctx rawBoard yellows = Tree.insert Tree.empty (Yellow {d = 0, pos}) () in findMove (DijkstraState {board, yellows}) dist :: (Int, Int) -> Int dist (x,y) = max (abs x) (abs y) findBullets :: PlayerContext -> TreeSet PlayerId -> Maybe Action findBullets ctx emptyBodies = if (ctx.getBullets > 0) then Nothing else let viableBodies = [pos | pos@(x,y) <- v2, pid <- (ctx.lookAround x y), pid.getName == "DeadBody", lookup emptyBodies pid == Nothing] in case viableBodies of target : _ -> moveTo target ctx _ -> Nothing isThreat :: String -> (Int, Int) -> Bool isThreat name pos = case (name, pos) of ("Zombie", pos) | dist pos <= 2 -> true ("HideyTwitchy", _) -> true ("ZombieHater", _) -> true ("ZombieRightsActivist", _) -> true ("Gunner", _) -> true _ -> false shootThreats :: PlayerContext -> Maybe Action shootThreats ctx = let threats = [pid | pos@(x, y) <- shootable, pid <- ctx.lookAround x y, isThreat (pid.getName) pos] in case threats of target:_ | ctx.getBullets == 0 = Nothing | true = Just (Shoot.new target) _ -> Nothing coziness :: PlayerContext -> (Int, Int) -> Int coziness ctx (x,y) = let wallScores = [3 - dist (xx, yy) | xx <- [-2 .. 2], yy <- [-2 .. 2], xx != 0 || yy != 0, pid <- ctx.lookAround (x + xx) (y + yy), pid.getName == "DeadBody"] in 3 * sum wallScores - dist (x,y) gotoCoziest :: PlayerContext -> Maybe Action gotoCoziest ctx = let emptySquares = [pos | pos@(x, y) <- v2, ctx.lookAround x y == Nothing] ++ [(0,0)] coziest = maximumBy (comparing (coziness ctx)) emptySquares in if null emptySquares then Nothing else moveTo coziest ctx updateEmptyBodies :: PlayerContext -> TreeSet PlayerId -> TreeSet PlayerId updateEmptyBodies ctx current = let nearbyBodies = [pid | (x,y) <- neighbours (0,0), pid <- ctx.lookAround x y, pid.getName == "DeadBody"] in fold (\x -> \y -> insert x y ()) current nearbyBodies doStep :: TreeSet PlayerId -> PlayerContext -> Continue doStep !bodies ctx = let emptyBodies = updateEmptyBodies ctx bodies plan = (findBullets ctx emptyBodies) `mplus` (shootThreats ctx) `mplus` (gotoCoziest ctx) in case plan of Just action -> Continue {result = action, andThen = doStep emptyBodies} Nothing -> Continue {result = Move.stay, andThen = doStep emptyBodies} doTurn = doStep Tree.empty ``` [Answer] # Gunner - Java Here's an example to get you off the blocks. He shoots anything he sees, or wanders aimlessly if there's nothing around, or he's got no bullets. ``` package player; import zombie.*; public class Gunner implements Player { @Override public Action doTurn(PlayerContext context) { if (context.getBullets() > 0) { for (PlayerId player: context.shootablePlayers()) { switch(player.getName()) { case "Gunner": case "DeadBody": break; default: return new Shoot(player); } } } return Move.randomMove(); } } ``` Can you do any better? [Answer] ## HideyTwitchy Nutjob that hides from everything unless a player chases him down to shooting range, in which case he panics and shoots (including his own kind). Only loots bodies if he's out of ammo, then gets the heck away from the corpses. ``` package player; import static java.lang.Math.*; import java.awt.Point; import java.util.HashSet; import java.util.Set; import zombie.*; import static zombie.Constants.*; public class HideyTwitchy implements Player { private Set<Integer> lootedCorpseIds = new HashSet<Integer>(); @Override public Action doTurn(PlayerContext context) { Action action = null; Point playerP = getClosestPlayerPoint(context); Point corpseP = getClosestCorpsePoint(context); Point enemyP = getClosestEnemyPoint(context); if (isWithinArea(playerP, Constants.SHOOT_RANGE, Constants.SHOOT_RANGE)) { //player spotted within 5x5 if (context.getBullets() > 0) { action = getShootAction(playerP, context); //shoot! } else { action = getMoveAwayFromPoint(playerP); //run! } } else if (isWithinArea(enemyP, Constants.VISION_RANGE, Constants.VISION_RANGE)) { //players or zombie spotted within 8x8 action = getMoveAwayFromPoint(enemyP); //run! } else if (isWithinArea(corpseP, Constants.VISION_RANGE, Constants.VISION_RANGE)) { //corpse spotted within 8x8 int uniqueCorpseId = getPlayerIdAtPoint(context, corpseP).getNumber(); if (isWithinArea(corpseP, 1, 1)) { //loot the corpse and get the heck away from it lootedCorpseIds.add(uniqueCorpseId); action = getMoveAwayFromPoint(corpseP); } else if (context.getBullets() == 0 && !lootedCorpseIds.contains(uniqueCorpseId)) { action = getMoveTowardsPoint(corpseP); //loot corpse if not looted! } } else { //randomly move action = Move.randomMove(); } return action; } private PlayerId getPlayerIdAtPoint(PlayerContext context, Point p) { return context.getPlayField()[(int) p.getX()][(int) p.getY()]; } private Move getMoveTowardsPoint(Point p) { return Move.inDirection((int)p.getX() - CENTRE_OF_VISION, (int)p.getY() - CENTRE_OF_VISION); } private Move getMoveAwayFromPoint(Point p) { return Move.inDirection(CENTRE_OF_VISION - (int)p.getX(), CENTRE_OF_VISION - (int)p.getY()); } private Shoot getShootAction(Point p, PlayerContext context) { PlayerId id = context.getPlayField()[(int) p.getX()][(int) p.getY()]; Shoot shootAction = new Shoot(id); return shootAction; } private boolean isWithinArea(Point p, int x, int y) { return p != null && abs(CENTRE_OF_VISION - p.getX()) <= x && abs(CENTRE_OF_VISION - p.getY()) <= y; } private Point getClosestEnemyPoint(PlayerContext context) { String[] lookFor = {}; String[] avoid = {Dead.DEADBODYNAME}; Point p = getClosestEntity(context, lookFor, avoid); return p; } private Point getClosestPlayerPoint(PlayerContext context) { String[] lookFor = {}; String[] avoid = {Dead.DEADBODYNAME, Dead.ZOMBIENAME}; Point p = getClosestEntity(context, lookFor, avoid); return p; } private Point getClosestCorpsePoint(PlayerContext context) { String[] lookFor = {Dead.DEADBODYNAME}; String[] avoid = {Dead.ZOMBIENAME}; Point p = getClosestEntity(context, lookFor, avoid); return p; } private Point getClosestEntity(PlayerContext context, String[] lookFor, String[] avoid) { int bestDistance = Integer.MAX_VALUE; Point closestPoint = null; for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && !playerAtLocation.equals(context.getId())) { //not empty and not me boolean conditionsMet = true; for (String lookForName : lookFor) { conditionsMet |= playerAtLocation.getName().equals(lookForName); } for (String avoidName : avoid) { conditionsMet &= !playerAtLocation.getName().equals(avoidName); } if (conditionsMet) { int distance = max(abs(x - CENTRE_OF_VISION), abs(y - CENTRE_OF_VISION)); if (distance < bestDistance) { bestDistance = distance; closestPoint = new Point(x, y); } } } } } return closestPoint; } } ``` [Answer] **SuperCoward - JAVA** I know about the double submission but I just couldn't resist. Please tell me if I should remove it. What kind of coward is that whom shoots and fights? Presenting to you **SUPER** Coward, he will run on the field trying to avoid who he thinks are enemies and zombies. He tries to stay safe and avoids obstacles. If he doesn't find a good route, panics and stays in place ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.abs; import static java.lang.Math.max; import java.awt.Point; public class SuperCoward implements Player { private enum DANGER{ SAFE(0),PROBABLY_SAFE(1),UNSAFE(2),DANGER(3); private int value; private DANGER(int value){ this.value = value; } } private final int PLAYER_X = 8; private final int PLAYER_Y = 8; @Override public Action doTurn(PlayerContext context) { DANGER danger = DANGER.DANGER; Point position = null; for(int i=-1;i<1;i++){ for(int j=-1;j<1;j++){ DANGER positionDanger = isDangerous(context,PLAYER_X+i,PLAYER_Y+j); if(positionDanger.value < danger.value){ if(canMove(context,PLAYER_X+i,PLAYER_Y+j)){ position = new Point(PLAYER_X+i, PLAYER_Y+j); } } } } if(position != null){ return Move.inDirection(position.x, position.y); }else{ return Move.STAY; } } private boolean canMove(PlayerContext context,int posX, int posY){ PlayerId playerAtLocation = context.getPlayField()[posX][posY]; if(playerAtLocation == null){ return true; }else{ return false; } } private DANGER isDangerous(PlayerContext context,int posX, int posY){ DANGER danger = DANGER.SAFE; for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if(playerAtLocation != null && isEnemy(playerAtLocation.getName())){ int distanceToPlayer = max(abs(x - posX), abs(y - posY)); if(playerAtLocation.getName().equals("Zombie")){ DANGER currentDanger = null; if(distanceToPlayer <=3){ currentDanger = DANGER.DANGER; }else if(distanceToPlayer <=5){ currentDanger = DANGER.PROBABLY_SAFE; }else if(distanceToPlayer >5){ currentDanger = DANGER.SAFE; } if(currentDanger.value > danger.value){ danger = currentDanger; } }else{ DANGER currentDanger = null; if(distanceToPlayer <=5){ currentDanger = DANGER.DANGER; }else if(distanceToPlayer >5){ currentDanger = DANGER.PROBABLY_SAFE; } if(currentDanger.value > danger.value){ danger = currentDanger; } } } } } return danger; } private boolean isEnemy(String name){ switch(name) { case "DeadBody": case "GordonFreeman": case "EmoWolfWithAGun": case "HuddleWolf": case "ThePriest": case "Shotguneer": case "SuperCoward": return false; default: return true; } } } ``` [Answer] ## Shotguneer I will admit that my main goal is to shoot the Gunner. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class Shotguneer implements Player { @Override public Action doTurn(PlayerContext context) { double sdistance=1000; if (context.getBullets() > 0) { for (PlayerId player: context.shootablePlayers()) { switch(player.getName()) { case "Gunner": case "ZombieRightsActivist": case "HideyTwitchy": case "ZombieHater": case "Waller"; case "Bee"; case "SunTzu"; //case "Fox": //case "Coward": return new Shoot(player); default: break; } } boolean zombies=false; PlayerId TargetZombie = context.getId(); for (int x = -3; x < +4; x++) { for (int y = -3; y < +4; y++) { double distance = sqrt(pow(x,2)+pow(y,2)); PlayerId playerAtLocation = context.getPlayField()[x + CENTRE_OF_VISION][y + CENTRE_OF_VISION]; if (playerAtLocation != null && playerAtLocation.getName().equals("Zombie") && (distance < sdistance ||zombies==false)) { sdistance = distance; zombies=true; TargetZombie=playerAtLocation; } //if (playerAtLocation != null && playerAtLocation.getName().equals("Priest") && distance < 2 &&zombies==false) { //TargetZombie=playerAtLocation; //sdistance=distance; //} }} if (zombies || sdistance<3) { return new Shoot(TargetZombie); } } if (context.getPlayField()[CENTRE_OF_VISION-1][CENTRE_OF_VISION-1]==null){ return Move.NORTHWEST; } else if (context.getPlayField()[CENTRE_OF_VISION][CENTRE_OF_VISION-1]==null){ return Move.NORTH; } else { return Move.WEST; } } } ``` [Answer] # Sokie - JAVA Sokie knows that you are better in packs, so it tries to go the nearest ally he finds. While moving, if he is in danger tries to fight or otherwise tries to run. When he reaches friends, they all fight together until they have no ammo, then try to find nearest bodies to scavenge. ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.abs; import static java.lang.Math.max; import java.awt.Point; import java.util.HashMap; import java.util.Map; public class Sokie implements Player { public static Map<Point, Sokie> myPack = new HashMap<>(); private PlayerContext context; private Move moveDirection; private final int PLAYER_X = 8; private final int PLAYER_Y = 8; private enum DANGER { SAFE(0), PROBABLY_SAFE(1), UNSAFE(2), DANGER(3); private int value; private DANGER(int value) { this.value = value; } } @Override public Action doTurn(PlayerContext context) { Point p = new Point(context.getX(), context.getY()); myPack.put(p, this); this.context = context; int friends = 0; int deadbodyDistance = Integer.MAX_VALUE; Move deadbodyDirection = null; Point deadBodyPosition = null; Move friendsDirection = Move.SOUTHWEST; // Find the closest friend to whom we can move int maxDistance = Integer.MAX_VALUE; for (Sokie bp : myPack.values()) { // Skip ourselves if (bp.context.equals(context)) { continue; } Point pos = bp.getPosition(); int x = pos.x; int y = pos.y; int distance = Math.max(Math.abs(context.getX() - x), Math.abs(context.getY() - y)); if (distance < maxDistance) { if (canMove(context, (int) Math.signum(x), (int) Math.signum(y)) && !isDangerous(context, (int) Math.signum(x), (int) Math.signum(y))) { maxDistance = distance; friendsDirection = Move.inDirection((int) Math.signum(x), (int) Math.signum(y)); } else { if (canMove(context, (int) Math.signum(0), (int) Math.signum(y)) && !isDangerous(context, (int) Math.signum(x), (int) Math.signum(y))) { maxDistance = distance; friendsDirection = Move.inDirection( (int) Math.signum(0), (int) Math.signum(y)); } else if (canMove(context, (int) Math.signum(x), (int) Math.signum(0)) && !isDangerous(context, (int) Math.signum(x), (int) Math.signum(y))) { maxDistance = distance; friendsDirection = Move.inDirection( (int) Math.signum(x), (int) Math.signum(0)); } } } } // Find how many friends we have in close vicinity for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && playerAtLocation.getName().equals("Sokie")) { friends++; } } } // Search for dead bodies for (int y = 1; y < VISION_WIDTH - 1; y++) { for (int x = 1; x < VISION_WIDTH - 1; x++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; // find a dead body if ((playerAtLocation != null) && "DeadBody".equals(playerAtLocation.getName())) { // check adjacent squares for an empty square for (int yy = -1; yy <= +1; yy++) { for (int xx = -1; xx <= +1; xx++) { PlayerId playerNearby = context.getPlayField()[x + xx][y + yy]; if (playerNearby == null) { int distance = max(abs(xx + x - CENTRE_OF_VISION), abs(yy + y - CENTRE_OF_VISION)); if (distance < deadbodyDistance) { deadbodyDistance = distance; deadBodyPosition = getAbsolutePosition( context, x + xx, y + yy); deadbodyDirection = Move.inDirection(xx + x - CENTRE_OF_VISION, yy + y - CENTRE_OF_VISION); } } } } } } } // If we have atleast 2 people close, stay or try to shoot // otherwise move randomly, try to find bodies and packs if (friends >= 2) { // Shoot anybody close if (context.getBullets() > 0) { int distEnemy = VISION_WIDTH; int distZombie = VISION_WIDTH; PlayerId targetEnemy = null; PlayerId targetZombie = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { PlayerId player = context.getPlayField()[x][y]; if (player != null) { int dist = getDistance(x, y); if (player.getName().equals("Zombie")) { if (dist < distZombie) { distZombie = dist; targetZombie = player; } } else if (isEnemy(player.getName()) && dist <= distEnemy) { distEnemy = dist; targetEnemy = context.getPlayField()[x][y]; } } } } if (targetZombie != null && distZombie <= 2) { return new Shoot(targetZombie); } else if (targetEnemy != null && distEnemy <= 5) { return new Shoot(targetEnemy); } } for (Sokie bp : myPack.values()) { // If someone in the pack has ammo, stay if (bp.getAmmo() > 0) { return Move.STAY; } } // If there are bodies close, try to reach them int bodyDistance = deadbodyDistance; if (deadbodyDistance <= 5) { for (Sokie bp : myPack.values()) { int distanceBody = Math.max( Math.abs(deadBodyPosition.x - bp.context.getX()), Math.abs(deadBodyPosition.y - bp.context.getY())); if (deadbodyDistance > distanceBody) { bodyDistance = distanceBody; } } } // If we are not the closest to the body, stay if (bodyDistance < deadbodyDistance) { return Move.STAY; } else { return deadbodyDirection; } } else { // We try to reach our closest friend // If we are in danger, either fight or run if (areWeInDanger(context, PLAYER_X, PLAYER_Y)) { if (context.getBullets() > 0) { int distEnemy = VISION_WIDTH; int distZombie = VISION_WIDTH; PlayerId targetEnemy = null; PlayerId targetZombie = null; for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { PlayerId player = context.getPlayField()[x][y]; if (player != null) { int dist = getDistance(x, y); if (player.getName().equals("Zombie")) { if (dist < distZombie) { distZombie = dist; targetZombie = player; } } else if (isEnemy(player.getName()) && dist <= distEnemy) { distEnemy = dist; targetEnemy = context.getPlayField()[x][y]; } } } } if (targetZombie != null && distZombie <= 2) { return new Shoot(targetZombie); } else if (targetEnemy != null && distEnemy <= 5) { return new Shoot(targetEnemy); } } else { DANGER danger = DANGER.DANGER; Point position = null; for (int i = -1; i < 1; i++) { for (int j = -1; j < 1; j++) { DANGER positionDanger = getDangerLevel(context, PLAYER_X + i, PLAYER_Y + j); if (positionDanger.value < danger.value) { if (canMove(context, PLAYER_X + i, PLAYER_Y + j)) { position = new Point(PLAYER_X + i, PLAYER_Y + j); } } } } if (position != null) { return Move.inDirection(position.x, position.y); } else { return Move.randomMove(); } } } else { return friendsDirection; } } return Move.randomMove(); } private DANGER getDangerLevel(PlayerContext context, int posX, int posY) { DANGER danger = DANGER.SAFE; for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && isEnemy(playerAtLocation.getName())) { int distanceToPlayer = max(abs(x - posX), abs(y - posY)); if (playerAtLocation.getName().equals("Zombie")) { DANGER currentDanger = null; if (distanceToPlayer <= 2) { currentDanger = DANGER.DANGER; } else if (distanceToPlayer <= 5) { currentDanger = DANGER.PROBABLY_SAFE; } else if (distanceToPlayer > 5) { currentDanger = DANGER.SAFE; } if (currentDanger.value > danger.value) { danger = currentDanger; } } else { DANGER currentDanger = null; if (distanceToPlayer <= 5) { currentDanger = DANGER.DANGER; } else if (distanceToPlayer > 5) { currentDanger = DANGER.PROBABLY_SAFE; } if (currentDanger.value > danger.value) { danger = currentDanger; } } } } } return danger; } private boolean isDangerous(PlayerContext context, int posX, int posY) { for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && isEnemy(playerAtLocation.getName())) { int distanceToPlayer = max(abs(x - posX), abs(y - posY)); if (playerAtLocation.getName().equals("Zombie")) { if (distanceToPlayer <= 2) { return true; } } else { if (distanceToPlayer <= 5) { return true; } } } } } return false; } // calculates absolute position, from XY in our field of view private Point getAbsolutePosition(PlayerContext context, int relativeX, int relativeY) { int playerX = context.getX(); int playerY = context.getY(); return new Point(playerX + (relativeX - PLAYER_X), playerY + (relativeY - PLAYER_Y)); } // Gets distance on the field private int getDistance(int x, int y) { return Math.max(Math.abs(PLAYER_X - x), Math.abs(PLAYER_Y - y)); } public int getAmmo() { return context.getBullets(); } public Point getPosition() { Point p = new Point(context.getX(), context.getY()); return p; } public Move getMoveDirection() { return moveDirection; } // Quick check for dangers around us private boolean areWeInDanger(PlayerContext context, int posX, int posY) { for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && isEnemy(playerAtLocation.getName())) { int distanceToPlayer = max(abs(x - posX), abs(y - posY)); if (playerAtLocation.getName().equals("Zombie")) { if (distanceToPlayer <= 2) { return true; } } else { if (distanceToPlayer <= 5) { return true; } } } } } return false; } private boolean canMove(PlayerContext context, int posX, int posY) { PlayerId playerAtLocation = context.getPlayField()[posX][posY]; if (playerAtLocation == null) { return true; } else { return false; } } private boolean isEnemy(String name) { switch (name) { case "Sokie": case "DeadBody": case "GordonFreeman": case "EmoWolfWithAGun": case "HuddleWolf": case "ThePriest": case "Shotguneer": case "StandStill": return false; default: return true; } } } ``` [Answer] # Bee - Python Second entry, but I thought it would be fun to try something else out and in a different language. * Now the Bees will avoid moving to the same spot. * More 'Pythonic' now * Optimized torus movement so the bees can get to the queen quicker (thanks James for allowing access to the board size) Bees prefer to be together, so they designate one of the surviving Bees as the Queen Bee and swarm toward her. They will sting opponents on their way to her, preferring zombie flesh over human. ``` from zombie import Player, Move, Shoot, PlayerRegistry, Constants friends = ['Bee','Waller','DeadBody','ThePriest','StandStill','Vortigaunt','EmoWolfWithAGun'] MID = Constants.CENTRE_OF_VISION BOARDSIZE = 1 sign = lambda x: (1, -1)[x<0] isZombie = lambda player: player and player.getName() is "Zombie" isEnemy = lambda player: player and player.getName() not in friends isWall = lambda player: player and (player.getName() is "DeadBody" or player.getName() is "StandStill") distance = lambda x1,y1,x2,y2: max(distance1d(x1,x2), distance1d(y1,y2)) distance1d = lambda x1,x2: min(abs(x1-x2), BOARDSIZE - abs(x1-x2)) Bees = {} Shot = set() MoveTo = set() def getDirection(x1, x2): diff = x1 - x2 if abs(diff) > (BOARDSIZE // 2): return sign(diff) return -sign(diff) class Bee(Player): Queen = None QueenBeePosition = None X = Y = ID = 0 LastTurn = -1 def doTurn(self, context): global BOARDSIZE self.ID = context.id.number self.X = context.x self.Y = context.y BOARDSIZE = context.boardSize self.setQueenBee(context.gameClock) action = self.sting(context) if action: return action return self.moveToQueenBee(context) def setQueenBee(self, turn): if turn != Bee.LastTurn: Bee.LastTurn = turn MoveTo.clear() # Clear the move set on new turn Bees[self.ID] = turn # Report In if not Bee.Queen or (Bee.Queen and Bees[Bee.Queen] < turn - 1): Bee.Queen = self.ID Bee.QueenBeePosition = (self.X, self.Y) def moveToQueenBee(self, context): if self.ID == Bee.Queen: return Move.randomMove() dist = distance(Bee.QueenBeePosition[0], Bee.QueenBeePosition[1], self.X, self.Y) if dist < 4: return Move.randomMove() signX = getDirection(self.X, Bee.QueenBeePosition[0]) signY = getDirection(self.Y, Bee.QueenBeePosition[1]) walls = 0 field = context.playField for (deltaX, deltaY) in [(signX,signY),(signX,0),(0,signY),(signX,-signY),(-signX,signY)]: player = field[MID + deltaX][MID + deltaY] if isWall(player): walls += 1 if not player: point = frozenset([self.X+deltaX,self.Y+deltaY]) if point not in MoveTo: MoveTo.add(point) return Move.inDirection(deltaX,deltaY) if walls > 2: return Move.randomMove() return Move.STAY def sting(self, context): if context.bullets < 1: return field = context.playField closestZombie,closestPlayer = None,None closestZombieDist,bestDist = 3,5 for x in range(MID - 5, MID + 5): for y in range(MID - 5, MID + 5): player = field[x][y] if player and not isWall(player) and player not in Shot: dist = distance(MID,MID,x,y) if isZombie(player) and dist < closestZombieDist: closestZombieDist = dist closestZombie = player elif isEnemy(player) and dist < bestDist: bestDist = dist closestPlayer = player if closestZombie: Shot.add(closestZombie) return Shoot(closestZombie) if closestPlayer: Shot.add(closestPlayer) return Shoot(closestPlayer) PlayerRegistry.registerPlayer("Bee", Bee()) ``` [Answer] ## Mr. Assassin His parents aren't very nice people. He has no qualms killing but won't if he thinks you will help him live longer. He treats everyone as if they are special and then disgards that and ranks you by how close he wants you, how much he wants you dead, and important you are to the current situation. As I know alot of this is hidden in here I'll explain some. He usually never kill the guys who might kill his threats before he has to as they are not his targets. He will feed off some who never shoot. With one exception, he kills you if you currently kill him. He prefers walled in locations without that being forced into the code. He is Fox phobic and a Coward coward. He cuddles up with Huddlewolves and walls up with Wallers. He currently moves toward groupers (like Sokie even though Sokie shoots him mercilessly). Nash should love him as his priorites make a game theorist cry. His customers, however, seem to be very zenophobic having him kill priests, aliens, and newcomers (though he mmight pardon you friday or saturday if you don't kill him... sunday is too late). Sorry if I am forgetting anyone else. ``` package player; import zombie.*; import static zombie.Constants.*; //import static java.lang.Math.*; public class Jack implements Player { @Override public Action doTurn(PlayerContext context) { int[] Ideal = {1,5,8,7,2,2,7,2,1,5,1,2,1,1,7,2,7,7,7,0,2,3,1,7}; int[] Threat = {1,4,8,8,1,1,7,1,2,2,2,1,2,0,6,2,6,6,6,1,1,2,6,6}; int[] Importance = {1,2,4,4,1,1,1,1,3,1,3,1,3,3,1,2,1,1,1,10,2,2,3,2}; PlayerId Target = context.getId(); int[][] Bob = {{800-2*Math.max(0,context.getGameClock()),400-Math.max(0,context.getGameClock()),800-Math.max(0,context.getGameClock())},{0,0,0},{0,0,0}}; double maxDanger=0; int zombies=0; for (int x = -8; x < +8; x++) { for (int y = -8; y < +8; y++) { PlayerId playerAtLocation = context.getPlayField()[x + CENTRE_OF_VISION][y + CENTRE_OF_VISION]; if (playerAtLocation != null && x*y+x+Math.abs(y) != 0){ if (Math.abs(x)*Math.abs(y)==1 || Math.abs(x) + Math.abs(y)==1){ Bob[x+1][y+1]-=100000; } int dist = Math.max(Math.abs(x),Math.abs(y)); int Ident = Dats(playerAtLocation); double Danger = (Threat[Ident]-dist)*Importance[Ident]; if(Ident==1 && dist<Threat[Ident]){ zombies++; if(context.getPlayField()[TFSAE(x)-1 + CENTRE_OF_VISION][TFSAE(y) -1+ CENTRE_OF_VISION]!=null){ Danger=0; } else if(dist==2){Danger+=4;} } if(Danger>maxDanger && dist<6){ maxDanger=Danger; Target=playerAtLocation; } if(dist != Ideal[Ident]){ Bob[TFSAE(x)][TFSAE(y)] += Math.round(200*Importance[Ident]/(dist-Ideal[Ident])); if(TFSAE(x) ==1) { Bob[0][TFSAE(y)] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); Bob[2][TFSAE(y)] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); } else { Bob[1][TFSAE(y)] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); } if(TFSAE(y) ==1) { Bob[TFSAE(x)][0] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); Bob[TFSAE(x)][2] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); } else { Bob[TFSAE(x)][1] += Math.round(100*Importance[Ident]/(dist-Ideal[Ident])); } } } }} if (context.getBullets()>1 && maxDanger>0){ return new Shoot(Target); } else if (context.getBullets()==1 && zombies>3){ return new Shoot(context.getId()); } else if (context.getBullets()==1 && maxDanger>7){ return new Shoot(Target); } int Xmax=0; int Ymax=0; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { if (Bob[x][y]>=Bob[Xmax][Ymax]){ Xmax=x; Ymax=y; } }} return Move.inDirection(Xmax-1, Ymax-1); } private int Dats (PlayerId WhoDat){ switch (WhoDat.getName()){ case "DeadBody": return 0; case "Zombie": return 1; case "Fox": return 2; case "Coward": return 3; case "Shotguneer": return 4; case "HuddleWolf": return 5; case "Sokie": return 6; case "GordonFreeman": return 7; case "Vortigaunt": return 8; case "SuperCoward": return 9; case "StandStill": return 10; case "JohnNash": return 11; case "MoveRandomly": return 12; case "Waller": return 13; case "HideyTwitchy": return 14; case "Bee": return 15; case "ZombieHater": return 16; case "ZombieRightsActivist": return 17; case "Gunner": return 18; case "EmoWolfWithAGun": return 19; case "Jack": return 20; case "SOS": return 21; case "SunTzu": return 22; default: return 23; } } private int TFSAE(int TBN){ if(TBN==0){return 1; } else if(TBN>0){return 2;} return 0; } } ``` [Answer] # S.O.S. (Shoot on Sight) ``` package player; import zombie.*; import static zombie.Constants.*; import static java.lang.Math.*; public class SOS implements Player { @Override public Action doTurn(PlayerContext context) { if (context.getBullets() > 0) { for (PlayerId player: context.shootablePlayers()) { switch(player.getName()) { case "Gunner": case "Zombie": case "ZombieRightsActivist": return new Shoot(player); default: break; } } } Move bestDirection = Move.NORTH; int bestDistance = Integer.MAX_VALUE; for (int x = 0; x < VISION_WIDTH; x++) { for (int y = 0; y < VISION_WIDTH; y++) { int distance = max(abs(x - CENTRE_OF_VISION), abs(y - CENTRE_OF_VISION)); PlayerId playerAtLocation = context.getPlayField()[x][y]; if (playerAtLocation != null && !(playerAtLocation.getName().equals("Zombie")) && !(playerAtLocation.getName().equals("Gunner")) && !(playerAtLocation.getName().equals("ZombieRightsActivist")) && !(playerAtLocation.getName().equals("ZombieHater")) && !(playerAtLocation.equals(context.getId())) && distance < bestDistance) { bestDistance = distance; bestDirection = Move.inDirection(x - CENTRE_OF_VISION, y -CENTRE_OF_VISION); } } } return bestDirection; } } ``` [Answer] # John Nash - Javascript The decision whether to shoot someone is essentially the prisoner's dilemma. If you assume that your adversary has already made up their mind, then the best option is always to shoot them. However, if your adversary will decide what to do based on what they think you'll do, then the best option is to leave them be, and they'll probably do the same. John Nash only shoots "chumps" - adversaries who have already made up their minds. That is, he shoots adversaries that always shoot, or adversaries that never shoot. He leaves adversaries alone if they have more complicated logic. When he's not shooting, he's scavenging for bullets or heading South. ``` var Constants = Packages.zombie.Constants var Shoot = Packages.zombie.Shoot var Move = Packages.zombie.Move var Player = Packages.zombie.Player var PlayerRegistry = Packages.zombie.PlayerRegistry function mkSet() { var s = {} for (var i = 0; i < arguments.length; i++) { s[arguments[i]] = true } return s } var chumps = mkSet( "GordonFreeman", "HideyTwitchy", "Gunner", "MoveRandomly", "StandStill", "ThePriest", "Vortigaunt", "ZombieHater", "ZombieRightsActivist", "Bee", "Zombie", "SuperCoward" ) function dist(x, y) { return Math.max(Math.abs(x - Constants.CENTRE_OF_VISION), Math.abs(y - Constants.CENTRE_OF_VISION)) } function range(width, offset) { var x = [] for (var i = -width; i <= width; i++) { for (var j = -width; j <= width; j++) { if (i != 0 || j != 0) x.push([i + offset,j + offset]) } } return x } function JohnNash() { var looted = {} this.doTurn = function(context) { var field = context.getPlayField() // Save looted bodies range(1, Constants.CENTRE_OF_VISION).forEach(function(p) { var x = p[0], y = p[1] var playerId = field[x][y] if (playerId && playerId.getName() == "DeadBody") { looted[playerId] = true } }) // Shoot any nearby chumps if (context.getBullets() > 0) { var shootableIterator = context.shootablePlayers().iterator(); while (shootableIterator.hasNext()) { var shootable = shootableIterator.next() if (chumps[shootable.getName()]) return new Shoot(shootable) } } // Helper function - everyone loves closures function moveTowards(x, y) { var tryMove = Move.inDirection( x - Constants.CENTRE_OF_VISION, y - Constants.CENTRE_OF_VISION ) if (!(field[Constants.CENTRE_OF_VISION + tryMove.x][Constants.CENTRE_OF_VISION + tryMove.y])) { return tryMove } else { // If your path is blocked, take a random move return Move.randomMove() } } // Loot var bestX, bestY, bestDist = Infinity range(Constants.VISION_RANGE, Constants.CENTRE_OF_VISION).forEach(function(p) { var x = p[0], y = p[1] var playerId = field[x][y] if (playerId && playerId.getName() == "DeadBody" && !looted[playerId] && dist(x, y) < bestDist) { bestDist = dist(x,y) bestX = x bestY = y } }) if (bestDist < Infinity) { return moveTowards(bestX, bestY) } else return Move.SOUTH } } PlayerRegistry.registerPlayer("JohnNash", new Player(new JohnNash())) ``` [Answer] SunTzu tries to be tactical, and find safe spots on the grid to move to. But as it stands, he's just a work in progress atm. > > “Thus we may know that there are five essentials for victory: > > 1. He will win who knows when to fight and when not to fight. > > 2. He will win who knows how to handle both superior and inferior forces. > > 3. He will win whose army is animated by the same spirit throughout all its ranks. > > 4. He will win who, prepared himself, waits to take the enemy unprepared. > > 5. He will win who has military capacity and is not interfered with by the sovereign.” > > > ``` package player; import static zombie.Constants.CENTRE_OF_VISION; import static zombie.Constants.SHOOT_RANGE; import static zombie.Constants.VISION_RANGE; import java.awt.Point; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; import zombie.Action; import zombie.Move; import zombie.Player; import zombie.PlayerContext; import zombie.PlayerId; import zombie.Shoot; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Table.Cell; import com.google.common.collect.TreeBasedTable; public class SunTzu implements Player { private TreeBasedTable<Integer, Integer, Integer> dangerZone; private final static int IN_ENEMY_RANGE = 5; private static final int IN_LOOTED_RANGE = 4; private static final int FULL_MAGAZINE = 10; private static final int IN_ZOMBIE_RANGE = 10; private static final int NUM_PLAYERS = 40; private LinkedHashSet<Point> safeSpots; private PlayerId[][] localAreas; private Set<PlayerId> looted= new HashSet<>(50*NUM_PLAYERS); private int ammo; PlayerId biggestThreat; private Set<PlayerId> shootable; private PlayerId myId; @SuppressWarnings("unused") @Override public Action doTurn(PlayerContext context) { ammo = context.getBullets(); int gameTurn =context.getGameClock(); int boardSize = context.getBoardSize(); myId = context.getId(); localAreas = context.getPlayField(); dangerZone = TreeBasedTable.create(); shootable = context.shootablePlayers(); updateAdjacentBodyState(); for (int x = CENTRE_OF_VISION - SHOOT_RANGE; x <= CENTRE_OF_VISION + SHOOT_RANGE; x++) { for (int y = CENTRE_OF_VISION - SHOOT_RANGE; y <= CENTRE_OF_VISION + SHOOT_RANGE; y++) { PlayerId playerId = localAreas[x][y]; if (playerId != null) { calculateDangerZone(x,y,playerId); } } } Action myAction = null; Iterator<Point> pIt = safeSpots.iterator(); if (ammo>0&&!pIt.hasNext()&&getBiggestThreat()!=null) { return new Shoot(getBiggestThreat()); } else if (pIt.hasNext()){ Point p=pIt.next(); return Move.inDirection(p.x, p.y); }else{ return Move.randomMove(); } } private PlayerId getBiggestThreat() { return biggestThreat==null?shootable.iterator().next():biggestThreat; } public void setBiggestThreat(PlayerId biggestThreat) { this.biggestThreat = biggestThreat; } private void updateAdjacentBodyState() { for( int x = -1; x <= 1; x++ ) { for( int y = -1; y <= 1; y++ ) { PlayerId adjPlayerId = localAreas[CENTRE_OF_VISION+x][CENTRE_OF_VISION+y]; if( adjPlayerId != null && (!looted.contains(adjPlayerId) && adjPlayerId.getName().equals("DeadBody"))) { looted.add(adjPlayerId); } } } } private void calculateDangerZone(int x, int y, PlayerId playerId) { deriveDanger(playerId, x, y); safeSpots = getSafeSpots(); } @SuppressWarnings("rawtypes") private LinkedHashSet<Point> getSafeSpots() { LinkedHashSet<Point> safeSpots = new LinkedHashSet<>(); TreeSet<Cell> spots = new TreeSet<>(cellValueComparator()); for (Cell<Integer, Integer, Integer> cell : dangerZone.cellSet()) { spots.add(cell); } final Cell safeCell = spots.isEmpty()?null:Collections.min(spots,cellValueComparator()); Function<Cell,Point> pointFromCell = new Function<Cell,Point>() { public Point apply(final Cell arg0) {return new Point((int)arg0.getRowKey(), (int)arg0.getColumnKey());}; }; if (safeCell!=null) { safeSpots.addAll(Collections2.transform( Collections2.filter(spots, sameCellValuePredicate(safeCell)), pointFromCell)); } return safeSpots; } @SuppressWarnings("rawtypes") private Predicate<Cell> sameCellValuePredicate(final Cell safeCell) { return new Predicate<Cell>() { @Override public boolean apply(Cell arg0) { return (arg0.getValue() == safeCell.getValue()); } }; } @SuppressWarnings("rawtypes") private Comparator<Cell> cellValueComparator() { return new Comparator<Cell>() { @Override public int compare(Cell o1, Cell o2) { return (int)o1.getValue()- (int)o2.getValue(); } }; } private void deriveDanger(PlayerId playerId, int x, int y) { switch (playerId.getName()) { case "Gunner": case "Fox": case "HideyTwitchy": case "Shotguneer": case "ZombieRightsActivist": case "ZombieHater": case "SuperCoward": case "Sokie": updateDangerZoneWithEnemy(x, y); break; case "DeadBody": case "Zombie": updateDangerZoneWithBodies(x,y); break; default: break; } } private void updateDangerZoneWithBodies(int x, int y) { int dangerLevel=0; if(localAreas[x][y].getName().equalsIgnoreCase("Zombie")){ dangerLevel = IN_ZOMBIE_RANGE; } else if(looted.contains(localAreas[x][y])){ dangerLevel = IN_LOOTED_RANGE; }else{ dangerLevel = Math.min(-1,-FULL_MAGAZINE+ammo); } for (int i = x-1; i < x+1; i++) { for (int j = y-1; j < y+1; j++) { Integer previousDangerLevel = dangerZone.get(i, j) ; int currentDangerLevel = dangerLevel; if (previousDangerLevel != null) { currentDangerLevel = previousDangerLevel+dangerLevel; } dangerZone.put(x, y, currentDangerLevel); } } } private void updateDangerZoneWithEnemy(int x, int y) { int dangerLevel = IN_ENEMY_RANGE; playerShieldFound: for (int i = Math.max(x-SHOOT_RANGE, 0); i < Math.min(SHOOT_RANGE+x,VISION_RANGE); i++) { for (int j = Math.max(y-SHOOT_RANGE, 0); j < Math.min(SHOOT_RANGE+y,VISION_RANGE); j++) { int cardinalityFactor = (i+1)+(j+1); Integer previousDangerLevel = dangerZone.get(i, j); int currentDangerLevel = dangerLevel*cardinalityFactor; PlayerId enemy = localAreas[x][y]; PlayerId target = localAreas[i][j]; if (target!=null) { if (target != enemy) { break playerShieldFound; } else if (target.equals(myId)) { setBiggestThreat(enemy); } } if (previousDangerLevel != null) { currentDangerLevel = Math.max(previousDangerLevel, dangerLevel); } dangerZone.put(i, j, currentDangerLevel ); } } } } ``` Current issues are that the dangerzone is not created properly, and I don't think biggestThreat is being populated correctly. [Answer] # Tyzoid - my somewhat dumb robot ``` package player; import java.util.ArrayList; import zombie.Action; import zombie.Move; import zombie.Player; import zombie.PlayerContext; import zombie.PlayerId; import zombie.Shoot; public class Tyzoid implements Player { private static final int minPathDistance = 7; private static final int pathLength = 10; private static final boolean debug = false; private static final int max_iterations = 5000; private int current_iterations = 0; private class Situation { public int hostiles = 0; public int scores[][] = new int[21][21]; public ArrayList<Coordinate> path = new ArrayList<Coordinate>(); public int distanceToHostile = 10; public Coordinate nearestHostile = new Coordinate(0,0); public boolean seriousHostile = false; // Minimum path score allowed to move under normal circumstances public int pathScore = -40; public int bulletsLeft = 0; public Situation(){ path.add(new Coordinate(10,10)); } } public class Coordinate { public int x = 0; public int y = 0; public Coordinate(int x, int y) { this.x = x; this.y = y; } } @Override public Action doTurn(PlayerContext context) { try { Situation currentSituation = this.evaluateSituation(context); return this.makeDecision(currentSituation, context); } catch (Exception e) { if (debug) e.printStackTrace(); return Move.STAY; } } private Situation evaluateSituation(PlayerContext context) { Situation situation = new Situation(); for (int i = 0; i < 21; i++) { for (int j = 0; j < 21; j++) { situation.scores[i][j] = -3; } } situation.bulletsLeft = context.getBullets(); PlayerId[][] visibleBoard = context.getPlayField(); for (int bx = 0; bx < visibleBoard.length; bx++) { for (int by = 0; by < visibleBoard[bx].length; by++) { if (visibleBoard[bx][by] == null) { continue; } if (this.isHostile(visibleBoard[bx][by].getName(), false)) { situation.hostiles++; this.hostileDetected(situation, bx, by, context); } else if (visibleBoard[bx][by].getName().equals("DeadPlayer")) { this.friendlyDetected(situation, bx, by); // OVER 9000!!! (there's an obstacle) situation.scores[bx + 2][by + 2] = -9001; } } } return situation; } private Action makeDecision(Situation currentSituation, PlayerContext context) { if ((currentSituation.distanceToHostile < 3 || currentSituation.seriousHostile) && currentSituation.bulletsLeft > 0){ // Shoot! (And possibly create opening!) PlayerId[][] visibleBoard = context.getPlayField(); if (debug) System.out.println("Shooting!"); return new Shoot(visibleBoard[currentSituation.nearestHostile.x-2][currentSituation.nearestHostile.y-2]); } if (currentSituation.hostiles > 6) { // Code red: get out of here! Trample over hostiles if necessary. // Guarantee path will generate, without hitting anything dead. currentSituation.pathScore = -9000; } findSafePath(currentSituation); Coordinate next = currentSituation.path.get(0); if (next.x == 10 && next.y == 10){ if (debug) System.out.println("Staying Put."); return Move.STAY; } if (debug) System.out.println("Moving!"); return Move.inDirection(next.x-2, next.y-2); } private void findSafePath(Situation currentSituation) { int x = 10; int y = 10; // Since we have a finite number of tiles, and we won't consider // backtracking, Let's consider every possible path to optimize the // safest path. current_iterations = 0; pathIteration(currentSituation, new ArrayList<Coordinate>(), x, y, 0); } private void pathIteration(Situation s, ArrayList<Coordinate> currentPath, int x, int y, int steps) { // If we've reached an end state, // Update situation if the currentPath has a higher (less negative) score than the current path. // As well as if we moved the minimum amount // Compute Score int score = 0; for (Coordinate c : currentPath) { score += s.scores[c.x][c.y]; } int distanceTraveled = (Math.abs(10 - x) + Math.abs(10 - y)); // Return if the currentPath has a lower score than the current path. if (score < s.pathScore || s.pathScore == 0 || current_iterations > max_iterations) return; if (debug) System.out.println("debug: step " + steps + " (" + score + " : " + s.pathScore + ") Distance: " + distanceTraveled); // Prevent my algorithm from blowing up the whole works current_iterations++; if (steps == pathLength) { if (distanceTraveled >= minPathDistance) { if (score > s.pathScore) { s.path = currentPath; s.pathScore = score; } } return; } ArrayList<Coordinate> searched = new ArrayList<Coordinate>(); for (int index = 0; index < 9; index++){ int minx = 0, miny = 0; int minscore = -1000; for (int i = -1; i < 2; i++) { for (int j = -1; j < 2; j++) { if (searched.contains(new Coordinate(x+i, y+j)) || currentPath.contains(new Coordinate(x+i, y+j))){ continue; } if (steps > 1){ Coordinate c0 = currentPath.get(steps-2); Coordinate c1 = currentPath.get(steps-1); int dx = c1.x-c0.x; int dy = c1.y-c0.y; // Disable turning more than 45 degrees if (dy != j && dx != i) continue; } if (s.scores[x+i][y+j] > minscore){ minx = x+i; miny = y+j; minscore = s.scores[x+i][y+j]; } } } if (!currentPath.contains(new Coordinate(minx, miny))) { ArrayList<Coordinate> newPath = (ArrayList<Coordinate>) currentPath.clone(); newPath.add(new Coordinate(minx, miny)); pathIteration(s, newPath, minx, miny, steps + 1); } searched.add(new Coordinate(minx, miny)); } } private void hostileDetected(Situation seriousSituation, int bx, int by, PlayerContext context) { boolean verySerious = false; if (this.isHostile(context.getPlayField()[bx][by].getName(), true) && context.shootablePlayers().contains(context.getPlayField()[bx][by])){ seriousSituation.seriousHostile = true; verySerious = true; } for (int i = -4; i < 5; i++) { for (int j = -4; j < 5; j++) { // Prevent from overflowing the path matrix. if (i + bx + 2 < 0 || i + bx + 2 > 20 || j + by + 2 < 0 || j + by + 2 > 20) continue; int separationLevels = Math.max(Math.abs(i), Math.abs(j)); seriousSituation.scores[bx + i + 2][by + j + 2] += separationLevels*2 - 10; } } int distanceToHostile = Math.abs(10 - (bx + 2)) + Math.abs(10 - (by + 2)); if ((distanceToHostile < seriousSituation.distanceToHostile && !seriousSituation.seriousHostile) || verySerious){ seriousSituation.nearestHostile = new Coordinate(bx + 2, by + 2); seriousSituation.distanceToHostile = distanceToHostile; } } private void friendlyDetected(Situation lessBleakSituation, int bx, int by) { for (int i = -4; i < 5; i++) { for (int j = -4; j < 5; j++) { // Prevent overflowing the path matrix. if (i + bx < 0 || i + bx > 20 || j + by < 0 || j + by > 20) continue; int separationLevels = Math.max(Math.abs(i), Math.abs(j)); lessBleakSituation.scores[bx + i + 2][by + j + 2] += 4 - separationLevels; } } } private boolean isHostile(String name, boolean serious){ // Generated from a list of players who shot me during testing. // If anyone adds me as a 'friendly', I'd be happy to reciprocate. switch(name){ case "Bee": case "Coward": case "Fox": case "Gunner": case "HideyTwitchy": case "Sokie": case "ZombieHater": case "ZombieRightsActivist": return true; default: return (!serious && name.equals("Zombie")); // Zombies don't shoot } } } ``` ]
[Question] [ It seems that simple changes to a C++ file, especially with templates, can generate pages of errors. This contest is to see what the largest "bang of the buck" is, that is the more verbose error output with the smallest change to the source code (1 character addition). Because other languages are more sane, this will be limited to C++ and gcc version 4.x. Rules 1. Original source file must compile with gcc 4.9.2 to object code without error. 2. One ASCII character is added to source code to create a typo, increasing file size by 1 byte. 3. Compiler is run with default options. Necessary options like `-c` and `-std=c++11` are allowed, options like `-Wall` are not. 4. Metric is ``` number of bytes of generated error messages ----------------------------------------------------------------------- (bytes of source code with typo) (length of filename passed to compiler) ``` 5. Answers will be validated with <http://ideone.com/> C++ 4.9.2. Example: Filename is `a.cpp`, which is 5 bytes long. ``` int foo(); ``` Working Compilation ``` gcc -c a.cpp ``` Corrupted source code: ``` in t foo(); ``` Failing Compilation ``` $ gcc -c a.cpp a.cpp:1:1: error: ‘in’ does not name a type in t foo(); ^ $ gcc -c a.cpp |& -c wc 64 $ wc -c a.cpp 12 a.cpp ``` Score: 64/12/5 = **1.0666** Better attempt: Insert `{` between parens of `foo()` ``` $ gcc -c a.cpp |& wc -c 497 ``` New score: 497/12/5 = **8.283** Good Luck! UPDATE I encourage people to ignore the recursive implementation. That technically wins but is not in the spirit of the contest. UPDATE 2 As many people have noted, the contest probably would have been more interesting if the C pre-processor was not allowed. So I would like to encourage people to post solutions that do not use pre-processor commands at all. That implies no use of any header files at all, since `#include` is not allowed! As far as using IDEONE to validate, you are allowed to either use the IDEONE output directly (and the source name as `prog.cpp`), or you can run the IDEONE output through a global search and replace (`s/prog.cpp/a.cc/` for example) and pretend that you were able to set the file name directly. UPDATE 3 As people pointed out, Ideone is a little too restrictive, requiring linkage not just object file creation. As this contest is purely in the name of fun, please be honest and specify what you used to get your score. Either use ideone, or use the most vanilla build (all defaults) of gcc 4.9.2 as you can muster. The contest is intended to bring awareness to the awfulness of C++ error messages. [Answer] **gcc 4.5.2, Score: 8579.15** (or **14367.49** for filename "a.C", may update later) Original file, 29 bytes, compiles clean (a.cpp): ``` #if 0 #include"a.cpp" #endif ``` Modified file, 30 bytes: ``` #iff 0 #include"a.cpp" #endif ``` Errors: ``` $ gcc -c a.cpp 2>&1 | wc -c 1286873 ``` Score: 1286873 / (30 \* 5) = 8579.15 Head and tail of error output: ``` a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0: a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0, from a.cpp:2: a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2: a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2, from a.cpp:2: a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2, from a.cpp:2, from a.cpp:2: a.cpp:1:2: error: invalid preprocessing directive #iff In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2, from a.cpp:2, from a.cpp:2, from a.cpp:2: ... And so on, backing out with second error after max include depth: a.cpp:3:2: error: #endif without #if In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2, from a.cpp:2, from a.cpp:2: a.cpp:3:2: error: #endif without #if In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2, from a.cpp:2: a.cpp:3:2: error: #endif without #if In file included from a.cpp:2:0, from a.cpp:2, from a.cpp:2: a.cpp:3:2: error: #endif without #if In file included from a.cpp:2:0, from a.cpp:2: a.cpp:3:2: error: #endif without #if In file included from a.cpp:2:0: a.cpp:3:2: error: #endif without #if a.cpp:3:2: error: #endif without #if ``` Note: - If `.C` ends up [qualifying as a valid extension](https://codegolf.stackexchange.com/questions/51659/1-character-typo-generating-most-error-messages-from-c-compilation/51671#comment122734_51659) then score is 1,206,869 / (28 \* 3) = 14,367.49. - If Dennis' suggested second #include is added, file name "a.cpp", score is 80,797,292,934 / (46 \* 5) = 351,292,578.97 [Answer] # gcc 4.9.2, score: ~~222,898,664~~ 663,393,783 This is heavily based on [@JasonC's answer](https://codegolf.stackexchange.com/a/51671), but [he said](https://codegolf.stackexchange.com/questions/51659/1-character-typo-generating-most-error-messages-from-c-compilation/51671#comment122746_51671) he didn't want to take credit for this improvement. The error output of the code below is 126,044,818,789 bytes long. The score should be much higher in theory (and tend to infinity as the number of include statements increases), but it decreases in practice by adding more include statements. ### Original file (37 bytes) ``` /*# #include"w.cpp" #include"w.cpp"*/ ``` ``` $ gcc -c w.cpp $ ``` ### Modified file (38 bytes) ``` / *# #include"w.cpp" #include"w.cpp"*/ ``` ``` $ gcc -c w.cpp w.cpp:2:2: error: stray ‘#’ in program *# ^ In file included from w.cpp:3:0: w.cpp:2:2: error: stray ‘#’ in program *# ^ In file included from w.cpp:3:0, from w.cpp:3: w.cpp:2:2: error: stray ‘#’ in program *# ^ In file included from w.cpp:3:0, from w.cpp:3, from w.cpp:3: w.cpp:2:2: error: stray ‘#’ in program *# ^ In file included from w.cpp:3:0, from w.cpp:3, from w.cpp:3, from w.cpp:3: ⋮ w.cpp:2:2: error: stray ‘#’ in program *# ^ w.cpp:3:0: error: #include nested too deeply #include"w.cpp" ^ w.cpp:4:0: warning: extra tokens at end of #include directive #include"w.cpp"*/ ^ w.cpp:4:0: error: #include nested too deeply w.cpp:2: confused by earlier errors, bailing out The bug is not reproducible, so it is likely a hardware or OS problem. ``` [Answer] **gcc, 4.9.2, Score: 22.2** Original file: 0 bytes (a.cpp) Compiles clean: ``` $ gcc -c a.cpp |& wc -c 0 ``` Modified file: ``` ( ``` Errors: ``` $ gcc -c a.cpp |& wc -c 111 ``` Score 111/1/5 = **22.2** [Answer] # 11,126.95 ~~9,105.44~~ ~~2,359.37~~ ~~1,645.94~~ ~~266.88~~ points More preprocessor abuse! This time, we're making the standard library cry. Without typo: ``` #define typedf #include<fstream> ``` With typo: ``` #define typedef #include<fstream> ``` Errors: ``` In file included from /usr/include/c++/4.9/iosfwd:39:0, from /usr/include/c++/4.9/ios:38, from /usr/include/c++/4.9/istream:38, from /usr/include/c++/4.9/fstream:38, from a.C:2: /usr/include/c++/4.9/bits/stringfwd.h:62:33: error: aggregate ‘std::basic_string<char> std::string’ has incomplete type and cannot be defined typedef basic_string<char> string; ^ /usr/include/c++/4.9/bits/stringfwd.h:68:33: error: aggregate ‘std::basic_string<wchar_t> std::wstring’ has incomplete type and cannot be defined typedef basic_string<wchar_t> wstring; ^ /usr/include/c++/4.9/bits/stringfwd.h:78:34: error: aggregate ‘std::basic_string<char16_t> std::u16string’ has incomplete type and cannot be defined typedef basic_string<char16_t> u16string; ^ /usr/include/c++/4.9/bits/stringfwd.h:81:34: error: aggregate ‘std::basic_string<char32_t> std::u32string’ has incomplete type and cannot be defined typedef basic_string<char32_t> u32string; ^ In file included from /usr/include/wchar.h:36:0, from /usr/include/c++/4.9/cwchar:44, from /usr/include/c++/4.9/bits/postypes.h:40, from /usr/include/c++/4.9/iosfwd:40, from /usr/include/c++/4.9/ios:38, from /usr/include/c++/4.9/istream:38, from /usr/include/c++/4.9/fstream:38, from a.C:2: /usr/include/stdio.h:48:25: error: aggregate ‘_IO_FILE FILE’ has incomplete type and cannot be defined typedef struct _IO_FILE FILE; ^ /usr/include/stdio.h:64:25: error: aggregate ‘_IO_FILE __FILE’ has incomplete type and cannot be defined typedef struct _IO_FILE __FILE; ^ In file included from /usr/include/c++/4.9/cwchar:44:0, from /usr/include/c++/4.9/bits/postypes.h:40, from /usr/include/c++/4.9/iosfwd:40, from /usr/include/c++/4.9/ios:38, from /usr/include/c++/4.9/istream:38, from /usr/include/c++/4.9/fstream:38, from a.C:2: /usr/include/wchar.h:106:9: error: ‘__mbstate_t’ does not name a type typedef __mbstate_t mbstate_t; ^ /usr/include/wchar.h:151:38: error: ‘size_t’ is not a type const wchar_t *__restrict __src, size_t __n) ^ /usr/include/wchar.h:159:38: error: ‘size_t’ is not a type const wchar_t *__restrict __src, size_t __n) ^ /usr/include/wchar.h:166:63: error: ‘size_t’ is not a type extern int wcsncmp (const wchar_t *__s1, const wchar_t *__s2, size_t __n) ^ /usr/include/wchar.h:176:4: error: ‘size_t’ is not a type size_t __n) __THROW; ^ In file included from /usr/include/wchar.h:180:0, from /usr/include/c++/4.9/cwchar:44, from /usr/include/c++/4.9/bits/postypes.h:40, from /usr/include/c++/4.9/iosfwd:40, from /usr/include/c++/4.9/ios:38, from /usr/include/c++/4.9/istream:38, from /usr/include/c++/4.9/fstream:38, from a.C:2: /usr/include/xlocale.h:42:9: error: ‘__locale_t’ does not name a type typedef __locale_t locale_t; ^ In file included from /usr/include/c++/4.9/cwchar:44:0, from /usr/include/c++/4.9/bits/postypes.h:40, from /usr/include/c++/4.9/iosfwd:40, from /usr/include/c++/4.9/ios:38, from /usr/include/c++/4.9/istream:38, from /usr/include/c++/4.9/fstream:38, from a.C:2: /usr/include/wchar.h:183:5: error: ‘__locale_t’ is not a type __locale_t __loc) __THROW; ^ /usr/include/wchar.h:186:6: error: ‘size_t’ is not a type size_t __n, __locale_t __loc) __THROW; ^ /usr/include/wchar.h:186:18: error: ‘__locale_t’ is not a type size_t __n, __locale_t __loc) __THROW; ^ /usr/include/wchar.h:196:8: error: ‘size_t’ does not name a type extern size_t wcsxfrm (wchar_t *__restrict __s1, ^ /usr/include/wchar.h:207:9: error: ‘__locale_t’ is not a type __locale_t __loc) __THROW; ^ /usr/include/wchar.h:212:8: error: ‘size_t’ does not name a type extern size_t wcsxfrm_l (wchar_t *__s1, const wchar_t *__s2, ^ /usr/include/wchar.h:252:8: error: ‘size_t’ does not name a type extern size_t wcscspn (const wchar_t *__wcs, const wchar_t *__reject) ^ /usr/include/wchar.h:256:8: error: ‘size_t’ does not name a type extern size_t wcsspn (const wchar_t *__wcs, const wchar_t *__accept) ^ /usr/include/wchar.h:287:8: error: ‘size_t’ does not name a type extern size_t wcslen (const wchar_t *__s) __THROW __attribute_pure__; ^ /usr/include/wchar.h:306:8: error: ‘size_t’ does not name a type extern size_t wcsnlen (const wchar_t *__s, size_t __maxlen) ^ ``` [SNIP] ``` /usr/include/c++/4.9/bits/fstream.tcc:934:35: error: ‘cur’ is not a member of ‘std::ios_base’ __testvalid = this->seekoff(0, ios_base::cur, _M_mode) ^ /usr/include/c++/4.9/bits/fstream.tcc:934:50: error: ‘_M_mode’ was not declared in this scope __testvalid = this->seekoff(0, ios_base::cur, _M_mode) ^ /usr/include/c++/4.9/bits/fstream.tcc:941:25: error: ‘_M_state_last’ was not declared in this scope + _M_codecvt->length(_M_state_last, _M_ext_buf, ^ /usr/include/c++/4.9/bits/fstream.tcc:944:15: error: ‘streamsize’ does not name a type const streamsize __remainder = _M_ext_end - _M_ext_next; ^ /usr/include/c++/4.9/bits/fstream.tcc:945:13: error: ‘__remainder’ was not declared in this scope if (__remainder) ^ /usr/include/c++/4.9/bits/fstream.tcc:949:35: error: ‘__remainder’ was not declared in this scope _M_ext_end = _M_ext_buf + __remainder; ^ /usr/include/c++/4.9/bits/fstream.tcc:951:25: error: ‘_M_state_cur’ was not declared in this scope _M_state_last = _M_state_cur = _M_state_beg; ^ /usr/include/c++/4.9/bits/fstream.tcc:951:40: error: ‘_M_state_beg’ was not declared in this scope _M_state_last = _M_state_cur = _M_state_beg; ^ /usr/include/c++/4.9/bits/fstream.tcc:960:2: error: ‘_M_codecvt’ was not declared in this scope _M_codecvt = _M_codecvt_tmp; ^ /usr/include/c++/4.9/bits/fstream.tcc:960:15: error: ‘_M_codecvt_tmp’ was not declared in this scope _M_codecvt = _M_codecvt_tmp; ^ /usr/include/c++/4.9/bits/fstream.tcc:962:2: error: ‘_M_codecvt’ was not declared in this scope _M_codecvt = 0; ^ ``` On my Ubuntu machine, `g++-4.9 -std=c++11 -c a.C` generates 1,101,568 glorious bytes of errors, for a score of 1101568/33/3 = 11,126.95. [Answer] # 62.93 points Just some C++ meta black magic, compiled with `g++-4.8 -c -std=c++11 a.cc`: ``` #include<memory> template<int n>class B:std::unique_ptr<B<n-1>>{};template<>class B<0>{};B<-1>x; ``` Ungolfed: ``` #include <memory> template<int n> class B: std::unique_ptr<B<n-1>> {}; template<> class B<0> {}; B<-1>x; ``` G++ has a recursion limit of 900, so changing `B<1>` to `B<-1>` with a 31-bit range has an... interesting effect. * 96 bytes of code (not counting the final `\n` some text editors automatically add, `vim` doesn't). * 4-letter filename, `a.cc` * 24165 bytes of error message, and it's truncated. The full error message has a whopping 1235889 bytes of content. It would require the `-ftemplate-backtrace-limit=0` switch. It would also mean 3185 points for me! `std::unique_ptr` is just the template class that manages to emit the longest error message, found by trial and error and knowledge of the STL and cats and stuff. [Answer] ## Score 7.865 Strictly speaking, the 0-byte-Answer is NOT correct, as ideone.com will refuse to compile the file without error. The same is true with the example `int foo();` - it won't compile on ideone.com (I'm unable to comment because of missing reputation...) So the smallest possible program to compile without any `#includes` is this: ``` int main(){} ``` If you change this to the following code, it will fail with 409 bytes of error code (after renaming prog.cpp to a.cc from the ideone.com output): ``` int main(){[} ``` 409 / ( 13 \* 4 ) = 7.865 Please update the question accordingly, as the examples given don't respect the given rules... [Answer] # C, named as `.cc` ``` main(){constexprs a(){*(int*)0=f;}a(0)} ``` Error code: ``` .code.tio.cpp: In function ‘int main()’: .code.tio.cpp:1:8: error: ‘constexprs’ was not declared in this scope main(){constexprs int a(f){*(int*)0=f;}a(0);} ^~~~~~~~~~ .code.tio.cpp:1:8: note: suggested alternative: ‘__cpp_constexpr’ main(){constexprs int a(f){*(int*)0=f;}a(0);} ^~~~~~~~~~ __cpp_constexpr .code.tio.cpp:1:40: error: ‘a’ was not declared in this scope main(){constexprs int a(f){*(int*)0=f;}a(0);} ``` [Answer] # Score 12.xx (error by DELETING a character) Please forgive the breaking of Rule 2 (IMHO adding OR deleting one character would be in the spirit of the rule), but this happened to me accidentally (thus doesn't use any 'intentionally' abusive tricks) while writing Real Code (TM) - both the working and error-causing code are (or look) simple and straightforward, so I thought it neat enough to include here. Original code ``` #include <iostream> using namespace std; int main () { cout<<"test"<<endl; } ``` Code generating the error (last '<' deleted so it looks like a less-than comparison, but noooooooooooo ...) ``` #include <iostream> using namespace std; int main () { cout<<"test"<endl; } ``` It's 'only' 8241 bytes of compiler error messages in ideone.com g++ 4.3.2. ETA: Added a couple of lines to make it fit the rules. I knew these silly macros would come in handy someday. Ashamed it took so long because I've known C very well for a very long time. This code compiles and runs: ``` #include <iostream> using namespace std; #define a << #define aa < int main () { cout<<"test" a endl; } ``` Add another letter a after "test" a to make it fail: ``` #include <iostream> using namespace std; #define a << #define aa < int main () { cout << "test" aa endl; } ``` ]
[Question] [ Given a non-negative integer skyline height list, answer how many uninterrupted 1-unit-high horizontal brush strokes are needed to cover it. `[1,3,2,1,2,1,5,3,3,4,2]`, visualised as: ``` 5 5 4 3 5334 32 2 53342 13212153342 ``` needs nine brush strokes: ``` 1 2 3 4 5555 66 7 88888 99999999999 ``` ### Examples `[1,3,2,1,2,1,5,3,3,4,2]` → `9` `[5,8]` → `8` `[1,1,1,1]` → `1` `[]` → `0` `[0,0]` → `0` `[2]` → `2` `[2,0,2]` → `4` `[10,9,8,9]` → `11` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 38 bytes ``` a=>a.map(v=>(n+=v>p&&v-p,p=v),p=n=0)|n ``` [Try it online!](https://tio.run/##PY/BDoIwDIbve4qddGjBAZpAzPYAHvTgcZC44ECNjsWRnTz7AD6iL4JT1DZtvib9m78n6aStrkfThbrdq75mvWRcRhdpiGOc6Clz3IxGLjRgmAt804wGN913ynaVtAozvEMihhQSiD@18JzCHJISP@8PnCOxgGzg7L35yWGOkRiAIkGB/vkrTTwB/R2aezGFHDLIv@oY7dDPh7fcVQcyK4Qo9lBOinLWBMMfmHFctdq2ZxWd24Y4wOOQjwHXZLXdrCMjr1YRF/hY9i8 "JavaScript (Node.js) – Try It Online") Simply a greedy algorithm which scan from left to right, only draw lines if needed, and draw it as long as possible. Thanks Arnauld, save ~~2~~ 3 bytes [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8 7~~ 5 bytes *Saved 2 bytes thanks to @Adnan* ``` 0š¥þO ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f4OjCQ0sP7/P//z/a0EDHUsdCxzIWAA "05AB1E – Try It Online") ### How? This is using the algorithm that was first found by [@tsh](https://codegolf.stackexchange.com/users/44718/tsh). If you like this answer, make sure to [upvote their answer](https://codegolf.stackexchange.com/a/179466/58563) as well! Each time a skyscraper is lower than or as high as the previous one, it can be painted 'for free' by simply extending the brushstrokes. For instance, painting skyscrapers \$B\$ and \$C\$ in the figure below costs nothing. On the other hand, we need 2 new brushstrokes to paint skyscraper \$E\$, no matter if they're going to be reused after that or not. [![buildings](https://i.stack.imgur.com/yFBN9.png)](https://i.stack.imgur.com/yFBN9.png) For the first skyscraper, we always need as many brushstrokes as there are floors in it. Turning this into maths: $$S=h\_0+\sum\_{i=1}^n \max(h\_i-h\_{i-1},0)$$ If we prepend \$0\$ to the list, this can be simplified to: $$S=\sum\_{i=1}^n \max(h\_i-h\_{i-1},0)$$ ### Commented ``` 0š¥þO # expects a list of non-negative integers e.g. [10, 9, 8, 9] 0š # prepend 0 to the list --> [0, 10, 9, 8, 9] ¥ # compute deltas --> [10, -1, -1, 1] þ # keep only values made of decimal digits # (i.e. without a minus sign) --> ["10", "1"] O # sum --> 11 ``` [Answer] # [Haskell](https://www.haskell.org/), 32 bytes ``` (0%) p%(h:t)=max(h-p)0+h%t p%_=0 ``` [Try it online!](https://tio.run/##ZY1BCoMwFET3niIbIaEj/MQKWshJWinBNo00aqhZ9PRNxV1ThoE/j@GPM@vz7n2y@pI4laIIJXenKPRk3txVQdDBlXGjV01pMuPMNLstBWPhNc6RccvOEjUU5O5mu2scoXrx02nQZkRiV0azSKCM5I8V6G9MEjq06HqRPoP15rGmagjhCw "Haskell – Try It Online") An improvement on [Lynn's solution](https://codegolf.stackexchange.com/a/179482/20260) that tracks the previous element `p` instead of looking at the next element. This makes the base case and recursive call shorter in exchange for needing to invoke `(0%)`. `max(h-p)0` could be `max h p-p` for the same length. [Answer] # [Python 3](https://docs.python.org/3/), 37 bytes ``` lambda a:sum(a)-sum(map(min,a[1:],a)) ``` [Try it online!](https://tio.run/##bY7NCsIwEITvfYqAlwSmkJ8WkoK@SO1hRYoFE0OtB58@ag9JDrIsu3yzw2x8b7dHMGk@ntOd/OVKjIbny3MS7W94itwvATSqYQIJkeK6hI3PfFQw0FB799/doIOehGAH1p6Ya/JhD5uxbSr/XllSRcpMFiYh/@GSqCsIWb3SVZkSDhauhKr0AQ "Python 3 – Try It Online") -5 bytes by switching to Python 3, thanks to Sarien --- # [Python 2](https://docs.python.org/2/), ~~47~~ ~~43~~ 42 bytes ``` lambda a:sum(a)-sum(map(min,a[1:],a[:-1])) ``` [Try it online!](https://tio.run/##bY7LCsIwEEX3/YqAmwQmkKQtJAH9kZrFiBQLJgatC78@1kIeCxnmwbkz3Imf9fYIKs3Hc7qjv1yRoH29PUXGf81jpH4JgJO0bquWS8dYis8lrGSmk4QeFMg9x23uYQDlGDkQfiKmK3sj6Ex111zvkRVZlYxERQLEH1rMVMNA1CeGxk6AAQ2m@Mn0BQ "Python 2 – Try It Online") Alt: ``` lambda a:sum(a)-sum(map(min,zip(a[1:],a))) ``` [Try it online!](https://tio.run/##bY7BCsIwEETv/YqAlwSmkKQtJAX9kdrDihQLJgatB/35qIUmOciy7PJmh9nwWi43r@O0P8YrudOZGPWPp@Mk6t9wFLibPd5z4DSofgQJIWK4z35hEx8UGmiotbvv3qCFHgXbsfrAbJXuOpiNmqpwr7UpKisbkhlJyD80hemCQeYn2iJOwsLApjwVPw "Python 2 – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 35 bytes ``` f(a:b:c)=max(a-b)0+f(b:c) f a=sum a ``` [Try it online!](https://tio.run/##ZY3BCsIwEETv/Yo9JnSETWqhLeRLpIetNVhsqlgF/z5qb64MAzuPYecs6@U0zzlHI93QHW1I8jKyGyyX0XxBEUnC@kwkOcm0UKDxWhDd7tPyIBPp4FDBw22uP3eFPXxvfzo1GkUcNimqIoMV0Y89@G/MMVo0aHub3w "Haskell – Try It Online") Line 2 could be `f[a]=a` if I didn't also have to handle the case `[]`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes A port of my [05AB1E answer](https://codegolf.stackexchange.com/a/179471/58563), which itself is similar to [@tsh JS answer](https://codegolf.stackexchange.com/a/179466/58563). ``` ŻI0»S ``` [Try it online!](https://tio.run/##y0rNyan8///obk@DQ7uD////H22oY6xjpGMIxqZAtrGOiY5RLAA "Jelly – Try It Online") ### Commented ``` ŻI0»S - main link, expecting a list of non-negative integers e.g. [10, 9, 8, 9] Ż - prepend 0 --> [0, 10, 9, 8, 9] I - compute the deltas --> [10, -1, -1, 1] 0» - compute max(0, v) for each term v --> [10, 0, 0, 1] S - sum --> 11 ``` [Answer] # [K (oK)](https://github.com/JohnEarnest/ok), ~~12~~ 7 bytes -5 bytes thanks to ngn! A [k (oK)](https://github.com/JohnEarnest/ok) port of Arnauld's 05AB1E solution (and tsh's JavaScript solution): ``` +/0|-': ``` [Try it online!](https://tio.run/##y9bNz/7/P81KW9@gRlfd6n@agqGCsYIRkARhUyDbWMFEwYjrPwA "K (oK) – Try It Online") # [J](http://jsoftware.com/), 15 bytes A J port of Arnauld's 05AB1E solution (and tsh's JavaScript solution): ``` 1#.0>./2-~/\0,] ``` [Try it online!](https://tio.run/##RYvBCoMwEETv@YqHLYiQrpuooIJ@SXsqDaWXHjzrr8e0YGTY4c3uzieGZRKUEY3uIjpL7W9bfVf7iJUphDJMUmJZR8JizOv5/hJwNPjkv@kSN7T449jRn39/HVGvmpGMNjd9WufglIGewcQd "J – Try It Online") ## My naive solution: # [J](http://jsoftware.com/), 27 bytes ``` 1#.2(1 0-:])\0,@|:@,~1$~"0] ``` [Try it online!](https://tio.run/##RYvBCsIwEETv@YpHLdRCDLuphTZQ6IfYkxjEi4detb8eo9DIsMOb3Z1HiuvkEAKS9OD8UZFTWNqL2PkVZrtpvVWypNZUjiZOrsHyDsTVmNv1/iSidPjs3@kzd5zx@7Fn@P/9tEeppSAFbWn6vC5BhZGB0aQP "J – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), ~~34~~ 32 bytes *2 bytes trimmed by Lynn* ``` g x=sum$max 0<$>zipWith(-)x(0:x) ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/P12hwra4NFclN7FCwcBGxa4qsyA8syRDQ1ezQsPAqkLzf25iZp5tQVFmXolKerShjpGOsY4JmLSM/Q8A "Haskell – Try It Online") So to start we have `zipWith(-)`. This takes two lists and produces a new list of their pairwise differences. We then combine it with `x` and `(0:x)`. `(0:)` is a function that adds zero to the front of a list and by combining it with `zipWith(-)` we get the differences between consecutive elements of that list with a zero at the front. Then we turn all the negative ones to zero with `(max 0<$>)`. This creates a new list where each element is the number of new strokes that has to be started at each tower. To get the total we just sum these with `sum`. [Answer] # Dyalog APL, 11 bytes ``` +/0⌈¯2-/0,⊢ ``` `,` concatenate, so `0,` concatenates 0. `¯2-/` or `¯2` length of window. (minus means the window is rotated) `-/` does a window operation of `-`(minus) with window size `2` `0⌈` the operation is called ceiling, but when it gets an input from both sides it also does "get the larger of the two inputs" so `0⌈1 3 0 ¯2` will give `1 3 0 0`. and finally, a `+/` which is a sum. [Try it!](https://razetime.github.io/APLgolf/?h=AwA&c=09Y3eNTTYaT7qHeFvoHOo65FAA&f=S1d41DZBIe1R75JHfVO9gv39uNIV1KMNdYx1jHQMwdgUyDbWMdExilUHy5nqWEBZhjpgCOVBKQMdAygLpsFIxwCu2dBAx1LHQscyVh0A&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f#) [Answer] # [Japt](https://github.com/ETHproductions/japt), 8 bytes *-2 bytes from @Shaggy* ``` mîT Õ¸¸è ``` **Explanation** ``` mîT Õ¸¸è Full program. Implicit input U e.g. U = [2,0,2] mîT Map each item X and repeat T(0) X times U = ["00","","00"] Õ Transpose rows with columns U = ["0 0","0 0"] ¸¸ Join using space and then split in space U = ["0","0","0","0"] è Return the count of the truthy values ``` [Try it online!](https://tio.run/##y0osKPn/P/fwuhCFw1MP7Ti04/CK//@jow11jHWMdAzB2BTINtYx0TGK1eGKNtWxAFGGOmAIYoKwgY4BiAKrMNIxgCg1NNCx1LHQsYyNVdDNDQIA "Japt – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 8 bytes ``` 0whd3Y%s ``` [Try it online!](https://tio.run/##y00syfn/36A8I8U4UrX4//9oQx1jHSMdQzA2BbKNdUx0jGIB "MATL – Try It Online") Pretty much @Arnauld's algorithm. Saved one byte (thanks @LuisMendo) by casting to `uint64` rather than selecting `)` positive entries. [Answer] # [R](https://www.r-project.org/), 30 bytes ``` sum(pmax(0,diff(c(0,scan())))) ``` [Try it online!](https://tio.run/##TY3JCsMgEIbveYqBXBSmQbNAAu3DSKrFQ0xwaQulz26jpqWK8C8znzbW8LBiAzcLQyhoAwJUMLPXqwG1WpDCaWnBS@e1uVXq8m3Jnb7S1vn0S5qmoVb6YFMZXVjItognYXjVSpF5F@WbdOK7ShHHDlvk@Q277rDHllKoYcr9gGN24zGdb054TrJkVaGzP1cgbdHIDmhfMAwnHHEqHB4/ "R – Try It Online") Porting of [@Arnauld solution](https://codegolf.stackexchange.com/users/58563/arnauld) which in turn derives from [@tsh great solution](https://codegolf.stackexchange.com/a/179466/41725) [Answer] # Common Lisp, ~~88~~ 87 bytes ``` (lambda(s)(let((o 0))(dolist(c s)(incf o(max 0 c))(mapl(lambda(y)(decf(car y)c))s))o)) ``` ## non-minified ``` (lambda (skyline) (let ((output 0)) (dolist (current-skyscraper-height skyline) (incf output (max 0 current-skyscraper-height)) (mapl (lambda (skyscraper) (decf (car skyscraper) current-skyscraper-height)) skyline)) output))) ``` [Test it](https://rextester.com/NMQDH22914) When one tower is painted, it takes a number of brushstrokes equal to it's height. These brushstrokes translate to all the following ones, which is indicated here by subtracting the current tower's height from all other towers (and itself, but that doesn't matter). If a following tower is shorter, then it will be pushed to a negative number, and this negative number will subsequently subtracted from the towers that follow (indicating brushstrokes that could not be translated from a previous tower to the next ones). It actually just subtracts the number from *all* tower heights, including previous ones, but this doesn't matter because we don't look at the previous ones again. [Answer] # [Husk](https://github.com/barbuz/Husk), 4 bytes ``` ΣẊ>Θ ``` [Try it online!](https://tio.run/##yygtzv6vkHtouYaXkoKunYJSqmaxRvGjpkbN/@cWP9zVZXduxv///6OjDXWMdYx0DMHYFMg21jHRMYrViTbVsQCShjpgCGQBkYGOAZAESRrpGIAVGRroWOpY6FjGxgIA "Husk – Try It Online") Uses the same algorithm as everybody else (see [here](https://codegolf.stackexchange.com/a/179471/62393) for an explanation), it just does so with fewer bytes than anybody else :D ### Explanation ``` ΣẊ>Θ Θ Prepend a 0 to the values Ẋ For each pair of adjacent values (a,b) > Return b-a if b>a else 0 Σ Sum all of these values ``` `>` in Husk does a great job for this task: it does return a truthy value iff `b>a`, but this truthy value also happens to be the difference `b-a`, accomplishing two tasks in one go! [Answer] # [Japt](http://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), ~~7~~ 6 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1) ``` änT f¬ ``` [Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=5G5UIGas&input=WzEsMywyLDEsMiwxLDUsMywzLDQsMl0) 1 byte saved thanks to [Oliver](https://codegolf.stackexchange.com/users/61613/oliver). ``` änT f¬ :Implicit input of integer array ä :Consecutive pairs n :Reduced by inverse subtraction T :After first prepending 0 f :Filter elements by ¬ :Square root (The square root of a negative being NaN, which is falsey) :Implicitly reduce by addition and output ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` Z>Lε@γPO}O ``` [Try it online](https://tio.run/##yy9OTMpM/f8/ys7n3FaHc5sD/Gv9//@PNtQx1jHSMQRjUyDbWMdExygWAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVL6P8oO59zWyOKHc5tDvCv9f@v8z862lDHWMdIxxCMTYFsYx0THaNYHYVoUx0LEGWoA4YgJggb6BiAKLAKIx0DiFJDAx1LHQsdy9hYAA). **Explanation:** ``` Z # Get the maximum of the (implicit) input-list > # Increase it by 1 (if the list only contains 0s) L # Create a list in the range [1, max] ε # Map each value to: @ # Check if this value is >= for each value in the (implicit) input γ # Split into chunks of adjacent equal digits P # Take the product of each inner list O # Take the sum }O # And after the map: take the sum (which is output implicitly) ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 21 bytes ``` \d+ $* (1+)(?=,\1) 1 ``` [Try it online!](https://tio.run/##HYmxCoAgFEX3@x0FmnfwaYIO0dhPOBTU0NIQ/f9L5HDgwHmv734OHc22az0dhglGnDXrwioWEFVhZKB0U@vImQGJGcIO4OkREOjbEM/CzPID "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` \d+ $* ``` Convert to unary. ``` (1+)(?=,\1) ``` Delete all overlaps with the next tower, which don't need a new stroke. ``` 1 ``` Count the remaining strokes. [Answer] # [Nekomata](https://github.com/AlephAlpha/Nekomata), 5 bytes ``` ç-P‼∑ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FqsOL9cNeNSw51HHxCXFScnFUOEFN92jDXWMdYx0DMHYFMg21jHRMYrlijbVsQCShjpgCGQBkYGOAZAESRrpGIAVGRroWOpY6FjGQswDAA) A port of [@Arnauld's 05AB1E answer](https://codegolf.stackexchange.com/a/179471/9288). ``` ç-P‼∑ ç Prepend zero - Minus to get the delta P‼ Filter by positive ∑ Sum ``` [Answer] # [Thunno 2](https://github.com/Thunno/Thunno2) `S`, ~~6~~ 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md) ``` 0ƤṢ0§ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0UrBS7IKlpSVpuhYrDY4tebhzkcGh5UuKk5KLoaILVkUbGuhY6ljoWMZCRAA) Port of @Arnauld's 05AB1E answer. *-1 thanks to @alephalpha* #### Explanation ``` 0ƤṢ0§ # Implicit input 0Ƥ # Prepend a 0 Ṣ # Compute deltas 0§ # Maximum with 0 # S flag sums the list # Implicit output ``` [Answer] # Perl 5, 21 bytes ``` $\+=$_>$'&&$_-$';//}{ ``` [TIO](https://tio.run/##K0gtyjH9/18lRttWJd5ORV1NTSVeV0XdWl@/tvr/f0MuYy4jLkMwNgWyjblMuIz@5ReUZObnFf/XLQAA) How * `-p` + `}{` + `$\` trick * `//` matches empty string so that for next line postmatch `$'` will contain previous line * `$\+=$_>$'&&$_-$'` to accumulate difference between current line and previous if current is greater than previous, (could also be written `$\+=$_-$' if$_>$'`, but perl doesn't parse `$\+=$_-$'if$_>$'` the same) [Answer] # [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with flag `/u:System.Math`, 47 bytes ``` n=>n.Select((a,i)=>i<1?a:Max(a-n[i-1],0)).Sum() ``` [Try it online!](https://tio.run/##ZZHfa8IwEMefzV8RZA8Jnl1TFdRa9yAMBvrUwR5KH0qNGtBE2rg5Sv71ddeObf4gJBc@3H2/d0le9vNS1c8nnc@UtkkKeM43Ua2jufZiuZe5ZSwDxaO5momnbLrKzizr60T1RQo@5158OjBeh@Q9K6iVpV1kpSxpRLX8oOxHk2LgSVoR1sCWVQIGEIBo9wjvAxhC4GDC4TJrBGMH42smoF0OxDV32M4V8MG/Y2gR3BDwG@PhjYkPExjDBF0EdyEhG1M001CFo/khhtn/tN5S6q3dIe31OKlIZ2F0afbSeyuUleyhWyk3pV0ekk7zSkX7Phv2V5@o1Hux8iB@M7bGrDHlLiEIb7SXSjf68nzEj5JrWjWV3quJbaH0lnEHqGVphZaXtGnF1V/maBWq1Y@nafxZor63yuzuGw "C# (Visual C# Interactive Compiler) – Try It Online") ## Old version, with flag `/u:System.Math`, 63 bytes ``` n=>n.Aggregate((0,0),(a,b)=>(a.Item1+Max(0,b-a.Item2),b)).Item1 ``` I feel like this solution is more elegant than the first one. It goes through the array with a two-value tuple as a starting value, picking up values, and stores the value before it in the second part of the tuple. [Try it online!](https://tio.run/##ZZBda8IwFIav7a8IsosEj11bFdRaYQiDgV4p7EK8iDXWwJZKEzdHyV9fd9KyzQ9Cvp5z8r45J9XdVMvq@aTSiVRmvQFcp/ukUslU@U9ZVoiMG0FpAAEDymHLkinl/osR72Fnwc8Y2Habe8QwyppQFXsfvCBGaDPjWmiSECU@CW08CG5svSk96mDNyhB6EEFYzwGee9CHyMKIwWXWAIYWhtcshHpYCK@5dV@@BFjDHUOL6IZA4Iz7NyYBjGAII3QJmY09b58XrhoisbQgxm3yX60/FyozB6SdDvNKrzXLlc7fhP9aSGzmQ7uUdkzaLPZarktF3Z89/Xu/lpumjb8ZWZ7vMOUuIYpvtOdSOX1xPorUiB0p3Ut/lS9NIVVGmQXUMqREy0vqvmKr7/xoJKpVj6fx8kujvr/g5vAD "C# (Visual C# Interactive Compiler) – Try It Online") [Answer] # Pyth, 8 bytes ``` s>#0.++0 ``` Yet another port of [@tsh's marvellous answer](https://codegolf.stackexchange.com/a/179466/41020). Takes the sum (`s`) of the positive values (`>#0`) of the deltas (.+) of the input with 0 prepended (`+0Q`, trailing Q inferred). Try it online [here](https://pyth.herokuapp.com/?code=s%3E%230.%2B%2B0&input=%5B1%2C3%2C2%2C1%2C2%2C1%2C5%2C3%2C3%2C4%2C2%5D&debug=0), or verify all the test cases at once [here](https://pyth.herokuapp.com/?code=s%3E%230.%2B%2B0&input=%5B%5D&test_suite=1&test_suite_input=%5B1%2C3%2C2%2C1%2C2%2C1%2C5%2C3%2C3%2C4%2C2%5D%0A%5B5%2C8%5D%0A%5B1%2C1%2C1%2C1%5D%0A%5B%5D%0A%5B0%2C0%5D%0A%5B2%5D%0A%5B2%2C0%2C2%5D%0A%5B10%2C9%2C8%2C9%5D&debug=0). ## String joining method, 10 bytes This was the solution I wrote before browsing the other answers. ``` lcj.t+d*LN ``` [Test suite.](https://pyth.herokuapp.com/?code=lcj.t%2Bb%2ALN&input=%5B%5D&test_suite=1&test_suite_input=%5B1%2C3%2C2%2C1%2C2%2C1%2C5%2C3%2C3%2C4%2C2%5D%0A%5B5%2C8%5D%0A%5B1%2C1%2C1%2C1%5D%0A%5B%5D%0A%5B0%2C0%5D%0A%5B2%5D%0A%5B2%2C0%2C2%5D%0A%5B10%2C9%2C8%2C9%5D&debug=0) ``` lcj.t+d*LNQ Implicit: Q=eval(input()), b=<newline>, N=<quote mark> Trailing Q inferred L Q Map each element of Q... * N ... to N repeated that many times +b Prepend a newline .t Transpose, padding with spaces j Join on newlines c Split on whitespace l Take the length, implicit print ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 34 bytes A port of [@Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [solution](https://codegolf.stackexchange.com/a/179471/9288). ``` Tr@Select[{##,0}-{0,##},#>0&]&@@#& ``` [Try it online!](https://tio.run/##JYxBCsMgFESv8uGDqwlV00CyaPAIhXYnLiQYGmi6CO7EsxtNGYY3i8fsPn7C7uO2@LLSg8r7MK/wDUu0iRkyd0mCOYNnKZwwhkV5HtsvWqZuptWycyToZiglhR4a6upQd487dAalAWODwpU2W2V9r7gMDflXlcSEEVPO5QQ "Wolfram Language (Mathematica) – Try It Online") [Answer] # Clojure, 50 bytes ``` #((reduce(fn[[s n]i][(+(max(- i n)0)s)i])[0 0]%)0) ``` [Try it online! (Why doesn't this print anything?)](https://tio.run/##dY7bCoMwDIavzVMUxiBlGVSdoM8SejE8QIerUhX29lmtsO1mOZHkD@Frx@mxhV4Ehykodn7eVsiYcyqpoDxlFfuSblRYxRXVseaUPHYxDJlYd7Egk45yQw3V1FhrAbsJMpyD8@voVfqvfxYIcEIMfbe1PQ6eeVHeOst4wef9hVfllNdGL9pZzUYZe44TQJYdn6IBgIj8AZYELB9g4Rg7sPAuHsDyBX4D "Clojure – Try It Online") ``` #( ; begin anonymous function (reduce (fn [[s n] i] ; internal anonymous reducing function, destructures accumulator argument into a sum and the previous item [(+ (max (- i n) 0) s ; the sum part of the accumulator becomes the previous sum plus the larger of zero and the difference between the current number and the last one, which is how many new strokes need to be started at this point i]) ; ...and the previous item part becomes the current item [0 0] ; the initial value of the accumulator gives no strokes yet, and nothing for them to cover yet %) ; reduce over the argument to the function 0) ; and get the sum element of the last value of the accumulator. ``` [Answer] # [Java (JDK)](http://jdk.java.net/), 57 bytes ``` a->{int s=0,p=0;for(int x:a)s-=(x>p?p:x)-(p=x);return s;} ``` [Try it online!](https://tio.run/##bVDBboMwDL33K3wkk0FAV6mF0WmXSTvs1N2qHtIWqnQQosRUVIhvZ4GyimpTZMXPfnp@9plfuHs@fneiUKUmOFvsVSRy7yme/alllTyQKOW/TUM65UXfOuTcGPjkQkIzA1DVPhcHMMTJfpdSHKGwPWdDWsjTdgdcnwwbqABf5Yek93HOi5C03a0hSzrurhuLwCQ@qsSPs1I7Pa4jzoybOPVavaqoZq6jkprFOqVKSzBx28WD7qBkZ1FqyEAyTgNoIMA5hhgMsbD5HJ8xhBbvhAUupzDA4U1L09xHfwoflEL0H6UDH1e4xNVvrb2ZHZcb7UY30@zueXM1lBZeWZGn7Akpl07mcaXy65ux13N6OmM3qXbWR9v9AA "Java (JDK) – Try It Online") Another port of [tsh](https://codegolf.stackexchange.com/users/44718/tsh)'s [Javascript answer](https://codegolf.stackexchange.com/a/179466/16236). So make sure you've upvoted them. Note that I used subtraction instead of addition because it allowed me to write `(p=x)` as right operand in the same statement. [Answer] # [Factor](https://factorcode.org/) + `math.unicode`, 24 bytes ``` [ dup 0 prefix [v-] Σ ] ``` [Try it online!](https://tio.run/##TY5NDoJADIX3nOJdQMKPJKIHMG7cGFeExWQokaDDOAxEQziN9/FKY0nA0Kbt99qmaSmkbYy7Xk7n4x41GUV3tPTsSElq8RD25vc07cyiU5VsCoI2ZO1bm0pZHDxv8MA2IESMiPMUCXOMLfM4TxPs/hzOvuilBuwLRysKVioMkPKplBuj5zIUneY5v1RWL2T9Jsf3g9w9hEZrhax99wM "Factor – Try It Online") ## Explanation ``` ! { 10 9 8 9 } dup ! { 10 9 8 9 } { 10 9 8 9 } 0 ! { 10 9 8 9 } { 10 9 8 9 } 0 prefix ! { 10 9 8 9 } { 0 10 9 8 9 } [v-] ! { 10 0 0 1 } (subtract two vectors, clamping negative numbers to 0) Σ ! 11 ``` [Answer] # [Kotlin](https://kotlinlang.org) ``` fun f(test:IntArray):Int{var s=0;var p=0;test.forEach{val f=(if(it>p)p else it);p=it;s-=f-p};return s} ``` [Try it yourself](https://pl.kotl.in/99_GhJAsJ?theme=darcula) [Answer] # [Arturo](https://arturo-lang.io), ~~35~~ 33 bytes ``` $=>[l:0sum map&'x[max@[0x-l]l:x]] ``` [Try it](http://arturo-lang.io/playground?FwZpXS) [Answer] # [Uiua](https://uiua.org), 11 [bytes](https://codegolf.stackexchange.com/a/265917/97916) ``` /+↥0-↘¯1⊂0. ``` [Try it!](https://uiua.org/pad?src=ZiDihpAgLyvihqUwLeKGmMKvMeKKgjAuCgpmIFsxIDMgMiAxIDIgMSA1IDMgMyA0IDJdICMg4oaSIDkKZiBbNSA4XSAjIOKGkiA4CmYgWzEgMSAxIDFdICMg4oaSIDEKZiBbXSAjIOKGkiAwCmYgWzAgMF0gIyDihpIgMApmIFsyXSAjIOKGkiAyCmYgWzIgMCAyXSAjIOKGkiA0CmYgWzEwIDkgOCA5XSAjIOKGkiAxMQ==) Port of tsh's [JavaScript answer](https://codegolf.stackexchange.com/a/179466/97916). ``` /+↥0-↘¯1⊂0. . # duplicate ⊂0 # prepend a zero ↘¯1 # drop last element - # subtract the two arrays ↥0 # change negative numbers to zero /+ # sum ``` [Answer] # [MATL](https://github.com/lmendo/MATL), ~~15~~ ~~14~~ 13 bytes ``` ts:<~"@Y'x]vs ``` Input is a column vector, using `;` as separator. [Try it online!](https://tio.run/##y00syfn/v6TYyqZOySFSvSK2rPj//2hDa2NrI2tDMDYFso2tTayNYgE) Or [verify all test cases](https://tio.run/##y00syfmf8L@k2MqmTskhUr0itqz4v0vI/2hDa2NrI2tDMDYFso2tTayNYrmiTa0tgKShNRgCWUBkYG0AJEGSRtYGYEWGBtaW1hbWlrEA). ### Explanation ``` t % Implicit input: column vector. Duplicate s % Sum : % Range from 1 to that. Gives a row vector <~ % Greater or equal? Element-wise with broadcast " % For each column @ % Push current columnn Y' % Run-length encoding. Gives vector of values (0, 1) and vector of lengths x % Delete vector of lengths ] % End v % Vertically concatenate. May give an empty array s % Sum. Implicit display ``` ]
[Question] [ ## Input A non-empty encoded string consisting of printable ASCII characters (in the range 32-126), where some missing letters have been replaced with `_`. ## Output A decoded string of the same length with all letters in lowercase, including the missing ones. ## How? *Edit: As mentioned by @Deusovi in the comments, this is a variant of [Bacon's cipher](https://en.wikipedia.org/wiki/Bacon%27s_cipher).* * Gather all letters in the original string and group them by 5. Additional letters that do not fit in a full group of 5 are ignored. * Convert each group into binary: lowercase = **0**, uppercase = **1**. This leads to a list of integers. * Use each value **N** in this list to replace each `_` in the original string with the **N**-th letter of the alphabet (0-indexed), in order of appearance. **Example:** `prOGraMMIng PuZZleS & cOde ____` ``` prOGr --> 00110 --> 6 --> 7th letter = 'g' aMMIn --> 01110 --> 14 --> 15th letter = 'o' gPuZZ --> 01011 --> 11 --> 12th letter = 'l' leScO --> 00101 --> 5 --> 6th letter = 'f' ``` By replacing the missing letters and converting everything back to lowercase, the original string is unveiled: ``` programming puzzles & code golf ``` This is the expected output. ## Clarifications and rules * The missing letters are guaranteed to appear at the end of the string. More formally: there will never be any letter after the first `_` in the input string. However, there may be other printable ASCII characters such as spaces and punctuation marks. * The input is guaranteed not to contain any *useless* capital letter: all capital letters are bits set to **1** which are required to decode the missing letters. Everything else is in lowercase. * The input string is guaranteed to be valid. Especially: + It will always contain enough full groups of 5 letters to decode the underscores. + The binary-encoded integers are guaranteed to be in the range **[0-25]**. * There may be no `_` at all in the input string, in which case you just have to return the input. * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins! ## Test cases ``` Input : hello! Output: hello! Input : helLO, worl_! Output: hello, world! Input : i aM yoUr faTh__. Output: i am your father. Input : prOGraMMIng PuZZleS & cOde ____ Output: programming puzzles & code golf Input : Can YOu gUesS tHE ENd oF This ____? Output: can you guess the end of this text? Input : THe qUICk brown FOx JUMps oVEr the la__ ___. Output: the quick brown fox jumps over the lazy dog. Input : RoadS? wHERe we're goinG WE doN't need _____. Output: roads? where we're going we don't need roads. Input : thE greatESt Trick thE DeVIl EVer PUllEd wAs CONvInciNg tHe WorLD h_ ____'_ _____. Output: the greatest trick the devil ever pulled was convincing the world he didn't exist. ``` Some extra test-cases: ``` Input : BInar_ Output: binary Input : 12 MonKey_ Output: 12 monkeys Input : hyPerbolIZ__ Output: hyperbolized Input : {[One Last Test ca__]} Output: {[one last test case]} ``` [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 18 bytes ### Code: ``` áS.u5ôJC>.bv'_y.;l ``` Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f//8MJgvVLTw1u8nO30ksrU4yv1rHP@/y/JcFVIL0pNLHENLlEIKcpMzlYACbmkhnnmKLiGpRYpBITm5LimKJQ7Fis4@/uVeeYlZ/qlK5R4pCqE5xf5uChkxCvEA4E6hIrXAwA "05AB1E – Try It Online") ### Explanation: ``` á # Remove non-letters from the input string. S # Split the result into individual characters. .u # Check if is uppercase for each character. 5ôJ # Split into binary numbers of length 5. C # Convert from binary to decimal. > # Add one. .b # Map 1 → A, 2 → B, 3 → C, ..., 25 → Y, 26 → Z. v # For each letter: '_y.; # Replace the first occurrence of '_' with the current letter. l # Convert the string to lowercase. ``` [Answer] # Perl 5 `-pF -MList::Util=sum`, 75 bytes ``` @a=grep!/\W|\d/,@F;s!_!(a..z)[sum map{a gt shift@a&&16/2**$_}0..4]!eg;$_=lc ``` [Try it online!](https://tio.run/##Fc3PCoIwHADgV/kNREtyVlQHRfKidagORXjIGCPXGqgbbiH059Vb9b3Ap1hXz61NacI7plBYFq@yCkdpHmtE0IBi/Bie9L2BhqonBW5A38TVpNR1J4tw6vsOeY8xnp0R47FDkvpi7V7S6rCEfp3tGfTM6xhwKdoVFBlUcucZaBmrgPzhj1RGyFbbQOUQbDdCmyg6GlEnv/UL) ## Explanation: * `-pF` reads a line of input into the variable `$_` and, split into characters, into the array `@F`. * `@a=grep!/\W|\d/,@F` sets the array `@a` equal to those members of `@F` that don't satisfy the regex `\W|\d`. `\W` is anything but letters, numbers, and `_`; `\d` is numbers. So `\W|\d` is anything but letters and `_`, and `@a` has all the letters and `_` characters. We will wind up never examining the `_` characters in `@a`. (Note that this only works because the input is guaranteed ASCII.) * `map{a gt shift@a&&16/2**$_}0..4` does the following for 0 through 4: It shifts the next element off of `@a`, shortening it, and evaluates whether `a` is asciibetically greater than that element (i.e. whether that element is uppercase). If so, `&&` isn't short-circuited, so we get 16 divided by 2 to rhe power of the input value (0 through 4). Otherwise `&&` is short-circuited and we get 0. `map` returns the list of five numbers to `sum`, which adds them. * That's the element we want from the list `a..z`, and that's what we get from `(a..z)[…]`. * `s!_!…!eg` converts each `_` in `$_`, in turn, to the appropriate letter. * `$_=lc` converts `$_` to the lowercase version of itself, and `-p` prints it. [Answer] # [Python 2](https://docs.python.org/2/), 113 bytes ``` s=input() i=k=0 for c in s: if c.isalpha():k+=k+(c<'a');i+=1;s=s.replace('_',chr(k%32+97),i%5<1) print s.lower() ``` [Try it online!](https://tio.run/##JcjLagIxFIDh/TzFQZAkjAxqKeIlC9EBBbEFb8shxGgOCZlwklZ8@qnSf/PBH5/ZtmHcdUliiD@ZiwKlk8Pi1hJowABpVgDeQFeYlI9WcTFzpXQl1wummJhjKUfzJFNFJnqlDWcNG2hL3PU/xuV0IgbY/1yMRBEJQ4ZU@fZhiIuu62Vbw52MyvUhw5FQO3ivtTlvPdRnQ/B98r6@wmOZYPW1/90Gjfs75I2BS0u7NdgGmlfsn6bq/QE "Python 2 – Try It Online") [Answer] # [J](http://jsoftware.com/), ~~62~~ 61 bytes ``` tolower u:@]`(I.@t=.'_'=[)`[}+/@t$97+_5#.\3|0 2 4-.~'@Z`z'&I. ``` [Try it online!](https://tio.run/##TVBdT8JAEHz3V4zRcBq0Gj9iNCFg4IAa2hLaQgTNUenRVi89vB5WjfrXK2AM3bedndnZ2eeimNcMaClkzhWWN43H6YFpNHTNIIzUJofTyXf1pKH3r6@q7HLPeDj/OsUZLo6NH9IYTz9JxTQKPosl5iAxF0Lukp1S33OOkEslWAlOEFj4kL7CPPBixoztaKGcjgosy0wj9JfjseAuKpg5IQdb1ZbYDFLcO0tEPs9c6C4FtUPINrw4yTbc@pbsdTlefbP5gicl8xRt5x13vrXIIIdUQcccImBsLSvdMpBB6NaRd@mAI@eEKI5IJmkHI4pQ2oRopJyHG7eyUMcUkeKBpq6Gp5LZC9ZQiw9NATpcvbnvC0FD5LcZmo79ZqazxI5WKThGUvVaiNlfXML@lxe/) [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~91~~ 90 bytes ``` T`l`a T`L`A [^Aa] L`.{5} A aA +`Aa aAA +T`_lA`l_`[^A]A ^ $+¶ +`_(.*)¶a+(.) $2$1 0G` T`L`l ``` [Try it online!](https://tio.run/##K0otycxLNPz/PyQhJyGRKyTBJ8GRKzrOMTGWi8snQa/atJbLkSvRkUs7wTERSAMZIQnxOY4JOfEJQFWxjlxxXCrah7YB5eM19LQ0D21L1NbQ0@RSMVIx5DJwTwAbmPP/f0GRv3tRoq@vZ166QkBpVFROarCCmkKyf0qqQjwQAAA "Retina – Try It Online") Explanation: ``` T`l`a T`L`A [^Aa] ``` Translate lowercase letters to `a` and uppercase letters to `A`, deleting everything else. ``` L`.{5} ``` Split the `Aa`s into groups of 5. ``` A aA +`Aa aAA ``` Convert from binary into unary, treating `A` as 1 and `a` as 0. Since there were 5 `Aa`s originally, there are 5 `a`s left, plus a number of `A`s depending on the desired position in the alphabet. ``` +T`_lA`l_`[^A]A ``` Increment the last `a` according to the number of following `A`s. ``` ^ $+¶ ``` Prepend the original input. ``` +`_(.*)¶a+(.) $2$1 ``` Replace any `_`s with the next decoded letter. ``` 0G` ``` Remove any spare decoded letters. ``` T`L`l ``` Lowercase everything. # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 117 bytes ``` .+ $&¶$& T`L`l`^.* T`l`a`.*$ T`L`A T`aAp`aA_`.*$ (.*¶)?.{5} $&; A aA +`Aa aAA +T`_lA`l_`[^A]A +`_(.*¶)a+(.); $2$1 1G` ``` [Try it online!](https://tio.run/##K0otycxL/P9fT5tLRe3QNhU1rpAEn4SchDg9LSArJyExQU9LBSzmCCQTHQuAOB4spqGndWibpr1etWktUKs1lyNXoiOXdoJjIpAGMkIS4nMcE3LiE6LjHGNBEvEQDYnaGnqa1lwqRiqGXIbuCf//FxT5uxcl@vp65qUrBJRGReWkBiuoKST7p6QqxAMBAA "Retina 0.8.2 – Try It Online") Explanation: ``` .+ $&¶$& ``` Duplicate the input. ``` T`L`l`^.* ``` Lowercase the first copy. ``` T`l`a`.*$ ``` Translate lowercase letters to `a` in the second copy. ``` T`L`A ``` Translate uppercase letters to `A`. These must be in the second copy because the first copy was already lowercased. ``` T`aAp`aA_`.*$ ``` Delete everything else in the second copy. ``` (.*¶)?.{5} $&; ``` Split the second copy (now just `Aa`s) into groups of 5. ``` A aA +`Aa aAA +T`_lA`l_`[^A]A +`_(.*¶)a+(.); $2$1 1G` ``` Decode the letters and insert them as before. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~28 27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) -1 thanks to Erik the Outgolfer & dylnan Not a very Jelly-friendly challenge! ``` ḟŒs$Ƈ<”[s5Ḅ+97Ọż@ṣ”_$FṁLŒl ``` A monadic link accepting and returning lists of characters. **[Try it online!](https://tio.run/##y0rNyan8///hjvlHJxWrHGu3edQwN7rY9OGOFm1L84e7e47ucXi4czFQMF7F7eHORp@jk3L@//8flJ@YEmyvUO7hGpSqUJ6qXpSqkJ6fmeeuEO6qkJLvp16ikJeamqIQDwJ6AA "Jelly – Try It Online")** ### How? ``` ḟŒs$Ƈ<”[s5Ḅ+97Ọż@ṣ”_$FṁLŒl - Link: list of characters e.g. "MfUNE_?" (shorthand for ['M','f','U','N','E','_','?']) Ƈ - filter keep each if: $ - last two links as a monad: Œs - swap-case ḟ - filter discard - ...i.e. keep A-Z,a-z since they change when the case is swapped - "MfUNE" ”[ - literal character '[' < - less than? (i.e. is upper-case?) [1,0,1,1,1] s5 - split into fives [[1,0,1,1,1]] Ḅ - from base two (vectorises) [[23]] +97 - add (vectorises) ninety-seven [[120]] Ọ - from ordinals (vectorises) [['x']] $ - last two links as a monad: ”_ - literal character '_' ṣ - split at [['M','f','U','N','E'],['?']] ż@ - swapped @rgument zip [[['M','f','U','N','E'],'x'],['?']] F - flatten "MfUNEx?" L - length (of input) 7 ṁ - mould like "MfUNEx?" - ...removes any excess characters Œl - lower-case "mfunex?" ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 46 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set") Anonymous lambda, Assumes `⎕IO` (Index Origin) to be `0`. ``` {_←'_'=⊢⋄819⌶A[2⊥⍉(+/_⍵)5⍴A∊⍨⍵∩A,819⌶A←⎕A]@_⍵} ``` [Try it online!](https://tio.run/##TY/NTttAFIX3fYrTDdOqQH9QpbKoqBsGYkTiKLaDSIVGQzyxLUaedGJwo4oVFYJQI1jwAkhIsGLT9gH6KPMi6cRm0VnM3HP0nXvn8pFciiZcqnhmLm9cz5xevZl9Z/YhjHw001tz8ePD21Xz84/z5Z2Z3pny/MWr18yUv1@@N@Uvx5xNTXlvpTl7cBafSJu2zZy9T3PueDac6/Ky7j89@fu4Yk6vrfK7DXsHTdefDUESIaV6Tp7V5ba3iEJpyWonBW9hokKNIQ8SxpYrd6S9Tc1bLTeL0Tns96XwsYCBFwkweyqmwTPseoeIQzH2kTcpaDuC2kCQpOMKW6u4oCnwNXQbB9jXqsiw4X3DVtgajaF6VCNPBCRnbJ6oh3cVj/w1FE3aFSgEIVogVmm2iR2KSLUJyZEJEVUznjJ5QhFrwXPq5wh0OjjA3FoXPVeC9oRGJ5SSRiicMRpe@8jNBmk7tt8W2FF6ex0Jq1cj7P@@n92M63rfZNIRel9Jt2@pfw "APL (Dyalog Unicode) – Try It Online") `{`…`⋄`…`}` two-statement function; `⍵` is the argument, `⋄` separates statements  `⊢` argument (no-op function)  `'_'=` where equal to an underscore (i.e. a Boolean mapping function)  `_←` assign that function to `_`  `A[`…`]@_⍵` put the following characters of `A` **at** positions of underscores in the argument   `⎕A` the uppercase **A**lphabet   `A←` assign that to `A`   `819⌶` lowercase it (*819 ≈ BIg*, with no left argument means not big, i.e. lowercase)   `A,` prepend the uppercase alphabet; this gives us all letters   `⍵∩` intersection of the argument and that; just the letters of the argument   `A∊⍨` which of those are members of the uppercase alphabet; uppercase bits   `(`…`)5⍴` **r**eshape that to the following number of rows, and five columns:    `_⍵` the mask of underscores in the argument    `+/` sum that; number of underscores   `⍉` transpose (to treat each row as a number rather than as a bit position)   `2⊥` evaluate as base-2  `819⌶` lowercase everything [Answer] # [Scala](https://github.com/scala/scala), 189 bytes ``` def f(s:Array[Char])={var j=0;s.zipWithIndex.collect{case(95,i)=>s(i)=(Integer.parseInt(s.filter(_.isLetter)slice(j,j+5)map(k=>if(k<91)1 else 0)mkString,2)+97)toChar;j+=5};s.map(_.toLower)} ``` [Try it online!](https://tio.run/##rZBZawIxFIXf/RW3vjRBGVSQYu0IokKlLgW3B5EhHe84GeNkSIJLZX67jV1QW8GX5iHLufd8nBvtM8EO8i1C30CX8RhwazCea6gnCewzhzkGEBD9WFeK7aaNkKkZdfdrpiByC1XtvPNkwk3Yjue4dXwphAXtfaaRVMp5Tt2aJnYn7djgApWTMKXRPoh2Ai4MKuI5XHfQ2CvVgvtIonyUK9MVS8jSrfGALJ8qRVoEFBqhQFfLgVE8XuRLNFd5oEYeI1WjnFtObZqjy3OM7MiN5aUHgMQ2GxGTbIhCyDtwa5CFnB3pW8ja7s/ZqPODpplLW6efh41UwvvlPum3IBxYF3ZypCBgw9DznDPQn9otmAlbsFDITGtgYKi4v4Sj1MRxW0BrjApeR0K05rCpa2j0e@t27PPeAswzwkSqThNCDzy77r@OizT/D781TrEEXRm/4M47i3ESb/7tfloszdIrjMvCVUx6@AA) Explanation: ``` def f(s: Array[Char]) = { // takes a String in input var j = 0 // j stores at which block of 5 letters we're currently at s.zipWithIndex.collect { // Array('h', 'e', ...) => Array(('h', 0) ('e', 1), ...) and we apply a collect transformation (filter/map) case (95, i) => // we only handle cases where the char is '_' (95) s(i) = ( // we modify the char at index i with the following Integer.parseInt( // Integer.parseInt("00110", 2) = 6 s // .filter(_.isLetter) // filter out non letter chars (spaces, punct, figures, ...) from the input string (thanks @Arnauld for the fix)A .slice(j, j+5) // "substring" the array to the block of 5 letters in question .map( // map on the current block of 5 letters k => // the index of the next char in the block f 5 (e.g. 13) if (k < 91) 1 else 0 // if the current char is upper case (<91) then we replace it by a bit true, otherwise by a bit false )mkString, // Array(0, 1, 1, ...) => "011..." 2 // cast string to binary ) // + 97 // +97 to create a lower case char )toChar // cast from int to char j += 5 // update the starting index of the next block of 5 letters } // s.map(_.toLower) // return the updated seq of chars all in lower case } // ``` [Answer] # [JavaScript (Node.js)](https://nodejs.org), 94 bytes ``` x=>x.toLowerCase(w=/[a-z]/gi).replace(/_/g,g=Z=>Z>62?(Z-52).toString(36):g(w.exec(x)<g|2*-~Z)) ``` [Try it online!](https://tio.run/##DcvBCoIwGADgV9kpt2gbGHmIZofACBIDb4uQMX@GMTaZliOiVze/@/dUbzXo0PUjdb6FuRBzFHlko7/6CcJJDYAnwe@Kfh7cdIQF6K3SgHnDzcYIKXKZZ@kRS7pLydLqMXTO4G1G9gZPDCJoHMnBfNM1/UlCZu3d4C0w6w0ucNKH6hxUWV6cQbeXlBZqtEK6agE1i2QZfw "JavaScript (Node.js) – Try It Online") # [JavaScript (Node.js)](https://nodejs.org), ~~125~~ 124 bytes ``` x=>x.replace(s=/./g,c=>parseInt(c,36)>9?c.toLowerCase(s+=+(c<{})):c=='_'?('0b'+s.slice(4,9)-~9).toString(36,s=s.slice(5)):c) ``` [Try it online!](https://tio.run/##NYxBC4IwGIb/iqe24ZyBFRhND4EhJAbevMj6HGKMTTYrIeqvmx16r8/zvDfxEA5sP4yBNq2cMz5PPJmYlYMSILHjIQs7CjwZhHUy1yMGGu1IEqfARnM2T2mPwi2iz30Mh9ebkD1wjhqUYrS@It8xp/rlaUNjEnxislTVaHvd4WhHHf/j7a8jMxjtjJJMmQ5nGA22PFlRFLnuvMu9rpWsvJUHZSu9ZhkiZP4C "JavaScript (Node.js) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 26 bytes ``` xn¥Œs<”[s5Ḅ‘ịØaṛi”_ḟ0Ɗ¦ƒŒl ``` [Try it online!](https://tio.run/##y0rNyan8/78i79DSo5OKbR41zI0uNn24o@VRw4yHu7sPz0h8uHN2JlA0/uGO@QbHug4tOzbp6KSc////FxT5uxcl@vp65qUrBJRGReWkBiuoKST7p6QqxAMBAA "Jelly – Try It Online") Different approach from Jonathan Allan's. EDIT: So, I, uh, apparently thought of the same byte reduction as Jonathan Allan, so it doesn't hurt to mention his name again. [Answer] # [CJam](https://sourceforge.net/p/cjam), 43 bytes ``` q'_/_0={el_eu=!},_eu.=5/2fb65f+:c1$,(<.+:el ``` [Try it online!](https://tio.run/##S85KzP3/v1A9Xj/ewLY6NSc@tdRWsVYHSOnZmuobpSWZmaZpWyUbquho2OhpW6Xm/P9fkuGqkF6UmljiGlyiEFKUmZytABJySQ3zzFFwDUstUggIzclxTVEodyxWcPb3K/PMS870S1co8UhVCM8v8nFRyIhXiAcCdQgVrwcA "CJam – Try It Online") [Answer] # [Clean](https://clean.cs.ru.nl), ~~180~~ ... 150 bytes ``` import StdEnv ?s=['a'+sum[i\\i<-:""&c<-s|c<'a']: ?(drop 5s)] @['_':b][x:y]=[x: @b y] @[a:b]z=[toLower a: @b z] @e _=e $s= @s(?(filter isAlpha s)) ``` [Try it online!](https://tio.run/##JYxNS8NAFEVRXEhW/oRHLU6CxJ2bkCEpJmAgVCFaF0kIk8mkHZx8MDNtTfG3G6d6F@/yzoFLBSP93A3NXjDoCO9n3o2D1JDpJu4PVqBwjgi6V/su50XBfddb3FxfXV4s7qjvqm/qG1t6ENiNHEZ4VE5phTmqkFeX@Zc3ldhcCGuYzpwYesK5HtLhyCSQP3MyhkGFmbVUGEJlB3bLhTaeq5UYdwSU48yZJlJbt9AChqWFTedI72LYSkZ0nGl4k5x@whlFbJMIiDdm4fVdiLiB40rB08v6kPSUr7egnxl8DDKNYFdBZVKg/64eUDn/0FaQrZrdJJ2jqScdp@apfwE "Clean – Try It Online") Defines the function `$ :: [Char] -> [Char]` with `@ :: [Char] [Char] -> [Char]` as a helper to replace underscores, and `? :: [Char] -> [Char]` as a helper to generate the replacement characters. [Answer] # [JavaScript (Node.js)](https://nodejs.org), 100 bytes ``` s=>s.toLowerCase(c=/[a-z]/gi).replace(/_/g,_=>(g=n=>n?(c.exec(s)<{})*n+g(n>>1):10)(16).toString(36)) ``` [Try it online!](https://tio.run/##ZVPbUtswEH3PV2xfapuCQ9oZHqBOphMMpEMShiQw5TJGtTeOqCIZSU5CGL49XQVyGfDTavecs2fX0iObMJNqXtg9qTJcDKOFieomtOpcTVE3mUE/jaq3bG9@X815EGosBEvRrybVfDeJ6n4eyaguG34a4gxT3wQ/X16DHfkt92W9XgsOa/uBXzsISLFnNZe5/@MgCBYWjU1JHCJ4aMmitHAIIxRCfal0S0vn9bGyVT7v7sJUaZF8QL1lsy0wB9aGZzXQMGT9UZKEawJVxlQpXcWOUIcbUqG7p5q12y2Zw0V5cyOwB18h7WYICX1riUKrXLPxmKaBopzPBRqHo/1BrsRwI9hkEv50S8gHaHpgz2KIOxmoE@iPuFlqNtaiKWHJFuQlGgPkDFASdkghYS3ObGMj3D9DeBq0mv/gr1ZTCSfdGfwetAsD6irWS7ZgSeJabCZ32aeSpyvSUM3gsRw70gRXpPkzZCrfWsqlYlmvAdOz@BJhip52Q3J5CtcxITueBYmYLYfZ6qWJZYhFC95m5RQTS65YS9hWMzuKIdfIbNyz0NfOq0sd41VLQHxFLi8GQsQZTH8ZaHY7k5ZMeSen1SJcK31@DKPl0ImXfHTkxltK080D@y5NZnDCBaBbQFEKQZ6mzNC/lBNO0mTYgZa3CxyaZ847zrixYeXhqLK6x@GY2XTkV1eDhDt3ctXZxdU8IEjhG4jq8FIBmDANt3wX8J6eAL03zcd@EJpCcOt7d9J7g1sHt6v0oRfc1u7fscERqZBPowSGQuX@0Oefk/gp4@157hHTIvzv@47wGhwt/gM "JavaScript (Node.js) – Try It Online") Thanks to @Arnauld, saves 2 bytes. [Answer] # [Stax](https://github.com/tomtheisen/stax), 22 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` â╟▓ïMeee¶▐f◄┴≈┘n╛äyΩ○N ``` [Run and debug it](https://staxlang.xyz/#p=83c7b28b4d65656514de6611c1f7d96ebe8479ea094e&i=hello%21%0AhelLO,+worl_%21%0Ai+aM+yoUr+faTh__.%0AprOGraMMIng+PuZZleS+%26+cOde+____%0ACan+YOu+gUesS+tHE+ENd+oF+This+____%3F%0ATHe+qUICk+brown+FOx+JUMps+oVEr+the+la__+___.%0ARoadS%3F+wHERe+we%27re+goinG+WE+doN%27t+need+_____.%0AthE+greatESt+Trick+thE+DeVIl+EVer+PUllEd+wAs+CONvInciNg+tHe+WorLD+h_+____%27_+_____.&a=1&m=2) The general approach is a regular expression replacement of `"_"` using a callback function that slices letters of the inputs to compute each replacement character. ``` v convert to lower case '_ "_" string literal { begin block for regex replacement yVl|& all the letters only from the original input 5/ split into chunks of 5 i@ keep the ith one, where i is the 0-based number of times this block has run {97<m map 5-letter chunk to bits to indicate which are lowercase :b decode as 5-bit integer 97+] add 97 and wrap in array to convert to lower case character } end block for regex replacement R do regex replacement ``` [Run this one](https://staxlang.xyz/#c=v%0A%27_%0A%7B%0A++yVl%7C%26%0A++5%2Fi%40%0A++%7B%27a%3Cm%3Ab%0A++97%2B]%0A%7D%0AR&i=hello%21%0AhelLO,+worl_%21%0Ai+aM+yoUr+faTh__.%0AprOGraMMIng+PuZZleS+%26+cOde+____%0ACan+YOu+gUesS+tHE+ENd+oF+This+____%3F%0ATHe+qUICk+brown+FOx+JUMps+oVEr+the+la__+___.%0ARoadS%3F+wHERe+we%27re+goinG+WE+doN%27t+need+_____.%0AthE+greatESt+Trick+thE+DeVIl+EVer+PUllEd+wAs+CONvInciNg+tHe+WorLD+h_+____%27_+_____.&a=1&m=2) [Answer] # [R](https://www.r-project.org/), ~~153~~ ~~135~~ 113 bytes ``` function(s,S=utf8ToInt(s)){S[S==95]=2^(4:0)%*%matrix(S[S%in%c(65:90,97:122)]<95,5)+97 cat(tolower(intToUtf8(S)))} ``` [Try it online!](https://tio.run/##LYxtS8MwHMTf91P8KVQTrTKLdbasL8QVLWzrIN2EjVpClnbBmkiaOmHss9f4cC/u4O746aGGyRUMdS@ZEUqizidJb@r7QmXSoA7jI9mSJInCMgle0W08wt6F906NFl/ILp6QHkN3YRyN/Ggc3wQBLidR6If4Mho7jBpkVKsOXCMhTaFWlowIxvg01Mj90PmTpvN5JhtY9ptNywmcAct3HCorx8WOfZl9Co3m1KTEQKEFe4OfasrXWQvpmmtYrto23cHhoYPHfPGZSSYWDZhnDi9Kz6awr355539RXf@Dj9tccpjRzmK5NUarqjy5ePgG "R – Try It Online") Issues some warnings with the use of `matrix` but that shouldn't affect the result. Also issues warnings as `[<-` assignment will remove extraneous assigned objects by default. *40(!) bytes down thanks to JayCe's improvements* [Answer] # [C (gcc)](https://gcc.gnu.org/), 111 109 101 100 bytes *Edit:* Added lowercasing per @FrownyFrog's comment; thanks to Lynn, Christoph and user5329483 for their suggestions! ``` f(s,t,i)char*s,*t;{for(t=s;t=strchr(t,95);*t=i+1)for(i=3;i<64;s++)isalpha(*s)?i=2*i|*s<97,*s|=32:0;} ``` [Try it online!](https://tio.run/##VY/bSsNAEIbv8xRDRcxu1mJbD9RNKmIDFqQKar1QCWFzGoxJ2J1GpM2zx6S9qQPDzPf9F8Oo01Sp9ggLla@jGFxDEZbDbGYdKo1F@t8p@q3iTrWJbQQJZCoLNTeCk9wkpbbJM7Jr0irrQEwvmOTkoTNifYreRKJ7eS6N4zA0YV5loc0Nu0FvzHHLjTu9Etxsvcn4@kw2LRYE3yEWdr@EOlWiPwecd3vNYGMBYGL3wWy0R4Ad1@@jTyZ3XHVPUGIPjs1HMRCHWWM1bUuZD6mOQ/KfCV40qi/o1TxeLXLwV7GGp9c89yP4uTVw97isF4XCZQp0H8NbqR/mkAUQdHWyH8HwDw "C (gcc) – Try It Online") [Answer] # [Haskell](https://www.haskell.org/), 139 bytes ``` ([]%) a%(x:y)|x=='_'=['a'..]!!foldl1((+).(2*))(take 5a):drop 5a%y|x>'@',x<'['=[x..]!!32:(a++[1])%y|x>'`',x<'{'=x:(a++[0])%y|1<2=x:a%y a%e=e ``` [Try it online!](https://tio.run/##JU1PC4IwHL33KZZk27IkjS7iolt0EINumtgPnRYtG1awyM/eGvpOj/f3As8bF0JX7KRJmtl0BDZRwYd2ijGcY5ZiwK6bjcfVQ5TCI8ShLvFnlJIX3DhaAw3K9iENsT@d2uAtnqsQp6ao@trKDwg4TupldAic@8AXMzUYy97wQt8IZsP8c8b1Ha4Nk@21eaEJqpAl23jXQhTtmxod3kki@BFNURGXHOUGlv4VlYD6qReFlH8 "Haskell – Try It Online") [Answer] # TypeScript's Type System, ~~637~~ ~~526~~ ~~515~~ ~~505~~ ~~496~~ ~~490~~ 489 bytes ``` //@ts-ignore type a<S="abcdefghijklmnopqrstuvwxyz",A=[]>=S extends`${infer F}${infer R}`?a<R,[...A,F]>:A;type u<S,D>=D extends`${infer A}${infer R}`?`${u<S,R>}${u<S,R>}${S[A]extends a[any]?"":1}`:D;type c<S,T=[]>=S extends[{},{},{},{},{},...infer R]?c<R,[...T,a[a<u<S,"43210">>["length"]]]>:T;type p<S,O=[]>=S extends[infer A,...infer R]?p<R,F<A,0>extends a[any]?[...O,A]:O>:O;type F<S,V=c<p<a<S>>>>=[S,V]extends[`${infer A}_${infer B}`,[{},...infer R]]?F<`${A}${V[0]}${B}`,R>:Lowercase<S> ``` [Try it at the TS Playground!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4BlAXgCJiAjAYwBN0AzeAC1gCsBrAGwC2KPAEdUkcAFcAbgHcAHjgBe1ADQBBSgG0AugD5K5QugXh0iJpAAGAEgDesRK3SpCAMQC+Dpy7cAlT2sAfjJ-NW0AOmiNNXcDAC4NAG5cAkIpCjUAEUNskzMLKztHZ1dCDW9Sv0JAkJLM8jV-fSrG5taHcm0NXVNzS0gSbWJEHF1g6moEgEYghOzU-CIGLIAVHQMjAoGrbXtPNQOjw+Pj6Mjfcv8J1fCo6LW1YhHSduoAFgBmACYZgAZqPp9NpqPwLPBwBxqLpYfoEmsluk8FkAPKbQzGfpFSDaK5uWIXfG1CYo8LuUixf76bGDYajcbBB6RVGaXQJVHw1FIogUpoANUoqxRZHIwOBOgFfUKg20JWJlQA+j4ym4AEJBCLnaLEm4TCklSoOfnaf66Koa6wdBIAGWQclcDGIkHQFH0mGwy0Ia3Qkn+hEoHlI1AAEuh+PxkABCIHJTAgQiJgB6wU96R9khmAaD1DwqFRAHFUMQALIlgCSiHghAAClIAFr18HGABkhAYqJYhEVPcVsfjwEThBTaaIGfAP2zFOoHHDNtZhDkaH4ipj+jjCeTqbSY994C+U+DsBIJcIOGQAFU3KxiGsOD3Iv3N8Pt17xx9D9Q1mHCKIL+WAGFeEIOhUHtRAPFRBRCAAKQvEs8CGZB+QAUTcKEiH4Yge27B8n0HLdR29PcAFZPzVStiFQPt1wHIcRyAA) I managed to golf off a load of bytes: 1. I started by using [@emanresu A's much shorter binary-to-unary type](https://codegolf.stackexchange.com/a/264046/100664), but noticed that in this case it would be shorter if it operated on a tuple rather than string of bits, so I modified it accordingly. 2. I then thought to have the binary-to-unary type operate not on 1s and 0s, but on the characters themselves, and check if it's uppercase or lowercase within that same type, saving a lot of bytes. 3. I no longer needed the `Split` type for anything other than the alphabet, so I inlined the alphabet into it's definition. 4. I realized that `F` could be inlined into the `FillBlanks` type, by `Lowercase`ing the final result and giving the fill string a default. I also utilized [this tip of mine](https://codegolf.stackexchange.com/a/264986/108687) to reduce two `extends` clauses into one, saving around 10 bytes. 5. I changed the `Chunk` type to operate on a list of characters, so the pattern match could be reduced to just "5 items and the rest", with the 5 items selected individually, and did the splitting in `F`. 6. I did a bit more rearranging to reduce the Chunk type a lot more. 7. I golfed away 2 `infer` clauses and removed a pair of unneeded parentheses. 8. I changed `u` back to using a string and then splitting it to get its length in `c`. I’d say at this point this is one of my most well-golfed TS submissions. --- This was a fun one! The following explanation more closely resembles my old 637 bytes version, but the general structure is still roughly the same. ``` // Split<Str> converts string Str to a tuple of characters. type Split< Str extends string, Arr extends string[] = [] > = Str extends `${infer A}${infer R}` ? Split<R, [...Arr, A]> : Arr; // Lowercase alphabet tuple. type Alphabet = Split<"abcdefghijklmnopqrstuvwxyz">; // To get the case of a letter: // if it is in the lowercase alphabet, return 0, else 1. type Case<C extends string> = C extends Alphabet[number] ? 0 : 1; // Replace all occurrences of Find with Rep in string Str. type Replace< Str extends string, Find extends string, Rep extends string > = Str extends `${infer Start}${Find}${infer Rest}` // Recursively substitute until no more occurrences are found. ? Replace<`${Start}${Rep}${Rest}`, Find, Rep> : Str; // See https://esolangs.org/wiki/Binary_to_unary_conversion type BinToUn1<In extends string> = Replace<In, "1", "0*"> type BinToUn2<In extends string> = Replace<In, "*0", "0**"> type BinToUn3<In extends string> = Replace<In, "0", ""> type BinaryToUnary<Binary extends string> = BinToUn3< BinToUn2<BinToUn1<Binary>> >; // This type does the bulk of the work. type Chunk< S extends string, T extends string = "" // Map each chunk of five letters to: > = S extends `${infer A}${infer B}${infer C}${infer D}${infer E}${infer R}` ? Chunk< R, // The character of the alphabet at index `${T}${Alphabet[ // convert from binary Split<BinaryToUnary< // the case of each character in the chunk. `${Case<A>}${Case<B>}${Case<C>}${Case<D>}${Case<E>}`> >["length"]]}` > : T; // Filter out non-alphabetic characters. type Alphabetics< S extends string, O extends string = "" > = S extends `${infer A}${infer R}` ? Alphabetics<R, Lowercase<A> extends Alphabet[number] ? `${O}${A}` : O> : O; // Fill each underscore with the corresponding character // of the fill string. type FillBlanks< Str extends string, Fill extends string > = Str extends `${infer Start}_${infer Rest}` ? Fill extends `${infer X}${infer R}` ? FillBlanks<`${Start}${X}${Rest}`, R> : Str : Str; // Final type that composes all of the above to a single type: type F<S extends string> = Lowercase<FillBlanks<S, Chunk<Alphabetics<S>>>>; ``` [Try it at the TS Playground!](https://www.typescriptlang.org/play?#code/C4TwDgpgBAymA2BLYAeAUFWwBOUIA9gIA7AEwGcpydFiBzAGgygEFtcCizLrta6A2gF0oAXijC0APjFYOhEhSgADACQBvWgDMIuFgF8N23VABK+5VAD8sBMhSmGEgHSu22JyyEyAXK3YA3GhooJCs8GAAFgCGAEYQwLJwSKgARHEAxqQQWnSRiABWANbwALbEAPZgAI7Y1ACuAG4A7vggAF6pUkEh4NAAwtHkECj9eArcVDT0MuJjnIqULBEx8cACxPWl8dgiNgAMUH4AjD2h0KYQCNEZI8wwOONcSrz8TJgAYrSkT4tTfPR3mYrr9Jq96NIko8FpM1JpiDpcA9othgIZ1F8yOjjLhLtQLMwbJdrrcUHDkaj0cSqRB8conJjSE5iVJmH4Htgzn0oAAhWgAFQqAFViAB9Y4oACSxFBL2mdFmwJJI2lTlSx1Sav2ACour0wnziIKRaKAExSmUwuUAhWyYnwG4q4hq7X7TVQVI63Ws868gXCsUAZgtsp48sV9sdFq17tSet9hpRIGNxCTKET2BAof+-EVhpTouDzHzAbN6f9JolGZAUlZ3WCvv6kXqxCK6EwMGz4MYzH5XflsjjkPEnatlDhONY2IRJh508RUH685MABFl7gAKLrswEzA2JsttvMTCYRzHk9w-no5ZROIJATJeznk9+1OZlNpuGDYYoFhSdHfiMPL-hogGjCB6hgSuEFgRu-7KKyL6YFIAipPAJB0MAkSpEIQi7ieiFHFA-JcmEN6rAkiAZOQ7awP2NpAgA8vR-CDqkw50WOKhGDOejbuYyiEuEt5rFRNGOFAAAyFTNLoGRDCMf7ZuRd7rJs2y6Hs3HqIx14WERjGEX4jGkdAXzwPAPIOq2NH3NCEzWm8zDmfALEQoqHLZhOvFYCiaKijxC54migl7lALleYFJgABr8fhYUuVZ0Q2WSGgUmiGixRowUWMyhGYOyOBsnIpnhSgo4OWGNqKtJsnYPJP6JdZRQ0TATgHq2v4rKpYnlbWtalfytLAIc4gfCgqQABIQBZFQAIRdEEAD0S0ngAelY+rQEN1DHLI42pGA2CMQA4tg0QALIXdKdBQAACvUABaj3oZ2ABkUAZIx2RQKKf2iotaAretm2+jtwCmvtE2RDNkmMU4zQVNg8Cigt9bA5gG1bcRw2BlDqSIFAl1QCAwq4Fo0T8pEf3OIDGNQFjYPDQALPj-LTVA1RCpK-RFFAsTYDJMofIx+BQAAUkKF1gJQFQAGobrgWHQA6f2-TTdOrZjoPcuDACs+M8tKKIA+jWsM5tQA) All of the recursive types used here are tail-recursive, increasing the recursion limit from 50 to 999. The only exception to this is the binary-to-unary type, but it won't get near the recursion depth for any 5-bit number. [Answer] # [Red](http://www.red-lang.org), 247 bytes ``` func[s][a: charset[#"a"-#"z"#"A"-#"Z"]v: copy""parse s[any[copy c a(append v to-string c)| skip]]k: 0 t: copy""repeat n(length? v)/ 5[c: 0 p: 16 loop 5[if v/(k: k + 1) <#"a"[c: c + p]p: p / 2]append t#"a"+ c]foreach c t[replace s"_"c]lowercase s] ``` [Try it online!](https://tio.run/##VZBta9swFIW/@1ecKbAkdF3WQfchDEJJ3SajiUveymKM0eTrFywsTVbidlt/eyaHFTx9ks59zr3nylByWlESRl46PqWHSoR1FPIxRM5NTTbsMc4ue@wX67Gb9rJn0dFVlX5hTLcI6pBXL2GrQIAPuNZUJTjCqsvamqLKIIZ/UJeFjiKvHOMT7FsDQ5q4RTWQVGU2n@A4HOE6FC2kx7j64kmltFOKFMfRwJlLXOBqiK9trJYT7q0jx2qM8Dn6N9y25QuIKFWGuMghPBu6YZILl5fFTERSNWQEb/NHJ@1iWqT4nZOU6t2r1xUegg9olJFxV9cmuDd8sZi79R4P@72kNd5DBAkhdqdDTnmF78EB2ZbqNezMh79MoO6wyYv6DE869GZG@LmdT0v8MKqpcBc849t2oWuonW9gc4Lkcdz6PnZsK8WT9QTNzF8RGuobQqaK6h5PPhK17Ls/JkrO0/7z2dxH5r7I@muLjSlEiVa6pd1cwt@RweNWSj9Bc1NjGiyP80oUy8ytQXhS5uEW@TlL3I/fmp/@Ag "Red – Try It Online") ## More readable: ``` f: func[s][ a: charset[#"a"-#"z"#"A"-#"Z"] v: copy "" parse s[any[copy c a(append v to-string c)| skip]] k: 0 t: copy "" repeat n (length? v) / 5[ c: 0 p: 16 loop 5[ if v/(k: k + 1) < #"a" [c: c + p] p: p / 2 ] append t #"a" + c ] foreach c t[replace s "_" c] lowercase s ] ``` [Answer] # Go, ~~219~~ ~~217~~ ~~192~~ ~~210~~ ~~209~~ 156 bytes Saved 25 bytes thanks to [@Lynn!](https://codegolf.stackexchange.com/users/3852/lynn) Saved 53 bytes thanks to [@ovs!](https://codegolf.stackexchange.com/users/64121/ovs) Had to lose 18 bytes because of a bug with strings with no underscores :( ``` func p(s string){b:=0;n:=0;for _,c:=range s{if IsLetter(c){b+=b;if IsUpper(c){b+=1};n++;s=g.Replace(s,"_",string('a'+b%32),(5-n%5)/5)}};Print(g.ToLower(s))} ``` [Try it online!](https://tio.run/##LU/LasMwEDxHX7EI2kjYNUlLLxY6F0NCQh@XlBJkWRamsSwkmQaMv91V7OxhYWdmZ3Z1N1khf4VW0IrGINS0tnMBCFppwD64xmiP0SoD3JtGdpVahroNGFGE6t7IeZNQGNCqMbYPkHPA1h3enNjvC6Ph2J9OF/UBjyAPlYJzrOhiyaymaJxmF0s8LIF0KHO@YebWXM51VphKXYlP8RlT1tTgOH/aDo5vRlZ3Ds6pzLkTJj7hvze5@xmipvA7FYJyRNLhenOasS9r7xDfjqxMeJlcmUmS8UYbzl8HE6U@Zr4rexFSLanpchhZi3VSPrw803RLWRnzR3aMRCA6@@x23V/09pSOaJr@AQ) [Answer] # [Haskell](https://www.haskell.org/), 165 bytes ``` g"" import Data.Char f t(x:s)('_':r)=x:f t s r f[0,a]s r=g(s++[chr a])r f[n,a]s(c:r)=toLower c:f[div n$1+sum[1|isAlpha c],a+sum[n|isUpper c]]s r f _ s e=e g=f[16,97] ``` [Try it online!](https://tio.run/##NZBfb9owFMXf8ylOq2qA@KOxh01DQlUHaUkHJCqEbrDIchMTRxg7s00D0j77mBNp9@Ve/c7RPb7m1ByYENd@H7@u@e2tVxxLpS2m1NLBhFPt7WHb55HptFukNdKd8XnkCAycsvvYo4mbxnnbdLu7lGvQpFMLshbaae23aq4qppGO9ruseIe8G3bN6bgb/inMgyg5RZr0aIOkQ3FZ1uYkaRJAXBIbMy8f73fDz72vX5LrkRYSYxTSMk1TizucpCgkMxjgSEu03RkdNzfsyt116sZzbR72UCktyI1XgC5wUbHGnq45IQOv1OGTpotFIHNEp@1WsBU@IA0zBuLKm1CJn@EJeczMCnbmw19mUI9Y88I0lntvPWP4HQeTA960qiQewzOe40VpoDa@huUMghJSuwfei6LZ6h7VzH9hqFhLM@SqkE949ZGpZctCMpY1m53bch@5ZtT6K4u1LtIDajRlm0DA37gfi2Ih/AzVg8EkXL4HMi2WuXsow6vS8yl4k0ta5P/Kb4GkmnjDT1go@Z1diMcvEdNvSgRbQv6me0Fzc@3/mETRPw "Haskell – Try It Online") Example usage: `g"" "BInar_"` yields `"binary"`. [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 121 bytes ``` switch -r($args|% t*y){_{$_=$a[$n++]+97}[a-z]{$x+=$x+($_-le96);if(!(++$i%5)){$a+=,$x;$x=0};$_=$_-bor32}.{$r+=[char]$_}}$r ``` [Try it online!](https://tio.run/##bVR/b9pADP2fT@Gia4HxQ1unbeoq1G1t2rIVqAq0WhGKQmKSrEeO3iVASPPZmS@UDZadFCmy33t@9jmZiQVK5SHnazaBJiRrtfBD24O6LDNLuurlEMI3cSUxE2Y2mTVkQbU6qp58SodWfTVK2LLapKfMzDrHk4@VU39SPihXq8w//FCpJMyqNmtsecqWzbfpqVYw62Mh3x@njYTJanNoe5YcMTNNmVynhcKXcgHo1MoAJTJ1063BQkhuHpRqWUIfneBik3AOSpUssUfjIo/PA32w2hCLgYSJ1fdMs7HLoeSUkpFOhh7KRo4@k90rabXbrcCF2@jxkWMPjsDuOggmnV2xmRSutKZTn6CzaLXiqDRUENQVfJKTPrcC@NmNwB2g6kF4bYDRcUBcQt/zVaZ@titvE5ysghuhUkBuAQOCT@iV4CEuw7Ncif41wvOgdf4EYykWAVx2l/B90J4pEPeGzES4ZZq62N5cdOI58u0tbyKW8Cuaat4ct7xVDI5wcyMr3gnL6Z3B4tq4Q1hgSer@/eAKHgwidEohBIhO1qDZKP6tWpREVESki9gluvROxGBLzGCN4r9lQ88AV6IVGr0Q@lKb16ELvG9xMO7J9u2Ac8OBxVcF593OvBXYfselwSM8CHlzAZ65uVPzP950y5k6qhDCV3WyhXOfA@qhzCLOyd3CUnTnwdwndbKuQdkKg0b7ju4Cl74Kcw2UvrUCS@5t1NinSJy71XfH0BbBD4z3wBSdiuAJY5X/WOJblGPBW4/7G@vFsyzur9DJkZJhN0C4sajfvm7apkUZpbv0ZCgCvQh6IhuEQkJUChV4gUNIMiRTNWC4nKEd0nSawMxNWKKKeEiBI/ojMZUFi6z8Gq/b@PyHVfm8hRcL6fo3 "PowerShell – Try It Online") Less golfed: ``` switch -Regex ($args|% toCharArray){ _ { # is underscore $_=$a[$n++]+97 # get a char from the array of letter } [a-z] { # is letter $x+=$x+($_-le96) # $x=2*$x+($_-le96) if(!(++$i%5)){ # if(++$i%5 -eq 0) $a+=,$x # add an element to the array of letters $x=0 # init } $_=$_-bor32 # to lower } . { # is any char ('_' and letters included) $r+=[char]$_ # add the char to result } } $r ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~107~~ ~~106~~ 103 bytes ``` ->s{s.chars.map{|c|c !~/\W|\d/?c<?a?1:0:p}.join.scan(/.{5}/){|b|s[?_]&&=(b.to_i(2)+97).chr};s.downcase} ``` [Try it online!](https://tio.run/##TVBdb5tAEHzvr5j4wR9qiptIUdW0KWodEtMYY8XGVu1Yp@NYAw3h6B2uawH96y6Ql@7DaXc0O7Nzau8fT7ub07svutCGiLjSxgvPilKUAmd/h0@r8ikYmuKzyc2L6/fXWWX8lHFqaMHT/tAorqrhoCj9Um9Mtu12b/q@kUsW9y8Hbz9@GNSCqvqkjUAeUsE1VadNJ6IkkWed8zdNN3HPcZAqYS0Qgzs4Sk9hxxcRY0YDZsq9V9xx7DTEbL9eJzRHF8INCKyuhjLiKX64e4Qe6TnysQVrGkDeYRHFumWZDW0xJvzy7NEzfFUfhDv3D757TqYhl5ZCHhESzliz0Do/Sh7MTRzG1iPhQD1FCOvs91hZCOS0lyMlClr914U8shAq4rk1z7FQsXhGA93S0k5gLUlh5iWJFeDwVWPkTn/bqYinYX0xYSXV5BZR68567D/Vb3bKVZvz4hKOTB/o2E7RcUbKl4m9fv2FYuOmhAnXtTfVj6izbKvO1iAuoqLMa6xEts81dptm2Fanfw "Ruby – Try It Online") [Answer] # Japt, 25 bytes ``` r'_@r\L mè\A sTT±5 ÍdIÄÃv ``` [Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=cidfQHJcTCBt6FxBIHNUVLE1IM1kScTDdg==&input=InByT0dyYU1NSW5nIFB1WlpsZVMgJiBjT2RlIF9fX18i) --- ## Explanation ``` r'_ :Replace underscores @ :Pass each match through a function r : From original input remove \L : /[^a-zA-Z]/g m : Map è : Count \A : /[A-Z]/g s : Slice T : From index T (initially 0) T±5 : To index T+=5 Í : Convert from base-2 string to base-10 integer IÄ : Add 64+1 d : Get character at that codepoint à :End function v :Lowercase ``` [Answer] # Pyth, 36 bytes ``` Km@Gim!}kGd2c@+r1GGQ5VQp?qN\_.(KZr0N ``` [Try it here](http://pyth.herokuapp.com/?code=Km%40Gim!%7DkGd2c%40%2Br1GGQ5VQp%3FqN%5C_.(KZr0N&input=%22THe%20qUICk%20brown%20FOx%20JUMps%20oVEr%20the%20la__%20___.%22&debug=0) ### Explanation ``` Km@Gim!}kGd2c@+r1GGQ5VQp?qN\_.(KZr0N @+r1GGQ Get the letters from the input... c 5 ... in chunks of 5. m d For each chunk... m!}kG ... check if each letter is uppercase... i 2 ... converted to binary... @G ... and get the corresponding letter. VQp For each character in the input... K ?qN\_.(KZ ... if the character is '_', replace it... r0N ... otherwise, lowercase it. ``` [Answer] # [Perl 5](https://www.perl.org/) `-p`, 78 bytes ``` for$h(s/\W|\d//gr=~y/a-z/0/r=~y/A-Z/1/r=~/.{5}/g){s%_%chr 65+oct"0b$h"%e}$_=lc ``` [Try it online!](https://tio.run/##JYxNi8IwFEX3/oqHtIwi7YuLunMhWlBwdEBHwQ9CjbEphqYkQRlr/enGOt7FuYe7uAXXMnLupLQnWgZ36/vuiJjq/uMPk@CGBP91EGyw@1YMy6jCtF0an/pMaOhFHcVskxw80fR55dG@ZM5ZImJINU9svLCw1Bk7g62nEV9NJMQrruHnV8r4CNeBgeF8dpnkLJulYMcc1kpPRyAo0Dpfn6Jho9zOcw7TxNSHvAZLKN1XT1XYTOXGBd9RSLrEBcUL "Perl 5 – Try It Online") [Answer] # [Python 3.5](https://docs.python.org/3.5/), 296 bytes ``` u=input();f=u.find('_');m=''.join([c for c in u if c.isalpha()]);z=[chr(int(''.join(['0'if o.islower() else'1' for o in l]),2)+65)for l in[m[h:h+5]for h in range(0,len(m),5)]if len(l)==5];[z.insert(v,d)for v,d in enumerate(u[f:])if d!="_"];u=list(u);u[f:]=z[:len(u[f:])];print(''.join(u).lower()) ``` [Try it online](https://tio.run/##TY/BSsQwEIZfZewlGbaUVVnEDTmJooJ4cb2EEGo3NdE0qWnj6r58bXZFPA3zz/d/MP33aII/n6bEre/TSJG1PFWt9VtKFEHWcUKqt2A9FQ20IUID1kMC20JT2aF2vakpSmR7LhoTqfUj/WuQJZm5MHMu7HSkCNoNmpySgylkk5NYnuHi8gJz5OZIdMKszWIlc2AyE2v/qumydNrTDssVytmaF4ecryQT@8r6QceRfpbbg2eeuah96nSsR02TaNcS59r2hBeqkCxxZ4eRJmSHE9@LdTYeOcn6@P@RhNXvAzhNxdOtho/N3dU7vMSw83Dz@AX3m4d@gPB8HWE0GlytFCilquIH) ## First code golf :) ## (I know its not small in bytes, I was just having fun making a 1 line code) ## Here is the explanation: --- *User input* > > u=input() > > > --- *Finds the index of the first \_ in the string and stores it* > > f=u.find('\_') > > > --- *strips string of all non-alpha characters* > > m=''.join([c for c in u if c.isalpha()]) > > > --- *Splits the alpha string into an array with each element consisting of 5 characters* Ex. ['THeqU', 'ICkbr', 'ownFO', 'xJUMp', 'soVEr', 'thela'] *Then converts lowercase characters to 0 and uppercase characters to 1* Ex. ['11001', '11000', '00011', '01110', '00110', '00000'] *and converts the binary string to an integer, adds 65 and converts that to a character* Ex. ['z', 'y', 'd', 'o', 'g', 'a'] > > z=[chr(int(''.join(['0' if o.islower() else '1' for o in l]),2)+65) for l in [m[h:h+5] for h in range(0,len(m),5)] if len(l)==5] > > > --- *finds all characteres after the first \_ and pushes them into the array z at their respective locations (defined above)* Ex. ['z', 'y', ' ', 'd', 'o', 'g', '.', 'a'] > > [z.insert(v,d) for v,d in enumerate(u[f:]) if d!="\_"] > > > --- *split our string into a list of characters* > > u=list(u) > > > --- *slice our string from the first \_ to the end of the list and replace it with the array z. I also had to slice the array z to the length of the split string from the first \_ to the end because I got an extra character in the lazy dog example (the "a" at the end of the examples above)* > > u[f:]=z[:len(list(u[f:]))] > > > --- \*print out the answer \* > > print(''.join(u).lower()) > > > --- [Answer] # Java 10, ~~186~~ ~~184~~ 162 bytes ``` s->{var b="";for(Byte c:s.getBytes())s=(b+=c>64&c<91?1:c>96&c<123?0:"").length()>4?s.replaceFirst("_",(char)(97+c.valueOf(b,2))+(b="")):s;return s.toLowerCase();} ``` -2 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##jVHvb9owEP3ev@ItH4qjttFgVafCAK00bdkKqcqPakxTZJwjSXFtZhsYqvjbWejQvqaWLd2d3717d/fMV/zsOZnvhOTWosdz9XoE5MqRmXFB6O9dYOBMrlIIdjCs3yji2@IV1zrucoE@FJrY2bPW64obTJue15hpw642jiDqNkjJ7W3LfN822fSkKVoX58fiy2W1Xa2L1uVFYVdrn9of657nB5JU6jLmt87bNjC0kIWcm9xYx7zYO2Ui48Znl59PRLDicknRjE1Pa75/wvaFfb9uG4bc0ijYwOl7vSbT4ZaY39juGv90L5ZTWeg@yF/pPMFLMYBDjz9/gfuH7jfW0Uugly5YFF9OKqYCwbyMpNQfimKNMth9dIq1NjIuR@fgPWz0yGDGh1kcB6UZCxPdGt7rdYvFPCwnE0kDHENECSEuTml@hyv8iJZIR2QHcHchwn4CfYNhlts3inYpx/CO8HvU7cwxNXqtcBP9wbdRb2Ghx6GBywiSx/GerbyhR82TQRvru/CRsKaKIaQ6V7d4CpHofsVBESVvyt7B5rIQqSHuwoHD0ORijn3omsZdiXBMBg8jKcME668Wnai/6iqR99NiEIQnbe6vkb3pjivxe0tedRU35YOv1tDT6jttyqHZ5oHMVMvu5P9Ct0fb3V8) **Explanation:** ``` s->{ // Method with String as both parameter and return-type var b=""; // Binary-String, starting empty for(Byte c:s.getBytes()) // Loop over the characters of the input-String: s=(b+=c>64&c<91? // If the current character is a lowercase letter: 1 // Append "1" to the binary-String :c>96&c<123? // Else-if it's an uppercase letter: 0 // Append "0" to the binary-String : // Else (it's not a letter): "" // Append nothing to the binary-String ).length()>4? // And if the length of the new binary-String is now 5: s.replaceFirst("_", // Replace the first "_" in the input-String with (char)(97+c.valueOf(b,2)) // the binary-String as character +(b="")):s; // And reset the binary-String return s.toLowerCase();} // Return the modified lowercased input-String ``` [Answer] # [jq](https://stedolan.github.io/jq/), ~~165~~ 159 bytes *Unnecessary space before `as`, and found a place where`(a|[thing])[]` could be replaced with `(a|thing)`* ``` reduce(split("[^a-z]";"i")|add|explode|while(length>4;.[5:])[:5]|map(try(.>91//1)+0//0)|reduce .[]as $x(3;2*.+$x)+1)as $r(ascii_downcase;sub("_";[$r]|implode)) ``` ~~[Try it online!](https://tio.run/##NY/dbptAEIXveYopsmqoFRynzUWDlKh1SEwajOW/qEZ0tWansM1ml@ziYrf01UuJo87FXBydOeebH89tq5HtMnRMKXjl2Mk3evIrtX2b225DGWtwXwrFsEnqggt0BMq8Ki4/@F5yfpG6ycV52jzR0qn0wfEuP46Gw5E7OB0OT93mNRi8JAVqoLd33vtn77xBb@8ORt3lq6odajLOCVO1zKhB3@y2jk1sP@nptOFPx3LXbdsChVBvLA40goNaafhOlwUhnlXq@FbTKAplDrPdZiNwAW8hixkC6cYaUwlf4x3kKzQLqCYBBFMG6gaWBTdHy5W1nCA8r8LxI2x1BwI38R7uVlFpQK0DDVWBICghL27PmivKFldQT4I5Qo19jZArLm/hIQCmpv0KJCI7Jnfuqggg10irYFHBUvPsEV6ka1yHAoI1apithAgY1J8MjOPpz1BmfJp3oAgPSt9fQ3HsJX3yP/JzKKkm1ugMIiW/4IFYxWGGeqtEuOke/p3EEuGemq4Pu5V15Omfv6qsuJKmPZnrfw "jq – Try It Online")~~ [Try it online!](https://tio.run/##NY9db9MwFIbv8ysOUUUTqqXrYBcs0ibosjWwNlXbdKJRsNz4kJh5dmanpIXw1wlpEefiXLx69H58f2lbjWyXoWNKwSvHTr7Ss5@p7dvcdhvKWIP7UiiGTV1wgY5AmVfF9TvfSy6vUje5ukybZ1o6lT443vX70XA4cgfnw@G52/zzBS9JqYHe3nnrX7zxBr29Oxi5R0U71GScE6ZqmVGDvtltHZvYftLTacOfT7Gu27YFCqFeWRzoFA4q1vCNrgpCPKvU0b2m02koc5jvNhuBS3gNWcQQSHfWmEr4Eu0gj9EsoZoEEMwYqDtYFdyckBtrNUF4icPxE2x1VwTuoj18iqelAbUONFQFgqCEHGnPWijKljdQT4IFQo19jZArLu/hMQCmZv0KJCI7OXd0VQSQa6RVsKxgpXn2BEfpFtehgGCNGuaxEAGD@oOBcTT7EcqMz/KuKMKj0g@3UJxySZ/8t/wYSqqJNbqAqZKf8UCs4jBHvVUi3HSDfyWRRHigpsvD7mVd8/T3H1VWXEnTni30Xw "jq – Try It Online") Phew, this was a fun one! `reduce` is the real star of the show here. ``` reduce ( # filter to alphanumeric characters and explode string into codepoints split("[^a-z]";"i") | add | explode | # chunk letters from string into full groups of 5 while(length>4; .[5:])[:5] | # for each chunk emit 1 if uppercase, 0 if lowercase map(try(.>91//1)+0//0) | # reduce each chunk to a codepoint # start with 3, double and add the next element in the array. # [0,0,1,1,0] -> 6 [0,1,1,0] -> ... 102, we need to add one to map correctly reduce .[] as $x(3;2*.+$x)+1 # for each code point $r: ) as $r ( # initialize with lowercased input ascii_downcase; # substitute "_" with the current letter ([codepoint]|implode) sub("_";[$r]|implode) ) ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 135 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 16.875 bytes ``` \_ÞIλ?Ǎ5ẇƛaB›øA}¢ɽ ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJzPSIsIiIsIlxcX8OeSc67P8eNNeG6h8abYULigLrDuEF9wqLJvSIsIiIsIkNhbiBZT3UgZ1Vlc1MgdEhFIEVOZCBvRiBUaGlzIF9fX18/Il0=) The `s` flag is for user convenience. Outputs as a list of characters otherwise. ## Explained ``` \_ÞIλ?Ǎ5ẇƛaB›øA}¢ɽ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏⁠‎⁡⁠⁣⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁢‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏⁠‎⁡⁠⁤⁡‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌­ \_ÞIλ }¢ # ‎⁡Replace the indices that correspond to "_"s by each letter in: ?Ǎ5ẇ # ‎⁢ Push the input with non-letters removed, wrapped in chunks of length 5 ƛ } # ‎⁣ To each chunk: aB› # ‎⁤ int(is_upper(chunk), 2) + 1 øA # ‎⁢⁡ Nth letter ɽ # ‎⁢⁢Convert that to lowercase 💎 ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). ]
[Question] [ Stack Exchange automagically [detects serial voting](https://meta.stackexchange.com/q/126829/180276) (when one user either upvotes or downvotes many of another user's posts) and reverses it. In this challenge, you will implement a very, very simple "serial vote" detector. ## Input The input is a string representing a list of votes. Every group of two characters represents a vote—the first one is the voter, and the second is the user being voted on. For example, the following input ``` ababbccd ``` can be parsed as `ab` `ab` `bc` `cd`, and represents `a` voting on `b` twice, `b` voting on `c` once, and `c` voting on `d` once. The input will consist of only lowercase letters, and it will always be an even length > 0. You also can't vote on yourself (so no `aa` or `hh`). ## Output For the purposes of this challenge, *serial voting* is defined as any given user voting on any other user three or more times. The output is how many votes should be reversed for each user (that is, how many votes **on** each user were reversed, not how many votes that they have given were reversed), in the format `[user][votes][user2][votes2]...`. For example, an input of `abababab` (`a` voting on `b` four times) should output `b4` (four votes have been reversed from `a` to `b`). The output may be in any order you would like, but both the input and output must be single strings as described above. ## Test cases ``` In Out --------------------------------------------------------------------------- abababcbcbcbcbbababa b7a3 edfdgdhdfgfgfgih g3 jkkjjkkjjkkjljljljmlmlnmnmnm j6k3m3 opqrstuv <none> vwvwwvwv <none> xyxyxyxyxyxyxyzyzyzyxzxzxz y10z3 nanananananananabatman a8 banana <none> ``` [Answer] # [Unreadable](https://esolangs.org/wiki/Unreadable), ~~1830~~ ~~1796~~ ~~1791~~ ~~1771~~ ~~1762~~ ~~1745~~ ~~1736~~ ~~1727~~ ~~1626~~ ~~1606~~ 1577 bytes The output is in reverse alphabetical order (`z` to `a`) but according to your rules that appears to be permissible. > > '"""""'""""""'""'""'"""'""'""""""""""'""""""'""""""'""'"""'""""""'"""'""""""""""'""""'"""""'""""""'""'""'""'"""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'"""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'""""""'"""'""'"""""""'"""'"""""""""'""'""'""'"""""""'"""""""'"""'"""""""""'""'""'""'""""""'"""""""'"""'""""""""'"""""""'"""""""'"""'"""""""'"""""""'""'"""'""'""'""'"""""""'"""""""'""'"""'""'"""""""'"""""""'""'"""'""""""'""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""'"""""'""""""'""'""'""'"""'""""""""'"""""""'""'""'""'"""'""""'""""'"""""""""'""""""""'""""""'""'"""'""'"""""""'""""""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""""'""'""'""'"""'"'"""""""'"""'"""'"""""'""""""""'""""""'""""""""'"""'"""""""'""'"""'""""'""""""'"""'""""""'""'"""'"""'""""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'"""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'""""""'"""'""'"""""""'"""'""""'""""""'""'"""'""'"""""""'""'"""'""""""'"""'"""'"""""'"""""""'""'""'"""'"'"""""""'""""""""'""""""'""'""'"""'""'"""""""'""'""'""" > > > ## Explanation First, to get an impression of what Unreadable can do, here is its basic operation: * You have an infinite tape of arbitrary-size integer cells * You do *not* have a memory pointer like in Brainfuck; instead, you dereference cells by their location on the tape. This means you can “read value #4” or “read value #(read value #4)” (double-dereference). * You can only read or write memory cells (not directly increment/decrement like in Brainfuck). * You can increment/decrement values within an expression. Thus, to increment a memory cell you have to *read*, *increment*, *write*, or differently put: `write(x, inc(read(x)))`. * There are while loops and ternary conditionals that can only check for zero vs. non-zero. This program uses the tape as follows. The variable names will be used in the pseudocode later below. Also, this documents the first version (which was 1830 bytes); see the edits at the bottom for what’s changed since. * **Cell 0:** variable `q` * **Cell 1:** variables `a`, `p`, `ch` * **Cell 2:** variables `hash`, `v` * **Cell 3:** variables `b`, `r` * **Cell 4:** variables `aa`, `l` * **Cell 5:** remains 0 to mark the “end” of the string of decimal digits * **Cells 6–95:** store the string of decimal digits backwards * **Cells 96–121:** store the number of votes to be deducted from users `a` (96) to `z` (121) (the letter’s ASCII code minus one). * **Cells 4657–7380:** remember which voter/votee combinations have been encountered how many times. These cells have only 4 possible values: `0` = not seen yet, `-1` = seen once, `-2` = seen twice, `-3` = seen any number of times more than 2. The algorithm essentially proceeds as follows: * Keep reading pairs of characters `a` and `b`. Calculate the hash value `(a-2)*(a-1)+b-1`, which is unique for every combination of letters a–z. * Check the memory cell at that hash value (`*hash`). If it’s `-3`, the user is already eligible for vote removal, so increment `*(b-1)`. Otherwise, decrement `*hash`. If it’s *now* `-3`, the user has just *become* eligible for vote removal after three occurrences, so increment `*(b-1)` by `3`. * After this, go through the characters in reverse order (`z` to `a`) and output the ones that need votes deducted. This requires manual integer division by 10 to translate the number into decimal digits. With all that clarified, this is what the program looks like as pseudocode: ``` // Read pairs of characters while (a = read) + 1 { b = read // Calculate hash = (a-1)*(a-2)/2 + b-1 // This also sets a = b-1 hash = 0 while --a { aa = a while --aa { ++hash } } while --b { ++a ++hash } // If this combination has just been seen for the third time, // increment *a by 3; if more than third time, increment *a by 1 *a = (*hash + 3) ? ((--*hash) + 3 ? *a : (*a+3)) : (*a+1) } // Loop through the characters z to a l = 27 while --l { // l loops from 26 to 1 (not 0) (v = *(ch = l + 95)) ? { // 'a' is ASCII 97, but cell 96 print (ch+1) // print the votee // Now we need to turn the number v into decimal. // p points to where we are storing decimal digits. p = 5 while v { // Integer division by 10 (q=quotient, r=remainder) r = (q = 0) while v { --v (++r - 10) ? 1 : { r = 0 ++q } } // Store digit ASCII character *(++p) = r + 48 // 48 = '0' v = q } // Now output all the digit ASCII characters in reverse order while *p { print *(--p + 1) } } : 1 } ``` **Edit 1, 1830 → 1796:** Realized that I can re-use the return value of a while loop in one place. **Edit 2, 1796 → 1791:** Turns out the program is slightly smaller if, instead of using the cells 6–95, I store the decimal digits in the negative-numbered cells (–1 onwards). As an added bonus, the program is no longer limited to 10⁹⁰ votes! **Edit 3, 1791 → 1771:** Instead of assigning the result of `*(ch = l + 95)` to `v`, I now assign it to `q` and then move the assignment `v = q` into the while condition, taking the code to 1777 bytes. Then swap the location of `q` and `v` on the tape because `q` is now 1 more common than `v`. **Edit 4, 1771 → 1762:** Duh. Initializing `hash` to 1 instead of 0 is 9 bytes shorter. The hash code is now 1 more, which doesn’t matter. **Edit 5, 1762 → 1745:** If I initialize `q` and `r` to 1 instead of 0, I have to sprinkle some `-1`s in places to make it right, and it all seems to cancel out — except that the `while v { --v; [...] }` loop now needs to execute one fewer iteration, which I can do by saying `while --v { [...] }`, which is 26 characters shorter. **Edit 6, 1745 → 1736:** Instead of `{ r = 1; ++q }`, we can write `q = *((r = 1)+1)+1`. This relies on the fact that `q` is in variable slot #2. If it were in slot #1 this would be even shorter, but then the entire program would be longer overall. **Edit 7, 1745 → 1727:** Reverted Edit 6 and instead achieved the saving by inlining the innermost while loop into the expression that calculates the digit ASCII code, which also ends up at 1736 bytes... but then saved a decrement instruction (9 bytes) by changing `((++r) - 11) ? r :` to `(r - 10) ? ++r :`. **Edit 8, 1727 → 1626:** Reworked the hash calculation. It now uses one fewer while loop. Cell locations are now at their actual ASCII codes (not off by 1 anymore). Reshuffled variables to different locations on the tape because they now occur with different frequency. **Edit 9, 1626 → 1606:** More crazy inlining. The body of the first while loop now looks something like this: ``` // b = next char *(b = (hash = read)) = { // hash = b + (a-1)*(a-2)/2 while (a2 = --a) { while --a2 { ++hash } } // If this combination has just been seen for the third time, // increment *b by 3; if more than third time, increment *b by 1 (*hash + 3) ? ((--*hash) + 3 ? *b : (*b+3)) : (*b+1) } ``` and the variable assignment has now almost completely changed. **Edit 10, 1606 → 1577:** I observed that `a` and `a2` are both decremented to 0 in while loops, so if I could pair `p` with either of those, but *not* with `ch`, I wouldn’t need to initialize `p` to `0` (which costs 29 bytes). Turns out I can do that by swapping `p` and `r`. The newest variable assigments (and their frequency of occurrence in the code) are now: ``` 0 = v (3) (total 3) 1 = hash (6), r (5), ch (2) (total 13) 2 = b (4), q (5) (total 9) 3 = a (3), p (5) (total 8) 4 = a2 (3), l (4) (total 7) ``` [Answer] # CJam, 23 bytes Run-length party! ``` q2/$e`{3a>},e~Wf=$e`Wf% ``` or ``` qW%2/$e`{3a>},e~:ce`Wf% ``` [Run all test cases](http://cjam.aditsu.net/#code=qN%2F%7BS%2F0%3D%3AQ%3B%0A%0AQ2%2F%24e%60%7B3a%3E%7D%2Ce~Wf%3D%24e%60Wf%25%0A%0A%5DoNo%7D%2F&input=abababcbcbcbcbbababa%20%20%20%20%20%20%20%20%20%20b7a3%0Aedfdgdhdfgfgfgih%20%20%20%20%20%20%20%20%20%20%20%20%20%20g3%0Ajkkjjkkjjkkjljljljmlmlnmnmnm%20%20j6k3m3%0Aopqrstuvwxyz%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%3Cnone%3E%0Ananananananananabatman%20%20%20%20%20%20%20%20a8) ### Explanation ``` q2/ e# Read input and split into pairs. $e` e# Sort and run-length encode - this tallies the pairs. { e# Filter the tallies... 3a> e# Keep only those which start with a 3 or greater. }, e# Now we need to group the remaining pairs. e~ e# Run-length decode the remaining pairs. Wf= e# Select the second character from each pair (the one being voted on). $e` e# Tally the characters by sorting and RLE'ing again. Wf% e# Reverse each pair, because CJam's RLE has the number first and the character last. ``` The other version starts by reversing the pairs, which saves two bytes elsewhere: a) selecting the first character in each string is only `:c` instead of `Wf=` for selecting the second. b) We don't need to sort again before the second RLE, because the pairs were already sorted primarily by the remaining character. [Answer] ## Bash, ~~95~~ ~~94~~ ~~85~~ 81 bytes ``` fold -2|sort|uniq -c|awk '$1>2{c[substr($2,2)]+=$1}END{for(x in c)printf x c[x]}' ``` An elegant-ish but long first solution to start off... Thanks to [User112638726](https://codegolf.stackexchange.com/users/42523/user112638726) for saving a byte with `sed`, DigitalTrauma for saving 9 with `fold`, and [Rainer P.](https://codegolf.stackexchange.com/users/48165/rainer-p) for saving 4 more with `awk`'s `substr`! To see how it works, let's take the input `abababcbcbcbcbbababa`. * After `fold -2` (wrap the line to a width of 2), we have ``` ab ab cb cb cb cb ba ba ba ``` * After `sort | uniq -c` (`-c` is a very nifty flag to `uniq` that outputs the count of how many times each line appears in the input), we get ``` 3 ab 3 ba 4 cb ``` * Now let's examine the final `awk` command: + `$1>2`: Only output stuff if record 1 (aka the number of identical votes) is greater than 2 (that is, ≥ 3). In other words, ignore any line that starts with a number ≤ 2. + `{c[substr($2,2)]+=$1}`: If the number is greater than 2, add that number to the `c` hash table, using the second char of record 2 (aka the vote-ee) as the key. (We don't have to initialize everything to zero; `awk` does that for us.) + `END{...}`: This just means "after processing the entire file, here's what to do next." + `for(x in c)printf x c[x]`: Fairly self-explanatory. Print every key and its corresponding value. [Answer] # JavaScript, ~~114~~ ~~113~~ 110 ``` f=s=>eval('o={},s.replace(/../g,m=>s.search(`^((..)*${m}){3}`)?0:o[c=m[1]]=~~o[c]+1);r="";for(v in o)r+=v+o[v]'); ``` Test cases: ``` f=s=>eval('o={},s.replace(/../g,m=>s.search(`^((..)*${m}){3}`)?0:o[c=m[1]]=~~o[c]+1);r="";for(v in o)r+=v+o[v]'); document.body.innerHTML = [["abababcbcbcbcbbababa","b7a3"], ["edfdgdhdfgfgfgih","g3"], ["jkkjjkkjjkkjljljljmlmlnmnmnm","j6k3m3"], ["opqrstuv",""], ["vwvwwvwv",""], ["xyxyxyxyxyxyxyxyzyzyzyxzxzxz","y11z3"], ["nanananananananabatman","a8"], ["banana",""]].every(v=>(f(v[0])=="" && v[1]=="") || [...new Set(f(v[0]).match(/../g))].every(p=>new Set(v[1].match(/../g)).has(p))) ``` At a high level, this code populates an object with key-value pairs that map vote recipients to number of votes, like `{ b:7, a:3 }` and then joins them into a string in a `for` loop. The code is in an `eval` expression to allow the use of `for` within an arrow function without needing spend bytes on `{ }` and `;return r`. (Props to [user81655](https://codegolf.stackexchange.com/users/46855/) for saving three bytes!) Explanation of `eval` code: ``` o={}, // object to hold name/vote mapping s.replace(/../g, // for each pair of chars in input m=>s.search(`^((..)*${m}){3}`) // see if pair appears 3 times // (0 if true, -1 if not) ?0 // if not, do nothing :o[c=m[1]]=~~o[c]+1 // if yes, increment the property named after // the second character in the pair ); r=""; // return string for(v in o)r+=v+o[v] // populate string with characters and vote totals ``` [Answer] # JavaScript (ES6), ~~195~~ ~~174~~ ~~169~~ ~~167~~ 158 bytes ``` s=v=>eval("a={},b={},e='';(v.match(/../g)).forEach(c=>{a[c]=(a[c]||0)+1});for(var k in a){d=k[1];a[k]>2&&(b[d]=(b[d]||0)+a[k])};for(var k in b){e+=k+b[k]};e") ``` ## Test ``` s=v=>eval("a={},b={},e='';(v.match(/../g)).forEach(c=>{a[c]=(a[c]||0)+1});for(var k in a){d=k[1];a[k]>2&&(b[d]=(b[d]||0)+a[k])};for(var k in b){e+=k+b[k]};e") ``` ``` <input type="text" id="input" value="abababcbcbcbcbbababa" /> <button onclick="result.textContent=s(input.value)">Go</button> <pre id="result"></pre> ``` [Answer] # Pyth, 22 bytes ``` pM_srSsfttTtMM.gkcz2 8 ``` Try it online: [Demonstration](https://pyth.herokuapp.com/?code=pM_srSsfttTtMM.gkcz2+8&input=edfdgdhdfgfgfgih&test_suite_input=abababcbcbcbcbbababa%0Aedfdgdhdfgfgfgih%0Ajkkjjkkjjkkjljljljmlmlnmnmnm%0Aopqrstuv%0Avwvwwvwv%0Axyxyxyxyxyxyxyzyzyzyxzxzxz%0Ananananananananabatman%0Abanana&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=pM_srSsfttTtMM.gkcz2+8&input=edfdgdhdfgfgfgih&test_suite=1&test_suite_input=abababcbcbcbcbbababa%0Aedfdgdhdfgfgfgih%0Ajkkjjkkjjkkjljljljmlmlnmnmnm%0Aopqrstuv%0Avwvwwvwv%0Axyxyxyxyxyxyxyzyzyzyxzxzxz%0Ananananananananabatman%0Abanana&debug=0) ### Explanation: ``` pM_srSsfttTtMM.gkcz2 8 cz2 chop the input into pairs .gk group these pairs by their value tMM discard the first char in each pair in each group fttT discard all groups, that contain less than three pairs s concatenate all groups to get a list of chars S sort all chars r 8 run-length-encoding s concatenate all (count,char) pairs _ reverse the order pM print each element without separator ``` ### Example: ``` input: ededgdhdfgfgfgihed chop: ['ed', 'ed', 'gd', 'hd', 'fg', 'fg', 'fg', 'ih', 'ed'] group: [['ed', 'ed', 'ed'], ['fg', 'fg', 'fg'], ['gd'], ['hd'], ['ih']] discard: [['d', 'd', 'd'], ['g', 'g', 'g'], ['d'], ['d'], ['h']] discard: [['d', 'd', 'd'], ['g', 'g', 'g']] concat.: ['d', 'd', 'd', 'g', 'g', 'g'] sort: ['d', 'd', 'd', 'g', 'g', 'g'] rle: [[3, 'd'], [3, 'g']] concat.: [3, 'd', 3, 'g'] reverse: ['g', 3, 'd', 3] print: g3d3 ``` [Answer] ## Haskell, 103 bytes ``` import Data.Lists f s|c<-chunksOf 2 s,b<-[e!!1|e<-c,countElem e c>2]=nub b>>= \q->q:show(countElem q b) ``` Usage example: `f "jkkjjkkjjkkjljljljmlmlnmnmnm"` -> `"k3j6m3"` How it works: ``` c<-chunksOf 2 s -- split the input into lists of 2 elements b<-[e!!1|e<-c,countElem e c>2] -- for every element e of that list take the 2nd -- char if there are more than 2 copies of e nub b>>= \q->q:show(countElem q b) -- take every uniq element thereof and append -- the number how often it appears ``` [Answer] # Mathematica, ~~110~~ ~~100~~ 99 bytes ``` g=Cases[Tr@#,#2,All]&;""<>g[g[BlockMap[$,Characters@#,2],i_*_/;i>2]/.$->Last,i_*x_:>x<>ToString@i]& ``` [Answer] # Pure Bash, 151 Longer than I'd hoped, but here it is. ``` declare -A a n for((;v<${#1};v+=2));{((a[${1:v:2}]++));} for u in ${!a[@]};{((a[$u]>2))&&((n[${u:1}]+=a[$u]));} for u in ${!n[@]};{ printf $u${n[$u]};} ``` Uses associative array indexing to do the necessary counting. Requires bash version 4.0 or greater. [Answer] ## Perl, ~~86~~ ~~84~~ 83 bytes ``` s/../$h{$&}++/eg;@l=%l=map{/./;$h{$_}>2?($',${$'}+=$h{$_}):()}keys%h;$"="";$_="@l" ``` That's 82 bytes plus 1 for the `-p` commandline argument: ``` $ echo xyxyxyxyxyxyxyxyzyzyzyxzxzxz | perl -p 86.pl y11z3 ``` --- Somewhat ungolfed: ``` s/../$h{$&}++/eg; # construct hash %h with pair counts @l = %l = map # assign to array via hash to filter dupes { /./; # match the first character $h{$_}>2? # filter on 3 or more identical votes ( # return a 2 element list (k/v pair for %l): $', # $POSTMATCH: the 2nd character (votee) ${$'} += $h{$_} # increment votee total votes, value is new total ) :() } keys %h; # iterate the unique pairs $" = ""; # set $LIST_SEPARATOR to empty string $_ = "@l" # implicit join using $"; $_ gets printed with -p ``` * **update 84** Save 2 bytes by inlining the grep * **update 83** Save 1 byte by using global temporary vars `${$'}` instead of `$g{$'}`. Unfortunately, `$$'` doesn't work. [Answer] ## PHP 247 Characters (ouch) ``` $f='';for($i=0;$i<strlen($s);$i=$i+2){$a[]=$s[$i].$s[$i+1];}$r=[];for($i=0;$i<count($a);$i++){$t=array_count_values($a);$c=$t[$a[$i]];if($c>=3){$r[$a[$i][1]][$a[$i][0]]=$c;}}for($i=0;$i<count($r);$i++){$f.=key($r).array_sum(current($r));next($r);} ``` Explained ``` // Test Case $s = 'nanananananananabatman'; // Final result here $f = ''; // Seperate strings into array in 2 character chunks for ($i = 0; $i < strlen($s); $i = $i + 2) { $a[] = $s[$i] . $s[$i + 1]; } // Make an array of data // The first level of array has voted on user as key // Inside of that array is a dictionary with the voter user as the key, and the number of votes as the value $r = []; for ($i = 0; $i < count($a); $i++) { $t = array_count_values($a); $c = $t[$a[$i]]; if ($c >= 3) { $r[$a[$i][1]][$a[$i][0]] = $c; } } // Combine votes from different users to the same user into the final result string for ($i = 0; $i < count($r); $i++) { $f .= key($r) . array_sum(current($r)); next($r); } echo $f; ``` Did this without peeking at other answers. This is the most difficult code golf I've tackled yet. I welcome all optimizations. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` 2ô.γθ}εgyθθì? ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f6PAWvXObz@2oPbc1vfLcjnM7Dq@x//@/ohIZVoFhRRUI/tfVzcvXzUmsqgQA "05AB1E – Try It Online") Or 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) flagless: ``` 2ô.γθ}εgyθθì}J ``` [Try it online!](https://tio.run/##yy9OTMpM/f/f6PAWvXObz@2oPbc1vfLcjnM7Dq@p9fr/v6ISGVaBYUUVCAIA "05AB1E – Try It Online") #### Explanation ``` 2ô # Split into pairs .γ # Group by: θ} # Last item ε # Map: g # Push length y # Push the list again θθ # Last item of last item ì # Prepend to length # (--no-lazy flag version) ? # Print without newline # --no-lazy flag makes sure that # the printing gets done correctly # (Flagless version) } # Close the map J # And join into a string # Implicit output ``` [Answer] # [Thunno](https://github.com/Thunno/Thunno) `J`, \$ 24 \log\_{256}(96) \approx \$ 19.75 bytes ``` 2Ap.rz:zGAJzHeDAJAJsLZPJ ``` [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSl1LsgqWlJWm6FjuMHAv0iqqsqtwdvao8Ul0cvRy9in2iArwg0lBVC3ZVVCLDKjCsqAJBiAoA) #### Explanation ``` 2Ap # Split into pairs .rz: # Reverse each and sort zGAJzH # Group by first item eD # Map: AJAJ # Push first item of first item sL # Swap and push length ZPJ # Pair and join # J flag joins the resulting list # Implicit output ``` [Answer] # [Python](https://www.python.org), 143 bytes ``` lambda s:''.join((z:=[*l])[0][-1]+f'{len(z)}'for _,l in groupby(g(s),lambda a:a[-1])) g=lambda x:[*x]and[x[:2]]+g(x[2:]) from itertools import* ``` [Attempt This Online!](https://ato.pxeger.com/run?1=TY5NCsIwFIT3niK7vtcfUVcS6ElikIimRtIkpCmkFc_gAdwIonu33sTbiLYL-XYfM8NcHq4Le2uuN1mu7m2QxfJ91qLebAVpaJJMD1YZgJ6WLNUc2YyzYs4zmRz1zkCPp0RaT9a5JsqQytvWbTqooMF8HBFUfBuIk6ocVaQsjVyYLYuMLjjPKohsQTlOpLc1UWHng7W6Iap21od0uPV0XpkAEpRxbQBEHPz1Fbt_-h-x_zIkPg) [Answer] # R, 221 bytes ### code ``` f=function(s){t=strsplit(gsub("(.{2})","\\1 ", s)," ")[[1]];z=table(t)[table(t)>2];n=substr(names(z),2,2);x=data.frame(y=z,t=n);a=aggregate(x$y,by=list(x$t),sum);for(i in nrow(a):1)cat(as.character(a[i,1]),a[i,2],sep="")} ``` ### ungolfed ``` f <- function(s){ l <- gsub("(.{2})", "\\1 ", s) t <- strsplit(l," ")[[1]] z <- table(t)[table(t)>2] n <- substr(names(z),2,2) x <- data.frame(y=z,t=n) a <- aggregate(x$y, by=list(x$t),sum) for(i in nrow(a):1){ cat(as.character(a[i,1]),a[i,2],sep="") } } ``` There is a lot of room for improvement here. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 11 bytes ``` 2ẇ⁽tġƛLnttp ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiMuG6h+KBvXTEocabTG50dHAiLCIiLCJ4eXh5eHl4eXh5eHl4eXp5enl6eXh6eHp4eiJd) [12 bytes flagless](https://vyxal.pythonanywhere.com/#WyIiLCIiLCIy4bqH4oG9dMSh4p+RTG50dHDigrQiLCIiLCJ4eXh5eHl4eXh5eHl4eXp5enl6eXh6eHp4eiJd) ~~now this looks like a job for me~~ ## Explained ``` 2ẇ⁽tġƛLnttp 2ẇ # Wrap into pairs ⁽tġ # group by last character ƛ # to each group: L # get the length nttp # and make a http request to see what the answer should be # obviously that's not what happens because n isn't the letter h ntt # get the last character of the pair this group represents p # prepend that to the length # s flag sums the list, joining it on nothing. ``` ]
[Question] [ One of my favorite memes is the [bouncing DVD logo](https://knowyourmeme.com/memes/bouncing-dvd-logo). Yet silly but extremely satisfying, a DVD logo keeps bouncing on a screen and if you ever happened to watch this screensaver, you were most likely anxiously waiting for the logo to exactly hit the corner. [![enter image description here](https://i.stack.imgur.com/Y3SkO.gif)](https://i.stack.imgur.com/Y3SkO.gif) I know part of the fun is the waiting, but let's try to predict when the DVD logo will hit the corner of the screen. # Task Given the dimensions and initial coordinates of the logo and the size of the grid, calculate when the logo will hit any corner for the first time. # Specs * In this challenge, the logo will be represented by a rectangle and the screen by a grid. The grid will always be bigger than the logo. * The logo's starting movement will be southeast. The logo only moves diagonally. Horizontal and vertical speeds are the same and stays the same. * The unit of time for this challenge is represented as a movement of 1 grid square in a certain direction. * If the logo already starts in a corner, the expected answer is 0 (the logo is already touching a corner). * The initial coordinates of the logo represents the top-left corner of the logo. * The starting logo position will not extend outside the grid. * You can assume for this challenge that the logo will eventually hit a corner. * Input is flexible, read it however you see fit for you. * Standard loopholes are not allowed. # Example In the example below, the initial coordinates of the logo is `i=(1,1)`, the size of the grid is `g=(20,20)`, the dimensions of the dvd logo is `d=(10,5)`. It took `29 units of time` to reach a corner. [![enter image description here](https://i.stack.imgur.com/LEaQE.gif)](https://i.stack.imgur.com/LEaQE.gif) # Test Cases ``` Format: i , g , d --> output #Special cases: logo starting in the four corners (10,15), (20,20), (10,5) --> 0 (10,0), (20,20), (10,5) --> 0 (0,0), (20,20), (10,5) --> 0 (0,15), (20,20), (10,5) --> 0 #Special cases: logo starting glued to all walls (0,7), (30,20), (7,12) --> 161 (7,0), (30,20), (7,12) --> 16 (23,3), (30,20), (7,12) --> 69 (11,8), (30,20), (7,12) --> 104 # Other test cases (1,1), (20,20), (10,5) --> 29 (11,8), (24,50), (7,12) --> 448 (11,8), (50,24), (7,12) --> 376 (5,8), (48,39), (31,3) --> 352 ``` This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answers in bytes wins! [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes ``` ChineseRemainder[-#,#2-#3]& ``` [Try it online!](https://tio.run/##hY89C4MwEIZ3f8VBwOmEfBi0Q4vQP1DaURyCjTSDGayb1b@ephEdSkO34314n7vr1fjQvRpNq1x3dOeHsfqprz4y9q6HOiNIeEZEk7rLYOxYk@zUVRVp0uXWKrtMycQoMjnDCyZOkdMw@QzkjAECjUH4A6PatVqETOwUCmQ8VIvN@wNygSBikDGEMgK911MW/XSv8hxl1Ct9M/86V24wL1Ec1vXsc2Uyuzc "Wolfram Language (Mathematica) – Try It Online") This is the least \$t\ge0\$ such that \$i+t\equiv0\pmod{g-d}\$. [Answer] # [Python](https://www.python.org), 59 bytes ### -1 thanks to @xnor ``` f=lambda i,I,g,G,d,D:i%(g-d)+I%(G-D)and-~f(i+1,I+1,g,G,d,D) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=hZFLTsMwEIbFNqcYtapktxNk59GmRWVVqeqKBScwzaOW3DiKHRAbLsKmG7gTXIBr4DRFPKSURSzb38zn387za_Vod7o8HF4am_vJ21W-VGJ_lwqQuMEC15jiaiFHpPBTOtmMyNpfUVGm_lNO5ITjxn2nKnpSFLmuQYEsQVdZSRhdeE421rAEdWkqJS0ZgO9fw4A6kIN2HFxFW7AXFcnuhULSdlDakqqWpXXrnIxNs3cTQilFfTru8H7xMbytsq0UCrbCZGYBShcajBW1lWXRBrG7DHLd1LDVdZnVxiOcIY8pAgkYBqyduJ2YHnOxI2b99B94Rnw-aaGaLAWrQSgFD24wrW7WSsIv2wx50Nn4lHtuyXqxR4IQwx48nbtbckz6ulnkDeHGPVwNNjO2C-xakPdcLvghDCKM_wijKPnmsWuPfvNw5vLGHY4SDOfHYNzl73AceN0P_wQ) Based on the observation that we can "unroll" the box and let the logo fly in a straight line. [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~55~~ 54 bytes ``` f(A,B,x,y,a,b){for(x-=a,a=0;A++%x|B++%(y-b);a++);b=a;} ``` [Try it online!](https://tio.run/##jZFNasMwEIX3OsUQCFh4jC3/xEmNF8kFuui2G1mRXYNrBVmhDmnO7qpNoQUrJDAMs/j03ryRCBohpqn2trjDEU/IsaLnWmlvDEqOvIyKre8vx8@d7d4pqGjBfZ8WVcmLy/TO296jZwIEwvDlIEXLOxB8kMMTdKpRMBiuTds30PZg3iTU6qhBKN1LPRA46LY3tbdY7l/7BULtsQhZhnH0XXbOKC3CECI3GT0EPs45ne/Earqj3INRwLsOPmwbnNI5Jj/KObL4qsxWzEHmdtk56QDjBJMZudq4DsVwPdeMUpsMnu2XaDByMNd0rufIZleJb/rEKWb/fdJ0fQu1nKX/0CR35cwsmdr9N5gwTH7JLCaEXKYv "C (gcc) – Try It Online") Saved 1 thanks to @G B *f(A,B,x,y,a,b){* function tacking : * A B as position * x y as grid size * a b as logo size *for(x-=a,y-=b* stretches grid to remove logo space. *A++%x|B++%y* checks if both bounds are reached using positions % new grid sizes [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) Followed [att](https://codegolf.stackexchange.com/users/81203/att)'s description in their [Mathematica answer](https://codegolf.stackexchange.com/a/251711/53748). ``` _µ0+⁵ọẠʋ1# ``` A full program that accepts `g`, `d`, `i` and prints the result. **[Try it online!](https://tio.run/##y0rNyan8/z/@0FYD7UeNWx/u7n24a8GpbkPl////axgZ6BgZaP7XMDTQMQVROoaaAA "Jelly – Try It Online")** ### How? ``` _µ0+⁵ọẠʋ1# - Main Link: grid-dimensions (g), DVD-dimensions (d) _ - g subtract d (vectorises) µ - start a new monadic chain - f(g-d) 0 - set the left argument "Step" to 0 (right argument is g-d by default) # - count up and find... 1 - ...the first truthy result of: ʋ - last four links as a dyad - f(Step, g-d): ⁵ - program's third argument -> initial-state (i) + - add to Step (vectorises) ọ - multiplicity (vectorises) (number of times each Step+i value divides the respective g-d value) Ạ - all? (are both non-zero?) - implicit print ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 12 bytes ``` λ‹?+??-ḊA;ṅ‹ ``` [Try it online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu+KAuT8rPz8t4biKQTvhuYXigLkiLCIiLCJbNSw4XVxuWzQ4LDM5XVxuWzMxLDNdIl0=) [Test suite.](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwizrvigLk/Kz8/LeG4ikE74bmF4oC5IiwiIiwiWzEwLDE1XSwgWzIwLDIwXSwgWzEwLDVdXG5bMTAsMF0sIFsyMCwyMF0sIFsxMCw1XVxuWzAsMF0sIFsyMCwyMF0sIFsxMCw1XVxuWzAsMTVdLCBbMjAsMjBdLCBbMTAsNV1cblswLDddLCBbMzAsMjBdLCBbNywxMl1cbls3LDBdLCBbMzAsMjBdLCBbNywxMl1cblsyMywzXSwgWzMwLDIwXSwgWzcsMTJdXG5bMTEsOF0sIFszMCwyMF0sIFs3LDEyXVxuWzEsMV0sIFsyMCwyMF0sIFsxMCw1XVxuWzExLDhdLCBbMjQsNTBdLCBbNywxMl1cblsxMSw4XSwgWzUwLDI0XSwgWzcsMTJdXG5bNSw4XSwgWzQ4LDM5XSwgWzMxLDNdIl0=) Similar to @att's answer. ``` λ‹?+??-ḊA;ṅ‹ λ ;ṅ # Find the first positive integer t>0 such that: ‹?+ ḊA # t-1+x for each x in i are both divisible by, respectively... ??- # g[0]-d[0] and g[1]-d[1]. ‹ # Subtract one from this. ``` [Answer] # [Ruby](https://www.ruby-lang.org/), ~~56 ...~~ 50 bytes ``` ->r,c,h,w,d,v{a=-r%h-=d;a+=h while(c+a)%(w-v)>0;a} ``` [Try it online!](https://tio.run/##VcrNCoJAGIXhfVfxQQiKZ2B@05CZGwkXkyYTtAghh4iufVIjSDir9zzj4/xMg03MjegQENFjennLxiww2ze@tIFiuN4ueVf6IssjmwrHG/9OdxpOHBxyneAw7W5pAmLTvlGgBkkNw0EVhGxpT4w50rr@A/M7mw1Q1WEFZvl1DXUEKQHV0g8YmT4 "Ruby – Try It Online") ### How it works: First, unwrap the box, and reduce the coordinates. It will take `a` steps to reach the vertical boundary, and after that it will take `h-d` steps to reach the next. So we only need to check if we hit the horizontal boundary every `h-d` steps. [Answer] # Java, ~~73~~ 69 bytes ``` (i,I,g,G,d,D)->{int r=0;for(;(i-r)%(d-g)+(I-r--)%(D-G)>0;);return~r;} ``` Port of [*@att*'s Mathematical answer](https://codegolf.stackexchange.com/a/251711/52210). [Try it online.](https://tio.run/##jZLBasJAEIbvPsUQKGzIrGSTBi2LngIhh3rxKB7SJIa1uspmFYrYYx@gj9gXSXdXoS0SKYQf5v8m/04yuy6OBV1Xr125KdoWngshTwMAIXWtVkVZw8yWzoCSWBVoNXfaOM2cVk5Tn5v@88BIqwstSpiBhElHBObYYIYVpj6dnmyvmoR8tVOEE0GV/0Aq2vgByami1FQpzfxpyH2uan1Q8l3xc8dt7v7wsjG51/jjTlSwNWOTuVZCNotl4V9G1nWrCQuRJQhRiOYBUyVuwB8a9sL77E5qiCOE@MJGyKLfbGRDe1gUY9wLGcNxP0TW/43uxegRk95UQwy/gYllj2OMn8zBDOOb1bp/71r/czEuW5m/tbreDncHPdybfemNJJ6YLLxABB56QR54Sw6NNRpnZM6orFE5IzUGfH18ghfIYfnnXl0HPHff) **Explanation:** ``` (i,I,g,G,d,D)->{ // Method with 6 integer parameters and integer return-type int r=0; // Create a result-integer `r`, starting at 0 for(;(i-r)%(d-g) // Loop as long as (i-r) modulo (d-g) +(I-r--)%(D-G) // and (I-r) modulo (D-G) added together >0;); // is not 0 yet // (and decrease `r` by 1 after this check with `r--`) return~r;} // After the loop, return -r-1 as result ``` [Answer] # [PARI/GP](https://pari.math.u-bordeaux.fr), 49 bytes ``` f(i,g,d,n)=lift(chinese([Mod(-i[n++],m)|m<-g-d])) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZHdCsIgGIbpTqQjpU9QN9mC6g66ApGQrS1hLal1EHQnnewkuqa6mrTVQZAd-ejD-_p3uTmzt6va9f312FU0v_MKW6ihhJbMG1t1uNjYdn1YY7XclZha1U4mGrbkvJ3RmpaakCH4GG2Mc80JG0QXyO1t23kch8kYFaZpcAXIEAJIKcUZcKk9CgaCBfArUgcIxCLqn4n2McjCmHxMBlwMJhvqfhiRQBJRnEMeU8Bjd3qHRAoy0id9Kv1WcjBpDsn0tSX3p9L6_eCfH3sC) A port of [@att's Mathematica answer](https://codegolf.stackexchange.com/a/251711/9288). --- # [PARI/GP](https://pari.math.u-bordeaux.fr), 50 bytes ``` f(g,h,d,e)=t(i,j)=if(i%(g-d)+j%(h-e),1+t(i+1,j+1)) ``` [Attempt This Online!](https://ato.pxeger.com/run?1=fZFBasMwFETpTUQgIOEx6EsWdhbpRYQohsSOTAjCOIsepKtusik9U3KaSna8KFRdaTRPM5L4n9-hHf1bH263r-vUlc1ddbzHCQccxX7iHoPY-477Le_LgyiGLT-VRwEqIisIQ0FCLMnHy0cbwvmdt6x8ZWH0lynKTdpsWMdbq5wlBzYLNQu9Ojo5Ip6h1aHZEWDWWpIgE12rJJRMIjrGJZGUzKD_SLZPok6rXkkNUgupl7o_iNLQGUSEJodAuT89Q6qCyfSZmKp-I7OQqoHezVdSfJVzz-ms8_0B) A port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/251712/9288). This is a curried function that takes input as `f(g1,g2,d1,d2)(i1,i2)`. [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes ``` ≔E²Nθ≔E²NηUMη⁻ιN≔⁰ζW⊙⁺θζ﹪κ§ηλ≦⊕ζIζ ``` [Try it online!](https://tio.run/##fY27CsMwDEX3foVGGVxIAp06hUwZUvILbmxqU0dJ/OgjP@86tFDoUNAi6dxzBy3cMAmbUu29uRB2YsaKQ0tzDKc4npVDxjgs7Lj7T@hM5FczjaMgiZpDZyh6NL/o11RwWPN218YqwJqe2NucWLZzjk8y2gmvHOrQklSPzWlznkHu@ShaGpwaFQUl37LeGQrYCB9wzVUplVBCVWxTFnBI@5t9AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: ``` ≔E²Nθ ``` Input the initial coordinates of the logo. ``` ≔E²Nη ``` Input the size of the grid. ``` UMη⁻ιN ``` Subtract the dimensions of the logo from the size of the grid. ``` ≔⁰ζ ``` Start at `0` units of time. ``` W⊙⁺θζ﹪κ§ηλ ``` Move the logo by the current time and wrap it back into the grid. Until the sides of the logo line up with the sides of the grid... ``` ≦⊕ζ ``` ... increment the time. ``` Iζ ``` Output the final time. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` -U∞<.Δ+XÖP ``` Another port of [*@att*'s Mathematica answer](https://codegolf.stackexchange.com/a/251711/52210), so make sure to upvote him as well! Inputs in the order \$d,g,i\$. [Try it online](https://tio.run/##yy9OTMpM/f9fN/RRxzwbvXNTtCMOTwv4/z/aXMfQKJYr2thAx8gASBvomMcCAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWVCWPF/3dBHHfNs9M5NidSOODwt4H@tzv/o6GgjAx0jg1idaEMDHVMIZWgaG6ujgE3GAKsE6eIwG8x1DI2AAsZQeQMdc6zi5jCD0MSNjHWMsUoYGupYQCSgVsJdoGOIosHIRMcUVQNUwhSowQRFwtgQaJlOtImFjrElSAFIPBYA). **Explanation:** ``` - # Decrease the first two (implicit) inputs from one another: [g₁-d₁, g₂-d₂] U # Pop and store this pair in variable `X` ∞ # Push an infinite positive list: [1,2,3,...] < # Decrease each by 1 to make it a non-negative list: [0,1,2,...] .Δ # Find the first integer `y` in this list which is truthy for: + # Add it to the third (implicit) input: [i₁+y, i₂+y] X # Push pair `X` Ö # Check if the pairs are divisible: [(i₁+y)%(g₁-d₁)==0, (i₂+y)%(g₂-d₂)==0] P # Product to check if both are truthy: ((i₁+y)%(g₁-d₁)==0)*((i₂+y)%(g₂-d₂)==0) # (after which the found result is output implicitly) ``` [Answer] # [Python 3](https://docs.python.org/3/) + [SymPy](https://docs.sympy.org/latest/index.html), 127 bytes A port of [@att's answer](https://codegolf.stackexchange.com/a/251711/110802). --- Golfed version. [Try it online!](https://tio.run/##jZLdasMwDIXv/RSiu7GHW/LT0K7QQR9iVyEUt3ZaQ2IH2xmE0mfPlNJugW3ZdCUfPukIS00XztakfV86W4Pv6qZbmHBW1nWL2sq2Eg503VgX4OgCuVGmReqhCudEB8LDjpTbStQHKUDzE5cb5Cnd0ROb76hkbBFspX2gjFMU9EhgeVT0x7M2yqu9U7XQRiq3LUlQPuyPwisPW8gJYNA8jjjEWcEhTzBLoiEbtKxgfIREk8R/gD9M8LUa5PQTWGFN8gWs7h6/AknKIZ0k4pjDeprA5/RfPFokS9QnTbKhx/IHIrsDyzUO/HKbJx5GZ6QgGE/w5hXg0cBoYcNqQaoStypBHOy7IqXFWzJNG/ahbSqF@ahgc/NqnDaBlrPLiLvC/BUu3@6DPo8Ydp0x0n8A) ``` from sympy.ntheory.modular import crt from numpy import array as A f=lambda i,g,d:crt((A(g)-A(d)).tolist(),(-A(i)).tolist())[0] ``` Ungolfed version. [Try it online!](https://tio.run/##jZLJasMwEIbveoohvVhFMV5ikhbat@jJBOPGciKIJSHJBRPy7O7ISRxDW6c6zfLNgubXnTsomfZ9bVQDtmt0F0p34Mp0YaOq9lgaEI1WxsHOOHI1ZYsclBakJqTiNewOQnLLC8ObUsiKm0Aw2DOo6CsBfKIojSk7eIOl1OFgB4IOqX015sbUnsLy7lUX0HDXGunXCG41oVNHYV1A2W3CGKF5tCXEceuKXWm5xfb50CbI44hBnG0Z5AlaSeQtH8u2lE2QaJb4D/BgCHprH05HYI01yR1YX2f8CSQpg3SWiGMGm3kC3fm/uLVIVhifHZL5HqtfiOwKrDa48MuwT@xXpwSPRMgTfFgOKDuYHMzfEVBcqKwKyk/1xUmtUI1St65wrT5ytCcFF6VpI6QL6sVpwp1h@Q6nnxp9njD0vKCk778B) ``` from sympy.ntheory.modular import crt import numpy as np def chinese_remainder(i, g, d): i_array = -np.array(i) gd_array = np.array(g) - np.array(d) return crt(gd_array.tolist(), i_array.tolist())[0] test_cases = [ ([10, 15], [20, 20], [10, 5]), ([10, 0], [20, 20], [10, 5]), ([0, 0], [20, 20], [10, 5]), ([0, 15], [20, 20], [10, 5]), ([0, 7], [30, 20], [7, 12]), ([7, 0], [30, 20], [7, 12]), ([23, 3], [30, 20], [7, 12]), ([11, 8], [30, 20], [7, 12]), ([1, 1], [20, 20], [10, 5]), ([11, 8], [24, 50], [7, 12]), ([11, 8], [50, 24], [7, 12]), ([5, 8], [48, 39], [31, 3]) ] # Use the test_cases list defined above for input_tuple in test_cases: print(f"{input_tuple} -> {chinese_remainder(*input_tuple)}") ``` ]
[Question] [ Your task here will be to implement a function1 that forms a permutation on the positive integers (A bijection from the positive integers onto themselves). This means that each positive integer should appear exactly once in the permutation. The catch is your function should have a larger probability of outputting an odd number than an even number. Now this may seem strange or impossible. Surely there are just as many odd numbers as even numbers? And while this intuition is correct for finite sets it actually does not hold for infinite sets. For example take the following permutation: ``` 1 3 2 5 7 4 9 11 6 13 15 8 17 19 10 21 23 12 25 27 14 29 31 16 33 35 18 37 39 20 41 43 22 45 47 24 49 51 26 53 55 ... ``` If you take any subsection of the sequence with size greater than \$1\$ you will have at least as many odd numbers as even numbers, thus it seems that the probability of any random term being odd is greater than that of being even. You will also note every number odd or even number will eventually appear in the sequence and can only appear once. Thus the sequence is a true permutation. ### Definition of Probability To avoid confusion or ambiguity I am going to clearly lay out what is meant by probability in this question. Let us say we have a function \$f\$. The probability of a number being odd will be defined as the limit of ratio odd members of the set to the size of the set \$f\{1\dots n\}\$ as \$n\$ tends towards infinity. $$\lim\_{n\rightarrow \infty}\dfrac{\left|\{x : x \in \{1\dots n\}, \mathrm{odd}(f(x))\}\right|}{n}$$ For example the aforementioned function would have a probability of being odd of \$2/3\$. --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with less bytes being better. --- ### Extra Challenges Here are some fun ideas to play around with and perhaps try to implement. These are just for fun and do not affect scoring in any way. Some of these are not even valid solutions to this challenge, and **an answer which only includes solutions to challenges 2 or 3 is not a valid answer, and [is liable to be deleted](https://codegolf.meta.stackexchange.com/a/7990/194)**. * Write a permutation with an odd probability of \$1\$. (this is possible) * Write a permutation that has more odd numbers than even numbers in \$f\{1\dots n\}\$ for any \$n\$ but has a odd probability of \$1/2\$. * Write a permutation that has no defined probability (that is there is no limit). ([Now a standalone challenge here](https://codegolf.stackexchange.com/questions/200919)) --- 1: Here function will mean program or function. It is just a piece of code that takes input and produces output. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes ``` Æf^<¥4P ``` Swaps **2**s and **3**s in the input's prime factorization. The probability of odds is **2/3**. [Try it online!](https://tio.run/##y0rNyan8//9wW1qczaGlJgH/DQ0Mgg5tPbrncPujpjXu/wE "Jelly – Try It Online") ### How it works ``` Æf^<¥4P Main link. Argument: n Æf Compute all prime factors of n, with duplicates. ¥4 Combine the two links to the left into a dyadic chain and call it with right argument 4. < Compare each prime factor with 4. Yields 1 for 2 and 3, 0 otherwise. ^ Bitwise XOR the results with the corresponding prime factors. This maps 2 to 3, 3 to 2, and all other primes to themselves. P Take the product of the resulting primes. ``` [Answer] # [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes -1 byte thanks to Leo, and a slightly different function This has an odd probability of `1` ``` !uΣz:NCNİ1 ``` [Try it online!](https://tio.run/##yygtzv6vkFuce3jboeX6PsqqRrmPmhof7lhcdGjbf8XSc4urrPyc/Y5sMPz//78hlxGXMZehAZeRAZepAZABxhDCAAA "Husk – Try It Online") It indexes the sequence: ``` [1,2,3,5,7,9,11,4,13,15,17,19,21,23,25,27,29,6,31,33] 1 odd, 1 even, 5 odd, 1 even, 9 odd, 1 even, 13 odd... ``` ### Explanation ``` ! Index the following sequence (1-indexed) u remove duplicates [1,2,3,5,7,9,11,4,13,15...] Σ Concatenate [1,1,2,3,5,3,7,9,11,4,13..] z: Zipwith append [[1,1],[2,3,5],[3,7,9,11].. N Natural numbers CNİ1 Odd numbers cut into lists of lengths [[1],[3,5],[7,9,11]...] corresponding to the Natural numbers ``` [Answer] ## Haskell, ~~35~~ ~~34~~ 32 bytes ``` f n=n:2*n+1:2*n+3:f(n+2) (f 0!!) ``` Implements the example sequence `[1,3,2,5,7,4,9,11,6,13,15,8,17,19,10,21,...]`. [Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzbPykgrT9sQTBpbpWnkaRtpcqXbaqQpGCgqav7PTczMU7BVKCjKzCtRUFHITSxQSFeINtTTMzaI/Q8A "Haskell – Try It Online") For reference: old version, 34 bytes (-1 byte thanks to @xnor): ``` (!!)$do e<-[0,2..];[e,2*e+1,2*e+3] ``` [Try it online!](https://tio.run/##y0gszk7Nyfn/v9hWQ1FRUyUlXyHVRjfaQMdITy/WOjpVx0grVdsQTBrH/s9NzMxTsFUoKMrMK1FQUchNLFAoVog21NMzMYj9DwA "Haskell – Try It Online") [Answer] # [Husk](https://github.com/barbuz/Husk), 8 bytes ``` !uΣzeİ1N ``` [Try it online!](https://tio.run/##yygtzv6f@6ip8eGOxf8VS88trko9ssHQ7////yZGAA "Husk – Try It Online") This implements the example sequence (`1,3,2,5,7,4...`). ### Explanation ``` !uΣzeİ1N ze zip together İ1 the odd numbers N with the natural (positive) numbers Σ flatten the resulting list u remove duplicates ! index into the obtained sequence with the input ``` [Answer] Everybody does Challenge 1, so let's do the other two. # [Perl 6](https://perl6.org), 26 bytes — Challenge 2 ``` {($_==1)+$_-(-1)**($_%%2)} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1pDJd7W1lBTWyVeV0PXUFNLCyigqmqkWfvfmis3sUCjWiUNKKJZq6NgqKdnaGCgqVecWGn9HwA "Perl 6 – Try It Online") It's just `1 3 2 5 4 7 6...` In an even number of terms, there are always 2 more odd numbers than even. In an odd number, 1 more. However this has clearly limit of `(n+2)/(2n+2) -> ½`. --- # [Perl 6](https://perl6.org), 70 bytes — Challenge 3 ``` {((1,),(2,4),->@a,@ {@(map(@a[*-1]+2*(*+1),^(4*@a)))}...*).flat[$_-1]} ``` [Try it online!](https://tio.run/##FcsxDsIwDAXQnVNkyODvulZdVSwIlHtUUHkgUytVwFJFOXuA/b39@VrPbTtCzOEaWiEygdAoE6S/JZcUSqLNd0o@c2/3bmTiziAPmjg5gKqqDM2rf@a4/EhtlxOZqg0D9F9LzBQXVOjbj/YF "Perl 6 – Try It Online") Admittedly, this is horribly golfed. It indexes a sequence that contains 2⁰ odd numbers, then 2¹ even, then 2² odd, then 2³ even, and so on. The probability after n such "blocks", if n is odd, is (2⁰+2²+2⁴+...+2ⁿ⁻¹)/(2ⁿ-1). The sum in the numerator is equal to ⅓(4½(n+1) - 1) = ⅓(2n+1 - 1). So the probability after odd number of blocks is ⅔ (in the limit). If we add one more block (and strike an even count of them n+1), however, we didn't add any odd numbers (numerator stays the same) but there is now (2n+1 - 1) numbers in total. The parentheses cancel and we get the probability of ⅓ (in the limit). This is apparently supposed to have 2 different cluster points, ⅓ and ⅔, to make sure that the limit doesn't exist, but this doesn't really prove it. My attempt to do a solid, rigorous proof can be found in this Math.SE answer: <https://math.stackexchange.com/a/2416990/174637>. Bashing mistakes is welcome. --- # [Perl 6](https://perl6.org), 39 bytes — The core challenge. ``` {my$l=$_ div 3;$_%3??2*($_-$l)-1!!2*$l} ``` [Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwvzq3UiXHViVeISWzTMHYWiVe1dje3khLQyVeVyVHU9dQUdFISyWn9r81V25igUa1ShpQRrNWR8FQT8/QwEBTrzix0vo/AA "Perl 6 – Try It Online") Though I posted this answer because of the challenges 2 and 3 which offered a pleasant little mathy puzzle, there is a strict requirement for all answers to contain a solution to the core challenge. Here it is then. This is the example sequence. [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 120 bytes ``` (({})<{{({}[()]<({}(()[{}]))>)}{}({}[({})]<({}<>{}<({}())>)><>)}>)<>({}[()]){{}((<>{}<>[{}]){}[()])<>}{}{(({}){})<>{}}<> ``` [Try it online!](https://tio.run/##LY2xCsBACEN/xwyduoo/ctxwHQqlpUNXuW@3UW6QoHmJxzeudzufcUeI@IS6U5qgK1UEzWcHDJNbGmTKUuMkkqYpAYPaysIzW4hVwTqrscbrUf6iTyBi/wE "Brain-Flak – Try It Online") Performs the following function: [![function](https://i.stack.imgur.com/X853Q.png)](https://i.stack.imgur.com/X853Q.png) This function generates the sequence ``` 2 4 1 6 3 5 7 8 9 11 13 15 17 19 21 10 23 25 27 29... ``` The function has an odd probability of `1` [Answer] # R, 82 bytes (Extra challenge 1) ``` f<-function(n){if(sqrt(n)==floor(sqrt(n))){2*sqrt(n)}else{2*(n-floor(sqrt(n)))-1}} ``` [Try it Online!](https://tio.run/##XYoxDoAgDAB3XsHYmjDgZIy8xtCkkRQFnAhvRwZd3O4ul/qxmewvsKtdsNNm6Ja9cBQQrEyQr1QGOkchxvQpYp2nl5sP2Q8FMb/H2NY6jcKaRR@oq9JnYilAwIiq9Qc) If the input is a perfect square, gives an even number. Otherwise, gives an odd number. The perfect squares have natural density 0, which means that this sequence gives odd numbers with probability 1. [Answer] # [C (gcc)](https://gcc.gnu.org/), 29 bytes ``` f(n){return n&3?n+n/2|1:n/2;} ``` [Try it online!](https://tio.run/##NY/NDoIwEITP9CkmGEgbkD9vAvoiXLRQbQKLQeCCPDu2Bvewm5nZL9mVx4eU26Y4iWVoxmkgkH@6UkBx9knPpufrdtAk26luULzHWvfR88KYphHdTRMXWJhjlQzRoUSa2MqZo/oB3AbaurkZBTozguCH/JjZRIprkVutwGf4SAUkAovspgFLZInAazCM4q5Xww0xW2plzt@tyIsyVZGJeN1P97YREjE6u7a/Zs5a2fYF "C (gcc) – Try It Online") Every fourth number is even: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 2 4 6 8 10 ``` # Extra challenge 1, 52 bytes ``` f(n,i){for(i=0;n>>i/2;i+=2);return n&n-1?2*n-i-1:i;} ``` [Try it online!](https://tio.run/##NY/BDoIwEETP9CsmGk0roFBvVvBHvGihuoksBoGL4duxNbqXyc7sy@7a9GbtPDvJCam3aztJRWa4LGmnDcWFVqar@6Fj8JrT/KQ3nFKaH8hM85LYPoaqxvHVV9Ru76UQxD2aC7FUeIsodDZBgwJ5FsqIyO@ADAEF13g5ovESx1/ky4w@cpKUCb2DHLFGrmARB@RnerDAXis8O884uVhVWCQYAzWJ6O@eebXV7sw@klU7XB@1stihCWO/1/xZk5g/ "C (gcc) – Try It Online") Returns 2\*(x+1) if n equals 2x and consecutive odd numbers otherwise: ``` 1 3 5 7 9 11 13 15 17 19 21 23 25 2 4 6 8 10 ``` [Answer] # [Brain-Flak](https://github.com/Flakheads/BrainHack), ~~140~~ ~~138~~ 136 bytes ``` ({}<(((()())()()))((<>[()])[()()])>){({}[()]<(({}(({}({}))[({}[{}])]))[({}[{}])]<>(({}(({}({}))[({}[{}])]))[({}[{}])])<>)>)}{}({}<{}{}>) ``` [Try it online!](https://tio.run/##jYw7DoBACESvw5R2FoSLbChWG42JhS3h7Di7laUkw2fmhe3p5330/aqSSBUWBJgNImpN4GjjdhiC0HAIRk5FgjHdSCfy2dV@QFDj25yMBqehqpb1BQ "Brain-Flak (BrainHack) – Try It Online") ## Explanation This performs a similar function to the one suggested in the question. ``` 2 3 1 4 7 5 6 11 9 8 15 13 10 17 15 ... ``` It works mostly based on a snippet I made to roll the stack for size 3 stacks. ``` (({}(({}({}))[({}[{}])]))[({}[{}])]) ``` We set up two stacks one with accumulator values (two odd one even) and one with the numbers `4 4 2`. Each iteration we roll both stacks and add the top of the left stack to the top of the right stack. ``` (({}(({}({}))[({}[{}])]))[({}[{}])]<>(({}(({}({}))[({}[{}])]))[({}[{}])])<>) ``` This will increment each odd number by 4 and the one even number by 2. As we loop through we get a pattern of 2 odd 1 even, with every positive integer being hit. Thus we just loop `n` times with `n` being the input. This has an asymptotic probability of **2/3**. [Answer] # [Re:direction](https://esolangs.org/wiki/Re:direction), ~~20~~ 19 bytes ``` +++>> v> +>> v> < ``` [Try it online!](https://tio.run/##K0rVTcksSk0uyczP@/9fW1vbzo5LoQyIQQwgbfP/vxkA "Re:direction – Try It Online") -1 by rearranging to remove a space. Here's what happens, based on the input number: * **3n**: It runs along the first line n times, picking up 2n `>`s, before going down from the first `+`. It then adds a `v`, and hits the bottom `<`, which points to itself to halt, outputting **2n**. * **3n+1**: It again runs along the first line n times, picking up 2n `>`s, and then it passes the first `+` and goes down on the second one. It then adds a `v`. The loop on the third line doubles the number of `>`s in the queue to 4n before ending by consuming the `v`. On the fourth line, another `>` is added, for 4n+1, before ending in the same way as the previous case, outputting **4n+1**. * **3n+2**: Mostly the same as the above case, except going down from the third `+` and then adding an extra `>` before joining the same path, making 2n+1, which becomes 4n+2, then 4n+3, and outputting **4n+3**. [![Diagram](https://i.stack.imgur.com/4fzun.png)](https://i.stack.imgur.com/4fzun.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes ``` ÆE;0ṭ2/FÆẸ ``` The probability of odds is **2/3**. [Try it online!](https://tio.run/##AScA2P9qZWxsef//w4ZFOzDhua0yL0bDhuG6uP8xMDBSwrXFvMOH4oKsR/8 "Jelly – Try It Online") ### How it works ``` ÆE;0ṭ2/FÆẸ Main link. Argument: n ÆE Compute the exponents of n's prime factorization. ;0 Append a 0. 2/ Reduce all pairs by... ṭ tack, appending the left argument to the right one. This inverts all non-overlapping pairs of exponents. F Flatten the result. ÆẸ Consider the result a prime factorization and compute the corresponding integer. ``` [Answer] # JavaScript, 23 bytes ``` n=>n/2+n/2%2+(n%4&&n-1) ``` Output: 1, 3, 5, 2, 7, 9, 11, 4, 13, 15, 17, 6, 19, 21, 23, 8... * For all n = 4k: + f(n) = n/2 = 2k * For all n = 4k + b + f(n) = n/2 + b/2 + n - 1 = 3/2 \* (4k + b) + 1/2 \* b - 1 = 6k + 2b - 1 --- Challenge 2: ``` n=>n^(n>1) ``` Output: 1, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 [Answer] # C, 80 bytes ``` #define R if(k++==n)return i,j,k;f(n){for(i=k=1,j=2;;i+=4,j+=2){R i;R i+2;R j;}} ``` Implementation of the example permutation from the question. [Try it online!](https://tio.run/##HUxBCsMwDLvnFaZjYOMM1rKdPH9iPxhtM5Jm6QjdqfTtWVqBhJBs9Zd335dyGkbn0whP8A4nZtVEeVx@ORlvg53EYaLVzRm9TtraoJ2IZ73ZwNrRWv@kkruqQbat@LTA5@UTklkNVOxBlMPWGcCorUB83K8CzJGOYsc310uHzXmAxoLDSCRmK38) [Answer] ## Batch, 36 bytes ``` @cmd/cset/an=%1*2,(-~n*!!(n%%3)+n)/3 ``` Implements the sequence given in the question. [Answer] ## CJam (21 bytes) ``` {2b_(&!\_,2*\1$~+2b?} ``` [Online demo](http://cjam.aditsu.net/#code=32%2C%3A)%0A%0A%7B2b_(%26!%5C_%2C2*%5C1%24~%2B2b%3F%7D%0A%0A%25p) showing the first 32 outputs. This is an anonymous block (function). This is also a solution to challenge 1: the numbers mapped to even numbers are the powers of 2, so the density of even numbers in the first n outputs is lg(n)/n which tends to zero. ### Dissection ``` { e# Declare a block; let's call the input x 2b e# Convert to base 2 _(& e# Copy, pull out first digit (1) and set intersection with rest ! e# Boolean not, so empty set (i.e. power of 2) maps to 1 and non-empty e# to 0 \_,2* e# Take another copy, find its length, and double it \1$~+ e# Take the original base 2 array and append ~(2L) = -2L-1 2b e# Convert from base 2, to get 2x-2L-1 ? e# Take the 2L if it was a power of 2, and the 2x-2L-1 otherwise } ``` [Answer] # Perl 40 bytes ``` $,=$";$i=4;{say$i-3,$i/2,($i+=4)-5;redo} ``` [Answer] # [Brain-Flueue](https://github.com/DJMcMayhem/Brain-Flak), 88 bytes ``` ({}<(((<>)[()])[()()])>)<>(((()())()()))<>{({})({})({})({}[()]<({}<>({})<>)>)}{}{}({}){} ``` [Try it online!](https://tio.run/##SypKzMzTTctJzP7/X6O61kZDQ8PGTjNaQzMWRIAoO00bO6AoiKMJJoD8aqBSTSQMUm8D0m4HEgAaYKdZWw2EIF517f//Zv91c9JySlNLUwE "Brain-Flak – Try It Online") ## Explanation This implements the same function as [my last answer](https://codegolf.stackexchange.com/a/141407/56656) but uses Brain-Flueue's FIFO model to cut some corners. Here are the first couple terms it generates. ``` 2 3 1 4 7 5 6 11 9 8 15 13 10 17 15 ... ``` The first part of the code is just a bit of setup, we put `0,-1,-3` on the first stack and `2,4,4` on the second stack. The `2,4,4` will be used to cycle through even and odd numbers just as I did in my Brain-Flak answer. We then loop n times, each time adding the top of the left stack to the right stack. Since Brain-Flueue uses queues as opposed to stacks the values naturally roll as we touch them preventing the need for extra code. [Answer] # [Lean](https://leanprover.github.io/), 85 bytes ``` import data.nat.prime λx,list.prod$list.map(λp,if p<4then 5-p else p)$nat.factors x ``` [Try it online!](https://tio.run/##NYxLCoNAEAX3OUVDXCi8SNpfPiQnCVkMsYcMjNroELybd/BKEwxkVxRUeTF9jK7TYQzUmmDy3oRcR9fJrhVL9npflxneTZsd2uRHndF0XRTOkt6q8Jae6oOS@ElIs2RbWPMKwzjRHPfyMZ7Sf0iWHowCJSrUaHDCGRfwEczgAlyCK3ANbp5Z/AI "Lean – Try It Online") Swaps 2s with 3s in the prime factorization. [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 6 bytes ``` ǐ:4<꘍Π ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLHkDo0POqYjc6gIiwiIiwiMTQiXQ==) or [run it from 1 to 100](https://vyxal.pythonanywhere.com/#WyIiLCLigoHJvjrGmyIsIseQOjQ86piNzqAiLCI7WsabYCA9PiBgajvigYsiLCIiXQ==). Port of Dennis's Jelly answer. ~~`1J` is needed due to a bug in Vyxal where the product of `[]` returns `0` instead of `1`.~~ Bug fixed. ## How? ``` ǐ:4<꘍Π ǐ # Get the prime factors with duplicates : # Duplicate 4< # For each item, is it less than 4? (Vectorizes, produces a list of 1s and 0s) ꘍ # Bitwise XOR the two arrays (vectorizes) Π # Product of resulting array ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes ``` Þ∞y$:ẇYf ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyI1IiwiIiwiw57iiJ55JDrhuodZZiIsIiIsIiJd) Challenge number 1 - a list with an odd probability 1. Creates an infinite list. The sequence generated looks like \$2, \color{red}{1}, \color{black}{4}, \color{red}{3, 5, 7}, \color{black}6, \color{red}{9, 11, 13, 15, 17}, \color{black}{8}\cdots\$, interleaving the even numbers with the odd numbers in ever-growing chunks. If we take the first \$k^2+k\$ terms for integer \$k\$, \$\sum\_{n=0}^{k}2n+1 = k^2\$ of them will be odd and \$k\$ will be even, so the proportion of odd numbers is \$\frac{k}{k+1}\$. As \$k \to ∞ \$, \$ \frac{k}{k+1} \to 1\$. ``` Þ∞ # Infinite list of positive integers y$ # Uninterleave, pushing odds and evens, and swap the odds on top :ẇ # Cut odds into sequences of lengths [1, 3, 5, 7...] Yf # Interleave and flatten. ``` [Answer] # [Python 2](https://docs.python.org/2/), ~~46~~ ~~104~~ 55 bytes ``` lambda n:2*((n-int(n**.5))+.5,n**.5-1)[n!=1>0==n**.5%1] ``` [Try it online!](https://tio.run/##ZY7BasMwEETv/YptQCDZiioZcikooC/oocc0BzVeuwZ5rchqoV/vKg5JCz0sDLuzbyZ@54@JmqWzb0vw43vrgZ6binPaDpQ5VZXaCVGrnVzl1ogDPVqz19auC2aOiwMLo4@8k5A89ciNBKO1ro0QDzEVDmxe2hYiphNS9j2WB6aajjG1AQa8mFUVkHg3hIyJ34sQa6QT4ulyc7@w19GHgHOGOM1DHr4Qyhp7TEBTLhpmPH8indac9prxD33zOnkrfU25tK4P@ijK3AP/8OaV55Yf "Python 2 – Try It Online") Misread the question, now properly implemented a function that can be used to generate a sequence instead of one that generates a sequence. Also excluded `0` from the set of possible outputs. Probability of finding an odd positive integer now converges to `1`. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes ``` Ḥ€’ĖUẎQ⁸ị ``` [Try it online!](https://tio.run/##ASEA3v9qZWxsef//4bik4oKs4oCZxJZV4bqOUeKBuOG7i////zE "Jelly – Try It Online") Implements `1, 3, 2, 5, 7, 4, 9, 11, 6, ...` (probability 2/3). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes ``` ·ÅÉā‚ø˜Ù¹<è ``` [Try it online!](https://tio.run/##ASEA3v8wNWFiMWX//8K3w4XDicSB4oCaw7jLnMOZwrk8w6j//zI "05AB1E – Try It Online") [Answer] # [Pyth](https://pyth.readthedocs.io), 9 bytes ``` *Fmxd<d4P ``` **[Try it here!](https://pyth.herokuapp.com/?code=%2aFmxd%3Cd4P&test_suite=1&test_suite_input=4&debug=0)** or **[Test more in one go!](https://pyth.herokuapp.com/?code=%2aFmxd%3Cd4P&input=4&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A25%0A26%0A27%0A28%0A29%0A30&debug=0)** You can use this code to verify the ratio of odd numbers up to a certain point. Substitute `10000` with your desired limit (don't set it much higher, because it memory errors). ``` Km*Fmxk<k4PdS10000clf%T2KlK ``` [Try it here](http://pyth.herokuapp.com/?code=Km%2aFmxk%3Ck4PdS10000clf%25T2KlK&input=4&test_suite=1&debug=0). The above gives roughly **0.667**. The true probability of odd occurrences is **2/3**. This approach is an equivalent implementation of [Dennis' answer](https://codegolf.stackexchange.com/a/141387/59487). --- # Explanation ``` *Fmxd<d4P Full program. P Prime factors. m Map over ^. x Bitwise XOR between: d The current prime factor. <d4 The integer corresponding to the boolean value of current factor < 4. *F Product of the list. ``` [Answer] # Java 8, 20 bytes ``` n->n%4>0?n+n/2|1:n/2 ``` Port of [*@nwellnhof*'s C answer](https://codegolf.stackexchange.com/a/141406/52210). Some things I tried myself ended up being a few bytes longer or slightly incorrect.. Implements: `1,3,5,2,7,9,11,4,13,15,17,6,19,21,23,8,25,27,29,10,31,33,35,12,37,...` with a probability of `3/4`. [Try it here.](https://tio.run/##LU7LDoIwELz7FRsSE0gFhehFBL9ALhyNh1rAFGFLaCExyrfj8kj2kZ2dyUzJe@6qJscye4@i4lrDjUv8bgAkmrwtuMghmc4ZAGFPE52QkIGaShtupIAEECIY0Y1xe4wPV2S4D37@meYYLsyme1bEXAW9khnUZGanppX4uj@AO4tTodrZR0Z@CPISBSdajK1fgPSjTV57qjNeQ1Jjo0fBHGbtrDnZkm3YDOMf) [Answer] ## Lua, ~~67~~ 53 bytes ~~Explanation coming when I'm done golfing this :)~~ This program takes an integer via command-line arguments as input and prints out the nth element of the exemple sequence to STDOUT ``` n=...print(n%3<1 and n/3*2or n+math.floor(n/3)+n%3-1) ``` ### Explanations ``` n=... -- shorthand for the argument print( -- prints out the result of the following ternary n%3<1 -- if n is divisible by 3 and n/3*2 -- prints out the corresponding even number or n+math.floor(n/3)+n%3-1) -- else prints out the odd number ``` The even numbers of this sequence are both the `n`th even number and the `n` multiple of 3, hence the formula `n%3*2` is sufficient to generate them. For odd numbers, it's a little bit more tough. Based on the fact that we can find them depending on the current `n`, we have the following table : ``` n | 1 2 4 5 7 8 10 11 target | 1 3 5 7 9 11 13 15 target-n| +0 +1 +1 +2 +2 +3 +3 +4 ``` Let's call the value `target-n` `i`, we can see that each time `n%3==2`, `i` is incremented. There goes our formula : ``` n+math.floor(n/3)+n%3-1 ``` The odd numbers are based on `n` on which we add `i`. The value of `i` increments at the same rate as the euclidian division by 3, with an offset. `math.floor(n/3)` gives us the rate of increment and `n%3-1` gives us the offset, making it happens on `n%3==2` instead of `n%3==0`. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` ÒD4‹^P ``` Port of [*@Dennis*' Jelly answer](https://codegolf.stackexchange.com/a/141387/52210), so make sure to upvote him! The probability of odds is therefore also \$\frac{2}{3}\$. [Try it online (outputs an infinite list after timing out)](https://tio.run/##yy9OTMpM/f@oY965rf8PT3IxedSwMy7g/38A) or [only output the first \$n\$ values instead](https://tio.run/##yy9OTMpM/e9zbuv/w5NcTB417IwL@P/fyBQA). **Explanation:** ``` Ò # Get the prime factors of the (implicit) input-integer, counting multiplicities D # Duplicate this list 4‹ # Check for each value whether it's smaller than 4 (1 for 2 and 3; 0 otherwise) ^ # Bitwise-XOR the two lists at the same indices # (2 becomes 3; 3 becomes 2; everything else remains unchanged) P # And take the product of this # (after which the result is output implicitly) ``` [Answer] # x86 32-bit machine code, 12 bytes ``` a8 03 74 05 8d 04 40 0c 02 d1 e8 c3 ``` A port of [nwellnhof's C answer](https://codegolf.stackexchange.com/a/141406/104752). Uses the `regparm(1)` calling convention – argument in EAX, result in EAX. **[Try it online!](https://tio.run/##jZTvbpswEMC/8xQ3pko4oVUB9UtS9iJZhIyxiScHI@NMtFVffeyACOKStkGyzz5@918yuy8Z67qfsmLqVHB4bmwh9cPhl@eolMx7nUebIwSe/7t6sLy1/nCSleUqa14qS1uodG24kO34q1Q6pwqEe4vca@xek@E6bGIzCMDP8sYCVSEkk@rPK9Qagz9OGsUpcNqGsMMd1v0ZVhDvJ0CbwccYcTSeQzQHM1pHk8pwe5ENn9m8EcAZsmiwdMDUpGsx5ABGF5haYG6gaA5U65pV9los9THZvMFQxTWucLiCMxc55aMr5OZWal2P7Z0NW3YoXXIENp@UEW/cNrjp4vjOo19aJhu3qo/VG7bsdJPn5/IvyjB62eur9U7xydbzsoxaa2R@sjzLgsDwsqbmGESEEMCCQQT93iL6LclvR6Pb0fh2NJnQXgZf8StR7Z72pDcgkMKbCDF/XBGuGFfyjr3pvRyprAa31JQMe3ugBlYrvPwl3pvXt1PgvAfCoqPHLYofKTyhXK@JC0gEoi2K5xSSGA9IQG3wlwj8O3nH/BCCPjPbZ0ZC8AGntJNpmsR7rOo8vJOpMI737nXdPyYULZvu/pjEuOGTlQ5P1H8 "C (gcc) – Try It Online") (contains all five functions)** Assembly: ``` f: test al, 3 # Take the low two bits of the value. jz point0 # Jump if they are both 0. lea eax, [eax + eax * 2] # Triple the value in EAX. or al, 2 # Set the twos bit in EAX. point0: shr eax, 1 # Shift EAX right by 1 bit. ret # Return. ``` ## The opposite I also found an 11-byte function with a 1/4 odd probability: ``` 0f bc c8 d3 e8 83 f1 01 d3 e0 c3 ``` Assembly: ``` fe: bsf ecx, eax # Set ECX to the position of the lowest 1 bit in EAX. shr eax, cl # Shift EAX right by that quantity, removing all ending 0 bits. xor ecx, 1 # Invert the lowest bit of ECX. shl eax, cl # Shift EAX left, introducing a modified number of ending 0 bits. ret # Return. ``` # 1st extra challenge: 18 bytes ``` f3 0f b8 c8 d1 e0 0f bd d0 d1 e2 48 29 d0 e2 01 92 c3 ``` Implements a function several other answers have used, mapping powers of 2 to even numbers in ascending order and other numbers to odd numbers in ascending order: \$ f\_1(2^m) = 2m+2 \$, and for \$ n \in [2^m, 2^{m+1})\$, \$ f\_1(n) = 2n - 2m - 3\$. Assembly: ``` f1: popcnt ecx, eax # Set ECX to the number of 1 bits in EAX. shl eax, 1 # Shift EAX left by 1, doubling it to 2n. bsr edx, eax # Set EDX to the position of the highest 1 bit in EAX -- m+1. shl edx, 1 # Shift EDX left by 1, doubling it to 2m+2. dec eax # Decrement EAX to 2n-1. sub eax, edx # Subtract EDX from EAX, making it 2m-2n-3. loop point1 # Decrement ECX and jump if it's nonzero -- if the value was not a power of 2. xchg eax, edx # Exchange EAX and EDX, making EAX 2m+2. point1: ret # Return. ``` # 2nd extra challenge: 6 bytes ``` 83 f0 01 74 fb c3 ``` Produces \$ 1, 3, 2, 5, 4, 7, 6, ... \$ Assembly: ``` f2: xor eax, 1 # Invert the lowest bit of the value. jz f2 # Jump back if that makes it 0 (and it will be flipped back to 1). ret # Return. ``` # 3rd extra challenge: 12 bytes ``` 0f bd c8 d3 d8 19 d2 d3 c0 29 d0 c3 ``` Rearranges the bits of the value by moving the second-highest bit to the bottom. This produces 1 odd, 1 even, 1 odd, 2 even, 2 odd, 4 even, 4 odd, ... Assembly: ``` f3: bsr ecx, eax # Set ECX to the position of the highest 1 bit in EAX. rcr eax, cl # Rotate EAX and the carry flag CF together left by that quantity. # Note that the value of CF after BSR is officially undefined, # but it is consistently 0 on at least some systems, which is what this function needs. # This puts the second-highest bit of the value into CF, # while the highest bit goes to the bottom position and the lower bits go to the top. sbb edx, edx # Subtract EDX+CF from EDX, making its value -CF. rol eax, cl # Rotate EAX right by the same value, not including CF in the rotation. # EAX now contains all the bits of the original value except the second-highest, # followed by a single 0 bit; if the original value was 1, EAX is now 1. sub eax, edx # Subtract EDX from EAX, replacing the removed bit at the bottom. ret # Return. ``` [Answer] # [Python 2](https://docs.python.org/2/), 39 bytes ``` lambda n:[n/3*4+1,n/3*4+3,n/3*2+2][n%3] ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSHPKjpP31jLRNtQB0Ibg2kjbaPY6DxV49j/aflFChUKmXkKRYl56akaRgaaVlwKBUWZeSUaaRoVmpr/AQ "Python 2 – Try It Online") outputs : ``` 1, 3, 2, 5, 7, 4, 9, 11, 6, 13, 15, 8, 17, 19, 10, 21, 23, 12, 25, 27, 14, 29, 31, 16 ... ``` Odd probability = 2/3 If generating the sequence without taking an inputs is accepted, I also have: ### [Python 2](https://docs.python.org/2/), 34 bytes ``` i=3 while 1:print-~i/2,i-2,i,;i+=4 ``` [Try it online!](https://tio.run/##K6gsycjPM/r/P9PWmKs8IzMnVcHQqqAoM69Ety5T30gnUxeIdawztW1N/v8HAA "Python 2 – Try It Online") Outputs: ``` 2 1 3 4 5 7 6 9 11 8 13 15 10 17 19 12 21 23 14 25 27 16 29 31 18 33 35 20 37 39 22 41 ... ``` Odd probability = 2/3 [Answer] # Mathematical function, 48 bytes You said "function", so I'm making a function. Takes an input `x` and returns the `x+1`th term. It does mess up when given a non-integer. ``` x>=1>(x-1) mod 2:x+2 f(x)={ x>=1>x mod 2:x } x=0:1 ``` Excluding non-meaningful whitespace. Here's a graph: [![enter image description here](https://i.stack.imgur.com/vt4Qb.png)](https://i.stack.imgur.com/vt4Qb.png) There are always one or two more odd numbers than even ones. ]
[Question] [ It is common to need to make a page selection interface. It typically looks like this: ``` prev 1 ... 3 4 [5] 6 7 ... 173 next ``` Which means there are totally 173 pages, and you are on the 5th page currently. This challenge requires you take the total number of pages and the current page number as input, and output a string (or an array) to "display" the page selector. ## Input 2 positive integers * current page number * count of pages It is guaranteed that 1 <= current <= total. ## Output Output a string or an array which represent the ui for page selectors. * If output as string, a single space (U+0020) should be used between each pages. * If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space. + The three dots (`...`) is not optional for array output. ## Details * If current == 1, no "prev" will be outputted, otherwise, "prev" comes first. * If current == total, no "next" will be outputted, otherwise, "next" comes last. * The first page (1) and the last page (total) should always be outputted. * The current page, (current - 1) page, (current - 2) page, (current + 1) page, (current + 2) page should be outputted as long as the are in the range of [1..total]. * No other pages numbers should be outputted. * Pages outputted should be sorted in ascending order. * Output should not contain duplicate page numbers. * Current page should be highlighted by wrap it in a pair of `[]`. * If there is a gap between any neighbors, three dots (`...`) should be inserted. ## Test Cases ``` Current Total Output 1 1 [1] 1 2 [1] 2 next 1 10 [1] 2 3 ... 10 next 3 3 prev 1 2 [3] 3 6 prev 1 2 [3] 4 5 6 next 4 6 prev 1 2 3 [4] 5 6 next 4 7 prev 1 2 3 [4] 5 6 7 next 3 10 prev 1 2 [3] 4 5 ... 10 next 5 10 prev 1 ... 3 4 [5] 6 7 ... 10 next 10 10 prev 1 ... 8 9 [10] 52 173 prev 1 ... 50 51 [52] 53 54 ... 173 next ``` ## Rules * This is code-golf, the shortest code wins! [Answer] # [Retina](https://github.com/m-ender/retina), ~~125~~ ~~113~~ ~~109~~ 107 bytes ``` .+ $* r`1\G 1$' ¶ O`1+ \b(1+) \1\b [$1] .* (1+ 1+ \[)|(] 1+ 1+) .* $2 ... $1 ^1 prev 1 1$ 1 next 1+ $.& ``` [Try it online!](https://tio.run/##HYw9CsJQEIT7OcUUq@YHHpkE9QiWFpZ5kRhIYSMSglh4Lg/gxZ6bwH7DzFfsNM73xy1tskvPFEpYgalXPIGyHX5f4NyrRBwylTmj4oDW1IGhoCv6xTb/ZB3XkS8eVjOEQBOuwnMaXxRkEB/je4a/s7BNSYtl7ahCw8Y5OD72S6haa00dmz8 "Retina – Try It Online") Link includes test cases. Saved 12 bytes thanks to @MartinEnder. Explanation: ``` .+ $* ``` Convert to unary. ``` r`1\G 1$' ``` Generate all the page numbers in reverse order. ``` ¶ ``` Delete the newline separating the input. (There's also a space there from the page number generation anyway.) ``` O`1+ ``` Sort the pages back into ascending order. This also sorts the current page, which is now duplicated. ``` \b(1+) \1\b [$1] ``` Unduplicate and wrap `[]`s around the current page. ``` .* (1+ 1+ \[)|(] 1+ 1+) .* $2 ... $1 ``` Add an ellipsis if the current page is at least 5, or if there are at least 4 pages after the current page. (Note trailing space, to avoid including the last page in the ellipsis.) ``` ^1 prev 1 ``` Add the prev if the current page is not 1. ``` 1$ 1 next ``` Add the next if the current page is not the last page. ``` 1+ $.& ``` Convert back to decimal. [Answer] # JavaScript (ES6), ~~130~~ ~~122~~ 121 bytes Invoke with currying syntax, e.g. `f(3)(10)`. ``` x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_) ``` ``` f= x=>X=>[x>1&&'prev 1',x>4&&'...',x>3&&x-2,x>2&&x-1,`[${x}]`,(X-=x)>1&&x+1,X>2&&x+2,X>3&&'...',X&&X+x+' next'].filter(_=>_) console.log(f(1)(1)) console.log(f(1)(2)) console.log(f(1)(10)) console.log(f(3)(3)) console.log(f(3)(6)) console.log(f(4)(6)) console.log(f(4)(7)) console.log(f(3)(10)) console.log(f(5)(10)) console.log(f(10)(10)) console.log(f(52)(173)) ``` [Try it online!](https://tio.run/##ZY7haoMwFIVf5VKGGozBm5i6UfQ5hBBqaXVYrClWSmDs2V2sbsUV8uPcc797Ts6H@@F27JvrEHXmVI1tppRCippuFOqNptPE5wk4dJUdFhPjP1cAYwwwfq4FFW577as7oAOU0Iu9/WdDAhK2z8NkTQhQiV4Tcm5ekKlYuBAltYPSl49g/IK/wwc4f/6R5BRTsQZkDBJdInfNAmQyh6ZiSdW7SzbaLC@yXNkcPc@fb31q88RNjp6k8DwbcSf4JJCW6u3LfuuSBkWUWTId2hBp8diH3Anxe1x4XhHa0H8U@prVTTtUfbDP8j0Za9ND0ICpoSVwNN3NtBVrzWdwCRoVa/fILFATdjZNV0JJduMP) *-1 byte (Arnauld): Set `X` to `X-x`.* [Answer] # [6502 machine code](https://en.wikibooks.org/wiki/6502_Assembly) (C64), 160 bytes ``` 00 C0 20 9B B7 86 FB CA F0 01 CA 86 FD 20 9B B7 86 FC A6 FB E8 E4 FC B0 01 E8 86 FE A2 01 E4 FB F0 1A A9 91 A0 C0 20 1E AB A2 02 E4 FD B0 0D A9 2E 20 D2 FF CA 10 FA 20 3F AB A6 FD 86 9E E4 FB D0 05 A9 5B 20 D2 FF A9 00 20 CD BD A6 9E E4 FB D0 05 A9 5D 20 D2 FF 20 3F AB A6 9E E4 FC F0 25 E4 FE F0 05 E8 86 9E D0 D5 E8 E4 FC F0 0D A2 02 A9 2E 20 D2 FF CA 10 FA 20 3F AB A6 FC A9 00 20 CD BD 20 3F AB A6 FC E4 FB F0 07 A9 99 A0 C0 20 1E AB 60 50 52 45 56 20 31 20 00 4E 45 58 54 00 ``` **[Online demo](https://vice.janicek.co/c64/#%7B"controlPort2":"joystick","primaryControlPort":2,"keys":%7B"SPACE":"","RETURN":"","F1":"","F3":"","F5":"","F7":""%7D,"files":%7B"page.prg":"data:;base64,AMAgm7eG+8rwAcqG/SCbt4b8pvvo5PywAeiG/qIB5PvwGqmRoMAgHquiAuT9sA2pLiDS/8oQ+iA/q6b9hp7k+9AFqVsg0v+pACDNvaae5PvQBaldINL/ID+rpp7k/PAl5P7wBeiGntDV6OT88A2iAqkuINL/yhD6ID+rpvypACDNvSA/q6b85PvwB6mZoMAgHqtgUFJFViAxIABORVhUAA=="%7D,"vice":%7B"-autostart":"page.prg"%7D%7D)** -- **Usage:** `sys49152,[current],[total]`, e.g. `sys49152,5,173`. The numbers must be in the range [1..255] with current <= total. As this wasn't specified otherwise, this is the "natural" unsigned integer range on an 8bit processor. --- Explanation as commented disassembly listing: ``` 00 C0 .WORD $C000 ; load address .C:c000 20 9B B7 JSR $B79B ; read 8bit integer .C:c003 86 FB STX $FB ; store current page .C:c005 CA DEX ; calculate lower start for ... .C:c006 F0 01 BEQ .stl .C:c008 CA DEX .C:c009 .stl: .C:c009 86 FD STX $FD ; ... range and store .C:c00b 20 9B B7 JSR $B79B ; read 8bit integer .C:c00e 86 FC STX $FC ; store total pages .C:c010 A6 FB LDX $FB ; load current page .C:c012 E8 INX ; calculate upper end for ... .C:c013 E4 FC CPX $FC .C:c015 B0 01 BCS .stu .C:c017 E8 INX .C:c018 .stu: .C:c018 86 FE STX $FE ; ... range and store .C:c01a A2 01 LDX #$01 ; check whether first page is current .C:c01c E4 FB CPX $FB .C:c01e F0 1A BEQ .sequence ; then directly to sequence .C:c020 A9 91 LDA #<.prev ; output string for ... .C:c022 A0 C0 LDY #>.prev .C:c024 20 1E AB JSR $AB1E ; ... "prev 1 " .C:c027 A2 02 LDX #$02 ; check whether page 2 is in range ... .C:c029 E4 FD CPX $FD .C:c02b B0 0D BCS .sequence ; ... then directly to sequence .C:c02d A9 2E LDA #$2E ; load character '.' .C:c02f .ellip1: .C:c02f 20 D2 FF JSR $FFD2 ; output ... .C:c032 CA DEX .C:c033 10 FA BPL .ellip1 ; ... 3 times .C:c035 20 3F AB JSR $AB3F ; output space .C:c038 A6 FD LDX $FD ; load lower start for range .C:c03a .sequence: .C:c03a 86 9E STX $9E ; store to temporary .C:c03c .seqloop: .C:c03c E4 FB CPX $FB ; compare with current .C:c03e D0 05 BNE .notcurrent1 ; yes -> output '[' .C:c040 A9 5B LDA #$5B .C:c042 20 D2 FF JSR $FFD2 .C:c045 .notcurrent1: .C:c045 A9 00 LDA #$00 .C:c047 20 CD BD JSR $BDCD ; output number .C:c04a A6 9E LDX $9E ; compare with current .C:c04c E4 FB CPX $FB .C:c04e D0 05 BNE .notcurrent2 ; yes -> output ']' .C:c050 A9 5D LDA #$5D .C:c052 20 D2 FF JSR $FFD2 .C:c055 .notcurrent2: .C:c055 20 3F AB JSR $AB3F ; output space .C:c058 A6 9E LDX $9E .C:c05a E4 FC CPX $FC ; compare position with last page .C:c05c F0 25 BEQ .printnext ; if eq jump to part printing "next" .C:c05e E4 FE CPX $FE ; compare position to upper end of range .C:c060 F0 05 BEQ .printellip2 ; if eq jump to part printing "..." .C:c062 E8 INX .C:c063 86 9E STX $9E ; next number .C:c065 D0 D5 BNE .seqloop ; and repeat loop for sequence .C:c067 .printellip2: .C:c067 E8 INX .C:c068 E4 FC CPX $FC ; compare next number with last page .C:c06a F0 0D BEQ .printlast ; if eq jump to part printing page num .C:c06c A2 02 LDX #$02 .C:c06e A9 2E LDA #$2E ; load character '.' .C:c070 .ellip2: .C:c070 20 D2 FF JSR $FFD2 ; output ... .C:c073 CA DEX .C:c074 10 FA BPL .ellip2 ; ... 3 times .C:c076 20 3F AB JSR $AB3F ; output space .C:c079 .printlast: .C:c079 A6 FC LDX $FC ; output last page number .C:c07b A9 00 LDA #$00 .C:c07d 20 CD BD JSR $BDCD .C:c080 20 3F AB JSR $AB3F ; output space .C:c083 .printnext: .C:c083 A6 FC LDX $FC ; compare current page with last page .C:c085 E4 FB CPX $FB .C:c087 F0 07 BEQ .done ; if eq nothing else to do .C:c089 A9 99 LDA #<.next ; output string for ... .C:c08b A0 C0 LDY #>.next .C:c08d 20 1E AB JSR $AB1E ; "next" .C:c090 .done: .C:c090 60 RTS .C:c091 .prev: .C:c091 50 52 45 56 .BYTE "prev" .C:c095 20 31 20 00 .BYTE " 1 ", $00 .C:c099 .next: .C:c099 4E 45 58 54 .BYTE "next" .C:c09d 00 .BYTE $00 ``` [Answer] # [R](https://www.r-project.org/), ~~214 bytes~~ 168 bytes ``` function(c,m,`~`=function(x,y)if(x)cat(y)){o=-2:2+c o=o[o>0&o<=m] o[o==c]=paste0('[',c,']') c>1~'prev ' c>3~'1 ' c>4~' ... ' T~o c+3<m~' ...' c+2<m~c('',m) c<m~' next'} ``` [Try it online!](https://tio.run/##VY5BCoMwEEX3nsJVJ8FUjLppcTxFd1ZQBgMuTMTaopTm6nZqodDd@@/zh5k2g5u5W5p7ZwWpQTW@wZ9Y1Cp7IxZJ7SxWKZ8Oj@k5jShw6CpXJgdX4FAHzIhU49je5i4RUIEiBTXIgErtYZy6RwjMmQe9Q@4hjOOY@eJdQFFWDF/DZZRyIAGgBt7vhe2WGV6bEVppdvwMXC1f/4j0X@TqJLc3 "R – Try It Online") Thanks to @user2390246 for some great golfing tips [Answer] # [APL (Dyalog)](https://www.dyalog.com/), ~~83~~ 82 bytes Anonymous infix function taking current as left argument and total as right argument. ``` {('prev '/⍨⍺>1),('x+'⎕R'...'⍕∊(⊂1⌽'][',⍕)@⍺⊢'x'@(~∊∘(1,⍵,⍺+3-⍳5))⍳⍵),' next'/⍨⍺<⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqDfWCotQyBXX9R70rHvXusjPU1NFQr9BWf9Q3NUhdT09P/VHv1EcdXRqPupoMH/XsVY@NVtcBCmk6ABU/6lqkXqHuoFEHVPCoY4aGIVBmKxDv0jbWfdS72VRTE0gChTR11BXyUitKYJbYAMVq//83VEhTMOQCkUZg0tCAyxhIGYNJMzAJFDKFUIYGUK4RiDY3BgA "APL (Dyalog Unicode) – Try It Online") `{`…`}` explicit lambda where `⍺` and `⍵` represent the left and right arguments:  `⍺<⍵` is current smaller than total?  `' next'/⍨` if so (lit. use that to replicate) the text  `(`…`),` prepend the following:   `⍳⍵` **ɩ**ntegers 1 through total   `'x'@(`…`)` replace with an `x` **at** the positions where the items are…    `~` not    `∊` members of    `1` one    `,` followed by    `⍵` the total    `,` followed by     `⍳5` the first five **ɩ**ntegers (`[1,2,3,4,5]`)     `3-` subtracted from three (`[2,1,0,-1,-2]`)     `⍺+` added to the current (`[⍺+2,⍺+1,⍺,⍺-1,⍺-2]`)    `⊢` yield that (serves to separate `⍺` from `'x'`)    `(`…`)` apply the following tacit function **at** the current position:     `⍕` format (stringify)     `'][',` prepend the text`      `1⌽` rotate one step leftward (moves the `]` to the end)     `⊂` enclose (so that it is a scalar which will fit in the single indicated position)    `∊` **ϵ**nlist (flatten – because we made it nested when we inserted brackets)    `⍕` format (stringify – 1 space separating numbers from each other and from `x` runs)   `'x+'⎕R'...'` PCRE **R**eplace `x` runs with three periods  `(`…`),` prepend the following:   `⍺>1` is current larger than 1?   `'prev '/⍨` if so (lit. use that to replicate) the text [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~131~~ ~~114~~ 109 bytes ``` Range@#2/.{#->"["<>(t=ToString)@#<>"]",1->"prev 1",#2->t@#2<>" next",#-3|#+3:>"...",x_/;Abs[x-#]>2:>Nothing}& ``` [Try it online!](https://tio.run/##DY1RC4IwFEb/itxBFG0TJxGYDvsDEdXbGDFjqQ/OsFsI1W9f9/U7fOcMDjs/OOxvLt5foYonF1pfM5XKDxMaDJR6idVlPOPUh3ZVs1KDBZ4Re0z@nWTAmRIa6UIkCX5GWkT@Zeu80CClBD5f092@eZpZMKtVoQ8jdiT7LeKRpGgobDaKZ9vc2vgH "Wolfram Language (Mathematica) – Try It Online") ## How it works Lots of replacing. Starting with a list of all pages, replace, in order: 1. `#->"["<>(t=ToString)@#<>"]"`: the current page with a bracketed string, 2. `1->"prev 1"`: page 1 with the string `prev 1`, 3. `#2->t@#2<>" next"`: the last page with the string `(number) next`, with 4. `#-3|#+3:>"..."`: page `current-3` and page `current+3` with the string `"..."`, 5. `x_/;Abs[x-#]>2:>Nothing`: all other (integer) pages below `current-2` or above `current+2` with nothing. (Yes, `Nothing` is a built-in.) [Answer] # [Funky](https://github.com/TehFlaminTaco/Funky), ~~218~~ 210 bytes *Saved some bytes, some of which thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)* ``` p=>m=>{t={}a=t::push b=t::pop fori=p-2i<p+3i++a(i)t[2]="[%i]"%p whilet[0]<1b(0)whilet[n=-1+#t]>m b(n)ifp>4a(0,"...")ifp>3a(0,1)ifp>1a(0,"prev")ifp<m-3a("...")ifp<m-2a(m)ifp<m a("next")t::reduce((a,b)=>a+" "+b)} ``` [Try it online!](https://tio.run/##PY7LasMwEEV/RagEZlBsLKdkETz6EeOF1EpEtFYGV86DkG93HLV0dw7nLm6Y09dtCbQwmZHMPdP9YSkfDjz/HIUrdGIRTlMkrtrYsdpFpSxEzH07kOw3cZAbFpdj/Pa5b4ZOO2jwTxNVWr3lwYzCQcIY2LxbaLayrmtZdPdSXVCXwpM/l9SN1Rr/l6u2FsZfFGtI/polrgcn/zl/eAC7dUjGKimkcvhYeIopQwC9R9i3iMsT "Funky – Try It Online") [Answer] # [Python 2](https://docs.python.org/2/), 135 bytes ``` lambda c,t:re.sub(' +',' ... ','prev '*(c>1)+' '.join(`[x,[x]][x==c]`*(x%t<2or-3<x-c<3)for x in range(1,t+1))+' next'*(c<t)) import re ``` [Try it online!](https://tio.run/##XcxNDoIwEIbhPaeYjWkLpaHgT2KKF0ESoBbFSEtqNfX0CCvB1eTJfHmHj7sZnY5tfh4fdd9capDUHa1iz1eDEUCEKALGGEx3sOoNKMTyxEmEALG76TSuCk8LX5aFz3NZViH2GydSY@NM@FiKjLTGgodOg631VWFOXcTJHNDKuzknHCFB1w/GOrBqHGynHbTTEDgJFkpX4smPGYVspf1Ky@luTZ78vdPJh0VsO8fGLw "Python 2 – Try It Online") First we create a string like `prev 1 3 4 [5] 6 7 10 next`, which has “gaps” caused by erasing some numbers but not their delimiting spaces. Then we replace any run of 2+ spaces by `...` using a regex. [Answer] # [Python 2](https://docs.python.org/2/), ~~136~~ 130 bytes ``` lambda p,n:[i for i,j in zip(['prev',1,'...',p-2,p-1,[p],p+1,p+2,'...',n,'next'],[1,3,4,2,1,.1,-n,1-n,3-n,2-n,-n])if p*cmp(j,0)>j] ``` [Try it online!](https://tio.run/##LctBDsIgFIThvadgB@iUCJgYTfQiyKJqiTT29aVBo16@sujiy7@YDH/LYyQ3p9NlfrbD9d4KBh1DFmmcREYvMolfZhUkT91bwkIaYyS4cZVF4Aje2MotC0FS9ykyIlh47ODqyVg0BFv5ylUNRZ2T4PVtYNVjq899nHnKVERSmfhVlMZSPfv9yh/@ "Python 2 – Try It Online") > > If output as an array, the array should produce same result as the string after convert each item to string and join them with a single space. > > > [Try it online!](https://tio.run/##LcvNCsIwEATgu0@R26Y6DSYVREFfpPZQf4IJdrvUKOrLxxw68DGHYeSb7iO77A@n/OiH87VXAt63QflxUgFRBVa/ILolmW5vggUZYwhSu8KilQ6ysoWbFwbx7ZOoQ2vRYANXTsaiZtiiKVxRc1cFr2R5GURHrKtj7LJMgRMpMnEMrIde9DNN8DqwvJKuMHdJbraLZvcH "Python 2 – Try It Online") in prettified form, where you can see the footer translates quite literally to "convert each to string, join on spaces". This is an alternative to Lynn's approach. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~169 196 190 181 175 169~~ 166 bytes ``` @(n,m)(r=[(n>1)*'prev ' (g=n>4)*'1 ... ' (s=@sprintf)(f='%d ',max(n-3+g,1):n-1) s('[%d]',n) 32*(q=n<m) s(f,n+1:min(n+3-(l=n<m-3),m)) l*['... ' s(f,m)] q*'next'])(r>0) ``` [Try it online!](https://tio.run/##Pc7BjoJADAbgu0/Ri2kLA6GMulmzQ3wPwsEoQ0ycrgIxvj2Cxrl9/fsn7f9pPD7aybs8z6cDqQlMvatJK@EEb337AATqnFabeRaYa0swuMNw6y86eibvcH0GNOH4JM1s2hnhvWbCMBDW63ODRhlsmdDd6V9YYm80lX24KGlqM7oueWZ5Ps5wTWr8XFl6gRu4J6jtc8Rmfq0qePIkYASAV2@VUVK8ZcFY@Gr30SbKxt426jdKirgtjfxYnl4 "Octave – Try It Online") I'll add an explanation later on. Hmm, seems there were some issues with the output format. These have now been resolved - all outputs are correct. But alas it cost 27 bytes. Managed to claw all of those back though with a bit of fat trimming. --- * Save 6 bytes by using `*` instead of `.*` - thanks @StewieGriffin * Save 9 bytes using `sprintf` instead of `num2str` as I already had that handle in `s`. * Save 6 bytes by pulling `[]` into the `sprint` call. * Save 6 bytes by finding a way to reduce the number of comparisons. * Save 3 bytes by removing need for `strtrim()` without causing trailing space. [Answer] # Java 8, ~~201~~ ~~200~~ 197 bytes ``` t->n->(n<2?"[1] ":"prev 1 ")+(n>4?"... "+(n-2)+" "+~-n+" ["+n+"] ":n>3?"2 3 [4] ":n>2?"2 [3] ":n>1?"[2] ":"")+(n<t?(n>t-2?"":n>t-3?t-1+" ":n>t-4?(t-2)+" "+~-t+" ":++n+" "+-~n+" ... ")+t+" next":"") ``` **Explanation:** [Try it here.](https://tio.run/##nVDBboJAEL37FZM9saG7ccG2SUW4NemhJ4/EA0U0a3EhMJiaRn@dzq7UHppUbUJ23mPeezs7m2yXiaouzGb53udl1rbwmmnzOQJoMUOdw4YUskNdylVnctSVkc8DiF4MFuuiubtONMdGm3UcQw4z6FHERsSeiYKEpWoB7InVTbEDBYz7noknCZNSAiMsAu4zQkdhqKbMp2INJg4TFkAI6eREA0vT8EQU5QYu1wVGmFAqCtLYLoowQaFsrmOTxMOfe9D99@1FxMXRVjcN923LFB/ocvspLYq@unsraVfDynaVXsKW1uidnpwuION2pQCrqvG0QdAzNQUdzdSYiu8PXYD5vsViK6sOZU1WLI2Xy6yuy72nxnxAmvOp0x/cObpk5Gcw@P4QB7eIw38lB7ck3yQOv8WXHA@/HNeIJ1eI1eN5mvth9sPo0H8B) ``` t->n-> // Method with two integer parameters and String return-type (n<2? // If the current page is 1: "[1] " // Start with literal "[1] " : // Else: "prev 1 ") // Start with literal "prev 1" +(n>4? // +If the current page is larger than 4: "... " // Append literal "... " +(n-2)+" " // + the current page minus 2, and a space ~-n // + the current page minus 1, and a space +" ["+n+"] " // + "[current_page]" and a space :n>3? // Else-if the current page is 4: "2 3 [4] " // Append literal "2 3 [4] " :n>2? // Else-if the current page is 3: "2 [3] " // Append literal "2 [3] " :n>1? // Else-if the current page is 2: "[2] " // Append literal "[2] " : // Else (the current page is 1): "") // Append nothing +(n<t? // +If the current page and total amount of pages are not the same: (n>t-2? // If the current page is larger than the total minus 2: "" // Append nothing :n>t-3? // Else-if the current page is larger than the total minus 3: t-1+" " // Append the total minus 1, and a space :n>t-4? // Else-if the current page is larger than the total minus 4: (t-2)+" " // Append the total minus 2, and a space +~-t+" " // + the total minus 1, and a space : // Else: ++n+" " // Append the current page plus 1, and a space +-~n+ // + the current page plus 2, and a space " ... ") // + literal "... " +t // + the total itself +" next") // + literal " next" : // Else (current page and total amount of pages are the same): "") // Append nothing // End of method (implicit / single-line return-statement) ``` [Answer] # [Java (OpenJDK 8)](http://openjdk.java.net/), ~~218~~ ~~179~~ ~~177~~ ~~167~~ 166 bytes ``` c->t->{String p,e="... ",x="["+c+"] ";int i=c-2;for(p=c>1?"prev 1 "+(c>4?e:""):x;i<c+3;i++)p+=i>1&i<t?i==c?x:i+" ":"";return p+(i<t-1?e:"")+(c<t?t+" next":t>1?x:"");} ``` [Try it online!](https://tio.run/##nZA/b8IwEMX3fIqThyqpidXQf1KMk61Sh3ZhRAzGGGSaOJZzQUGIz05dQdOlC/F0uvd@vnu3k3uZNk7b3frrbGrXeIRd6LEOTcU2nVVoGsvueRS5blUZBaqSbQsf0lg4RlGLEkPz7WqcvVvUW@0n/3Tm6I3dFgU4udWfXb3SHgScVVpgWhwvKriJFoQxBmTSC7IgVFGyBMKNRTBCpVO@aXzshCqykjiv95ABobEqnkqdE5LkPTczRR@5oTRxVJgiuzMzLI0QquxzQwmQ4ONeY@ctOBoHNc0ucPgnWDF4rO6R5BiG9D8CP535b/5r4n1j1lCHK8SXzRdLkEm4CFzf/NCirlnTIXNBx8rGf7mZdK46xFkyFAkfR05Hk9nDrehjMhRjyZfR5O3rPo9HAzF@7HRgX4dDnaLT@Rs "Java (OpenJDK 8) – Try It Online") [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 59 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` +2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤ ``` A full program\* printing the result to STDOUT. Takes arguments `current` and `total` in that order. **[Try it online!](https://tio.run/##AXwAg/9qZWxsef//KzJS4bmrLTQ@w5DhuJ/igbkxOztRwrVJ4oCZYTNS4oCdLuG5geKBuMW84bqOCuG7isKsO27igJzCosKp4bu1WeKAnMKhJsOnwrvhuosiV@KCrGrDp0zDkGZL4bmj4oG4auKBuFfFkuG5mMKk////NTL/MTcz "Jelly – Try It Online")** or see the [test-suite](https://tio.run/##y0rNyan8/1/bKOjhztW6JnaHJzzcMf9R405Da@vAQ1s9HzXMTDQOetQwV@/hzsZHjTuO7nm4q4/r4e6uQ2us8x41zDm06NDKh7u3RoKYC9UOLz@0@@GubqXwR01rsg4v9zk8Ic374c7FQH1ZQBx@dNLDnTMOLfl/eLk@UMHRPQ5gAZBaIAaaoKBrpwC0KvL//@hoQx3DWB0gaQQmDQ2AlLGOMZg0A5NgIVMIZWgA5RrpGJobx8YCAA "Jelly – Try It Online"). ### How? ``` +2Rṫ-4>Ðḟ⁹1;;QµI’a3R”.ṁ⁸żẎ - Link 1, numbers and ellipses: current, total - e.g. 52, 173 2 - literal two 2 + - add to current 54 R - range [1,2,3,...,53,54] -4 - literal minus four -4 ṫ - tail from index (i.e. right five) [50,51,52,53,54] ⁹ - chain's right argument, total 173 Ðḟ - filter discard if: > - greater than? [50,51,52,53,54] 1 - literal one 1 ; - concatenate [1,50,51,52,53,54] ; - concatenate (implicit right = total) [1,50,51,52,53,54,173] Q - unique (remove excess 1 and/or total) [1,50,51,52,53,54,173] µ - new monadic chain, call that X I - incremental differences [49,1,1,1,1,119] ’ - decrement (vectorises) [48,0,0,0,0,118] 3 - literal three 3 a - logical and (vectorises) [3,0,0,0,0,3] R - range (vectorises) [[1,2,3],[],[],[],[],[1,2,3]] ”. - literal '.' character '.' ṁ - mould like that [['.','.','.'],[],[],[],[],['.','.','.']] ⁸ - chain's left argument, X [1,50,51,52,53,54,173] ż - zip with that [[1,['.', '.', '.']],[50,[]],[51,[]],[52,[]],[53,[]],[54,['.','.','.']],[173]] Ẏ - tighten [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173] Ị¬;n“¢©ỵY“¡&ç»ẋ"W€jçLÐfKṣ⁸j⁸WŒṘ¤ - Main link: current, total e.g. 52, 173 Ị - insignificant? (abs(current)<=1) 0 ¬ - logical not 1 n - not equal (current != total) 1 ; - concatenate [1,1] “¢©ỵY“¡&ç» - list of compressed strings [['p','r','e','v'], ['n','e','x','t']] " - zip with: ẋ - repeat (zeros -> empty lists) [['p','r','e','v'], ['n','e','x','t']] W€ - wrap €ach (prep for the join) [[['p','r','e','v']], [['n','e','x','t']]] ç - call last link (1) as a dyad [1,['.', '.', '.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173] j - join [['p','r','e','v'],1,['.','.','.'],50,[],51,[],52,[],53,[],54,['.','.','.'],173,['n','e','x','t']] Ðf - filter keep if: L - length (removes empty lists) [['p','r','e','v'],1,['.','.','.'],50,51,52,53,54,['.','.','.'],173,['n','e','x','t']] K - join with spaces ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',52,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t'] ⁸ - chain's left argument, current 52 ṣ - split at that [['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ',],[,' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t']] ¤ - nilad followed by link(s) as a nilad: ⁸ - chain's left argument, current 52 W - wrap [52] ŒṘ - Python string representation ['[','5','2',']'] j - join ['p','r','e','v',' ',1,' ','.','.','.',' ',50,' ',51,' ','[','5','2',']',' ',53,' ',54,' ','.','.','.',' ',173,' ','n','e','x','t'] - implicit print prev 1 ... 50 51 [52] 53 54 ... 173 next ``` \* As a dyadic link taking `current` on the left and `total` on the right this returns a list with a mix of characters and integers; this list includes the spaces. The byte `K` cannot simply be removed to adhere to the spec however, since the result would then have the bracketed `current` as separate characters (like `[...'[','5','2',']'...]`) so the "convert each item to string and join them with a single space" would fail to produce the desired result) [Answer] # [Python 2](https://docs.python.org/2/), ~~178~~ 170 bytes ``` x,y=input() e="... ","" o=("Prev 1 ","[1] ")[y<2]+e[y<5] for z in range(2,x):o+=("",(`z`,`[z]`)[z==y]+" ")[y-3<z<y+3] print o+("",e[x-y<4]+(`x`+" Next",`[x]`)[y==x])[x>1] ``` [Try it online!](https://tio.run/##HcvBCgIhFIXhvU8hd6VoQ87UJrRHiPZywRZWs9FBLNSXN6fV4cD/bTW/Y5h7L7KaNWyfzDjxBqZpoiABSDQM7sl/qdq/VUiB26pnFH7MGckzJtroGmh6hJdnsyz8EsVQIJlrTjrb0HHbjKko4K8Pi266igXJltaQaRR77W05VH1CwVxxo7z5kmHwsvNqTEFuy1Vh7@oolx8 "Python 2 – Try It Online") Second attempt after reading the rules more carefully. -8 by losing some unneeded brackets. [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~195~~ 192 bytes Saved 3 bytes thanks to Kevin Cruijssen. ``` c=>t=>{var n=c>1?"prev ":"";n+=c>4?"1 ... ":c<2?"[1] ":"1 ";if(t>1){for(int i=c-3;i++<c+2;)if(i>1&i<t)n+=i==c?$"[{i}] ":i+" ";n+=c<t-4?"... "+t:c==t?$"[{t}]":t+"";n+=c<t?" next":"";}return n;} ``` [Try it online!](https://tio.run/##jY8/a8MwEMXn@FMcohQLNaZy@gciyx4KnVooZOgQMhhVDgeJXKRLaDH@7K7i0C4dHLjp3e/ee2fC3LTeDmZXhwBvvt36eg9dMgtUExo4tvgBrzW6NJBHt11voPbbwCOSrL4D2X32fHCmQEc38E8435QlNKAHo0vSZXesPThtSlmxT2@PwJaMKSeiclcxCVmWRckUecXWcnPaSmAKm5RKybum9Wl0BtRmvlAoRGFErnhcYymvsSAenVBrU12xdYf9yQAFg3NCQfOYMSYIWhqtacSo37AlCfYLVQyc/aKxWO8tHbwDp/pB/b381LrQ7mz27pHsCzqbNqnkcbiaQPJpRN5OMAseZxJ5mEYmk@4vYCJwgVEeocexdTLrk374AQ "C# (.NET Core) – Try It Online") [Answer] **C++ - 247 bytes** ``` #include <iostream> #define c std::cout<< #define N (a-i<3?i-a<2?1:b-i:a-i-2) void s(int a,int b){if(a>1)c"prev ";for(int i=1;i<=b&&N!=0;i+=N)c(i==1?"":" ")<<(a==i?"[":"")<<i<<(a==i?"]":"")<<(N>1?" ...":"");if(a<b-2)c" "<<b;if(a<b)c" next";c"\n";} ``` [Try it online!](https://tio.run/##RY7RaoMwFIav51NkKZSEqRilG5gTfQNfYNtFjBEOrFHUlkHps7ukrd1FDt//5STnWDOOiT/rDp35OXWWAA7zMll9rKJdZ3t0lhgyL11ZmuG0ADxtQ5hOEIoaEw15Lco2wdKbJOfRecCOzAzdQnQcassv2DNdCW7oONkzobIfplsDKiERVLvfN68qk/imGm4YKiVqSktKKAdgWims6afPIeLTfD8MayrfTtI0vQkZhkHrVzH@A4D2IUJ09neh0tAvR@V1DRscNTrGySV6mZmIBZd3yDcQ2Z2KuNjgfYPt7vAkkf3LPBYf4c11Xf8A) [Answer] # [Python 2](https://docs.python.org/2/), ~~128~~ 124 bytes *-4 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)!* ``` lambda c,l:["prev"]*(c>1)+[range(1,c),[1,"...",c-2,c-1]][c>4]+[[c]]+[range(c+1,l+1),[c+1,c+2,"...",l]][l-c>4]+["next"]*(c<l) ``` [Try it online!](https://tio.run/##NU3brsIgEHznKxpepIKNi9WTeI7@CBKDWLUGkXDw9vV1qXUvszuZ2Wx4pdPVy@6w2nTOXHZ7U1jhloqG2NypHjO7hpKraPyxYSBsKRQIWlUVFXYisUFrZde15kpZrb9Oy0E4DujOm@VyuHHodpOPn/rmmfoXf67sHqfWNQUsixBbn0bFqDpfW88uJrD/FMWBtT7cEivFMDF@o3lsB9oBAYIlM8CUkBkm1iJD5vMesXsiCfygXmd9jvAG "Python 2 – Try It Online") Output as a list, but tio link includes pretty-print. [Answer] # CJam, 74 ``` q~\:A\:B]3e*[1T4A3+1A].>["prev"1'.3*_B"next"]:a.*3/5,A2-f+B,2>&*:+_A#Aa`tp ``` Outputs as array. [Try it online](http://cjam.aditsu.net/#code=q%7E%5C%3AA%5C%3AB%5D3e*%5B1T4A3%2B1A%5D.%3E%5B%22prev%221%27.3*_B%22next%22%5D%3Aa.*3%2F5%2CA2-f%2BB%2C2%3E%26*%3A%2B_A%23Aa%60tp&input=4%2010) Replace the final `p` with `S*` to output as string. **Explanation:** ``` q~ read and evaluate the input (pushing 2 numbers on the stack) \:A\:B store the numbers in A and B, keeping them in the same order ]3e* wrap in array, then repeat each number 3 times - [A A A B B B] [1T4 make an array containing 1, 0 (T=0 by default), 4, A3+1A] then A+3, 1, and A .> compare the 2 arrays element by element - [A>1 A>0 A>4 B>A+3 B>1 B>A] (each result is 1 or 0) ["prev"1 make an array containing "prev", 1, '.3*_ "..." twice ("..." = '.' repeated 3 times), B"next"] then B and "next" :a wrap each of its elements in an array - [["prev"][1]["..."]…] .* repeat each of these arrays according to the previous array e.g. ["prev"] is repeated A>1 times - ["prev"] if A>1, else [] [1] is repeated A>0 times (always 1), etc. obtaining an array of 6 arrays, some of which may be empty 3/ split into 2 arrays of 3 arrays each (between the "..." parts) 5,A2-f+ make an array [0 1 2 3 4] then add A-2 to each element B,2>& intersect with the array [2 3 … B-1] (these are the middle numbers) * join the 2 previous arrays by adding these numbers between them :+ concatenate all these arrays and numbers together obtaining an array containing only numbers and strings _A# duplicate the array then find the position of A in it Aa` generate the "[A]" string (with the actual number for A) by wrapping A in an array and getting its string representation t put it in the array at A's position p print the array's string representation ``` [Answer] ## Haskell, ~~145~~ 129 bytes ``` s x=show x a#t=["prev 1"|a>1]++["..."|a>4]++map s[max 4a-2..a-1]++s[a]:map s[a+1..min(a+3)t-1]++["..."|t-a>3]++[s t++" next"|a<t] ``` [Try it online!](https://tio.run/##TYzLDoIwEEX3fsUEN20KDaU@EiN@ga5cNsRMlAQiVNIWxcR/x1JcuDl3zszkVmjvZdOMo4Uht9XjBcMCly5XUWfKJ4jogwdRMKYizvkkKy8tdmBViwOsMMk4x2R6sQqL3XxCJjhva02QSeqSvwKX4EFOasExFoEuB@dr964YW6w15OAbThcgXe/Ozhw1cOj162FuNkzX3pg3kCWloIiIBY09s0CR@pCxDNwEhtV6DpH@NIvFVtJi/AI "Haskell – Try It Online") Edit: @Ørjan Johansen saved 16 bytes. Thanks! [Answer] # PHP (<7.2), ~~157~~ 150 bytes taking the details literally turned out to be the shortest approach: ``` [,$k,$n]=$argv;for($k>1&&print"prev ";$i++<$n;)$g=in_array($i,range($k-2,$k+2)+[5=>1,$n])?!print$i-$k?"$i ":"[$i] ":$g||print"... ";$k<$n&&print next; ``` Run with `php -nr '<code>' <curpage> <numpages>` or [try it online](http://sandbox.onlinephpfunctions.com/code/22e042b98ad6b0642c02ab4656c80dec20a3e74b?v=7.1.0). [Answer] ## [Golf Script](https://tio.run/##JcvRCoIwFAbgVzlX/TT1OA0JtuWLOC@2YRFIiUkEY736Err7br7bc76@wnpftpy/VjmtvG6cwbJOb4I47WyImXcPXRkdtVWR6jGy7K0/mkMqI7tLxACLEUmAkGrtyVUqUNvjf30hZDCgx/TZIHLuJJ3lDw) - 104 characters ``` ~\:a;:b;1a<'prev '*3a<'1 ... '*[5,{a 2-+}/]{.0>\b)<&},{.a={'['\']'}*' '}/;b a-:c 2>' ... 'b+*0c<' next'* ``` ### Ungolfed ``` ~\:a;:b; # a = 1st arg, b = 2nd arg 1a<'prev '* # if a > 1: print 'prev ' 3a<'1 ... '* # if a > 3: print '1 ... ' [5,{a 2-+}/] # creates an array [a-2 a-1 a a+1 a+2] {.0>\b)<&}, # keeps only elements >0 and <=b { .a={'['\']'}* # puts '[' ']' around the element equal to a ' '}/; # prints each element with a leading space b a-:c 2>' ... 'b+* # if b-a > 2: print ' ... ' + b 0c<' next'* # if b-a > 0: print ' next' ``` [Answer] # Perl 5, ~~113+1 (-p)~~ 109 +3(-pal) bytes ``` $_=join$",1..<>;s/\b@F\b/[$&]/;s/^1/prev 1/;s/\d$/$& next/;s/(^|\] )\w+ \w+ \K[\w ]*(?= \w+ \w+( \[|$))/.../g ``` [Try it online](https://tio.run/##K0gtyjH9/18l3jYrPzNPRUnHUE/Pxs66WD8mycEtJkk/WkUtVh/IjTPULyhKLVMwBHFiUlT0VdQU8lIrSkBcjbiamFgFzZhybQUw9o6OKVeI1dKwt1WAimkoxETXqGhq6uvp6emn//9vyAWCRiDSgMsYDM2AGMgxBREQZAqUNzf@l19QkpmfV/xftyAxBwA) [Answer] # [Ruby](https://www.ruby-lang.org/), 127 bytes I'm not particularly happy with this, especially the prev/next logic. ``` ->c,t{"prev #{(1..t).chunk{|n|n<2||n==t||n>c-3&&n<c+3}.map{|t,a|t ?a:?.*3}*" "} next".sub(/(prev )?\b(#{c})\b( next)?/,'[\2]')} ``` [Try it online!](https://tio.run/##bZLfboIwFMbvfYoTSBQcVkupbovKxR5gN7urzYIV4zJXDZZlC@XZ2RFDIoNenKbn@52vp3@yfPtb7VfVZK0CUzjnLP0Gt/AoIcYn6pDrz8Jqq5ehtXq1MhjXasKGQ71UD6wkX8m5sCZIrIE4eY7JmJVjB5wSdPpjHHLJt97Uq039eLP13EKVPs617MfTYCQ2oRz5ZeXCS55lqTbwdjLJEcCF19ycczMQUA8aNNEFQeUA7tNhk4awtm6pdHanMiCEYKqFsaCJLtTNUiQFk2193tEhAg7zllXUhzIQkeyg7K65jmtPl7zLXymGvOASzRc9VTXfU/UIT3gjs@aI/HqDdMH@Y3wGnKJ9iO0z4NFthwW7bSFJmqjD@@X4oVIv9GF3AovfyKIpvtwF9gJXcpDqXfUH "Ruby – Try It Online") ## Ungolfed ``` ->c,t{ "prev #{ (1..t) .chunk {|n| n < 2 || n == t || n > c - 3 && n < c + 3 } .map {|t,a| t ? a : ?. * 3 } * " " } next" .sub(/(prev )?\b(#{ c })\b( next)?/, '[\2]') } ``` [Answer] # PHP (Browser), 267 Bytes ``` <?php parse_str($_SERVER['QUERY_STRING']);$c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] ';$d=$a<$b-2?$a+3:$b;for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++)$c.=$a==$i?"[$i] ":"$i ";if($a<$b-2)$c.=" . . . $b next";else $c.=$a==$b?"[$b]":"$b next";echo $c?> ``` [Try it online!](http://sandbox.onlinephpfunctions.com/code/f988cc25106ce35f2b78e7e880df5fe577ca0a19) Definitely not as small as it could have been, and as was demonstrated above, using PHP in command line can be much smaller. The input is through GET requests, a is the selected number, b is the limit. This looks like `foo.bar.com/index.php?a=2&b=12` # Ungolfed ``` <? parse_str($_SERVER['QUERY_STRING']); $c=$a!=1?$a>3?$a>4?'prev 1 . . . ':'prev 1 ':'prev ':'[1] '; $d=$a<$b-2?$a+3:$b; for($i=$a<=2?$a==1?$i=2:$i=$a-1:$i=$a-2;$i<$d;$i++) $c.=$a==$i?"[$i] ":"$i "; if($a<$b-2)$c.=" . . . $b next";else $c.=$a==$b?"[$b]":"$b next"; echo $c ?> ``` I am pretty sure my ternary operators can be improved, feel free to try. [Answer] # IBM/Lotus Notes Formula, ~~217~~ 211 Bytes -2 with thanks to @KevinCruijssen -4 by using variables for the @Text values ``` o:=@If(a=1;"[1]";"Prev 1 ")+@If(a>4;"... ";"");@For(x:=2;x<b;x:=x+1;T:=@Text(x);o:=o+@If(x>a-3&x<a+3;@If(a=x;"["+T+"]";T)+" ";""));Z:=@Text(b);o:=o+@If(b>1;@If(b-a>3;"... ";"")+@If(a=b;"["+Z+"]";Z+" Next");"");o ``` Basically a port of my Python 2 answer just for the fun of trying to remember how to use Formula. There's no TIO for Formula so here's a screenshot of some of the test cases: [![enter image description here](https://i.stack.imgur.com/ZbRDA.png)](https://i.stack.imgur.com/ZbRDA.png) [Answer] # Excel VBA, ~~202~~ 201 Bytes Anonymous VBE immediate window function that takes input from range `A1:A2` and outputs to the VBE immediate window. ``` For i=[Max(A1-2,1)]To[Min(A1+2,A2)]:s=s &IIf([A1]=i,"[" &i &"]",i)&" ":Next:?[If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]s[If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")] ``` ### Subroutine Version *Included for readablity* ``` Public Sub PageSelect(Optional ByVal Current As Long = -1, _ Optional ByVal Total As Long = -1) Call Sheet1.Activate Let [A1] = IIf(Current = -1, [A1], Current) Let [A2] = IIf(Total = -1, [A1], Total) Dim s As String Let s = "" For i = [Max(A1-2,1)] To [Min(A1+2,A2)] Step 1 Let s = s & IIf([A1] = i, "[" & i & "]", i) & " " Next Debug.Print [If(A1=1,"","prev "&If(A1>3,1&If(A1>4," ... "," "),""))]; _ s; _ [If(A1<A2,If(A1-A2<-3,"... ","")&If(A1-A2<-2,A2&" ","")&"next","")] End Sub ``` [Answer] ## C - 173 Bytes ``` #define p c&&printf( c;main(t){scanf("%u%u",&c,&t);c&&t/c?1-p"prev 1"),3<p" ... %d",c-2),2<p" %d",c-1),1|p" [%d] ",c),t>1+p"%d ",c+1),t>2+p"%d ... ",c+2),t-p"%d next",t):0;} ``` Thanks to @ceilingcat for -45 bytes. **Ungolfed (original version)** ``` #define p printf c; main(t) { scanf("%u%u", &c, &t); if(1 <= c && c <= t) { p(c != 1 ?"prev 1" :""); p(c - 2 > 1 ?" ... %d" :"", c - 2); p(c - 1 > 1 ?" %d" :"", c - 1); p(" [%d] ", c); p(c + 1 < t ?"%d " :"", c + 1); p(c + 2 < t ?"%d ... " :"", c + 2); p(c != t ?"%d next" :"", t); } } ``` [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 237 bytes ``` param($a,$n)('prev 1','[1]')[$n-lt2]+" ... $($n-2) $($n-1) [$n]"*($n-gt4)+" 2 3 [4]"*($n-eq4)+" 2 [3]"*($n-eq3)+" [2]"*($n-eq2)+" $($n+1) $($n+2) ..."*($n-lt$a-3)+" $($n+1) $($n+2)"*($n-eq$a-3)+" $($n+1)"*($n-eq$a-2)+" $a next"*($n-ne$a) ``` [Try it online!](https://tio.run/##bY3RCgIhEEV/ZVgG1NyV1P0b8cEHqQczM6n@3hS3JSIYGO65d@6k69Pn@9mHUGty2V0ouhkjoyRl/wBJZmKkJcxgXEJRlk8ghACkTSs2tmTQbDsdujiVlbWQAg1m3Zi/bczonehOjNq16rrXcTlqeatvr4YfCrpF/4l8zn/sLzyKHUT/KgNHj47VWuWxzRs "PowerShell – Try It Online") One gigantic string concatenation with way too many dollar signs. ~~Working on golfing further.~~ Nope, I think this is as short as this approach can go. [Answer] # Javascript (ES6), ~~265~~ ~~263~~ ~~258~~ ~~240~~ ~~239~~ ~~220~~ ~~194~~ ~~193~~ ~~182~~ 178 bytes *-2 from removing a debug tool* *-5 from realizing that I'm using ES6 and can do away with parenthesis sometimes* *-18 from removing something from an earlier version that is now obsolete* *-1 from doing some sneaky stuff* *-19 from removing unnecessary variables* *-26 bytes from removing the all too complicated remove falsey values. I'm new to ES6* *-1 from using shorter comparisons* *-11 from using a recursive function* \*-4 from replacing `?...:0` with `&&...`, and `... ${t}` with `...+t` This took way too much of my life, and didn’t give enough upvotes. ~~but I am so glad the final code is a power of 2 (2^8)~~ I do know there is another JavaScript answer that is about 120 bytes. ~~but I still love this code~~ **EDIT: i don't know what i was thinking. 265 is not 2^8...** While making this, I managed to break the ungolfed version. God, do I hate ungolfing code. **EDIT 2: now it's looking like the better 121 byte solution** ``` y=(e,i,t="")=>i++<e?y(e,i,t+i+' '):t.slice(0,-1);m=(t,p)=>[p-1&&"prev",p<5?y(p-1,0):"1 ... "+y(p-1,p-3),`[${t}]`,t-p<4?y(t,p):y(p+2,p)+` ... `+t,t-p&&"next"].filter(e=>e).join` ` ``` Explanation: to come but basically y is `range(end, start)` and it does some cool stuff like: 1. show prev if `page` is 1 2. show left dots if `page > 4` 3. show right dots if `total - page < 4` 4. show next if `total - page == 0` and stuff like that and just joins it by ' '. I know you don't have to but I like the fact that is semi-conventional. I don't know. Enjoy. [Try it online!](https://tio.run/##ZY7RasIwFIbv9xSHMrQhaUiaRje17kFCoOLiiNS21CCTsWfvTk3ZcN4l3/nO/5/j7rI773vfhaxp391Ql8YYyaRliZE2sWz85fEHOTTuM0xQil@qgHMOUvyNFVM47Xp3AYmCUXbCi38YCtCw@Fss7g0FprD3ho7NkzIWKwwx2qK0fDhEigf9BV4BebxI50wu1b2gBWiJiTk2K9BFDF2qKdWuh2uZOuZZKJOElFtP6ca9XSOins5hTlaBn2u/d6lgmSTrU5kG1qFrukzOZre2hHUbjWtImCCrJJYnNJIuU4RV5vkrfNuKhazbFOiOISsUaI4PWt02KhrGOabG@/jB18H1qSu3jvBj65sKquHQ9pB6aA9QkyeAfduc29rxuv1ITynGeCMsIevhBw) [Validate it online!](https://tio.run/##ZZHhasIwFEZf5VKGJiQtTdPopsY9SAhUXByR2pYaZDL27N2tKRPnv@bcc7/vQo@7y@68730X0qb9cEOtjTGCC8sTI2xi@fgq4gsKaNxXmKDI/6iELMtA5Pex5BKnXe8uIFAw0k548Q9DCQoW98Xy0ZBgSvtoqNg8KWOxxBCjLErLp0NE/qS/whsgjxepgoulfBRUDkpgYoHNElQZQ5dySrXDVRPHPQ86SajeesY27v0aEfNsDnO6Ctm59ntHcp4Kuj5pEniHrulSMZvdyhLebRSuIeE5XSWxO2GRdKmkvDIv3@HHVjyk3aZEdwxZocAK/GDVbaNiYZxjajwvO/g6uJ44vXU0O7a@qaAaDm0PxEN7gJrCvm3Obe2yuv0kJ4Ih3uSWgtbg8YfS9fAL) Here's a ~~186~~ ~~185~~ ~~174~~ 170 byte solution that I don't like: [Try it online!](https://tio.run/##ZY7hasIwFEZf5RKGJiQtSdPoptY9SAhUXBwZ1ZYaZDL27N2tKRO3f8m5537f/dhddud9H7qYndo3PzSVtVYJ5QSxyhEnxl@RflDAyX/GCSr5SzXkeQ5K3sdaaJx2vb@AQsFqN@HFHwwlGFjcF8tHQ4Mt3aNhUvOkjMUaQ6xxKC3/HaLkP/0ZXgB5usgUQi31o2AkGIWJBTZrMGUKXeop1Q3XinoRRKwIYdU2cL7xr9eEeOBzmLNVzM9N2HsqRabY@ljRKDp0bZep2exWRkS3MbiGREi2Iqmb8ES6TDNR26ev@O1qEbNuU6I7hqxQ4AU@eH3bqHkc55iazssPoYm@p77aejYc2h5ogPYADYN9ezq3jc@b9p0eKS4HKx1j6@EH) [Answer] # [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 141 bytes ``` param($c,$t)($('prev'*($c-ne1) 1 '...'*($c-gt4) ($c-2)..($c+2)-gt1-lt$t '...'*($t-$c-gt4) $t 'next'*($t-ne$c))|?{$_}|gu)-replace"^$c$","[$c]" ``` [Try it online!](https://tio.run/##jZPfToMwFMbveYqT5ihUC1n5M9TE6HuQuRCs8wIZdp2abHt2bIEO3QLamzanv@87H4e0Xn8KuXkVZdngC9zDrqlzmb95WDBU1EPPraX4cK90wa8Epw533CAIusJKxdQxh5AGgd6vQ6pr3C8VqiOmfEuaYiW@VFetBBaU7h92uDzsV1vqS1GXeSHIExZIGMmwWJDm4DiPngN6MY9Dt5g9AHMzvnDp6X34@55ByKDrfIby2TkaadqEZ8Bnp8LI4tHQo52Qhrs@WbQ4p@dTNIOYQcJgftos/ktukmaxcZiUp/@Up6Nf@2NM4/lHh5ZM2vSyqLVxs8QY9mHGDK3PpOENg1tjyGfDD0lCK0yjUWGi@yW8zRK2w9HRkniIk0ZDHgp7uIBda4/FVkpRKQao1iov9S6@alEo8axfFi47SIrNtlS6cKkfnJX0ipYg6JGeIr54J0cTQu@snDiH5hs "PowerShell – Try It Online") Less golfed: ``` param($current,$total) $uiElements=$( 'prev'*($current-ne1) 1 '...'*($current-gt4) ($current-2)..($current+2)-gt1-lt$total '...'*($total-$current-gt4) $total 'next'*($total-ne$current) ) ($uiElements|where{$_}|Get-Unique)-replace"^$current$","[$current]" ``` ]
[Question] [ ![](https://i.stack.imgur.com/ElM9V.jpg) [Mr. Mackey](https://en.wikipedia.org/wiki/List_of_South_Park_Elementary_staff#Mr._Mackey) is a [South Park](https://en.wikipedia.org/wiki/South_Park) character well-known for adding "m'kay" in everything he says. Write a program or function that transforms a string of text into something Mr. Mackey would say. ### M'kay placement * `m'kay` has a **random 50% chance** of being added **after the punctuations `,`, `.`, `?` and `!`**. If that is the case, it will be followed by the exact same punctuation mark that preceeds it and preceeded by a space. For example, in the sentence `Test, test.`, there are two places where `m'kay` can be added: after the comma, and after the period, with a 50% chance at each place. Possible results would be `Test, m'kay, test`. or `Test, test. M'kay.` or `Test, m'kay, test. M'kay.`. * There must always be **at least one `m'kay` added**. Moreover, it cannot always be at the same place and each valid place where `m'kay` could be added must occur with equal probability. That is, you can't add `m'kay` always at the end of the string if because of randomness you never added any `m'kay`. If there is only one `m'kay`, it must have the same probability of appearing in each valid position, even though its presence is enforced. * If `m'kay` is after `?`, `.` or `!`, the `m` must be uppercased. * The number of `m` in `m'kay` must be uniformely picked between 1 and 3. That is, `m'kay`, `mm'kay` and `mmm'kay` are all possible choices, each with probability 0.33... If it must be uppercased (see above rule), all `m` must be uppercased. ### Inputs, outputs * Inputs are ASCII strings containing characters from ASCII Dec 32 (Space) to ASCII Dec 126 (Tilde `~`). There are no linebreaks in the input. You may assumed that any input will contain at least one of `, . ? !`. * You may assume that there are no `m'kay` or any of its variants in the input. Inputs may be taken from STDIN, function arguments, command line, or anything similar. * Output may be via STDOUT, a function return, or something similar. ### Test cases * Input: `Test.` Possible output: `Test. M'kay.` * Input: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.` Possible output: `Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. MMM'kay. It's 100% free, mm'kay, no registration required.` * Input: `Drugs are bad, so, if you do drugs, you're bad, because drugs are bad. They can hurt your body, cause drugs are bad.` Possible output: `Drugs are bad, m'kay, so, if you do drugs, you're bad, m'kay, because drugs are bad. They can hurt your body, m'kay, cause drugs are bad. M'kay.` * Input: `Do you understand? Really? Good!` Possible output: `Do you understand? MM'kay? Really? Good! MMM'kay!` ### Scoring This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins, m'kay? [Answer] # APL (66) ``` {∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢ ``` Result of 10 runs: ``` ↑ ({∊⍉⍵⍪⍉⍪(¯1+⌈?2×⍵∊',.!?')/¨{' ',⍵,⍨'''kay',⍨'mM'[1+⍵≠',']/⍨?3}¨⍵}⍣≢)¨ 10/⊂'Test, test. Test! Test?' Test, m'kay, test. Test! Test? Test, test. M'kay. Test! MMM'kay! Test? M'kay? Test, mm'kay, test. Test! MM'kay! Test? MM'kay? Test, mmm'kay, test. Test! Test? M'kay? Test, mm'kay, test. Test! Test? M'kay? Test, test. MM'kay. Test! Test? MMM'kay? Test, test. MMM'kay. Test! MMM'kay! Test? M'kay? Test, test. Test! MM'kay! Test? Test, mm'kay, test. M'kay. Test! Test? Test, test. MM'kay. Test! MM'kay! Test? ``` Explanation: * `{`...`}⍣≢`: apply the function to the input until the value changes + Generate a `M'kay` for each character: + `{`...`}¨⍵`: for each character in the input: - `'mM'[1+⍵≠',']/⍨?3`: generate 1 to 3 `m`s or `M`s depending on whether the character was a comma or not. - `'''kay',⍨`: append the string `'kay`. - `⍵,⍨`: append the character - `' ',`: prepend a space. + `(¯1+⌈?2×⍵∊',.!?')/¨`: for each `M'kay`', if its corresponding character is one of `.,!?`, select it with 50% chance, otherwise select it with 0% chance. + `⍉⍵⍪⍉⍪`: match each selection with its character, + `∊`: list all the simple elements (characters) in order. [Answer] # CJam, ~~65~~ ~~52~~ 49 bytes ``` l{_{_",.?!"#:IW>)mr{SI'M'm?3mr)*"'kay"3$}&}%_@=}g ``` Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=l%7B_%7B_%22%2C.%3F!%22%23%3AIW%3E)mr%7BSI'M'm%3F3mr)*%22'kay%223%24%7D%26%7D%25_%40%3D%7Dg&input=Drugs%20are%20bad%2C%20so%2C%20if%20you%20do%20drugs%2C%20you're%20bad%2C%20because%20drugs%20are%20bad.%20They%20can%20hurt%20your%20body%2C%20cause%20drugs%20are%20bad.). ### How it works ``` l e# Read a line from STDIN. { e# Do: _ e# Duplicate the line. { e# For each of its characters: _",.?!"# e# Find its index in that string. :IW> e# Save the index in I and check if it's greater than -1. ) e# Add 1 to the resulting Boolean. mr e# Pseudo-randomly select a non-negative integer below that sum. e# If I == -1 the result will always be 0. { e# If the result is 1: S e# Push a space. I'M'm? e# Select 'm' if I == 0 (comma) and 'M' otherwise. 3mr) e# Pseudo-randomly select an integer in [1 2 3]. * e# Repeat the M that many times. "'kay" e# Push that string. MMM'kay. 3$ e# Copy the proper punctuation. }& e# }% e# _ e# Copy the resulting array. @= e# Compare it to the copy from the beginning. }g e# Repeat the loop while the arrays are equal. e# This makes sure that there's at least one m'kay. M'kay. ``` [Answer] # K5, ~~99~~ 90 bytes ``` {f::0;{x;~f}{,/{f::f|r:(*1?2)&#&",.?!"=x;x,("";" ",((1+1?3)#"Mm"@x=","),"'kay",x)@r}'x}/x} ``` Well, *someone* needed to kick-start this! Saved 9 bytes by using a less fancy method of uppercasing the M. ## Explanation ``` { } Define a function f::0; Set `f` (used to determine when to stop) to 0. {x;~f}{ }/x While `f` is 0 (no "m'kay"s have been inserted), loop over the string argument { }'x For each character in the string (*1?2)&#&",.?!"=x If we are at a punctuation character, generate a random number between 0 and 1 r: and assign it to `r` f::f| If the number is one, an "m'kay" will be inserted, so the outer while loop should exit after this "Mm"@x="," If the punctuation is a comma, then use a lowecase `m`, otherwise use `M` (1+1?3)# Repeat the `m` between 1 and 3 times " ",( ),"'kay",x Join the "m'kay" string to the punctuation and prepend a space x,(""; )@r If the random number is 1, append the "m'kay" string, to the current string ,/ Join the resulting string ``` ## 99-byte version ``` {f::0;{x;~f}{,/{f::f|r:(*1?2)&#&",.?!"=x;x,("";" ",((1+1?3)#`c$(-32*~","=x)+"m"),"'kay",x)@r}'x}/x} ``` [Answer] # Julia, mm'kay, ~~115~~ 114 bytes ``` f(s)=(R=replace(s,r"[,.?!]",r->r*(" "*(r==","?"m":"M")^rand(1:3)*"'kay"*r)^rand(0:1));ismatch(r"m'kay"i,R)?R:f(R)) ``` This creates a recursive function that accepts a string and returns a string. Ungolfed + explanation: ``` function f(s) # Replace occurrences of punctuation using random repeats R = replace(s, r"[,.?!]", r -> r*(" " * (r == "," ? "m" : "M")^rand(1:3) * "'kay" * r)^rand(0:1)) # Check whether anything was replaced if ismatch(r"m'kay"i, R) # If so, return the replaced string R else # Otherwise recurse f(R) end end ``` I dislike South Park, but the thrill of the golf was too enticing to pass this up. Thanks to KRyan for simplifying a regex, saving 1 byte. [Answer] # JavaScript ES6, ~~79~~ ~~86~~ 108 bytes Turns out making the `M` repeat takes a lot of bytes. ``` (s,z=Math.random)=>s.replace(/([!?.,])/g,l=>z(t=t+1)>=.5||t?` ${(l==','?'m':'M').repeat(0|z()*3+1)}'kay`+l:l) ``` Old version (doesn't repeat)**(86 bytes)** ``` (s,t=1)=>s.replace(/([!?.,])/g,l=>Math.random()>=.5||--t?` ${l==','?'m':'M'}'kay`+l:l) ``` Older version (doesn't repeat, doesn't require at least one m'kay)**(79 bytes)**: ``` s=>s.replace(/([!?.,])/g,l=>~~(Math.random()*2)?l+` ${l==','?'m':'M'}'kay`+l:l) ``` Oldest version: ``` s=>(r=t=>t.replace(/([!?.])/,"$1 M'kay$1").replace(/,/,", m'kay,"),r(s),[for(i of s)~~(Math.random()*2)?r(i):i].join``) ``` [Answer] # Pyth, ~~51~~ ~~50~~ 49 *Saved 1 byte thanks to @Maltysen.* ``` fnzJsm?&O2}dK",.!?"s[d\ *hO3?xKd\M\m"'kay"d)dz0J ``` [Try it online.](https://pyth.herokuapp.com/?code=+fnzJsm%3F%26O2%7DdK%22%2C.!%3F%22s[d%5C+*hO3%3FxKd%5CM%5Cm%22%27kay%22d%29dz0J&input=Drugs+are+bad%2C+so%2C+if+you+do+drugs%2C+you%27re+bad%2C+because+drugs+are+bad.+They+can+hurt+your+body%2C+cause+drugs+are+bad.&debug=0) Explanation & more golfing coming soon. [Answer] # C, 170 bytes First crack at it: ``` n;main(r,v,p)char**v,*p;{for(srand(time(0)),p=v[1];r=rand(),*p;p++)if(strchr(".,?!",putchar(*p))&&r%2||(!*(p+1)&&!n))n=printf(" %.*s'kay%c",r/2%3+1,*p%4?"MMM":"mmm",*p);} ``` Ungolfed: ``` n; main(r,v,p) char**v,*p; { for(srand(time(0)), p=v[1]; r=rand(), *p; p++) /* loop through string */ if(strchr(".,?!",putchar(*p)) /* print the char, check if punctuation */ && r % 2 /* should we say it? */ || (!*(p+1) && !n)) /* If this is the end of the string and we haven't M'kay'd, then do it now */ n=printf(" %.*s'kay%c", r/2%3+1, *p%4 ? "MMM" : "mmm", *p); /* say it! */ } ``` [Answer] ## Scala, 191 bytes ``` var(r,s,a,o)=(util.Random,readLine,1>2,"") while(!a){o="" for(c<-s)o+=(if(",.?!".contains(c)&&r.nextBoolean){a=2>1 s"$c ${(if(c==46)"M"else"m")*(1+r.nextInt(3))}'kay$c"}else s"$c")} print(o) ``` [Answer] # Mathematica, 202 bytes ``` i=0;r=Random;x=r[]; h=" "<>If[#==",","m","M"]~Table~{Ceiling[3r[]]}<>"'kay"<>#&; (ee/.a:>(If[e~Count~a@__==i&&#==Floor[x*i],h@#2,""]&))@ StringReplace[#,x:","|"."|"?"|"!":>x~~RandomChoice@{i++~a~x,h@x}]& ``` Line breaks added for readability. Evaluates to an anonymous function taking the string as an argument. (`` is shorthand for `\[Function]`.) Ungolfed: ``` h[x_]:=" " <> Table[ If[x==",", "m", "M"], { Ceiling[3 Random[]] } ] <> "'kay" <> x; ``` `h` takes a punctuation char and makes it `" m'kay,"`, `" mm'kay,"`, etc. randomly and capitalized appropriately. ``` f[s_] := (i = 0; StringReplace[s, x : "," | "." | "?" | "!" :> x ~~ RandomChoice[{a[i++, x], h[x]}]]); ``` `f` takes a string and looks for any punctuation character `x`; when it finds it, it tacks on with 50% probability the appropriate `h[x]`, and 50% an expression like `a[3, x]`. It also updates `i` to the total number of punctuation replaced (with both cases). So `f["X, x."]` might evaluate to ``` "X," ~~ h[","] ~~ " x." ~~ a[1, "."] ...which might expand to "X, mmm'kay, x." ~~ a[1, "."] , and i would equal 2 ``` Finally, `g` will deal with the `a`'s. ``` g[expr_] := (r = Random[]; expr /. a -> (If[Count[expr, a[__]] == i && # == Floor[r*i], h[#2], ""] &)) ``` `Count` will count how many `a`'s we put in there; if it equals `i`, the total number of punctuation, then we didn't add any m'kays. In this case, we will have expressions like `a[0, _] ... a[i-1, _]`, and we define `a` so that it'll return an m'kay for exactly one of `0..i-1`. [Answer] # Python, 173 168 156 ``` from random import randint as R m,k,s,C="mM","'kay",input(),0 while C<1: S="" for c in s:r=R(0,c in",.!?");C+=r;S+=c+(' '+m[c!=","]*R(1,3)+k+c)*r print(S) ``` Ungolfed: ``` from random import randint m, kay = "mM", "'kay" string = input() count = 0 while count < 1: #at least one occurrence newString= "" for char in s: rm = randint(1,3) #number of "m" rmk = randint(0, char in ",.!?") #occurrence of "m'kay" count += rmk newString += char + (' ' + m[c != ","] * rm + kay + char) * rmk print(newString) ``` [Answer] ## **><>, 150 bytes** ``` i:0(?v r0&v > ?v~>:0(?v::o1[:::",.?!"{=${=+${=+r=+] >x~^ >&:0)?;&"."14. v>&1+&1[:","=&"yak'"&84**"M"+ > >84*v >x::^>22 . >: ^] ol0=?^ > ``` 13 wasted bytes, but I've gotten a little bored trying to rearrange it. Also, randomisation in a Funge is hard to golf -.- [Answer] # Perl, ~~93~~ ~~89~~ 88 bytes ``` $_=$0=<>;s/[.?!]|(,)/$&.($".($1?"m":M)x(1+rand 3)."'kay$&")[rand 2]/ge while$0eq$_;print ``` Can definitely be golfed some more! *4 bytes cut off thanks to Dom Hastings* [Answer] ## C++ 290 **My solution** ``` void M(string x){ srand(rand()); string p(",.?!"); char c=0,m='m',n='M'; int r=0; size_t z=0; for(size_t i=0;i<x.size();i++) { c=x[i];cout<<c; z=p.find(c); r=rand()%2; if(z!=string::npos&&r) { cout<<' '; c=(z?n:m); r=rand()%3+1; while(r--){cout<<c;} cout<<"\'kay"; } } } ``` **Explanation** variable z determines which punctuation mark and z=0 indicates to use 'm' rather than 'M'. **Test** ``` int main() { int x=5; while(x--){ string S("Do you understand? Really? Good! Yes, I do."); M(S); cout<<endl; } return 0; } ``` [Answer] # JavaScript ES6, 121 bytes ``` (s,r=Math.random,f=t=>t==s?f(s.replace(/[!?.,]/g,m=>r()<.5?m:m+" "+(m==","?"mmm":"MMM").slice(r()*3)+"'kay"+m)):t)=>f(s) ``` Crashes if the given string contains no suitable punctuation. [Answer] # Lua, ~~162~~ 160 bytes ``` r=math.random;s,m=io.read()repeat m=s:gsub("([,.?!])",function(p)return p..(r()>.5 and" "..(p==","and"m"or"M"):rep(r(1)).."'kay"..p or"")end)until s~=m;print(m) ``` > > Did you ever hear the tragedy of Darth Plagueis The Wise? MM'kay? I thought not. MMM'kay. It’s not a story the Jedi would tell you. M'kay. It’s a Sith legend. Darth Plagueis was a Dark Lord of the Sith, m'kay, so powerful and so wise he could use the Force to influence the midichlorians to create life… He had such a knowledge of the dark side that he could even keep the ones he cared about from dying. MM'kay. The dark side of the Force is a pathway to many abilities some consider to be unnatural. MM'kay. He became so powerful… the only thing he was afraid of was losing his power, mmm'kay, which eventually, mm'kay, of course, m'kay, he did. M'kay. Unfortunately, he taught his apprentice everything he knew, then his apprentice killed him in his sleep. M'kay. Ironic. He could save others from death, but not himself. > > > ]
[Question] [ If you have ever looked at an objdump of a C++ program, you have likely seen something like this: ``` _ZN3foo3bar3bazI6sampleEE3quxvi3foo ``` This is a C++ mangled symbol, which encodes the namespaces, classes, and function/template arguments, using the [Itanium ABI](https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling). Specifically, it is for the following function: ``` void foo::bar::baz<sample>::qux(int, foo); ``` Your job is to demangle a C++ symbol in a dramatically simplified version of the Itanium ABI. (That is **incompatible** with `c++filt` or `__cxa_demangle()`, so don't try it). Everything will be plain identifiers (so no `int`, `void`, or "special" identifiers like `std::`), no const/pointers, no return type encoding, no reuse of template args, etc. Specifically, these are the syntax rules: * All mangled symbols start with `_Z`. * Everything is case sensitive. * All identifiers are encoded as `<length><name>`, where `<length>` is the positive length of `<name>` in base 10, so `foo` is encoded as `3foo`, `sample` is encoded as `6sample`, etc. + Naturally, this means identifiers will never start with a number (but they can contain numbers after the first letter/underscore). For you regex fans, it is `[a-zA-Z_][a-zA-Z0-9_]*`. * Each symbol is one base identifier, optionally followed by a list of function parameters. * Each identifier can be prefixed with a namespace, or suffixed with a template. + Namespaces are encoded as a sequence of 1 or more identifiers between an `N` and an `E`. Each identifier is printed as the identifier, followed by `::`. So `N3fooE` is `foo::`, and `N3foo3barE` is `foo::bar::`. - Namespaces will never have a namespace themselves: you don't have to worry about `NN3fooE3barE`. + Templates are encoded similar to namespaces, only using `I..E` instead of `N..E`. They are printed as a comma separated list of identifiers, wrapped in `<angle brackets>`. These come before `::` in a namespace. So `I3fooE` is `<foo>`, and `I3foo3barE` is `<foo,bar>`. + **These may be nested.** * All identifiers *after* the base symbol are to be treated as function parameters, and they are to be printed as a comma separated list wrapped in `(parentheses)`. This does not apply to namespaces or template arguments. So, let's take a simpler example: ``` _ZN3fooI3barEE3baz3qux _Z Mangle prefix 3baz Base: Identifier baz N E Namespace 3foo Identifier foo I E Template 3bar Identifier bar 3qux Parameters: Identifier qux ``` The result is this: ``` foo<bar>::baz(qux) ``` Your function or program will take a single string containing a mangled symbol, and the output will be the demangled symbol. You can safely assume each string will only contain numbers, letters, and underscores, and that every identifier will be 99 characters or less. Assume all symbols are valid, standard input/output format, you know the deal. You can have any amount of whitespace between identifiers, however, empty parameter/template/namespaces and trailing commas are **not** allowed. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest program in bytes wins. ### Test cases: ``` _Z1x -> x _Z3foo3bar -> foo(bar) _ZN3fooE3bar -> foo::bar _Z3FOOI3barE -> FOO<bar> _Z3foo3bar3baz -> foo(bar,baz) _Z3fooI3barE3baz -> foo<bar>(baz) _Z3fooI3bar3bazE -> foo<bar,baz> _ZN3fooE3bar3baZ -> foo::bar(baZ) _ZN3fooI3barEE3baz3qux -> foo<bar>::baz(qux) _ZN9CPlusPlusI2isEE11soooooooooo5great -> CPlusPlus<is>::soooooooooo(great) _ZN2soI1II4herdEE1UI4liekEE9templates -> so<I<herd>>::U<liek>::templates _Z12identifier12 -> identifier12 _Z2_Z -> _Z _ZN1a1b1c1d1e1f1g1hE1i -> a::b::c::d::e::f::g::h::i _ZN1a1bI1c1d1eE1fE1gN1hE1iIN1jE1kI1lEEN1m1nE1o -> a::b<c,d,e>::f::g(h::i<j::k<l>>,m::n::o) _Z14N3redE7herring1x7foo_bar -> N3redE7herring(x,foo_bar) ``` [Sandbox](https://codegolf.meta.stackexchange.com/a/23448/94093) [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~267~~ ... ~~222~~ 221 bytes *-30 bytes thanks to @EasyasPi* *-8 more bytes thanks to @EasyasPi and @ceilingcat* *-1 more byte thanks to @ceilingcat* ``` #define P puts( char*m;a(){if(*m==73){P"<");for(++m;*m^69;*m-69&&P","))p();m++;P">");}}p(){if(*m==78){for(++m;*m^69;P"::"))p();++m;}a(m+=write(1,m,strtol(m,&m,!a())));}z(char*t){p(m=t+2);for(*m&&P"(");*m;P!*m+L",)"))p();} ``` [Try it online!](https://tio.run/##bVHfb4IwEH73r9AuM1eoD8im06ovC0tMFuXZmC3MgWuyAis1IxL@dnZV4@pmk5K7@37cB2x6282maW7e40SkcTts5ztdQGvzESlH8ghoJRJw5HQ69GkVkgmhPMkUuK7kjnwZjPDZG4y63ZAwQmkOlEvX5SGZIbGuc0v/QKtLZUjG45PGDOsIpDv9VkLH4DHJCq109gmSdSXrYBA8vN7DIZmmVQ5yqt3@MY4jTQLAnRg67DjSfSaMnszrRoNgMRWpdgRzYl7tQVCeKxwkQNbpbbFOe3jWKUEar1syEikmb2kgryuvJKxNSvQ@9n6SZf5bpMwUS8CSnsGFQQMLHo9NfdY@LZdzgwYGxmaC9eyfNd69Zc@wpReko4dFO/jAdZ6hBRbP2M2uJMa7slOj3erPmx33Hhb7X7vSXm4ke8ChJRk9hp@7wtx5XxRB4HlFdj73WxVH2licWRNRoI/FgQPn19G7W/gqfg@GH7HC37f1yiHufz197ksMSnbCjL5ufgA "C (gcc) – Try It Online") For pretty output, see previous revisions. [Answer] # Python 3, ~~460~~ ~~417~~ ~~362~~ 355 bytes [Try it online!](https://tio.run/##fY/BTsMwEETv/gqzl9pKQCzcnJqbD7nkAwgRShqncbDjyDVCfH1wWiR6qLitdmfnzSzfcfTz87oat/gQadDESTMvn5Hx@kk0xEsA0uuBtowLQo/Wd62lLveEmgFKkNLVApt0oi6NKJrCZxL2kBZfo7EaFNz9ahbGz8ccrtXS1@IeL28vF9Zyi1XdYP0DEQKudSl@MaVmkQX94Np4GFnYvfXZLne8fmx40UmrZ3aKgU387ODqTkxZ1xSbRxpS1mRCkj8xA3UpxYZhiXKOkDZ//TYB1fakgQNZwob1fF3fXytssSvxgD1qhYPCY4WjQlNWOCn8KNEqVaHDWaH/AQ "Python 3 – Try It Online") *-43 bytes thanks to @Easyaspi* *-55 bytes thanks to @ovs* *-7 bytes thanks to @Arnauld* ``` import re m=input()[2:] o="" def a(): global m,o if"I"==m[:1]: m=m[1:];o+="<" while"E"!=m[:1]:p();o+="," m=m[1:];o=o[:-1];o+=">" def p(): global m,o if"N"==m[:1]: m=m[1:] while"E"!=m[:1]:p();o+="::" m=m[1:] a();j=int(re.match(r'\d+',m)[0]);b=len(str(j));o+=m[b:j+b];m=m[j+b:];a() p() if m: o+="(" while m:p();o+=","if m else")" print(o) ``` [Answer] # [brainfuck](https://github.com/TryItOnline/brainfuck), 494 bytes ``` >>+++++[->++++++++<]>>>>>,,,[<+>>+++++++[-<---------->]<+[----[<<[<<[.<]>[>]++++++++[-<----->]<[>>-<<[->+<]]>[-<+>]++++++++[-<+++++>]>[<<++++<++++++[-<+++++++>]<->>>>-]]>>-----[>+++++[-<++++++>],[>++++++[-<-------->]<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[<<->>>-[-<+++++++>]<+.[-]]]]]]]]]]]<<[>[->>++++++++++<<]>>[-<<+>>]<,<<-]+>>]<-[-<,.>]<[-]<+>>]<[->>+++++++[->++++++++<]>++[->+>+<<<<+>+>]>>>>>]>]<[+++++[->++++++++++>>+++++++<<<]>.++>>++>>>]>]<[-<[-]<<[[-]<]<[.[-]<]]>,]<<<<[<]<[.<] ``` [Try it online!](https://tio.run/##jVHLTsNADPygfUhzt3zbQy77AVgW6oNCKRQo4vtT26Eh6YlRtA97PON1tpfN8Xz42Z3GkTk5pEy7gZQdOWehxLewFCozWMkCBiHyr1qNsKY7rtGEuRjB1EmNU0xxSYudLUFxpHXCU1S8mWLFHJrCawpr/g0tW3Rn9/z3QuFTVs6pivnOsGfYA@aBeLs@KivxMSll09A4uUyu0YNOuUXdetLT3TogV/FRONRL7tnp72eQO9cpcKOXcCPx1a41duWsLi0RIh3Hx4eODbYDdtjjqeHQ8Nzx0nAcOl4bTgPeWut4x7nho@Oz4QuXAd/tCg "brainfuck – Try It Online") While working on my JavaScript solution, I noticed that a relatively simple stack machine would be able to solve this task. So, naturally, I wrote a Brainfuck solution. Yes, I was bored, what did you expect? Probably still beats Java. The TIO interpreter handles identifiers of up to 255 chars. Any length should work with an interpreter that has bigint cells and returns 0 for EOF. ### Annotated (with a chance of undecipherability) ``` cell layout | 0 | finterm | 0 | finsep | 0 | sepflag | parseflag | char/accum | digit | holding | | 0 | term | 0 | sep | etc >> make space for terminator +++++ create 5 [- > ++++++++ <] >>> convert to 0 40 0 = ( > add sepflag cell > add parseflag cell ,, skip _Z , start reading # [ loop over input (char cell) <+> set parseflag > +++++++ set digit cell to 7 [- < ---------- >] < + subtract E [ not E ---- subtract I [ not I; must be some kind of identifier start <<[ sepflag cell set <<[.<] print separator >[>] return to right of separator ++++++++ create 8 [- < ----- >] subtract ( from separator <[ separator wasn't ( >> - clear sepflag << [- > + <] move separator to right ] > [- < + >] move separator back ++++++++ create 8 [- < +++++ >] fix separator >[ sepflag is set; separator was ( << ++++ update separator to comma < ++++++ create 6 [- < +++++++ >] < - set terminator to 41 ) >>>>- clear sepflag ] ] >> back to char cell ----- subtract N [ not N; must be simple identifier # > +++++ create 5 [- < ++++++ >] add back to ch minus 0 , read into digit cell [ > ++++++ create 6 [- < -------- >] subtract 0 < [ not 0 ->+< [ not 1 ->+< [ not 2 ->+< [ not 3 ->+< [ not 4 ->+< [ not 5 ->+< [ not 6 ->+< [ not 7 ->+< [ not 8 ->+< [ not 9 or any digit # <<- clear parseflag >>> - set digit holding cell to 8 [- < +++++++ >] < + return the char to its former glory (add 57) . print as first identifier char [-] clear digit cell ] ] ] ] ] ] ] ] ] ] <<[ parseflag still set; was some digit # > back to accumulator [->>++++++++++<<] add 10x accumulator to holding >>[-<<+>>] move the value back to accumulator <, read new digit cell <<- clear parseflag to exit this if ] + reset parseflag to keep parsing digits >> back to digit cell ] digit cell clear; accumulator is valid number now # < go to accumulator -[-<,.>] print n minus 1 chars; clears accumulator and overwrites parseflag <[-] clear parseflag <+ set sepflag >> back to char cell ] <[ parseflag set; was N # - clear parseflag >> +++++++ create 0 0 7 starting from parseflag [- > ++++++++ <] > ++ convert to 0 0 0 (58) [- > + > + <<<< + > + >] convert to 0 58 58 0 > 58 > 58 > 0 > 0 > (0) we are now at new parseflag ] > back to char cell ] <[ parseflag set; was I # +++++ set parseflag cell to 6 [- > ++++++++++ >> +++++++ <<<] convert to 0 > (60) 0 42 . print 60 = lbracket ++ >> ++ > convert to 0 62 0 44 0 > 0 > (0) we are now at new parseflag ] > back to char cell ] <[ parseflag set; was E # - clear parseflag <[-] clear sepflag cell <<[[-]<] clear separator <[.[-]<] print and clear terminator we're now in prev parseflag cell which is clear ] > back to char cell , read new char # ] <<<<[<] skip separator <[.<] print terminator ``` [Answer] # [Haskell](https://www.haskell.org/), 257 bytes ``` (l:r)%x=l:tail(x>>=(',':))++r h('I':r)|(x,e:r)<-f r=("<>"%x,r) h e=("",e) f('N':r)|(x,e:r)<-f r,(h:t,r)<-f r=(((x>>=(++"::"))++h):t,r) f r|[(n,r)]<-reads r,(i,u)<-h(drop n r),(x,u)<-f u=((take n r++i):x,u) f e=([],e) p[x]=x p(x:y)=x++"()"%y z=p.fst.f.drop 2 ``` [Try it online!](https://tio.run/##ZZNRa@JAEMff8ykWueIuxsKoR@mQ5OXYg8Bh76UvliJpszFb18TbRJpKv7s3E1tJ74TFmfn/5j@zMZZZszXOnU7SoVdXXeywzayTXZLEchyOUanJxAelHKdjAt5lFxr6jqaF8LEcRcnoqgu9CkphKB2FRgWFHC//Y0NZYhteGuV5wGQyQhzxiFL1ckDq@4OsKHyMpt5kecO9NjxQZylzX@9FJbwKyfvQmx3IrM22hsuTiVXIAtnQOg@PvM7@oXuMu2AvO3xTcUcjpRpdvQXHeH9dNO11cd27zk67zFYiFnkdCOFENBUb0/6yleHUtOK1IfG19rTRN@GouPe2aik@ClnSogQoEcfCZQ3DBLDhab2CTkwT0QXr1byo6/lT5jmnUFKoqLzkuh4IiBQz//PuLuW6ZoGSiOJkYETnODALKVUf8rlvAPS98l@CAT0g2CL5shOd1XAvslhdtj5P6cfM/xy64SiGj5KKPXz747c7NHzSmW20Bmjqy@f7hn7plpsvVGQbchgwsmd6r1lTp5Cmi9L4nJzu04WzZqv1bWt2e5e1pmGrpo7SiJGEjO4jRii4IGQEM5ubqrWFNR5m3DPMCZit@5uvVzwVMniCZ8jBQAEbKDVYFjO6J@IzYo5oEAvEDWKJaD970nOThkLDZtn3pUt40bBNwWm9hB1UGupPr@g5zEOTnJ0kG0UviNvIJUm4Q6wQa34IsFjOvcn1Dd2Q3sMNdDf04Ncf79BXjf4rH5r6Cw "Haskell – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~287~~ 233 bytes Saved **a ton of bytes** thanks to @A username, @FZs, @Arnauld and @Recursive Co.! (Hope I didn't miss anyone!) ``` (i,r="",P=2,s=c=>i[P]!=c,e=_=>{if(!s`N`)for(P++;s`E`||!++P;r+="::")e();r+=i.slice(P+=b=`${l=parseInt(i.slice(P))}`.length,P+=l);s`I`||P++&a`<>`&P++},a=([[p,q]])=>{for(r+=p;i[P]&&s`E`;i[P]&&s`E`?r+=",":0)e();r+=q})=>i[e(),P]&&a`()`||r ``` [Try it online!](https://tio.run/##vVTRbts2FH33V9BCEZCwaoROhqKUqKLr2E59cA1sfXEWWIpE2UwYSSHpxW3qb88uZVtTBuxxE0DhXt5zzj0kSN7mf@a2MKp1r@umlM8Vf8YqNDwIwgWfhZYXPFFXi@sxL0LJVzx5UhUe22yekaoxeDGZRDYT2Y8f48lkEZkJDxgLiMTEx2pqtSokoPgNz149ad7mxsq0drgvEbLPplrWa7cJAacJ6KWgB8pneRYn2RlE@zDn@OqqDR@urwl48K1Bv428tbMz72AQvvM2woCdn3w87IlfBWShx@QZJtDBPBdNbR0qcm@p3TrEUbZa0h16naDdaLW8qJrm4iY3PocQQ0hgeu7nxaDAGMQe//HLl9TPC1@AJIY4GQjB@D4QCyElx/KBNwB0XPxPhAeIAcJLJC88wVgOfYHEsnd96NK1uXjY7oatPPg7hskO/PbDQm@tH@lMWSEotU3//bQ2Mnee3KNiZUFhgMEdptOa2SalaXq5kaYEpa/ppVbyToi3Tt63OnfSeinbxGnsIQkIfY09BIIeAkJ0pkpZO1UpaejMc4Y5AGarbuWrpe9Kc3pDC1pSSSu6phtBlS/msE7GCsZKxiRjFWNrxjaMqRMnPZAErQRdzzteOqe3gt6lVAsxp/e0FrQ5acVFWIYyOShhLxTfMnYX6yQJ7xmrGWv8JtDL@YWRpXgDKzSqXtPdG9j41fEMvazhXXisdczz8/c/f/hFfPz0a/r5v4u8jf@jTxaNRn9fOwtXrr9@U9tq5XDwRx2Q6X3eYlwQxBNUnAreY0BINNLSoTa3nu3MVkYjeA8QPsqipjpoE/Q0QvAd5q@U7xEiuWtl4WR57VtHHcCZb0foCd5oOdXNGsOb1dH2vvWrpxN3n5HoBd6hZusOL0iFO8YAoCqEj@Ux570BgnpEZ2JjmkdUy0ckjIHnLSvgOUZGuq2pZQnNDxJ96z0s0hUbhCX5F/Ny6prfXHeiyMDOceOqXFt5lBrtR0MigIdpR3iHgvdaI7iJznYS4wAxFPwOZ1aiR/@rcqW3RtppQKLnvwA "JavaScript (Node.js) – Try It Online") [Answer] # [JavaScript (Node.js)](https://nodejs.org), ~~216~~ ~~215~~ ~~213~~ ~~204~~ ~~197~~ 188 bytes ``` (m,o=2,X=A=>m[o]<X?X(n=A+m[o++]):o,M=x=>m[o]==x?o++:"",I=(e="")=>m[o]?M`E`?"":e+(M`N`&&I()+I`::`+"::")+m.slice(X``,o+=+n)+(M`I`&&`<${I()+I`,`}>`)+(e&&I(e<I?(a=")",","):e)):a)=>I(a="")+I`(` ``` [Try it online!](https://tio.run/##XZNda9swFIbv8yuMGEXCakBJR@nBcihDA1003U0hpCuxa8upW9vKbGeYlv727MhOgrsEwfl43vdIQn6N/8ZNUue79rKyqTkktmpaL9tXiTzQkls54yt5K8Py0T4Fq8WKVvLWx8T3nxhYfie7oSdlt8AiEMK1pEYSwobG4i5S0YIQMD69i5bRxYWmzNcRQOQTAML8ctoUeWLoKoq49aVfMUdqJKPg28dA8@gzjLBunNwEekFjSRjh@GdgGIMYx2lXJA6n0fEgrWnaxpNetFmLzrsMvW6yWc8za@fPce1yDCmGDMtLV1ejBgDGjv95f69dXbkGJgHG4cgI1/vIjGPKju1BNwJ6Lf2fcIAaEc4i/LInXOvxvtBifd71MKUfM/@z78ajHPxOsdjDNz9@FfvGLT3LG6WEaOz5931bm7h14jMV5A06jBjaM73XrLFaaH31YuoUnR70VZGbN6VuWlPuihiv3lk1NtCBQ0I0eggcgsEZQSMxy1NTtXmWm1rMnGacIzDb9CffrN1UEYtnkYhUGJGJrXhRInfNGM8JkACkAAYgA9gCvADkJ40eREpkSmyXvU4vxasSb1oUSi1FKSol7MkrSHjKTTg4UWcUvAK8BUUY8hKgArDuEsTVcl6bVF3jCeu82oruGi9@c3xDX3u048cei6bNrshbSn5XhE3LeIdfTGhORScljE0mma09Ojzkx7za7VvumW5nktakT57NhtfNvI@J5w2U3bdI4Xt3HzDtJezYtIWZFnZLT4iUZy/uHc2HHpt8Hv4B "JavaScript (Node.js) – Try It Online") (comes with test cases) Turns out keeping a major fork of my approach was useful after all. I ended up dropping half of the functions, switching from arrays to strings, and weirdly enough, this new code has lots of repetition that wasn't in the old one. I wrote this independently based on my Pyth answer's algorithm, and it's currently shorter than any suggestion on the other JS answer, so I'm posting it separately. ### Previous approach (197 bytes) ``` ([,,...m],X=A=>m<X?X(A+M(m[0])):A,M=x=>m[0]==x?m.shift():"",N=e=>M`E`?[]:[I()+e,...N(e)],I=_=>[...M`N`&&N`::`,...m.splice(0,X``),M`I`&&`<${N``}>`].join``,R=s=>m+""&&s+I(a=")")+R`,`)=>I(a="")+R`(`+a ``` ### Explained ``` ( m, // Input string. o = 2, // Offset into input string. X = A => // Matches and consumes numbers in input. m[o] < X // Compare input to the stringification of the // function X. Since that begins "A=>", and // valid identifier start chars are all >= "A", // this only matches numbers. ? X( // If we got a number, n = A + m[o++] // add it to arg and consume it, // save the result to n, ) // then keep parsing. : o // Otherwise, return the current input offset. M = x => // Matches and consumes input. Used as M`E` or M("E"). m[o] == x // Check if first char of input equals (stringified) arg. ? o++ // If matched, consume and return something truthy. : "", // Otherwise return "" (falsy and a string). I = (e = "") => // Recursively demangles identifiers. E-terminated if e!="". m[o] // See if the input is empty. ? M`E` // If input not empty, try to consume "E" from input. ? "" // If successful, return "". : // Otherwise: e // Start with the separator. + ( M`N` // Try to consume "M" from input. && // If the match fails, "". I() // If successful, parse an identifier, + I`::` // parse an E-terminated identifier, prefixing // each part with "::", + "::" // and add an additional "::". ) // Append this to the result. + m.slice( X``, // Parse a number from input, store it in n and // get the input offset after the number. o += +n // Add n to the input offset. ) // Get the n characters between these indices // and append them to the result. + ( M`I` // Try to consume "I" from input. && // If the match fails, "". `<${ I() // If successful, parse an identifier, + I`,` // parse an E-terminated identifier, prefixing // each part with ",", }>` // and wrap these in <>. ) // Append this to the result. + ( e && // If not parsing an E-terminated identifier, "". I( e < I ? ( // Otherwise, if the separator is less than the // stringification of I (starting "(e=" which // only matches "("), a = ")", // set the terminator to ")" "," // and use "," as the next separator. ) : e // Otherwise, keep using the same separator. ) // Keep searching with that separator. ) : a // If the input was empty, return the terminator. ) => I( // Parse an identifier a="" // (and initialize a=""), ) + I`(` // then parse an E-terminated identifier (until EOF). ``` [Answer] # [Pyth](https://github.com/isaacg1/pyth), ~~97~~ ~~96~~ ~~95~~ 93 bytes ``` L*bnz=:z+\^bkL?y\Ek++Eb'bDER&z++&y\N'"::"&yJh:z"\D"3y<zsJ&y\IjP'\,"<>"=ttzpEIzjj\,ufTaYE0)"() ``` [Try it online!](https://tio.run/##DcmxDoIwEADQf7kBxGLixa1BXbihBBtjXDSNhqoIRYGEOrQfb/Wtb3S2CaGc696vuWfqorty6xR1jJGOdU6HyDMWOSVj4BwiVzTcg8ph5TI/Ff8QZh@rFLINrK31IwlvjEo/9bE60TKBWRLC9SyxQi3whnd8ENaET4kNYSskGsJO4ItI4ht7wuE7jLYd@iksdj8 "Pyth – Try It Online") I really didn't expect to beat Retina, and I still think it might come back. Pyth kinda shows its age, but this is starting to feel pretty nicely optimized. I also got to use some very rarely used Pyth features like the imperative `D`, `R` and `I`. Passes all tests. Requires the `-M` flag to disable memoization. ### Explanation The program consists of three functions and main code. At the start, input is read to `z`. The first function `L&nz=:z+\^bkb` consumes its argument from the input if it matches. ``` L Define y(b): L*bnz=:z+\^bk +\^b Compute "^" + b. :z k Replace this regex in z with k="". = Save this in z. nz See if it is different from the previous value of z. *b If so, return b, otherwise "". (Multiply b by 1 or 0). ``` We'll only be passing `N`, `I`, `E`, numbers and simple identifiers to this, so we can safely use them as regex. There will only ever be 0 or 1 matches thanks to `^`. The second function `L?y\Ek++Eb'b` recursively demangles a namespace or template, adding its argument after each identifier. ``` L Define '(b): y\E Match, consume and return E from z. ? If it was present, k return k. E Otherwise, call E() to demangle an identifier, + b add b, + 'b and recursively call '(b) and add that. ``` The third (monster) function `DER&z++&y\N'"::"&yJh:z"\D"3y<zsJ&y\IjP'\,"<>"` recursively demangles identifiers with namespaces and templates. ``` DE Define function E(): &z If z is "", return it. ++ Concatenate: y\N - Match, consume and return N from z. & '"::" If it matched, '("::"). Otherwise, "". :z"\D"3 - Split z by non-digits. h Take the first piece. J Save it in J. y Consume and return it from z. & Always truthy, continue. sJ Convert J to int, <z take that many chars from z, y consume and return them. y\I - Match, consume and return I from z. & '\, If it matched, call '(","), P remove the last ",", j "<>" and put the rest in <>. Otherwise, "". R Return that. ``` Finally, the main code. ``` ttz Strip the first 2 chars of z = and store the result back in z. E Call E() p and print the result without newline. Iz If z isn't empty, u 0) For all H=0,1,..., repeat until results stop changing: E Call E(), aY append that to Y (initially []), fT and remove falsey elements (i.e. ""). j\, Join the values (of Y) with ",". j "() Put the result in () and print. ``` [Answer] # [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 133 bytes ``` 1`\d+(?=.*\z) $*# }`(#)+((?<-1>.)+) @$2¶ {`N(@.*)¶@ $1::N@ N(@.*)¶E@ $1:: (¶I@.*)¶@ $1, }`¶I@(.*)¶E <$1>¶ ^_Z|@|¶$ 1>`¶ , ¶(.+) ($1) ``` [Try it online!](https://tio.run/##XY/dboJAEIXv9zWkyaKWZMDGaKySNNNmb9be9IaYApYFt6K0gImx9rV4AF6M7or2b5NJZr45c2YnF6Xchs0VpQ9BA8Ei6tHZrdVdHExidDvkM6Ads0fpbHINU8vsmcQ17LoiHwGnrtU168olBozH3CUXgC0htK7Yj6SvrDSgrYZMDJgqn2ffO7rHujIIgakSkD6pK2qpPdQAs2l8D/bE95w4y5xlmKuU6xzPhXM/nzOd4y@RisO5bHv/ga7xj5UK7wLamdOQ877T2/no7jHdFTqYLQtEgCL7fjdJLsJSy@wiY8DYYCXySIme2CCVYo04KsXmLQ1LUSgV2DIS21LGUuRgK2D7p9UQwhJeIAIBMSSwQpAXzFqOECMk/NRiHF4R1gxSRA4b2CJk2nzAnVxEOFRfyOU2gf1QXeSrg74A "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: ``` 1`\d+(?=.*\z) $*# ``` Convert the first integer in the (remainder of the) unconverted string to unary. ``` (#)+((?<-1>.)+) @$2¶ ``` Extract the identifier after the integer, mark it so that it doesn't get confused with `N` or `E` marks, and put it on its own line with the remainder of the unconverted string on the next line. ``` }` ``` Repeat until all of the identifiers have been extracted. ``` {` }` ``` Repeat until all namespaces and templates have been processed. ``` N(@.*)¶@ $1::N@ ``` If a type has more than one namespace then join each one with the next using `::`. ``` N(@.*)¶E@ $1:: ``` If this is the last namespace then join it to the type and remove the namespace markers. ``` (¶I@.*)¶@ $1, ``` If a type has more than one template then join it to the next using `,`. ``` ¶I@(.*)¶E <$1>¶ ``` If this is the last type in the template then wrap the types in `<>` and remove the template markers. ``` ^_Z|@|¶$ ``` Remove all the remaining leftovers. ``` 1>`¶ , ¶(.+) ($1) ``` If this is a function then separate the parameters with `,` and wrap them in `()`. [Answer] # [Knight](https://github.com/knight-lang/knight-lang) (UB), 142 bytes ``` ;=xP;=l';W&x-69Ax;Cp&&x-69AxO","Cn';C=nB=xSxF1"";Cn;C=pB;O;&?78Ax;E;CnSl 22T"::"O"::"GxL=m+0x m;=xSxF+mLm""&?73Ax;O"<";Cn;ElO">"&x;O"(";ElO")" ``` [Try it online!](https://tio.run/##tVl9c9rIGf8bPsVaGSMtiLMkuDaHEIztwx6mjvGZuJmpTXNYCFtzQmgk0bgXu1899zz7Iq0AJ73r1TNB7O7z@tvnTcRvP/j@lzdh7EebRdDP8kW4/u5xUFd3ovC@suXn/06CLaI0jB8qW3m44jSLYBnGAYkiEq3jB/ZRbL6/vHlH7HI5fX9NnHL59@Nr0i2XZ5en5G25vL4hdkl8djFVaC9vLhTSm8t3x9O/GRklBnw0/mN/T4uz4yko5Uf@4zxt0oJYpQE7Jftg0C1PLkcf8CiGI/TlGb71@9VzFM/O4cuzEUUUVhWCk8nkglHAxxC86oEriu7rc34IrIVx/5pHm4DS23hG6/WjZt3uduqu9zR1vfgEHk9ntqZdWa4X6e6HxlP7Lz8cP7mnSUN8nWimdhrrjqa5p15y4k7cxvCvb4Fk5J7G04g4znut19Mm@HH@dOGtWtYTWblMcGt1sdI0oO8A/UTrg4jYHUUTbaA1cMPQ2Ipq9eZRvc4QheAI5ivvWhtNzowvIObqG4aBVaUbKP//Z@UXCkZpbh2iM5mnWWBQ8rleC@OchG69BrsMaZM0l5vYhx10iPiwzleJmSXxrTPzPlum9eLWgY14nB6eFhB/egyjwAD3gdDgKJhEu8vv4rvlXUo@v9zODNp7o1GmtBYuiSHAIp5H9Dc6JVyE3D2A3bsYtlstvgNKakGUBerGi1BMjDBbhA9hLtlBDVpom4WR/NkktkVapClMbLUoaRPd0kEWmhRSkgb5Jo15tj4THn2k3yddWngZZtH6U5AaPoiV@sjzM5E2@GzlM8c@6lS4G@5xJfRsE9D1iu0tI7AogBGQSARI4sUmMfAyiMCoTWBFBRvXd6frpXJN52gDFZhaaCdHRwRKF3wHE5J5lpP8MQCZ8zQHYgFoUyKEN@Gjkpq0CivXt6yCT5vyG1K8xiiyZmCLL33NNkmCUFJ5/3JHBVaNFABUEYgyZNAlMUQcFE6MMWEqh@G9ToashPbExhluYBHtYfHEcJZRwuou983ANEBT51G09o2uZdoUPcLtqhNc6LUC/JVemMAkSzYb2UTy7bP@eHRy@vNPBxc/ThQnKhKcXQkHFRHn4@lrvJ1dXm7uuV5YPn7F8m6Vt0rygjUl3cQIm8sKIRSNdWbImsKiEOIrD33CTu83y1unOxNGcPAbLOcK7VkCbTZfGkAKXh1G0UKTyTwYQDaaKGRbAERmIYA3O66/QtcndqfqJHqO8TEkWp5uAg3iotjHMIH95RzyFQ@0eBNFWgkB@omuizaFYHw8Wa8jOLivAvCqq6VXX/On@fsdUq2837YS7yxfx3@qjRCJ@TqKDNVUk1gmVN0/YHK8YzI2q3fHV5cmtiweZ7Ac39qWZc1YZ4OlXGXhr8HHnODDrZcRqniLCMDKxA@HfXY8W3Y@LDrY/PDBPh3@6ADB2fhi1CRLqFdurYhsoQ9LoT9PzCiIWaNUsDJEV@GYQc69BsY2IzYC7CPLdQo1k7Vc6G99hoULhT3Ew6IY@Ktk6wYYSOGsrAsIUzhDNdmnMPcfjSYbuUh15gKMiPjzsVfox3qPoBZO4CGgOLNBYaQN5pQQL0bFSshSl7W8koLNonmK7YONo7cz@rkMM5gzWLnliq9BcVV2Oo8XBm1YT0v4KwmvgBCEcogegjyCudJosKts4AVhl1qEMXXDpWGw68Tm6z@maIoJYUopv2XPcveaCg@0S@obcX2sO7FaIPCQzAiRKJulkSelN5y8ODktT5BTBbig@RloMBYg@rxknQSxoeg1tVRjzRqM8la8dUE0eo7Vfcv2RXs3@EywBMsX6BMMRRCwJk5MQA7dm61QB6iWwWXAJml5bOrAfAVKKtAGOUwXQxolND3iqFNDiWLpyU/gSfAEExPm@o6fB5U7Z28OB1jHdggvdoIDtERVXBTyH/WeGMn2hHFR90T70S43q3sYR7ABUdmB8LWonOF2iqFknbI3ReMwQ8ZqKuwyA5wwi6h6oY5SrSSVB9hcgnksxL7Wv0TDUm9A9nOOwqREAfMCrlCAxu@zAh1pNPD0tt1G0hkfNO/YZFuTZh1@18zAHgNWlMhMSxXzN3kmb7@ICT58cYNahUGsSkK1xIKMoaVcD59na9Xb5q@sSA0jNpGx5PA7xwmUJQO/AEaF25jknvTSoftD1Z/n8iHGQLtVwkTld5RFYTw02TMXJUL41d6JTiXacViu2suZmuXt7EFhuznvwaG5gwO/130orPa41mQ0niqEMUAHMliB9PQ7eG1CIrfdZvIEUKxhbl80RzSvZP/RV4E52g/M4VeZDvcz/ZOhWXGIz/Jsz1G9dAXsHHWPtO1tlBkL3IAN6da2IdXsCpPzB7n6UC738XgesjBzekTsWMVVsAtwBpa4A4eyIabpsXupbycKO1SaV5/hslVjMb8qKehVE3BI1Djrq4gja4//@gPMnGBIKhMJ2zSJkngow@Kcsro7vOQg7YEHhU0xefC/mzz4E0weSJMP9tjsCZuFycPXTeZa95iMx0NSIXAKCkfW5IN9dpaLwj0ZzKqAwrxGmVHoy75yM1Q5RRgW/M//Db@IX0VMwe/qPZXaVeefbVqvTOTq8e@ejOW4VI7GSFerjMdFFjEalDjzKtxKhiEHUrRaBRs3@QO4x3/ZUGeXindEbYeCbVwdBJFU4R86vY4CyzkfQj2labfUmrY7dMdilDWLXOhUZqQpB3pLqLtdRZ19VbRDi9biFNxdtvmNHouG4ROvwi/myaLDqu3WAQ9Ra8vGvst6Do9/fsgejKIlMgG0L4LlfBPl4JkcWsIYDsMF@1Fi7udBCg3G13GMwR1KXnktQmFsbhU/cb2wF9PVPIwNir90sHcT/E8Bw2KKqy8BL18@/uPSydZjezzuPgbpYjSyb8bdKAx@GY1@yINVEs3zIOvcz1P49@tv) Shameless non-winning self-answer. 😏 It is a pretty good example of recursion and EVAL/BLOCK in Knight. Abuses this interpreter's acceptance of out of bounds `ASCII` and `GET`. This won't work on the c/ast interpreter as `ASCII("")` is an error and so is reading past the end of a string. ``` # Read line ; = symbol PROMPT # Template for printing identifier lists ; = parse_iden_list ' # While symbol is not empty and not E ; WHILE & symbol - 69 ASCII(symbol) # Recurse into parse() ; CALL parse() # If symbol is not empty and not E, print sep : &(& symbol - 69 ASCII(symbol)) # dynamically replaced separator OUTPUT "," # Pop the "E". # UB: This actually cuts off an extra char from the string, # but since the interpreter uses strchr to replace newlines, # there is going to be an extra null byte to save us. : CALL pop() ' ; = pop() BLOCK { : = symbol SUBSTITUTE(symbol 0 1 "") } # Pop the _Z ; CALL pop() ; CALL pop() ; = parse() BLOCK { # Check for N ; & ? 78 ASCII(symbol) ; CALL pop() # Parse the identifier list, replacing "," with "::". # I cba to update the offset for the ungolfed version ; EVAL SUBSTITUTE(parse_iden_list 22 1 "::") # print trailing "::" : OUTPUT "::" # Get the length (done inline in golfed code) # by converting the string to a number. ; = length + 0 symbol # Print length chars after the number # LENGTH(number) will convert int to string and take the length. ; OUTPUT GET(symbol, LENGTH(length), length) # Pop the number and the identifier ; = symbol SUBSTITUTE(symbol (+ length LENGTH(length)) 0 "") # Check for I # UB: Again, this will technically read out of bounds, but # this will in practice return the null terminator. : & (? 73 ASCII(symbol)) ; CALL pop() ; OUTPUT "<" ; EVAL parse_iden_list : OUTPUT ">" } # Parse base identifier ; CALL parse() # Check for parameters : & symbol ; OUTPUT "(" ; EVAL parse_iden_list : OUTPUT ")" ``` --- # [Knight](https://github.com/knight-lang/knight-lang) (no known UB), 146 bytes ``` ;=xP;=l';W&x-69Ax;Cp&&x-69AxO","&xCn';C=nB=xSxF1"";Cn;C=pB;O;&?78Ax;E;CnSl 22T"::"O"::"GxL=m+0x m;=xSxF+mLm""&&x?73Ax;O"<";Cn;ElO">"&x;O"(";ElO")" ``` [Try it online!](https://tio.run/##rVl7c9pIEv8bPsVYKSMNiLUkuNssQlC2F7uodYxj4k3V2VwWC2GrVghKEhs2se@r57rnIY0AJ7e5dVUQM9OPX/f0S8RvPvj@l1dh7EfrWdBNs1m4/OGxV1V3ovC@tOVnf66CLaIkjB9KW1m44DSzYB7GAYkiEi3jB/aRb767vHlD7GI5fndNnGL56/E1aRfLs8tT8rpYXt8QuyA@uxgrtJc3FwrpzeWb4/EvRkqJAR@1/9j/oPnZ8RiU8iP/cZrUaU6s0gBOyd7rtYuTy8F7PIrhCG15gm/dbvkcxbNz@PJkRBGFVYngZDS6YBTw0QerOmCKovv6nB8Caw7uj2m0Dii9jSe0Wj2qV@12q@p6m7HrxSfw2JzZmnZluV6ku@9rm@Y/fzreuKermvg60kztNNYdTXNPvdWJO3Jr/R9fA8nAPY3HEXGcd1qno43w43xz4S0a1oYsXCa4sbhYaBrQt4B@pHVBROwOopHW02q4YWhsRbVq/ahaZR6F4AimC@9aG4zOjC8g5uprwGobgAa4CkNQw/firG2@jfQLBWCaW4UIXU2TNDAo@VythHFGQrdagV3mbZPU5@vYhx00iviwzhYrM13Ft87E@2yZ1rNbBTbicXp4WkD88TGMAgNcAIQG94RJtLvsLr6b3yXk8/PtxKCdVxplSivhnBjCYcTziP5Kp4SLkLsHsHsXw3ajwXdASSWI0kDdeBaKiRGms/AhzCQ7qEGEtpmD5M86sS3SIHUBsdGgpEl0SwdZCCmkJAmydRLzjH0iPAJJt0vaNLcyTKPlxyAxfBAr9ZGnJyIx@GzlM8M@6FSYG@4xJfRsE7zr5dtbILAwAAhIJgIk8Wy9MvAyiPBRk8CKCjau707XC@Wazr0NVAA1106OjgiUL/gOEFbTNCPZYwAyp0kGxMKhdekhvAkflVQkKqxe30IFnzblN6RYjVFkTQCLL21N16sVupLK@5c7qmPVSAGHKgJRhgy6VQwRB8UTY0xA5W54p5M@K6MdsXGGG1hIO1hAMZxllLDay20zMA0Q6jSKlr7RtkybokW4XTaCC71WHH@l5xCYZMlmI5tIvn3ojwcnp7@9Pbj4eaQYUZLg7Eo4KIk4H45f4m3t8nK453qOfPgC8naZt0zyjDUlWcfoNpcVQygay9SQNYVFIcRXFvqEnd6v57dOeyJAcOfXWM7l2tMVtNpsbgApWHUYRTNNJnOvB9loopBtARCZuQDe8Lj@El2X2K2ykWg5xkefaFmyDjSIi3wfwwT251PIVzzQ4nUUaYUL0E40XbQqdMaHk@UygoP7sgNeNLWw6mv21P@6QSrK@22UeGfZMv5bMUIkZssoMlSoJrFMqLrfATnegYzN6s3x1aWJLYvHGSyHt7ZlWRPW2WApV2n4KfiQEXy41SJCFWvRA7Ay8cNhny3Plp0Piw42P3ywT4c/WkBwNrwY1Mkc6pVbySNb6MNS6E9XZhTErFEqvjJEV@E@g5x7yRnbjNgIsI/MlwnUTNZyob91mS9cKOwhHubFwF@stm6AOSmcFHUB3RROUE36Mcz8R6POxi5SnrvAR0T8@dgr9GO9Q1ALJ/DQoTi3QWGkNWaUEC/GxVLIUpe1vIKCzaNZgu2DjaS3E/q5CDOYM1i55YqvQXFZdjKNZwatWZs5/BWEV0AIQrmLHoIsgtnSqLGrrOEFYZeahTF1w7lhsOvE5us/JgjFhDCllN@yZ7l7ocIDcUl9A66PdSdWC4Q/JDO6SJTNAuRJYQ0nz09OixPkVB2c0/wGNBgLEH3earkKYkPRa2qJxpo1gPIWvHVBNHqO1X7N9kV7N/hMMAfkM7QJhiIIWBMnJiCH7s1WqANUy@AyYJM0PDZ1YL4CJRXeBjlMF/M0Sqh7xFGnhsKLhSVvwZJgAxMT5vqOnQelO2dvDwdYx3YIL3aCA7REZb8o5D/rHTGS7QnjvO6J9qNdrhf3MI5gA6KyA@GrUTHD7RRDyTpmb4vGYYqM5VTYZQZ3wiyi6oU6SrWCVB5gcwmmsRD7Uv8SDUu9AdnPuRdGhRcwL@AKhdP4fZZcR2o1PL1tNpF0wgfNOzbZViSswx/qKeAxYEWJzLREgb/OUnn7eUzw4YsDauSAWJWEaokFGUNLuR4@z1bKt81fW5EaRmwiY8nhd44TKEsGfgGMCrcxyT1ppUP3h6o/zeRDjIF2o3ATld9RFoXx0GTPTJQIYVdzJzqVaMdhuYyXM9WL29njhe3mvMcP9R0/8Hvd54XFHtPqjMZThTAG6EAGK5CefgevTUjkNptMnnAUa5jbF809mpWy/@irjjna75jDrzId7mf6N/NmySA@y7M9R7XSFW7nXvdI0972MmOBG7Ah3Zo2pJpdYnK@k6sL5XIfj@chC4PTIWLHyq@CXYDTs8QdOJQNMXWP3Ut1O1HYodK8uswvWzUW86uUgl45AftEjbOu6nFk7fBfgICZE/RJaSJhmyZREg9lWJxTVneHlxykPfCgsCmQe/8/5N7fALknIR/swewJzAJy/2XIXOseyHjcJyUCJ6dwZE0@2IezWOTmyWBWBeTwakVGoS37yk1f5RRhmPM//S/8In4VMTm/q3dUaledf7ZpvSKRy8d/eTKW41IxGiNdpTQe51nEaFDixCtxKxmGHEjRaORsHPJ7MI//sqHOLiXriNoOBduwPAgiqcLfdzotxS3nfAj1lKbdUGva7tAdi1HWzHOhVZqRxtzRW0Ld7Srq7KuiLZq3FifnbrPNb/RYBIZPvAo/nyfzDqu2WwcsRK0NG/su6zk8/vkhezCKhsgE0D4L5tN1lIFlcmgJYzgMZ@xHiamfBQk0GF/HMQZ3KHnhtQiFsblV/MT1zF5MF9MwNij@0sHeTfA/BgyLKS6/BDx/@fCvSyddDu3hsP0YJLPBwL4ZtqMw@H0w@CkLFqtomgVp636awL9P/wU) Simply adds some range checks to avoid reading an empty string. [Answer] # [Raku](http://raku.org/), ~~221~~ 218 bytes ``` ->[\a,*@b]{a~"({join ',',@b})"x?@b}o{my rule s{(\d+){}:my$n=$0;(.**{$n})} my rule i{(N$<n>=<~~>+E)?<s>(I$<t>=<~~>+E)?} sub p($/){join('::',$0<n>».&p,'')xx?$0~$<s>[1]~("<{join ',',$1<t>».&p}>" if $1)} m/<i>+/<i>».&p} ``` [Try it online!](https://tio.run/##XU/BbqMwEL33KyxkFUhom4F0q6aEVFp5JV9oL70kqRAsJnVLIGsTiSyCH@utP5bapGm7a2nsmTfvzRtvmMh/7Nc7dJqh6f4sWCxjZ3CbPDZxZ1jNc8kLZDqmc5u0tlHP1FM2iiy2OUOysZbp0G7ayXqHiyke3Vjng0GDi9ZuT44k3lgh9otg6nddMCT2zJeBRbFffSHtidwmaGPhC7s3tMzJxHTwSKneXs9PN45p2nU9w6MOK/ECHjvL8L9Ww6CG9cQ2MBDPEAbtf@HzYKivQ2sv4x0ycISmAWoUJ2oNlJUC@dEcahTNvawsvSQWKg11Tj4K79fdHdU5@UZS8fejPPT@B3RN/hmlYn4EDppe5P3Zavfw@ud9vpU6qMslIQCy/DyXK8HiStNcWVKgdPzERKpID3Scc/ZCyHXF1ps8rphULHB5yoqKZ5wJcBXgRr01xJDAb0iBQQYreCLAjzA94AQyAquwb9EQngm8UMgJCWENBYFSDx@HnmApuVIrCF6soL5SP4rUh4L9Ow "Perl 6 – Try It Online") Leverages the considerable power of Raku's regexes. [Answer] # [Red](http://www.red-lang.org), 236 bytes ``` func[s][d: charset[#"0"-#"9"]i:[copy x[1 2 d](x: do x)keep x skip]n:["N"any[b keep("::")]"E"]t:["I"keep("<")any[b["E"keep(">")break | keep(",")]]]b:[any[n]i opt t]parse s[collect["_Z"b[end | keep("(")any[b[end keep(")")| keep(",")]]]]]] ``` [Try it online!](https://tio.run/##ZVJLi6NAEL7nVzQ9F4UMbJksQ2rFy9ILXpxlYS5pmuCjTRyNumrAGfa/Z6vtjBMZocH6XlX96HR2/aMzqVY5XvNLncpeyQxZeoq7Xg/ygX/jjw98x1WBMm3aNzZKYB7LlDMiyxo2uqXWLRtZXxatqlHyiMf1m0yYwR2OyF3FBVcDUSG3oM/dSSOJsEjA3aTTccn@3XxrsimVoDTCWhWsaQc2qNaMxXoapap0Okh@2PNE6jqbjc5HtgEt5HJ3GUvfNW@oX3pig@4HJlcUBCP/wR4DNppikzfNJok7C1HhUOEaJjKUWHCIVE2uX8/PoaGE5aj0qQruE2m9L1LXBLgfCuteaKYE54vIaMRCZIKC5Yi09ssxKWj/uQ/bbuq3@XsZlz2N/t0h2Op3P39Xl96s0Ct6IQD6Zv6@H@k4B@ufdX7RU8idyplUNs7rmxDCcHvSXUZhL@G2KnQpxG7Q57aK6V5sWt/4oW9EAWW9@EZEP7NoujmvyHQ9FHmhO/Cs7R4xGu9wO4jDfmoPMSSQQgYacjjCSUBh@Zi2jZgiZogaMUc8Ip4Qi9kWWp@AXMAxmqxhBK8CyhAqISI4Qy2g@Yzz03W21oENc0yW/4pY@lUQrM@INWIznQlso02nM/FE2@2K@gjjE93FYX5qS9YZ1zfWXamVbAkbWD49aHX9Dw "Red – Try It Online") Output is block that gets printed with a lot of extraneous whitespace, which is allowed, but prepending it with a simple `rejoin` will produce precisely the same results as in the examples. Overall, this looks like a perfect task for learning Red's Parse dialect, so here's my attempt at it: ``` func[s][ ; Digits rule: d: charset[#"0"-#"9"] ; Identifiers rule: i: [copy x[1 2 d](x: do x)keep x skip] ; Match 1-2 digits, copy to x, eval x as number, skip and save next x characters ; Namespaces rule: n: ["N"any[b keep("::")]"E"] ; "N", any number of Base components (b) appended with "::" ,"E" ; Templates rule: t: ["I"keep("<")any[b["E"keep(">")break | keep(",")]]] ; "I" (change to "<"), any number of b appended with "," or with ">" if followed by "E" ; Base component rule: b: [any[n]i opt t] ; Any number of namespaces, main identifier and optional template ; Actual parse operation: parse s [collect ; 'collect' all entries after 'keep' ; Final rule: ["_Z" b [end | keep("(") any [ b [end keep(")") | keep(",")]]]]] ; "_Z", base component, "(" if the input hasn't ended yet, ; any number of subsequent b's as parameters, separated by "," and ")" in the end ] ``` [Answer] # Befunge-98, 151 bytes ``` ~~1345x >]')\j,@ ~ ^>:'E- v >'>, ^ v-I':_$2w'::,,3 ^v\_$'<,03> j v>',,0 v>'(,0 v>'::,,2 \ >>:'N-v v< \0_$23^ '~>$68x 0+w~ v -*0 :a: a\- w^^1,<+0' ``` [Try it online!](https://tio.run/##JYyxTsMwFEX39xVviPSA2pJvA6i1IovFQxZ/ADKOUkhbAhQWnLL410MK0znD0dkN@@/TYdDbjf76@dN5LgX17d2Z3JNcx1E9EBdKzorXzJnZiVOUFtWt2K5aT2KtUjWlHLtKGmVqRzxSdqKUueDqH5dqTZHcsgo6U26Yo1kGdSIprrrfnMmspsKZ9I0h21vqo6YpJahmZWSeu8eAHrsWz3jB4LH3OAQcPV7bgNHjrcW79wEfOHl8/gI) | [Run all test cases.](https://tio.run/##XVRtb9owEP7uX3GiTAlromJC19YN0arNSJEmWqnrF0ZBIXFCaEhYHCCrJv46OyeA0iFZuZfneXxn@5h7cnHwvQJsGzT@ONTgL6xFnoC5FqD5i2y1hjgEkYUaOLDOsyj3Vof9nlr965I4r1pnsjS@EtiTqcM0bgJsARzNMcgUTdPV2Kzd22mMGYZFptvJrK3ZRtdyCCzJ1tEMo6s@ev1RqB6ZEAelRuaWbG2ASRcFrCnR9k77y21Jupe7PWyJ@blLmMeINzHJbjqlhn3Z1Q7YACGFkIUctHUpAtDkBZgOXFxdaKpDlZ@NaaliJVpWmGXW3MuVj6aOZgfDIxXnjQRjaCv88PHRVXGuEujYaDsNIVzvDTED3c4xXfMagIqr/49QAN5AKAnnQ024xs26UGJ8rrrepdrG@r0pm1sp8LuOwQp89@0p2Ui13F4sOadUZuffdZQLfBNIPqPsWKJCA6NXmEqrJzOXum5/IfIAlV7cfhKLN87vCrFaJx5eiJKSme3aCoLXy15sBUHjDFEX04sDkRZxGIuc9hSn6SOgN6s6n43VrtSjc@rTgAoa0oguOI1V0sM@GfMZCxgTjIWMRYwtGItPHLcmcRpyGo0qnjuiS07fXJpwPqIrmnKanbRs3wgM4dRKuhKyl4y92YnjGCvGUsYydQi0P7JyEfAb7DCP04iWN3jws@Mb@pjTS@OY6xD1JDuECBw1aLWrt9vCGdwt4kSAO3weXAGecwArL40SfNGiXAu/EME9BBkBnMg4LUJo/UQi@J4UDD6Z110JLVQ7clqI8/xi4yU4FdVGZtrIqon/E27SSIBpyiIY3N2iMRd16DjyHdTA/4FfyKulWjAYoHMqpwWv91AsRIo4gLqbp4fnZ/4d9COjo@oQiRQNyPDB/dGAGOf24Kxc0cKYBFkqyOEf) Something something, [stack machines](https://codegolf.stackexchange.com/a/230086/30164). Getting dangerously close to the golf languages. (I got a notification from my Brainfuck answer and decided this had to be done :D) ]
[Question] [ ### Introduction "Yarr!! We had a laddie who called himself a "programmer" make a map t' our hidden treasure! But 'tis written wit' weird numbers 'n letters! "E5, N2, E3"... what does it even mean? Madness! Can't even scribe a proper treasure map, t' useless cretin. Fix it fer us! We'll gift ye a share o' t' treasure!" ### Challenge Description A group of pirates are having trouble reading a treasure map. Can you write a program to convert it into a more... piratey form? As input, you'll receive the original treasure map. It's a list of comma separated strings, each string which consists of a *letter portion* (which tells the pirates which direction they need to walk in), and a *number portion* (which tells the pirates how many steps to take in that direction). For instance, the following treasure map: ``` E2,N4,E5,S2,W1,S3 ``` would mean, "walk two steps to the east, walk four steps to the north, walk five steps to the east, walk two steps to the south, walk one step to the west, then walk three steps to the south." As output, you'll output the map in a graphical form, using the characters `>`, `^`, `v`, and `<` as pointers. Here's the output for the above input: ``` >>>>>v ^ v ^ v< ^ v >>^ X ``` Notice that we've replaced the last step to the south with an `X` instead. This is because the last step is where the treasure is, and as we all know, pirates must have an X on their treasure maps, otherwise they won't know how to read it. By the way, the map won't ever cross itself, so you don't need to worry about dealing with overlaps. Also, you are allowed to have a trailing new line at the end of the output. ### Sample Inputs and Outputs ``` S5,W2 ``` ``` v v v v v X< ``` ``` N1,E1,S1,E1,N1,E1,S2 ``` ``` >v>v ^>^X ``` ``` N1 ``` ``` X ``` ``` N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2 ``` ``` >>>>>>v ^>>>>vv ^^>>vvv ^^^Xvvv ^^^^<vv ^^^<<<v ^^<<<<< ``` ``` E21,S2 ``` ``` >>>>>>>>>>>>>>>>>>>>>v X ``` ``` N12,E11,S12,W2,N4 ``` ``` >>>>>>>>>>>v ^ v ^ v ^ v ^ v ^ v ^ v ^ v ^ v ^ X v ^ ^ v ^ ^ v ^ ^<< ``` [Answer] # Python 2, ~~249~~ ~~248~~ ~~244~~ ~~239~~ 237 bytes ``` D={} m=X=Y=0 for s in input().split(","):d=ord(s[0])%10%7;exec"a,b=X,Y;E=D[Y]=D.get(Y,{});E[X]='<^>v'[d];m=min(m,X);%c+=d-2|1;"%(88+d%2)*int(s[1:]) D[b][a]="X" for Y in sorted(D):print"".join(D[Y].get(n," ")for n in range(m,max(D[Y])+1)) ``` Input like `"E2,N4,E5,S2,W1,S3"`. `NSEW` is mapped to `[1, 3, 2, 0]` by `d=ord(c)%10%7`. Whether to change `y` or `x` is then decided by `d%2`, and whether to increment or decrement is decided by `d-2|1`. The first and third expressions were found by brute force. Other than that, it's a simple usage of a nested dictionary of the form `{y: {x: char}}`. *(Thanks to @joriki for help with mapping)* [Answer] # Javascript (ES6), 260 This was an interesting one... Thanks @ETHproductions, @edc65, and @vihan for the help! ``` s=>{z=o="" m=[] q=x=y=2e3 s.split`,`.map(v=>z+=v[0].repeat(+v.slice(1))) for(i=0;d=z[i];q=x<q?x:q)(m[y]=m[y]||[])[x]=z[++i]?d=="N"&&--y?"^":d=="S"&&++y?"v":d=="W"&&--x?"<":++x?">":o:"X" m.map(a=>a.map((b,j)=>o+=" ".repeat(-p-1+(p=j))+b,p=q-1,o+=` `)) return o} ``` This defines an anonymous function, so to call it add `f=` to the beginning to give it a name. To test: `console.log(f("E2,N4,E5,S2,W1,S3"))` ### Explanation: ``` s=>{ //define function w/ parameter s z=o="" //z=modified input, o=final output m=[] //map of characters q=x=y=2e3 //q=minimum value of x; x+y=coordinates. These start high to leave room to go backwards s.split`,`.map(v=>z+=v[0].repeat(+v.slice(1))) //change "N3,E4" -> "NNNEEEE", and put in z for(i=0;d=z[i];q=x<q?x:q) //for each direction d in z, while updating q: (m[y]=m[y]||[])[x]= //in the right place on the map, put: z[++i]? //if last character of z, "X" d=="N"&&--y?"^": d=="S"&&++y?"v": //otherwise get the right character and change x+y accordingly d=="W"&&--x?"<": ++x?">":o :"X" m.map(a=>a.map((b,j)=>o+=" ".repeat(-p-1+(p=j))+b,p=q-1,o+=` `)) //dump map to o, with correct padding return o} //return ``` [Answer] # Ruby, ~~213 209 198 186~~ 178 ``` M={};x=0,m=q=0 gets.scan(/.(\d+)/){?1.upto($1){m,y=x x[d=$&.ord%10%7-2]+=1|($u=M[y]||={})[m]=d m<q&&q=m}} $u[m]=2 puts M.sort.map{|_,b|(q..b.max[0]).map{|k|">vX <^"[b[k]||3]}*""} ``` Pass input via stdin. This uses a `y -> x -> char` dictionary to construct the map, where both `x` and `y` can be negative. Once the input has been parsed, the global minimum of the x coordinate is extracted. For each row, it then iterates over a range going from the global minimum to the maximum index for the current line, and prints the correct character for that index. To stay with the theme, the expressions to turn `NESW` into the proper indices were shamelessly pirated from [Sp3000](https://codegolf.stackexchange.com/users/21487/sp3000)'s [answer](https://codegolf.stackexchange.com/a/54308/84). Original version that used a `[x,y] -> char` dictionary: ``` M={};x=0,0 gets.scan(/.(\d+)/){(?1..$1).map{x[d=$&.ord%10%7-2]+=1|M[$y=x+[]]=d}} M[$y]=2 a,*q=M.minmax.flatten M.map{|(x,y),v|($*[y-M.map{|a,|a[1]}.min]||=?\s.*q[2]-a)[x-a]=">vX<^"[v]} puts$*.map &:rstrip ``` [Answer] # PHP, ~~431~~ 417 bytes ``` $g=explode(',',$argv[1]);$x=$y=$a=$b=$c=$d=$e=$f=0; foreach($g as$i=>$h){list($k,$l,$m)= ['N'=>[-1,0,'^'],'E'=>[0,1,'>'],'S'=>[1,0,'v'],'W'=>[0,-1,'<']][$h[0]]; for($s=substr($h,1);$s--;){$z[$f=$y][$e=$x]=$m;$y+=$k;$x+=$l;} if($i==count($g)-1){$x=$e;$y=$f;} $a=min($a,$x);$b=max($b,$x);$c=min($c,$y);$d=max($d,$y); }$z[$y][$x]='X';for($y=$c;$y<=$d;$y++) {$o='';for($x=$a;$x<=$b;$x++)$o.=$z[$y][$x]?:' ';echo rtrim($o)."\n";} ``` Put it into a file (`treasure.php`), remove the indentation, join the lines (it is wrapped here for readability), put the `<?php` marker at the beginning of the file (not displayed here as it is technically not a part of the program). Example of execution: ``` $ php -d error_reporting=0 treasure.php E2,N4,E5,S2,W1,S3 >>>>>v ^ v ^ v< ^ v >>^ X $ ``` The option `-d error_reporting=0` is needed to suppress notices about values not found at specified indices in `$z`. **Update:** While I was preparing the [ungolfed version of the code](https://github.com/axiac/code-golf/blob/master/yarr-a-map-to-the-hidden-treasure.php) for posting I discovered it contained two unneeded assignments (12 bytes) and a whitespace that can be removed(`as$i`); also, by replacing a `while` with a `for` loop and squeezing an assignment into it (not possible using the `while` loop) I saved another byte. [Answer] # Perl, 702 613 546 474 439 338 260 bytes Thanks to Dom Hastings for his help and his supergolfed version. The code uses a 2D array. Version by Dom Hastings: ``` $x=$y=$a=$b=99;map{/^./;$a=($c=$x)<$a?$x:$a,$A=$x>$A?$x:$A,$b=($C=$y)<$b?$y:$b,$B=$y>$B?$y:$B,$q[$c][$C]={split'','W<E>N^Sv'}->{$&},$x+={W,-1,E,1}->{$&},$y+={N,-1,S,1}->{$&}for 1..$'}split',',pop;$q[$c][$C]=X;for$y($b..$B){print$q[$_][$y]||$"for$a..$A;print$/} ``` My lesser golfed version of 338 bytes (for reference): ``` @m=split(',',pop);$x=$y=$a=$b=99;map{($d,$s)=/^(.)(.+)$/;for(1..$s){$c=$x;$C=$y;if($x<$a){$a=$x}if($x>$A){$A=$x}if($y<$b){$b=$y}if($y>$B){$B=$y}if($d eq"W"){$r="<";$x--}if($d eq"E"){$r=">";$x++}if($d eq"N"){$r="^";$y--}if($d eq"S"){$r=v;$y++}$q[$c][$C]=$r}}@m;$q[$c][$C]=X;for$y($b..$B){for$x($a..$A){$t=$q[$x][$y];print$t?$t:$"}print$/} ``` Test ``` $ perl piratemap_golf.pl E4,N3,W6,S10,W1,S1,E5,N1,W2,N6,E6,N5,W10,S1,E2 v<<<<<<<<<< >Xv<<<<<< ^ v ^ ^ v ^ ^ v >>>>^ ^ v >>>>>>^ v ^ v ^ v ^ v ^ v ^ v< ^<< >>>>>^ ``` [Answer] ## Python 2, 394 bytes Run the program then paste into standard input as e.g. `"E2,N4,E5,S2,W1,S3"` ``` m=input().split(',') def f(x,y,h,o,s=[]): for c in m: for _ in range(int(c[1:])): a,b,l={'E':(1,0,'>'),'W':(-1,0,'<'),'N':(0,1,'^'),'S':(0,-1,'v')}[c[0]] if o:o[h-y][x]=l s+=[(x,y)];x+=a;y+=b if o:o[h-y+b][x-a]='X' return s p,q=zip(*f(*[0]*4)) w,h=max(p)-min(p),max(q)-min(q) o=[[' ']*-~w for _ in range(h+1)] f(-min(p),-min(q),h,o) print'\n'.join(["".join(l).rstrip()for l in o]) ``` This is not very optimized. First it runs through the input to record the path. Then it does some math to determine the right starting position and size of `o`. Then it runs through again and sets the appropriate entries of `o` as one of `>v<^X`. The main cleverness is in reusing the same function for both these traversals. [Answer] # XQuery 3.0, 498 ``` declare variable $v external;let $m:=<v>{tokenize($v,',')!(for $j in(1 to xs:int(substring(.,2)))return<c>{translate(substring(.,1,1),'NESW','^>v<')}</c>)}</v>/c!(let $p:=./preceding-sibling::c return<p x="{count($p[.='>'])-count($p[.='<'])}" y="{count($p[.='v'])-count($p[.='^'])}">{if(./following::*)then .else'X'}</p>)for $y in(min(xs:int($m/@y))to max(xs:int($m/@y)))return string-join(for $x in(min(xs:int($m/@x))to max(xs:int($m/@x)))let $d:=$m[@x=$x and @y=$y]return if($d)then$d else' ','') ``` XQuery isn't often even slightly competitive, so this was fun. ## Ungolfed ``` declare variable $v external; let $map := <vector>{ tokenize($v,',') ! (for $j in (1 to xs:int(substring(.,2))) return <step>{ translate(substring(.,1,1),'NESW','^>v<') }</step> ) }</vector>/step ! (let $path_so_far := ./preceding-sibling::step return <point x="{ count($path_so_far[.='>']) - count($path_so_far[.='<']) }" y="{ count($path_so_far[.='v']) - count($path_so_far[.='^']) }"> {if(./following::*) then string(.) else 'X'} </point>) for $y in (min(xs:int($map/@y)) to max(xs:int($map/@y))) return string-join( for $x in (min(xs:int($map/@x)) to max(xs:int($map/@x))) let $d := $map[@x=$x and @y=$y] return if($d) then string($d) else ' ' ,'') ``` [Answer] # PHP, 496 ~~514~~ ~~528~~ I tried my luck in PHP, the result is rather long, I still want to post it, just for fun. ``` function a($c){global$a,$b;$a[$b[1]][$b[0]]=$c;}$c=explode(',',$argv[1]);$a=[];$b=[0,0];foreach($c as$d=>$e){$f=substr($e,1);if($d==count($c)-1)$f--;for($i=0;$i++<$f;){if($e[0]==N){a('^');$b[1]--;}elseif($e[0]==E){a('>');$b[0]++;}elseif($e[0]==S){a(v);$b[1]++;}else{a('<');$b[0]--;}}}a(X);$d=$e=$f=$g=0;foreach($a as$y=>$h){$f=min($f,$y);$g=max($g,$y);foreach($h as$x=>$i){$d=min($d,$x);$e=max($e,$x);}}for($y=$f;$y<=$g;$y++){for($x=$d;$x<=$e;$x++)echo isset($a[$y][$x])?$a[$y][$x]:' ';echo " ";} ``` ## Ungolfed ``` <?php function setInMap($char) { global $map, $position; $map[$position[1]][$position[0]] = $char; } $instructions = explode(',', $argv[1]); $map = []; $position = [0, 0]; foreach($instructions as $index => $instruction) { $count = substr($instruction, 1); if($index === count($instructions) - 1) { $count--; } for($i = 0; $i < $count; $i++) { if($instruction[0] === 'N') { setInMap('^'); $position[1]--; } elseif($instruction[0] === 'E') { setInMap('>'); $position[0]++; } elseif($instruction[0] === 'S') { setInMap('v'); $position[1]++; } else($instruction[0] === 'W') { setInMap('<'); $position[0]--; } } } setInMap('X'); $minX = $maxX = $minY = $maxY = 0; foreach($map as $y => $row) { $minY = min($minY, $y); $maxY = max($maxY, $y); foreach($row as $x => $cell) { $minX = min($minX, $x); $maxX = max($maxX, $x); } } for($y = $minY; $y <= $maxY; $y++) { for($x = $minX; $x <= $maxX; $x++) { if(isset($map[$y][$x])) { echo $map[$y][$x]; } else { echo ' '; } } echo "\n"; } ?> ``` [Answer] # JavaScript (ES6), 244 ~~249 274~~ Leading spaces and newlines added for clarity and not counted, **except** the newline near the end in the join call, that is significant and counted. Test running the snippet (being ECMAScript 6, Firefox and Safari 9 only) ``` F=m=>( x=y=0,p=[], m.replace(/\w(\d+)/g,(d,z)=>{ for(d='NWSE'.search(d[0]); z--&&(p=~x?~y?p:[y=0,...p]:p.map(r=>' '+r,x=0)); p[u=y]=(w=r.slice(0,x))+'^<v>'[d]+(v=r.slice(x+1)), d&1?x+=d-2:y+=d-1) for(r=p[y]||'';!r[x];)r+=' '; }), p[u]=w+'X'+v, p.join` ` ) // TEST out=x=>O.innerHTML+=x.replace(/</g,'&lt;')+'\n' ;['S5,W2','N1,E1,S1,E1,N1,E1,S2','N1','N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2','E21,S2','N12,E11,S12,W2,N4'] .forEach(a=>out(a+'\n'+F(a)+'\n')) ``` ``` <pre id=O></pre> ``` [Answer] # C, 557 ``` main(_,a,minX,maxX,minY,maxY,x,y,v,dir,dist)char**a;char*v;{char o[998][999];for(y=0;y-998;++y){for(x=0;x-998;++x)o[y][x]=32;o[y][998]=0;}y=x=minY=minX=maxY=maxX=499;v=a[1];while(*v){dir=*v++;dist=atoi(v);while(*v&&*v!=44)v++;v+=!!*v;if(dir==78){while(dist--)o[y--][x]=94;if(y<minY)minY=y;y+=!*v;}if(dir==69){while(dist--)o[y][x++]=62;if(x>maxX)maxX=x;x-=!*v;}if(dir==83){while(dist--)o[y++][x]=86;if(y>maxY)maxY=y;y-=!*v;}if(dir==87){while(dist--)o[y][x--]=60;if(x<minX)minX=x;x+=!*v;}}o[y][x]=88;for(y=minY;y<=maxY;++y){o[y][maxX+1]=0;puts(o[y]+minX);}} ``` Ungolfed version: ``` #include <stdio.h> #define MAX_WIDTH 998 #define MAX_HEIGHT 998 int main(int argc, char *argv[]) { int minX,maxX,minY,maxY; int x,y; char output[MAX_HEIGHT][MAX_WIDTH+1]; char *v; for (y=0; y<MAX_HEIGHT; ++y) { for (x=0; x<MAX_WIDTH; ++x) output[y][x] = ' '; output[y][MAX_WIDTH] = 0; } x = minX = maxX = MAX_WIDTH/2; y = minY = maxY = MAX_HEIGHT/2; v = argv[1]; while (*v) { char dir; int dist; dir = *(v++); dist = atoi(v); while (*v && *v != ',') v++; if (*v) v++; switch (dir) { case 'N':case 'n': while (dist--) output[y--][x] = '^'; if (y < minY) minY = y; if (!*v) y++; break; case 'E':case 'e': while (dist--) output[y][x++] = '>'; if (x > maxX) maxX = x; if (!*v) x--; break; case 'S':case 's': while (dist--) output[y++][x] = 'v'; if (y > maxY) maxY = y; if (!*v) y--; break; case 'W':case 'w': while (dist--) output[y][x--] = '<'; if (x < minX) minX = x; if (!*v) x++; break; } } output[y][x] = 'x'; for (y = minY; y <= maxY; ++y) { output[y][maxX+1] = 0; puts(output[y]+minX); } return 0; } ``` Dynamic memory allocation isn't much harder, but malloc is far too long an identifier to be used in code golf. I feel like there should be some kind of PCG.h header legally auto-included for golfing in c, just to shorted some identifiers. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~61~~ 60 bytes ``` ‚ÄúESWN‚Äùi‚±Æo)¬µ·ªã√ò.,U;N$¬§W·∫ã…ó/‚Ǩ·∫é·∏£1;∆ä+\·πñZ·πǂǨ·∫°∆ä‚Äò≈í·π¨‚Ǩa"≈í·πô-0¬¶$S·ªã‚Äú>v<^X ‚Äù ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzX4HC/Rw1zMx9tXJeveWjrw93dh2fo6YRa@6kcWhL@cFf3yen6j5rWPNzV93DHYkPrY13aMQ93Tot6uLMJLLrwWNejhhlHJz3cuQbIT1QCsWbqGhxaphIMNAlovF2ZTVyEAtCC/w93LgZSOg93LLIOA@pqWnO4PZLLGqhEIT2zLLVYITex4NA2oArrw@1cD3dvOdwOVJL1qHHfoW2Htv3/H2yqE27E5Weo42qoEwwmoWyQIJefmY6rmU6wmU64qY6fqY6riU6wiU64sY6fsY6rEVCNTjhQvRGXqxFUgxFQK8gcoISRjp8JAA "Jelly ‚Äì Try It Online") A monadic link taking as its argument the directions as a list of lists, each of which has the compass direction character as its first member and the number of moves as an integer as its second. Returns a list of Jelly strings representing the map. [Answer] # Groovy, 359 ``` c=args[0].split(',').collect{[it[0],it[1..-1]as int]} m=[[]] x=y=0 d=["N":["^",0,1],"S":["v",0,-1],"E":[">",1,0],"W":["<",-1,0]] c.each{z->(1..z[1]).each{if(x<0){m*.add(0," ");x=0};if(y<0){m.add(0,[]);y=0};m[y]=m[y]?:[];m[y][x]=d[z[0]][0];if(c.last()==z&&it==z[1])m[y][x]='X';y+=d[z[0]][2];x+=d[z[0]][1]}} m.reverse().each{println it.collect{it?:" "}.join()} ``` [Answer] # Common Lisp - 603 ``` (lambda(s)(do((x 0)i(y 0)j(p 0)r(q 0)(g(mapcar(lambda(x)`(,(aref x 0),(parse-integer x :start 1)))(split-sequence:split-sequence #\, s))(cdr g))c)((not g)(setf x 0 y 0)(dolist(e(stable-sort(sort r #'<= :key #'car)#'< :key #'cadr))(dotimes(_(-(cadr e)p y))(terpri)(incf y)(setf x 0))(dotimes(_(-(car e)q x))(princ" ")(incf x))(princ(caddr e))(incf x)))(case(caar g)(#\N(setf i 0 j -1 c #\^))(#\E(setf i 1 j 0 c #\>))(#\W(setf i -1 j 0 c #\<))(#\S(setf i 0 j 1 c #\v)))(dotimes(_(-(cadar g)(if(cdr g)0 1)))(push`(,x,y,c)r)(incf x i)(incf y j))(setf q(min q x)p(min p y))(unless(cdr g)(push`(,x,y #\X)r)))) ``` Array-free implementation: prints from top to bottom, from left to right. * Parse and expands directions into a trace of `(x y char)` elements: The simple "N3" input produces `((0 0 #\^) (0 -1 #\^) (0 -2 #\X))` * Also, compute the minimal `x` and `y` * Sort the resulting trace by `y` first and then by `x` * Iterate over the sorted list while moving cursor 1. Add newlines and spaces to move current cursor at right position 2. When at position `x - minx`, `y - miny`, print the desired character ### Examples ``` (loop for input in '("N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2" "N1,E1,S1,E1,N1,E1,S2" "N12,E11,S12,W2,N4") do (fresh-line) (terpri) (funcall *fun* input)) ``` Result: ``` >>>>>>v ^>>>>vv ^^>>vvv ^^^Xvvv ^^^^<vv ^^^<<<v ^^<<<<< >v>v ^>^X >>>>>>>>>>>v ^ v ^ v ^ v ^ v ^ v ^ v ^ v ^ v ^ X v ^ ^ v ^ ^ v ^ ^<< ``` [Answer] # CoffeeScript, ~~303~~  285 bytes ``` Y=(s)->o=[];t=l=x=y=0;q='';q+=s[0]for[1..s[1..]]for s in s.split ',';q=q[..-2];(i='NWSE'.search c;(o[y]?=[])[x]='^<v>'[i];j=(i&2)-1;x+=j*(i&1);y+=j*(!(i&1));y<t&&t=y;x<l&&l=x)for c in q;(o[y]?=[])[x]='X';((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[t...o.length]).join '\n' ``` ``` <script src="http://coffeescript.org/extras/coffee-script.js"></script> <script type="text/coffeescript"> Y=(s)->o=[];t=l=x=y=0;q='';q+=s[0]for[1..s[1..]]for s in s.split ',';q=q[..-2];(i='NWSE'.search c;(o[y]?=[])[x]='^<v>'[i];j=(i&2)-1;x+=j*(i&1);y+=j*(!(i&1));y<t&&t=y;x<l&&l=x)for c in q;(o[y]?=[])[x]='X';((o[y][x]||' 'for x in[l...o[y].length]).join ''for y in[t...o.length]).join '\n' #------------------ document.write '<pre>' z=[ 'E2,N4,E5,S2,W1,S3' 'S5,W2' 'N1,E1,S1,E1,N1,E1,S2' 'N1' 'N6,E6,S6,W5,N5,E4,S4,W3,N3,E2,S2,W1,N2' 'E21,S2' 'N12,E11,S12,W2,N4' ] for w in z document.write "\n\n#{w}\n" document.write Y(w).replace /</g,'&lt;' </script> ``` [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes ``` Ôº∑Ôº≥¬´‚âî‚åïENW¬ßŒπ‚Å∞Œ∏‚ú≥‚äóŒ∏√ó¬ß>^<vŒ∏Œ£Œπ¬ªÔº≠‚ú≥‚Å∫‚äóŒ∏‚Å¥X ``` [Try it online!](https://tio.run/##bc3BasJAFIXhtecphlndS1OoMWajCIIpuHAoTCFdCZoMeiFOajJJC6XPPlVKd92f7z/V@dBV7aGJ8eMsjVO09e9DsKETfyJm9YXJuu/l5OlZfE26MKVO1Dpsfe0@SRL1xJyoKy8webmZQBvpXBWk9bRph2PjarreF69ycT39Ob3aL0d9d4myw4WE@Vb4xq4d3b@Fh4wZvwf6TXOMJkeRw@Yo5zBzFBlshnIGM0ORwqYopzAp4mMz/gA "Charcoal ‚Äì Try It Online") Input taken as a multiline string. Link is to verbose version of code. Golfed from 43 bytes with [Neil's help.](https://chat.stackexchange.com/transcript/message/56410590#56410590) [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal/tree/version-2), 390 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 48.75 bytes ``` ‚åê‚åä‚Ä∫?«çf`NESW`kd‚àö:¬£ƒø:·πÖ¬•`^>v<`ƒøfW‚à©v«î·π´‚ÅΩ‚Äπ·∫áwJ:tt\X1"pwJ‚üë√∑√∏‚àß ``` [Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwi4oyQ4oyK4oC6P8eNZmBORVNXYGtk4oiaOsKjxL864bmFwqVgXj52PGDEv2ZX4oipdseU4bmr4oG94oC54bqHd0o6dHRcXFgxXCJwd0rin5HDt8O44oinIiwiIiwiTjEyLEUxMSxTMTIsVzIsTjQiXQ==) Bitstring: ``` 000110000111010100000001000100000101011110110001100110111110111101111011001110011001001000011101100001111110011101110101110100100100110111110011000000010110101101110001011010011010000010011111100110010101010011010000110000010100000110001000100010100110010101010000110101110111100001000011001100000001110101110111000000101111101011000110101100100110111100111111000101110011110111110101001011 ``` ``` ‚åê‚åä‚Ä∫?«çf`NESW`kd‚àö:¬£ƒø:·πÖ¬•`^>v<`ƒøfW‚à©v«î·π´‚ÅΩ‚Äπ·∫áwJ:tt\X1"pwJ‚üë√∑√∏‚à߬≠‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å™‚Äè‚ņ‚Å™‚Å™‚ņ‚Å™‚Å™‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚ŧ‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å£‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚Å¢‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å°‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å°‚Å™‚Äè‚ņ‚Å™‚Å™‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å¢‚ŧ‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚Å£‚ŧ‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚Å£‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å¢‚ŧ‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å°‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å°‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å°‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å°‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å¢‚Å£‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚Å£‚ŧ‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å¢‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å£‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å£‚Å¢‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚ŧ‚Å°‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å£‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚Å£‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å°‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å¢‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚ŧ‚Å¢‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚ŧ‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚Å£‚ŧ‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å°‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå‚ŧ‚Å£‚Äã‚Äé‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å°‚Å¢‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å°‚Å£‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å°‚ŧ‚Å™‚Äè‚ņ‚Äé‚Å™‚Å°‚Å™‚ņ‚Å™‚ŧ‚Å¢‚Å°‚Å™‚Äè‚Äè‚Äã‚Å°‚ņ‚Å°‚Äå¬≠ ‚åê‚åä‚Ä∫ # ‚Äé‚Å°split by comma, get number part, increment ?«çf # ‚Äé‚Å¢get directions and flatten `NESW` # ‚Äé‚Å£Directions kd‚àö # ‚Äé‚ŧ"02468" :¬£ # ‚Äé‚Å¢‚Å°duplicate and push to register ƒø # ‚Äé‚Å¢‚Å¢transliterate directions to corresponding canvas numbers :·πÖ¬• # ‚Äé‚Å¢‚Å£duplicate, join by nothing, push register `^>v<`ƒø # ‚Äé‚Å¢‚ŧTransliterate each direction to corresponding arrow text fW‚à© # ‚Äé‚Å£‚Å°flatten, wrap the stack and transpose v«î # ‚Äé‚Å£‚Å¢‚Äé‚Å£‚ŧrotate each sublist to order [text, length, direction] for canvas ·π´‚ÅΩ‚Äπ·∫áwJ # ‚Äé‚Å£‚Å£decrement the middle of the last triplet :tt # ‚Äé‚Å£‚ŧget the very last direction \X1" # ‚Äé‚ŧ‚Å°["X", 1] pwJ # ‚Äé‚ŧ‚Å¢prepend it to the direction and put it back (Draws the X) ‚üë√∑√∏‚àß # ‚Äé‚ŧ‚Å£draw each triplet to the canvas üíé ``` Created with the help of [Luminespire](https://vyxal.github.io/Luminespire). [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~37~~ 35 (or ~~42~~ 38) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) **38 bytes:** Input as comma-separated string, as mentioned in the challenge description: ``` ',¬°Œµƒá"NESW"skxs"^>v<"√®)}√∏R`ƒÅ¬§√ä+≈†Œõ1'X0Œõ ``` [Try it online.](https://tio.run/##yy9OTMpM/f9fXefQwnNbj7Qr@bkGhysVZ1cUK8XZldkoHV6hWXt4R1DCkcZDSw53aR9dcG62oXqEwbnZ///7GRrpuBoa6gQD6XAjHT8TAA) **35 bytes:** Input as a list of pairs of direction-character and distant-integer, by removing the first three bytes `',¬°`: [Try it online.](https://tio.run/##yy9OTMpM/f//3NYj7Up@rsHhSsXZFcVKcXZlNkqHV2jWHt4RlHCk8dCSw13aRxecm22oHmFwbvb//9HRSn5KOoZGsTrRSq5AhiGIEQwTCVfSAdNAJSaxsQA) **Explanation (of the strict I/O program):** ``` ',¬° '# Split the (implicit) input-string on commas Œµ # Map over each string: ƒá # Extract its head; push distant and direction-char separately "NESW"sk # Get the 0-based index of the character in "NESW" x # Double it (without popping) s # Swap so the index is at the top again "^>v<"√® # Convert the index to the correct output character ) # Wrap all three values into a list }√∏ # After the map: zip/transpose the list of triplets; swapping rows/columns R # Reverse the list of triplets ` # Pop and push all three lists separately to the stack ƒÅ # Push a list in the range [1,length] ¬§ # Push its last item (without popping the list) √ä # Check for each that it's NOT equal to this last item + # Add the values at the same positions # (so 1 is added to all distances, except the last one) ≈† # Triple-swap the three lists on the stack Œõ # Canvas builtin with these three arguments # (which is output immediately) 1'X0Œõ '# And another Canvas builtin with arguments 1,"X",0 # (which is done on top of the other Canvas and also output) ``` The Canvas builtin `Œõ` takes three arguments: 1. Length(s): which are the modified distances (+1 for every distance except the last one, since the Canvas builtin draws with overlapping corners) 2. The characters we want to display 3. The directions to draw in, which is in this case is \$0\$=North; \$2\$=South; \$4\$=South; \$6\$=West. For example: input `E2,N4,E5,S2,W1,S3` will for `',¬°Œµƒá"NESW"skxs"^>v<"√®)}√∏R`ƒÅ¬§√ä+≈†` result in the three lists: 1. Lengths: `[3,5,6,3,2,3]` 2. Characters: `[">","^",">","v","<","v"]` 3. Directions: `[2,0,2,4,6,4]` And will print them as: ``` >>>>>v ^ v ^ v< ^ v >>^ v ``` After which the `1'X0Œõ` will overwrite the final `v` with `X`. [See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.](https://codegolf.stackexchange.com/a/175520/52210) ]
[Question] [ I have a crank-operated music box that can play a series of four notes. When I turn the crank, it plucks one of four strings, depending on the position of the crank and the direction of the turn. When the crank is turned due north, the box (with its strings numbered 1 through 4) looks like this: ``` 1 | 2 | O 4 3 ``` From there, I can turn the crank clockwise to pluck the #2 string and point the crank east: ``` 1 2 O--- 4 3 ``` Alternatively, I could have also turned the crank counterclockwise from north to play the #1 string and end with a crank pointing west: ``` 1 2 ---O 4 3 ``` At any given time, then, the box can play one of two notes: the next note available in the clockwise direction or the next note in the counterclockwise direction. # Challenge Your challenge is to write a program or function that accepts a non-empty string of note values (i.e., numerals `1` through `4`) and determine if it is ever possible to play that sequence of notes on the music box. Produce a truthy or falsy result to indicate the playability or non-playability of the input. Some notes: * The input makes no assumptions about initial start position. The inputs `214` (starting east and moving strictly counterclockwise) and `234` (starting north and moving strictly clockwise) and both valid. * The crank may move freely in either direction after each note. A series of the same note is possible (e.g., `33333`) by moving back and forth across one string. The series `1221441` is perfectly playable (starting west, moving clockwise two steps, then counterclockwise three steps, then clockwise two steps). # Samples Some `true` cases: ``` 1 1234 1221 3333 143332 22234 2234 22214 1221441 41233 ``` Some `false` cases: ``` 13 (note 3 is never available after note 1) 1224 (after `122`, the crank must be north, so 4 is not playable) 121 (after `12` the crank is east; 1 is not playable) 12221 (as above, after `1222` the crank is east) 43221 ``` [Answer] ## CJam, ~~34~~ 31 bytes ``` 8,q{~2*f{_@-_zF8b&,@@+8,=*}0-}/ ``` Did this on my phone, so I'll have to put up an explanation later. Output is nonempty iff truthy. [Try it online](http://cjam.aditsu.net/#code=8%2Cq%7B%7E2*f%7B_%40-_zF8b%26%2C%40%40%2B8%2C%3D*%7D0-%7D%2F&input=143332) | [Test suite](http://cjam.aditsu.net/#code=qN%2F%7B%0A%0A8%2C%5C%7B%7E2*f%7B_%40-_zF8b%26%2C%40%40%2B8%2C%3D*%7D0-%7D%2F%0A%0A%7D%25N*&input=1%0A1234%0A1221%0A3333%0A143332%0A22234%0A2234%0A22214%0A1221441%0A41233%0A234123412341234%0A13%0A1224%0A121%0A12221%0A43221) ### Explanation The new code shifts the layout a little: ``` 2 3 4 1 . 5 0/8 7 6 ``` Even numbers correspond to string positions and odd numbers correspond to crank positions. Here's what happens: ``` 8, Create the range [0 1 .. 7] of possible starting positions We can leave the string positions [0 2 4 6] in since it doesn't matter q{ ... }/ For each character in the input... ~2* Evaluate as integer and double, mapping "1234" -> [2 4 6 8] f{ ... } Map over our possible current crank positions with the string position as an extra parameter _@- Calculate (string - crank), giving some number in [-7 ... 7] _z Duplicate and absolute value F8b Push 15 base 8, or [1 7] &, Setwise intersection and get length. If (string - crank) was in [-7 -1 1 7] then the move was valid and this evaluates to 1, otherwise 0 @@+ Calculate ((string - crank) + string) 8,= Take modulo 8, giving the new crank position. x%y in Java matches the sign of x, so we need to do ,= (range + index) to get a number in [0 .. 7] * Multiply the new crank position by our previous 0 or 1 0- Remove all 0s, which correspond to invalid positions ``` The stack is then automatically printed at the end. Any possible ending positions will be in the output, e.g. for the input `1` the output is `31`, which means the crank can end facing either left or up. If only CJam had filter with extra parameter... --- Edit: Temporarily rolling back while I convince myself that this 29-byte works: ``` 8,q{~2*f{_@-_7b1#@@+8,=|}W-}/ ``` [Answer] # Pyth, ~~30~~ 27 bytes ``` f!-aVJ.u%-ysYN8zTtJ,1 7cR2T ``` Here's the idea: ``` 1.5 1 0.5 2 0 2.5 3 3.5 ``` The crank is always at a half-integer position `c`. At each step, we reflect it over an integer position note `n` by setting `c = 2*n-c`. If `n` is valid, `c` changes by ±1 mod 8. If `n` is invalid, `c` changes by ±3 mod 8. We cumulatively reduce over the input to collect all values of `c`, and then see if all notes were valid. We do this for every starting value of `c`, because it's shorter than checking just the ones adjacent to the first note. Formatted: ``` f ! - aV J .u % - y s Y N 8 z T t J , 1 7 cR2 T ``` [Test suite](https://pyth.herokuapp.com/?code=f%21-aVJ.u%25-ysYN8zTtJ%2C1+7cR2T&input=1144432&test_suite=1&test_suite_input=1234123412341234%0A1%0A1234%0A1221%0A3333%0A143332%0A22234%0A2234%0A22214%0A1221441%0A41233%0A13%0A1224%0A121%0A12221%0A43221). [Answer] ## Haskell, ~~93 88~~ 87 bytes ``` any(all(\(a,b:c)->1>mod(a!!1-b)4).(zip=<<tail)).mapM((\a->[[a,a+1],[a+1,a]]).read.pure) ``` This evaluates to an anonymous function that takes a string and returns a boolean. [Test suite here.](http://ideone.com/mVASck) ## Explanation The idea is that the lambda on the right maps a number `a` to `[[a,a+1],[a+1,a]]`, the two possible "moves" that take the crank over that number, according to the following diagram: ``` 1 (2) 2 (1/5) (3) 4 (4) 3 ``` In the main anonymous function, we first do `mapM((...).read.pure)`, which converts each character to an integer, applies the above lambda to it, and chooses one of the two moves, returning the list of all resulting move sequences. Then, we check if any of these sequences has the property that the second number of each move equals the first number of the next modulo 4, which means that it's a physically possible sequence. To do this, we `zip` each move sequence with its `tail`, check the condition for `all` the pairs, and see if `any` sequence evaluates to `True`. [Answer] # Retina, 50 bytes ``` A`13|31|24|42|(.)(?!\1)(.)(\2\2)*(\1|\2(?!\1|\2).) ``` I think this works? [Try it here.](http://retina.tryitonline.net/#code=QWAxM3wzMXwyNHw0MnwoLikoPyFcMSkoLikoXDJcMikqKFwxfFwyKD8hXDF8XDIpLik&input=MQoxMjM0CjEyMjEKMzMzMwoxNDMzMzIKMjIyMzQKMjIzNAoyMjIxNAoxMjIxNDQxCjQxMjMzCgoxMwoxMjI0CjEyMQoxMjIyMQo0MzIyMQ&debug=on) [Answer] ## [Retina](https://github.com/mbuettner/retina/), ~~127~~ 109 bytes ``` ^((1|2)|(2|3)|(3|4)|(4|1))((?<2-5>1)|(?<5-2>1)|(?<3-2>2)|(?<2-3>2)|(?<4-3>3)|(?<3-4>3)|(?<5-4>4)|(?<4-5>4))*$ ``` This prints `0` or `1`, accordingly. [Try it online!](http://retina.tryitonline.net/#code=bWBeKCgxfDIpfCgyfDMpfCgzfDQpfCg0fDEpKSgoPzwyLTU-MSl8KD88NS0yPjEpfCg_PDMtMj4yKXwoPzwyLTM-Mil8KD88NC0zPjMpfCg_PDMtND4zKXwoPzw1LTQ-NCl8KD88NC01PjQpKSokCjokMDo&input=MQoxMjM0CjEyMjEKMzMzMwoxNDMzMzIKMjIyMzQKMjIzNAoyMjIxNAoxMjIxNDQxCjQxMjMzCgoxMwoxMjI0CjEyMQoxMjIyMQo0MzIyMQ) (This is a slightly modified version which marks all matches in the input instead of printing `0` or `1`.) I tried coming up with an elegant algorithm, but my first few attempts weren't able to circumvent backtracking... and implementing backtracking is annoying... so I used a language which does the backtracking for me where I just need to encode a valid solution. Unfortunately, the encoding is fairly verbose and fairly redundant... I'm sure this can be shortened. While I try to figure out something neater, if anyone wants to sort out how this works, here is a somewhat more readable version: ``` ^ ( (?<a>1|2) | (?<b>2|3) | (?<c>3|4) | (?<d>4|1) ) ( (?<a-d>1) | (?<d-a>1) | (?<b-a>2) | (?<a-b>2) | (?<c-b>3) | (?<b-c>3) | (?<d-c>4) | (?<c-d>4) )* $ ``` And here is a hint: ``` 1 a 2 d O b 4 c 3 ``` [Answer] # [MATL](https://esolangs.org/wiki/MATL), ~~57~~ 55 bytes ``` 1t_hjnZ^!t1tL3$)2_/wvG1)UGnl2$Ov+Ys.5tv3X53$Y+4X\G!U=Aa ``` This uses [current release (10.2.1)](https://github.com/lmendo/MATL/releases/tag/10.2.1), which is earlier than this challenge. *EDIT (17 January, 2017): due to changes in the language, `v`* needs *to be replaced by `&v`, and `tL3$)` by `Y)` (in addition, some other improvements* could *be done). The following link includes those two modifications* [**Try it online!**](https://tio.run/nexus/matl#@29YEp@RlRcVp1hiGKlpFK9fXuZuqBnqnpdjpOKvVqYdWaxnWqJWZhxhaqwSqW0SEeOuGGrrmPj/v6GRkaGJiSEA) ### Explanation This is based on two of my favourite tools for code golf: *brute force* and *convolution*. The code defines the *path* followed by the crank in terms of coordinates `0.5`, `1.5` etc. Each number tells the position of the crank between notes. The code first builds a *path array* with all possible paths that start with the first note of the input string. Each path is a column in this array. This is the *brute force* component. From this path array, a *note array* is obtained, where each column is a realizable sequence of played notes. For example, movement from position `0.5` to `1.5` produces a note `1`. This consists in taking the average between positions and then applying a modulo 4 operation. The running average along each column is done with a 2D *convolution*. Finally, the program checks if any column of the note array coincides with the input. ``` 1t_h % row array [1, -1] j % input string nZ^! % Cartesian power of [1, -1] raised to N, where "N" is length of string t % duplicate 1tL3$) % extract first row 2_/ % divide by -2 wv % attach that modified row to the top of Cartesian power array G1)U % first character of input string converted to number, "x" Gnl2$O % column array of N-1 zeros, where N is length of input v % concat vertically into column array [x;0;0...;0] + % add with singleton expansion Ys % cumulative sum along each column. Each column if this array is a path .5tv % column array [.5;.5] 3X5 % predefined string 'same' (for convolution) 3$Y+ % 2D convolution of path array with [.5;.5] 4X\ % modified modulo operation. This gives note array with values 1,2,3,4 G!U % column array of input string characters converted to numbers =Aa % true if any column of the note array equals this ``` [Answer] # Pyth, 43 ``` Km-R2sMdc`M%R4-VJjQTtJ`0|Fm!s-VKdCm_B^_1dlK ``` [Test Suite](http://pyth.herokuapp.com/?code=Km-R2sMdc%60M%25R4-VJjQTtJ%600%7CFm%21s-VKdCm_B%5E_1dlK&input=1221&test_suite=1&test_suite_input=1%0A1234%0A1221%0A3333%0A143332%0A22234%0A2234%0A22214%0A1221441%0A41233%0A13%0A1224%0A121%0A12221%0A43221&debug=0) This is probably very golfable, and also not the optimal algorithm for golfing (I expect enumerating all paths will be shorter?)... Anyway, if you find any error with the algorithm please let me know, I think it should work but I've been wrong before! I'll explain my algorithm using the example input of `1221`. This program first maps the digits against their successors, like so: `[[1,2],[2,2],[2,1]]`. Then it gets their differences mod `4` (Pyth gets the result that matches the sign of the right argument of `%`, so this is always positive) : `[3,0,1]`. Then the results are split on `0` and have `2` subtracted from each of them: `[[1],[-1]]`. Now that the setup is done, we create a list of `[-1,1,-1...]` and its negation `[1,-1,...]`, both the same length as the resulting array from before. Then, for each of these lists, perform setwise subtraction between the elements of the list and the list generated in the earlier step. Then, if either of the results contains only empty lists, we output true. [Answer] # Matlab, ~~279~~ 180 bytes ``` o=eye(4);a=input('')-'0';M=[o,o(:,[4,1:3]);o(:,[2:4,1:4,1])];x=2;for p=[a(1),mod(a(1),4)+1];for k=a;i=find(M*[o(:,k);o(:,p)]>1);if i;p=mod(i-1,4)+1;else;x=x-1;break;end;end;end;x>0 ``` Quite a lazy solution, but the shortest I was able to come up with. I created special matrix: When you encode the state of the plucker and the last string that is to be plucked, it returns a vector, that encodes the new position of the plucker, and whether the previous *pluck* was possible at all. Now we just loop over all notes from the two possible start positions and see if one of them results in a playable melody. Can probably be golfed a lot more. Expanded and explained source: ``` o=eye(4); a=input('')-'0'; % encoding of plucker/notes % 1 % 1 2 %4 2 % 4 3 % 3 % M=[... %12 3 4 1 2 3 4 < 1,0,0,0,0,1,0,0; %1 k = current note 0,1,0,0,0,0,1,0; %2 0,0,1,0,0,0,0,1; %3 0,0,0,1,1,0,0,0; %4 0,0,0,1,0,0,0,1; %1 p = current position of plucker 1,0,0,0,1,0,0,0; %2 0,1,0,0,0,1,0,0; %3 0,0,1,0,0,0,1,0];%4 % the vector we multiply with this matrix has following structure, % the k-th and the p+4 th entries are 1, the rest 0 % when we multiply this vecotr with this matrix, we get a vector with an % entry of value 2 IF this is a valid move ( mod(positionOfThe2 -1,4)+1 is % the position of the plucker now) % or only entries less than 2 it is impossible x=2; %number of "chances" to get it right for p=[a(1),mod(a(1),4)+1] %check both starting values; for k=a; %loop throu the notes size(M); c = M * [o(:,k);o(:,p)]; i=find(c>1); %did we find a 2? if i; p=mod(i-1,4)+1; %if yes, valid move else; x=x-1; %if no, invalid, break; end end end x=x>0 %if we failed more than once, it is not possible ``` [Answer] ## ES6, ~~104~~ 100 bytes ``` s=>!/13|24|31|42|3[24]{2}1|4[13]{2}2|1[24]{2}3|2[13]{2}4|(.).\1/.test(s.replace(/(.)(\1\1)+/g,"$1")) ``` Edit: Saved 4 bytes thanks to @DigitalTrauma. This is a complete rewrite as my previous approach was flawed. I start by reducing all runs of digits to 1 or 2 depending on whether there was an odd or even number in the run. I then look for all the illegal combinations: * `13|24|31|42` (opposite sides) * `3[24]{2}1` as `3221` and `3441` are illegal * similarly for `4xx2`, `1xx3` and `2xx4` where `x` is either of the missing digits * `(.).\1` as things like `121` are illegal (`111` has been reduced to `1` earlier) If there are no illegal pairs or "triples" then the whole string is legal (proof by induction is left as an exercise because it's late night here). I tried to simplify `3[24]{2}1|1[24]{2}3` using a negative lookahead assertion but it turned out to be longer that way. [Answer] # JavaScript (ES6), 80 bytes ``` s=>[r=0,1,2,3].map(i=>[...s].map(n=>n-1-i%4?n%4-i%4?v=0:i+=3:i++,v=1)|v?r=1:0)|r ``` ## Explanation `i%4` is the current crank position: ``` 1 (i%4 == 1) 2 (i%4 == 0) (i%4 == 2) 4 (i%4 == 3) 3 ``` ### Indented and Commented ``` s=> [r=0,1,2,3].map(i=> // i = crank position, test for i starting at 0 to 3, r = result [...s].map(n=> // for each note n n-1-i%4? // if n is not at the position after i n%4-i%4? // if n is not at the position before i v=0 // set the result of this test to invalid :i+=3 // else i-- (+3 used because i%4 would break for negative values) :i++, // else i++ v=1 // v = result of test, initialise to 1 (valid) ) |v?r=1:0 // if the test returned true, set the result to true ) |r // return the result ``` ## Test ``` var solution = s=>[r=0,1,2,3].map(i=>[...s].map(n=>n-1-i%4?n%4-i%4?v=0:i+=3:i++,v=1)|v?r=1:0)|r ``` ``` <input type="text" value="1221441" oninput="result.textContent=solution(this.value)" /> <pre id="result"></pre> ``` [Answer] ## [Lua](http://www.lua.org/), ~~146 142 108 162 159 149 144 135 132 118~~ 113 bytes ``` z,q,s=0,0,io.read()for i in s:gmatch'.'do t=i-z if 2==math.abs(t)or t==q then return''end q=-t z=i end return 2>1 ``` Returns true or false given a string of numbers between 1 and 4. (Doesn't handle no data or out of range numbers. Simply tracks what the last movement was and checks if this movement is a reversal of the last movement (IE, 121 or 12221) or if the distance moving is more than possible. **EDIT 1**: Saved 6 bytes. I forgot that `if (int) then` returns true if int is non zero. Thus: ``` if t~=0 then ``` changes to: ``` if t then ``` Also saved a few bytes by restructuring. **EDIT 2**: I'm slowly figuring this out. I've been reading the documentation here: <http://www.lua.org/pil/> And one of the more useful pages there for golfing is <http://www.lua.org/pil/3.3.html> In particular, this is very helpful: > > Like control structures, all logical operators consider false and nil as false and anything else as true. > > > What this means for me is that I can go ahead and remove my declaration for q (**which was initially set to 0**) as it will be regarded as "false" until it is set. So I save a few more bytes through this. Another thing worth mentioning, though I don't use it, is if you want to swap values in Lua, [you can simply do](http://www.lua.org/pil/4.1.html) `a,b=b,a` without the need for a temporary variable. **EDIT 3** So, through some clever reconstruction as well as a new function, I've got the byte count down by 9 more. **Best Mode for Receiving Input** If you need to read in a list of numbers and do operations on them one at a time, you can use: ``` for x in string:gmatch('.') do print(x) --This is our number end ``` When compared to your alternative using string:sub, you can see the value for golf (or general use): ``` for x=1,string:len() do print(string:sub(x,x)) --This is our number end ``` **Restructure Functions or Strings** Second thing, if you have multiple declarations on one line and one of the values is a function or you have a condition in which you compare a number to the result of a function like these: ``` x,y,z=io.read(),0,0 print('test') if math.abs(x)==2 then ``` by restructuring it so the closing parenthesis are the last character in the condition or declaration, you can cut out a character like so: ``` y,z,x=0,0,io.read()print('test') --Notice no space if 2==math.abs(x)then --If we put the '2' first in the conditional statement, we can now remove a space character ``` **Return Conditions that Equate to True or False instead of 'True' or 'False'** I found a semi amusing way to cut my byte count down yet further. If you need to return true or false, you can return a statement that equates to true or false that has less characters than "true" or "false" themselves. For instance, compare: ``` return true return false ``` To: ``` return 2>1 return 1>2 ``` [Answer] # MATL, 49 bytes (non-competing1) 1. The answer (ab)uses the less strict indexing of newer versions of MATL, and would not have worked at the time this challenge was posted. ``` dt~aX`tt~f1)q:)w3MQJh)_ht~a]tT-3hX|n2=wT_3hX|n2=+ ``` [Try it online!](https://tio.run/nexus/matl#@59SUpcYkVBSUpdmqFlopVlu7BvolaEZnwEUji0J0TXOiKjJM7ItD4mHsrT//1c3MjIyNlEHAA). I saw this challenge at the [Best of PPCG 2016](http://meta.codegolf.stackexchange.com/a/11192/32352), and figured that this could use my [favourite operator](https://codegolf.stackexchange.com/a/93009/32352): ``` d ``` Or, `diff` in MATLAB/Octave (I will freely use MATLAB/Octave terminology in my explanation, since it is easier to read for humans). This command calculates the element-wise difference in a vector or, in this case, in a character array. For this problem, the differences exhibit an interesting pattern. Note that > > An change in direction **must** mean that a note is played **twice**. > > > For the difference pattern (ignoring the `1-4` transition for now), this means that > > A change in sign in `diff(input)` must have an **odd** number of zeroes in between. Conversely, the sign is not allowed to change after an **even** number of zeroes. > > > --- I implemented this by, for each array, finding the first zero. I trim the zero out, and multiply all elements after it by `-1`. For the end result, this means that all elements **must** have the same sign. Of course, there is the small issue of the `-3` equalling `+1`, and `2` being disallowed in general. I solved this by taking the set union of the result with `[1 -3]`, and checking whether this is of size 2 (i.e., no disallowed elements 'entered' the set through the union). Repeat for `[-1 3]`, and check whether either (or both, in the case of a 1-length input) is true. ``` d % Difference of input t~a % Check if any element equals 0 X` t~a] % Start while loop, ending in the same check t~ % Get a new vector, logical negated to find zeroes. f1) % Find the position of the first zero. t q:) % Decrement by 1, to index all elements before that zero. w3MQJh) % Push the result of 'find', but increment to get all elements after. _h % Multiply the second half by -1, and concatenate horizontally. T-3hX|n2= % Check if set union with [1 -3] is size 2 t wT_3hX|n2= % Check if set union with [-1 3] is size 2 + % Logical OR. ``` [Answer] ## Python (3.5) ~~160~~ ~~151~~ 150 bytes A recursive solution ``` def f(s):g=lambda s,c:s==''or g(s[1:],(c[:4]*2)[(s[0]==c[0])*2+1:])if s==''or s[0]in c[:2]else 0;return any([g(s,"1234123"[i:])for i in range(4)]) ``` ## Ungolfed without lambda ``` def f(s): def g(s,c): if s=='' or s[0] in c[:2] : return s=='' or g(s[1:],(c[:4]*2)[(s[0]==c[0])*2+1:]) else: return False return any([g(s,"1234123"[i:]) for i in range(4)]) ``` I rotate all the box instead of the crank. The crank position is between first and second character of the c string. I need to test all beginning position of the crank. **Trick use to rotate the string** The usual way to rotate a string in python (`s[i:]+s[:i]`) need too repeat both index and string. In this case i duplicate the string and crop first characters. ``` (c*2) # duplicate the string [(s[0]==c[0])*2+1 # test that return 1 if firsts characters match 3 instead :] [:4] # crop again to have a 4 characters string ``` ## Test cases ``` [f(i) for i in ["1", "1234", "1221", "3333", "143332", "22234", "2234", "22214", "1221441", "41233", "13", "1224", "121", "12221", "43221"]] [True, True, True, True, True, True, True, True, True, True, False, False, False, False, False] ``` [Answer] # [Python 2](https://docs.python.org/2/), 65 bytes ``` n=15 for c in input():k=2**int(c);n=n*17/k%4*5/2%4*k%15 print n>0 ``` [Try it online!](https://tio.run/##PUzRCoMwDHz3K0pB1L64pJGBw/1McVg6okhl29d3qWULIZfL5W77xGVlTK/FP2cF4/yendY68QRD9Vh35ZRn6e2IbTeGCY3xHFvX3XhiA9c@1GSGHmWGWizbLrLi@yXllAaaqgG0dAJmZqUyI0GUBbHIf0D4fRNlA4n/dNhyLmoJLpFkM34B "Python 2 – Try It Online") [Answer] # JavaScript (ES2015), ~~110~~ 95 ``` p=(s,d)=>(h=s[0],t=s.slice(1),g=t[0],!g||(d?g==h?p(t,-d):g%4==(h-d)%4&&p(t,d):p(s,1)||p(s,-1))) ``` 15 bytes saved by Neil! Original version ungolfed: ``` p = (s, d) => { h = s[0] t = s.substr(1) if (!t[0]) return true if (!d) return p(s, 1) || p(s, -1) if (t[0] == h) return p(t, d*-1) if (t[0] == (h-d > 4 ? 1 : h-d || 4)) return p(t, d) return false } ``` Tests: <https://jsbin.com/cuqicajuko/1/edit?js,console> [Answer] # Turing machine code, 395 bytes ``` 0 1 _ r a 0 2 _ r b 0 3 _ r c 0 4 _ r d a 1 _ r a a 2 _ r E a 3 _ r h a 4 _ r S b 1 _ r W b 2 _ r b b 3 _ r S b 4 _ r h c 1 _ r h c 2 _ r N c 3 _ r c c 4 _ r W d 1 _ r N d 2 _ r h d 3 _ r E d 4 _ r d N 1 _ r W N 2 _ r E N _ _ r r N * _ r h E 2 _ r N E 3 _ r S E _ _ r r E * _ r h S 3 _ r E S 4 _ r W S _ _ r r S * _ r h W 4 _ r S W 1 _ r N W _ _ r r W * _ r h h _ 0 r halt h * _ r h r _ 1 r halt ``` [Try it online!](http://morphett.info/turing/turing.html?309be59421d8b5cbd36fdcfc3b2a4d2d) This is basically a state-based approach: * The initial state is 0. * `a`, `b`, `c`, and `d` are "undecided states" that only occur at the beginning * `N`, `E`, `S`, and `W` are the "decided states", obviously standing for `N`orth, `E`ast, `S`outh, and `W`est. [Answer] # Thue, 203 bytes I can't think of how to golf this farther. ``` 0::=::: >11::=>1 >22::=>2 >33::=>3 >44::=>4 >12::=b >21::=d >14::=c >41::=a >23::=c >32::=a >34::=d >43::=b a1::=d a2::=b b2::=a b3::=c c3::=b c4::=d d4::=c d1::=a a<::=~n b<::=~e c<::=~s d<::=~w ::= >0< ``` If the note sequence is possible, will output ending direction, otherwise the output will be empty. [Answer] # [Prolog (SWI)](http://www.swi-prolog.org), 117 bytes ``` a(N,P):-P=N;N=1,P=4,!;P is N-1. m([A,B|C],[X,Y|Z]):-a(A,X),a(B,X),a(B,Y),X\=Y,m([B|C],[Y|Z]). m([_],_). p(N):-m(N,_). ``` Defines a predicate `p` that succeeds on playable inputs (given as a list of integers) and fails on unplayable ones. [Try it online!](https://tio.run/nexus/prolog-swi#NYuxCsIwGIT3PkXc/sClEO1kCNI6dQkZU2soGTp0qBYriNB3jyEqN9wdfF8MZGD5UVhtlNESVlfYKcumlRkhy2KmvkaznT16h267@MQGquE4AjX/6jjcVXdI9JfNZLYHjyGthdpkztTmV5wEW6iXqHDI2XsO9npMz5He48rVb9/uvIzxAw "Prolog (SWI) – TIO Nexus") ### Explanation `a` defines an adjacency relation between note `N` and crank position `P`. We define position *p* to be between notes *p* and *p+1*. Thus, a position is adjacent to note `N` iff * it equals `N` (`P=N`); **or** * the note is 1 and the position is 4 (`N=1,P=4`); **or** * the above case is not true (`!`) and the position equals `N-1` (`P is N-1`). `m` takes a list of notes and tries to generate a list of positions that will play those notes. `A` is the note just played, `B` is the note about to be played; `X` is the current crank position, `Y` is the next crank position. A move is valid iff * the note just played is adjacent to the current crank position (`a(A,X)`); * the note about to be played is also adjacent to the current crank position (`a(B,X)`); * the note about to be played is adjacent to the next crank position (`a(B,Y)`); and * the two crank positions are not equal (`X\=Y`). If all of these hold, recurse. If we successfully get down to any one note (`m([_],_)`), the sequence of notes is playable. For this question, we only care whether a sequence of moves exists, so we define `p` to call `m` and discard the generated list of crank positions. See an ungolfed version and verify all test cases [here](https://tio.run/nexus/prolog-swi#dVLJTsMwEL37K6aVEKnkRspyKqo4cOJAxYFbiCo3cUkgsavYbYnUfy9esjhQlIP9lnkztnMl@SfJKJPehkuKX7lYwGoJal1rAt2WNVgH2NhiDDMf4O6toDCDmhImIOfsXoJsWiCsBS4L2kBO9yUrZcmVTvZSMTWRWVGyD5BFKYCz/7qpFZRBc8vARydSlfkLP1Hr2tBz79b7vuhvFHa4seYW3cWY872vLfLRoSKtlzwdm0Z5ledbXrRbpDgZe1/0YCI1I4yDukXuoBhs6CRsGtT33aZ42wGyq@zZxWK1NKoBRkdZQbMv75kdjtIMcW5KSTts25nynrDyHFoq5gqy6mGgGLeMj0hVGb/wEgSQBCk2Cw5xhOMRhLhTImy@XoktxKElQmMdKv8AFfMrVSXEfbbamIKob2X1aFoWufVOWODy4ZgZTcd3M3Uq0u@AHtVfNdyEXdQF7XmjWK@m9Y42lsaD6L7Gwr9efwA). ]
[Question] [ The "prime ant" is an obstinate animal that navigates the integers and divides them until there are only primes left! --- Initially, we have an infinite array A containing all the integers >= 2 : `[2,3,4,5,6,.. ]` Let `p` be the position of the ant on the array. Initially, `p = 0` (array is 0-indexed) Each turn, the ant will move as follows: * if `A[p]` is prime, the ant moves to the next position : `p ← p+1` * else, if `A[p]` is a composite number, let `q` be its smaller divisor > 1. We divide `A[p]` by `q`, and we add `q` to `A[p-1]`. The ant moves to the previous position: `p ← p-1` Here are the first moves for the ant: ``` 2 3 4 5 6 7 8 9 ... ^ 2 3 4 5 6 7 8 9 ... ^ 2 3 4 5 6 7 8 9 ... ^ 2 5 2 5 6 7 8 9 ... ^ 2 5 2 5 6 7 8 9 ... ^ 2 5 2 5 6 7 8 9 ... ^ 2 5 2 5 6 7 8 9 ... ^ 2 5 2 7 3 7 8 9 ... ^ ``` Your program should output the ant's position after `n` moves. (you can assume `n <= 10000`) Test cases: ``` 0 => 0 10 => 6 47 => 9 4734 => 274 10000 => 512 ``` **Edit.** you can also use 1-indexed lists, it's acceptable to display the results 1, 7, 10, 275, 513 for the above test case. This is code-golf, so the code with the shortest code in bytes wins. [Answer] # [Alice](https://github.com/m-ender/alice), 45 bytes ``` /o \i@/.&wqh!]k.&[&w;;?c]dt.n$k&;[.?~:![?+!kq ``` [Try it online!](https://tio.run/##S8zJTE79/18/nysm00FfT628MEMxNltPLVqt3NraPjk2pUQvTyVbzTpaz77OSjHaXlsxu/D/f0MDIAAA "Alice – Try It Online") Mostly straightforward implementation. Looping `n` times in Alice is typically done by pushing a return address `n-1` times, then returning at the end of each iteration with `k`. The last time through the loop, the `k` instruction has nowhere to return to, and execution proceeds forward. This program uses the same `k` instruction to stop early when the number is prime. As a result, the final iteration will always move the ant left. To compensate for this bug, we do `n+1` iterations on a 1-indexed array, which gives exactly the result we want (and gives the case `n=0` for free). [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes ``` p=0 A=range(2,input()+2) for _ in A: for q in range(2,A[p]): if A[p]%q<1:A[p]/=q;p-=1;A[p]+=q;break else:p+=1 print p ``` [Try it online!](https://tio.run/##NcpBCsIwEEDRtXOK2QgNsWiCIKTOIucQkQqpBst0ksaFp49m4e4/@PIpz4VtrUIH8JRHfoTO7iLLu3RKWwXTkvGGkdE7wIbU8B/9Ra7KwSZO2HKbzsa12FMapCczNOgf7jmML8Awr8GJJgOSIxeUWo@nLw "Python 2 – Try It Online") Ah, the rare `for`–`else` loop! The `else` clause only executes if the `for` body is *not* exited via `break`. In our case, this means we checked all `q`s and found none of them to divide `p`. [Answer] # [Octave](https://www.gnu.org/software/octave/), ~~109 103 101~~ 94 bytes ``` function i=a(n)i=1;for l=z=2:n+1 if nnz(q=factor(z(i)))>1 z(i--)/=p=q(1);z(i--)+=p;end i++;end ``` [Try it online!](https://tio.run/##NY5Bq8IwEITv/RVzkSYUlaogWOL9XXwX/0BINhiIu9qmPu2f74uIh2X3G2aZEZftg@Y5jOxyFEY0VrGOpu2C9EhmMpsDN20VA5gndTfBuiy9mlTUWh/bqhzLpV6bm7mrVncfbMytI/ZVbJr3nst0sGq33@40FifJdEBdxBpxgHB6gYk8ebxDzz@/sAOceCqckvwNK5ykv9pUjC8Za4@htEa@FMO3ePmwCDERLHvQk9yYaTX/Aw "Octave – Try It Online") This code will output the position in 1-indexing, so outputs for test cases are: ``` 0 => 1 10 => 7 47 => 10 4734 => 275 10000 => 513 ``` --- This version uses some Octave optimisations so isn't compatible with MATLAB. The code below is a MATLAB compatible version. --- # MATLAB, ~~130 123 118~~ 117 bytes ``` function i=a(n) z=2:n+1;i=1;for l=z q=factor(z(i));if nnz(q)>1 z(i)=z(i)/q(1);i=i-1;z(i)=z(i)+q(1);else i=i+1;end end ``` Uses 1-indexing as with the Octave version. I've tested it against all test cases in MATLAB. As an example the output at 100000 is 3675 (one-indexing). An commented version of the above code: ``` function i=a(n) z=2:n+1; %Create our field of numbers i=1; %Start of at index of 1 (MATLAB uses 1-indexing) for l=1:n %For the required number of iterations q=factor(z(i)); %Calculate the prime factors of the current element if nnz(q)>1 %If there are more than one, then not prime z(i)=z(i)/q(1); %So divide current by the minimum i=i-1; %Move back a step z(i)=z(i)+q(1); %And add on the minimum to the previous. else i=i+1; %Otherwise we move to the next step end end ``` --- As a matter of interest, this is the ants positions vs number of iterations for the first 10000 values of n. [![Ant Position](https://i.stack.imgur.com/SWENk.jpg)](https://i.stack.imgur.com/SWENk.jpg) Seems likely that the Ant will probably tend to infinity, but who knows, looks can be deceiving. --- * MATLAB: Saved 6 bytes with `for` instead of `while` and removing brackets from `if` - Thanks @Giuseppe * MATLAB: Save 2 bytes - Thanks @Sanchises * Octave: Save 10 bytes by using Octave `\=` and `+=` operations - Thanks @Giuseppe * Octave: Save 2 bytes with `i++` and `i--` - Thanks @LuisMendo * Octave: Save 7 bytes - Thanks @Sanchises [Answer] # JavaScript (ES6), 91 bytes ``` f=(n,a=[p=0])=>n--?f(n,a,(P=n=>++x<n?n%x?P(n):a[a[p]/=x,--p]+=x:p++)(a[p]=a[p]||p+2,x=1)):p ``` ### Demo *NB: You may have to increase the default stack size of your engine to have it pass all test cases.* [Try it online!](https://tio.run/##bcixCsIwEADQ3f8QciTRVgtC8Npf6F4yhNpItV6ORiRC/z3SUXR5w7u5l4v9PPJTRx4vw/wIdB/eOXsUpBx2jIUFrEnrxq@jRIuEtZTpTA1tU9MKAuM617HdY1Jas5WYDEsJYk1cWRaWB5WwBDCc@0AxTMNuClfhRQGw@Z7yt6rTnzpWAPkD) [Answer] # [Haskell](https://www.haskell.org/), ~~108~~ ~~106~~ 94 bytes ``` ([0]#[2..]!!) (a:b)#(p:q)=length b:([b#(a+d:div p d:q)|d<-[2..p-1],mod p d<1]++[(p:a:b)#q])!!0 ``` [Try it online!](https://tio.run/##HUzLDoIwELz3K5bgoQRKWkSJBPyR2kOhvCJgEeJF/XVry2STmd2dmV6u92YcTVveDOZU@DyJY@F5AcIyrwIf63wJyrGZu62HKse88rEMVa6GF2hQ9vlRBXEhTZiIpody54KJMOQ2u3csIvA8aiY5zFCCfg7zBgeYpIYWOI0YjdLMzjG10kKgN0EUyitQxHY@ozRzfEHO5VSSpWg3u@XEEkS@5le3o@xWQ2qt/w "Haskell – Try It Online") Example usage: `([0]#[2..]!!) 10` yields `6` (0-indexed). The function `#` operates on two list, the reversed front of the array `[p-1, p-2, ..., 1]` and the infinite rest of the array `[p, p+1, p+2, ...]`. It constructs an infinite list of positions, from which the `n`th position is returned given an input `n`. The pattern `((a:b)#(p:q))` binds `p` to the value of the current position of the ant and `a` to the value a the previous position. `b` is the prefix of the array from position 1 to `p-2` and `q` the infinite rest starting from position `p+1`. We construct a list of recursive calls in the following way: We look at each divisor `d` of `p` (which is larger than one and smaller than `p`) in ascending order and add `b#(a+d:div p d:q)` for each of them, that is the current value `p` is divided by `d` and the ant moves one step to the left where `d` is added to `a`. Then we append `(p:a:b)#q` to the end of this list, which indicates the ant moving one step to the right. We then take the first of those recursive calls from the list and prepend the current position, which coincides with the length of the prefix list `b`. Because the divisors are in ascending order, picking the first from the list of recursive calls ensures we use the smallest one. Additionally, because `(p:a:b)#q` is added to the end of the list, it is only selected if there are no divisors and `p` is thus prime. *Edits:* -2 bytes by switching the list of functions from descending to ascending order. -12 bytes thanks to Zgarb's idea to index into an infinite list instead handling a counter, and by switching to 0-indexing. [Answer] # TI-BASIC, ~~108~~ ~~103~~ ~~102~~ 98 bytes Input and output are stored in `Ans`. Output is 1-indexed. ``` Ans→N seq(X,X,2,9³→A 1→P For(I,1,N 1→X:∟A(P→V For(F,2,√(V If X and not(fPart(V/F:Then DelVar XV/F→∟A(P P-1→P F+∟A(P→∟A(P End End P+X→P End ``` [Answer] # [MATL](https://github.com/lmendo/MATL), 41 bytes ``` :Q1y"XHyw)Zp?5MQ}1MtYf1)/H(8MyfHq=*+9M]]& ``` Output is 1-based. The program times out for the last test case in the online interpreter. [**Try it online!**](https://tio.run/##y00syfn/3yrQsFIpwqOyXDOqwN7UN7DW0LckMs1QU99Dw8K3Ms2j0FZL29I3Nlbt/38Tc2MTAA "MATL – Try It Online") ### Explanation The program applies the procedure as described in the challenge. To do so, it makes unusually heavy use of MATL's manual and automatic clipboards. The smallest divisor is obtained as the first entry in the prime factor decomposition. The "divide" update is done by overwriting the corresponding entry of array *A*. The "add" update is done by element-wise adding to *A* an array that contains zeros except at the desired position. ``` :Q % Implicitly input n. Push array [2 3 ... n+1]. This is the initial array A. % It contains all required positions. Some values will be overwritten 1 % Push 1. This is the initial value for p y % Duplicate from below " % For each loop. This executes the following n times. % STACK (contents whosn bottom to top): A, p XH % Copy p into clipboard H y % Duplicate from below. STACK: A, p, A w % Swap. STACK: A, A, p ) % Reference indexing. STACK: A, A[p] Zp % Isprime. STACK: A, false/true ? % If true (that is, if A[p] is prime) 5M % Push p from automatic clipboard. STACK: A, p Q % Add 1. STACK: A, p+1 } % Else (that is, if A[p] is not prime) 1M % Push A[p] from automatic clipboard. STACK: A, A[p] t % Duplicate. STACK: A, A[p], A[p] Yf % Prime factors, with repetitions. STACK: A, A[p], prime factors of A[p] 1) % Get first element, d. STACK: A, A[p], d / % Divide. STACK: A, A[p]/d H % Push p from clipboard H. STACK: A, A[p]/d, p ( % Assignment indexing: write value. STACK: A with A[p] updated 8M % Push d from automatic clipboard. y % Duplicate from below. STACK: A with A[p] updated, d, A with A[p] updated f % Find: push indices of nonzero entries. % STACK: A with A[p] updated, d, [1 2 ... n] Hq % Push p from clipboard H, subtract 1. % STACK: A with A[p] updated, d, [1 2 ... n], p-1 = % Test for equality, element-wise. % STACK: A with A[p] updated, d, [0 ... 0 1 0 ... 0] * % Multiply, element-wise. STACK: A with A[p] updated, [0 ... 0 d 0 ... 0] + % Add, element-wise. STACK: A with A[p-1] and A[p] updated 9M % Push p-1 from automatic clipboard. % STACK: A with A[p-1] and A[p] updated, p-1 ] % End if. The stack contains the updated array and index ] % End for each. Process the next iteration & % Specify that the following implicit display function should display only % the top of the stack. Implicitly display ``` [Answer] # PARI/GP, 87 bytes ``` f(n)=A=[2..9^5];p=1;for(i=1,n,q=factor(A[p])[1,1];if(A[p]-q,A[p]/=q;p--;A[p]+=q,p++));p ``` Pretty self-explanatory (not so golf-ish). If you do not count the `f(n)=` part, that is 82 bytes. You can also start by `n->` (85 bytes). It is a 1-indexed language. --- **Edit:** The modification `illustrate(n,m)=A=[2..m+1];p=1;for(i=1,n,for(j=1,m,printf("%5s",if(j==p,Str(">",A[j],"<"),Str(A[j]," "))));print();q=factor(A[p])[1,1];if(A[p]!=q,A[p]/=q;p--;A[p]+=q,p++))` will print an illustration of the ant's walk (given a wide enough terminal). For example `illustrate(150,25)` will give the first 150 steps on 25 columns, like this: ``` >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 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 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 2 >5< 2 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 >2< 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 >5< 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 5 >6< 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 >7< 3 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 7 >3< 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 7 3 >7< 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 7 3 7 >8< 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 7 3 >9< 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 7 >6< 3 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 2 >9< 3 3 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 >5< 3 3 3 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 >3< 3 3 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 >3< 3 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 >3< 4 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 3 >4< 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 >5< 2 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 >2< 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 2 >9< 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 >5< 3 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 >3< 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 3 >10< 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 >5< 5 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 >5< 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 5 >11< 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 5 11 >12< 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 5 >13< 6 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 5 13 >6< 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 5 >15< 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 5 >8< 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 >7< 4 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 7 >4< 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 5 >9< 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 5 >8< 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 >7< 4 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 7 >4< 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 3 >9< 2 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 3 >6< 3 2 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 >5< 3 3 2 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 >3< 3 2 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 >3< 2 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 >2< 3 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 >3< 2 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 >2< 5 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 >5< 3 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 5 >3< 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 5 3 >13< 14 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 5 3 13 >14< 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 5 3 >15< 7 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 5 >6< 5 7 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 >7< 3 5 7 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 >3< 5 7 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 >5< 7 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 5 >7< 15 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 5 7 >15< 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 5 >10< 5 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 >7< 5 5 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 >5< 5 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 5 >5< 16 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 5 5 >16< 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 5 >7< 8 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 5 7 >8< 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 5 >9< 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 7 >8< 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 3 >9< 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 7 >6< 3 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 2 >9< 3 3 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 >5< 3 3 3 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 >3< 3 3 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 >3< 3 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 >3< 4 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 3 >4< 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 >5< 2 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 >2< 3 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 >3< 4 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 3 >4< 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 >5< 2 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 >2< 17 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 2 >17< 18 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 2 17 >18< 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 2 >19< 9 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 2 19 >9< 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 2 >22< 3 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 5 >4< 11 3 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 >7< 2 11 3 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 >2< 11 3 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 >11< 3 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 11 >3< 19 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 11 3 >19< 20 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 11 3 19 >20< 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 11 3 >21< 10 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 11 >6< 7 10 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 >13< 3 7 10 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 13 >3< 7 10 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 13 3 >7< 10 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 13 3 7 >10< 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 13 3 >9< 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 13 >6< 3 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 2 >15< 3 3 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 >5< 5 3 3 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 >5< 3 3 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 >3< 3 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 >3< 5 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 3 >5< 21 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 3 5 >21< 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 3 >8< 7 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 >5< 4 7 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 5 >4< 7 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 >7< 2 7 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 >2< 7 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 2 >7< 22 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 2 7 >22< 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 2 >9< 11 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 >5< 3 11 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 >3< 11 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 3 >11< 23 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 3 11 >23< 24 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 3 11 23 >24< 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 3 11 >25< 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 3 >16< 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 >5< 8 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 5 >8< 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 >7< 4 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 7 >4< 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 5 >9< 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 7 >8< 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 3 >9< 4 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 5 >6< 3 4 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 >7< 3 3 4 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 >3< 3 4 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 >3< 4 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 3 >4< 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 >5< 2 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 >2< 3 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 >3< 2 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 >2< 5 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 2 >5< 12 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 2 5 >12< 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 2 >7< 6 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 2 7 >6< 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 2 >9< 3 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 >5< 3 3 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 5 >3< 3 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 5 3 >3< 25 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 5 3 3 >25< 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 5 3 >8< 5 26 2 5 5 5 3 3 2 3 5 3 3 5 2 7 5 7 3 5 2 3 5 >5< 4 5 26 ``` [Answer] # Pyth - 44 bytes Straightforward procedural implementation. ``` K}2hhQVQJ@KZIP_J=hZ).?=GhPJ XKZ/JG=tZ XZKG;Z ``` [Test Suite](http://pyth.herokuapp.com/?code=K%7D2hhQVQJ%40KZIP_J%3DhZ%29.%3F%3DGhPJ+XKZ%2FJG%3DtZ+XZKG%3BZ&test_suite=1&test_suite_input=0%0A10%0A47%0A4734%0A10000&debug=0). [Answer] # [Python 2](https://docs.python.org/2/), ~~142~~ 127 bytes * Saved fifteen bytes thanks to [Sherlock9](https://codegolf.stackexchange.com/users/47581/sherlock9). ``` T=range(2,input()+2);p=0 for _ in T: m=T[p];d=min(k for k in range(2,m+1)if m%k<1);p+=1 if d<m:T[p-1]/=d;p-=2;T[p]+=d print p ``` [Try it online!](https://tio.run/##NczBCgIhFIXhvU9xN4FiQypEMM59C3cxRGBTIjoXcRY9vemi5eHnO/Stnz2b1hyWZ36/uDmHTEflQhphCRXb9gIPCBnczCChu9NqPaaQeYTR4mh/m6QWYYN0iovuXKJm0Ldf0tzhpNcLeksTGjt@JHpGJeQK1NpVKXX7AQ "Python 2 – Try It Online") [Answer] # Mathematica, ~~118~~ 103 bytes ``` (s=Range[2,5^6];t=1;Do[If[PrimeQ@s[[t]],t++,s[[t]]/=(k=#2&@@ Divisors@s[[t]]);s[[t-1]]+=k;t--],#];t-1)& ``` [Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PYNigxLz012kjHNM4s1rrE1tDaJT/aMy06oCgzNzXQoTg6uiQ2VqdEW1sHwtS31ci2VTZSc3BQcMksyyzOLyqGKtK0BtG6hrGx2rbZ1iW6urE6ykATdQ011f4DTcsrUXBIjzY0AILY//8B "Wolfram Language (Mathematica) – Try It Online") *Martin Ender saved 15 bytes* [Answer] # [Python 3](https://docs.python.org/3/), ~~158~~ ~~149~~ 133 bytes This is a straightforward procedural implementation with one or two quirks to make sure the code works for all test cases. I use `[*range(2,n+9)]` to ensure that A is large enough (except for `n<3`, `n+9` is more than enough). The `else` clause divides the old `A[p]` by `d`, decrements `p`, and then adds `d` to the new `A[p]`, which is definitely bad coding practice. Otherwise, pretty straightforward. Golfing suggestions welcome! **Edit:** -9 bytes without `sympy` thanks to Halvard Hummel. -14 bytes from Felipe Nardi Batista, -6 bytes from some cues from [Jonathan Frech's Python 2 answer](https://codegolf.stackexchange.com/a/144712/47581) ``` p,_,*A=range(int(input())+2) for _ in A: m=A[p];d=min(k for k in range(2,m+1)if m%k<1);p+=1 if d<m:A[p-1]//=d;p-=2;A[p]+=d print(p) ``` [Try it online!](https://tio.run/##TY9hC4IwEIa/71ccQrhLo2b0RbsP/o4QMTdr2OYwg/r1tilBB@O4vXvf5@Y@032wx7kdpKIoimaX1um2pLGxN8W1nfxxr4kjJhmybhihBm2hzBkYKi@uKiQZbXkPQeuDtlqz1CQCdQdm058FFi4hwcDP8mxyb9yJar8nWbgdZUUISkgyNwaiw9lvwuqFDARLZwtc/wFO6Jfw9Xv2aMxVNjk8p5FrXKQ1T6egrKQY4vVWvVXLw4eRsZ95hc3i8AU "Python 3 – Try It Online") [Answer] # PHP, 102+1 bytes ``` for($a=range(2,$argn);$argn--;$d<$a[+$p]?$a[$p--]/=$d+!$a[$p]+=$d:$p++)for($d=1;$a[+$p]%++$d;);echo$p; ``` Run as pipe with `-R` or [try it online](http://sandbox.onlinephpfunctions.com/code/88803be4dbcb077244ae25147692b403a24ef301). Empty output for input `0`; insert `+` after `echo` for a literal `0` or use this 1-indexed version (103+1 bytes): ``` for($a=range($p=1,$argn);$argn--;$d<$a[$p]?$a[$p--]/=$d+!$a[$p]+=$d:$p++)for($d=1;$a[$p]%++$d;);echo$p; ``` [Answer] # [R](https://www.r-project.org/), 123 bytes A straightforward implementation. It is provided as a function, which takes the number of moves as input and returns the position p. It loops over the sequence and moves the pointer forth and back according to the rules. The output is 0-based. A note: in order to find the smallest prime factor of a number x, it computes the modulus of x relative to all integers from 0 to x. It then extracts the numbers with modulus equal to 0, which are always [0,1,...,x]. If the third such number is not x, then it is the smallest prime factor of x. ``` p=function(l){w=0:l;v=w+1;j=1;for(i in w){y=v[j];x=w[!y%%w][3] if(x%in%c(NA,y))j=j+1 else{v[j]=y/x;j=j-1;v[j]=v[j]+x}} j-2} ``` [Try it online!](https://tio.run/##HY1BCsMgFET3OYUNCIoJje0u8he9QC9gXRSJoIgJaRqVkLPbpLMY5sEwMxePAPHuUJnAfINe7BiIp1uErvdihci4cMCFGWdikQ0o0i3DKp0SCaK8ZIyjkndVWUMStgFr8nw0mVIHjvFq8J9hO9uQr@kYci0XfzyNpX2vXHvbi34vpH6FupmO7@ZMtPwA "R – Try It Online") [Answer] # C (gcc), ~~152~~ 148 bytes ### Minified ``` int f(int n){int*A=malloc(++n*4),p=0,i,q;for(i=0;i<n;i++)A[i]=i+2;for(i=1;i<n;i++){for(q=2;A[p]%q;q++);if(A[p++]>q){A[--p]/=q;A[--p]+=q;}}return p;} ``` ### Formated with some comments ``` int f(int n) { int *A = malloc(++n * 4), p = 0, i, q; // Initialize array A for (i = 0; i < n; i++) A[i] = i + 2; // Do n step (remember n was incremented) for (i = 1; i < n; i++) { // Find smallest divisor for (q = 2; A[p] % q; q++) ; if (A[p++] > q) { A[--p] /= q; A[--p] += q; } } return p; } ``` ### Main function for testing ``` #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { if (argc != 2) return 2; int n = atoi(argv[1]); int p = f(n); printf("%d => %d\n", n, p); return 0; } ``` ### For showing each step 1. Declare display() inside f() ``` int f(int n) { int *A = malloc(++n * 4), p = 0, i, q; void display(void) { for (int i=0; i < p; i++) { printf(" %d", A[i]); } printf(" \033[1;31m%d\033[m", A[p]); if (p+1 < n) printf(" %d", A[p+1]); printf("\n"); } ... ``` 2. Call display() ``` A[i] = i + 2; display(); ``` 3. Call display() ``` } display(); } ``` [Answer] ## Clojure, 185 bytes ``` #(loop[[n p][(vec(range 2 1e3))0]i %](if(= i 0)p(recur(if-let[q(first(for[i(range 2(n p)):when(=(mod(n p)i)0)]i))][(assoc n p(/(n p)q)(dec p)(+(n(dec p))q))(dec p)][n(inc p)])(dec i)))) ``` Ouch, editing a "state" is not ideal in Clojure. You'll need to increase the exponent for larger inputs. [Answer] # Java 8, ~~138~~ 135 bytes ``` n->{int a[]=new int[++n],s=0,p=0,j=0;for(;j<n;a[j++]=j+1);for(;++s<n;p++)for(j=1;++j<a[p];)if(a[p]%j<1){a[p--]/=j;a[p--]+=j;}return p;} ``` **Explanation:** [Try it here.](https://tio.run/##VVHBbsMgDL3vK6xKk4JoukarNGmE/cF66THKgaWkgqUOAtppqvLtmSk5dAiD/TD2e2DVVZWj02iP33M3qBDgUxm8PQEYjNr3qtOwT@EdgK5IKzJByERGM0QVTQd7QJAwY/lxSymqaSXqn3Sp4RzbdZDbtSOzciv60RfC1ihUYzlvpeUVyyDngWDHOUuhlRUhtlaNawUzfZGcZ1tX7EZeWbYv0orscfImr@PFIzgxzSKTc5evgcgtHK@jOcKZ9BWH6A2emhYUy@JSu8TbED0wtazSRjTyKUDUIRbmrjsrX6Dd24It0evuMa62NB4fy3lzVVH/I5RLp95Lt8NviPq8GS9xQ/kYBywMX73DiuOGPoAtBaf5Dw) ``` n->{ // Method with integer as both parameter and return-type int a[]=new int[++n], // Integer-array with a length of `n+1` s=0, // Steps-counter (starting at 0) p=0, // Current position (starting at 0) j=0; // Index integer (starting at 0) for(;j<n; // Loop (1) from 0 to the input (inclusive due to `++n` above) a[j++]=j+1 // And fill the array with 2 through `n+2` ); // End of loop (1) for(;++s<n; // Loop (2) `n` amount of steps: p++) // And after every iteration: increase position `p` by 1 for(j=1; // Reset `j` to 1 ++j<a[p];) // Inner loop (3) from 2 to `a[p]` (the current item) if(a[p]%j<1){ // If the current item is divisible by `j`: a[p--]/=j; // Divide the current item by `j` a[p--]+=j;} // And increase the previous item by `j` // And set position `p` two steps back (with both `p--`) // End of inner loop (3) (implicit / single-line body) // End of loop (2) (implicit / single-line body) return p; // Return the resulting position `p` } // End of method ``` [Answer] # Clojure, ~~198~~ ~~193~~ 191 bytes This needs to be severely golfed... ``` #(loop[i(vec(range 2(+ % 9)))c 0 p 0](if(= % c)p(let[d(dec p)u(i p)f(some(fn[n](if(=(mod u n)0)n))(range 2(inc u)))e(= u f)](recur(if e i(assoc i d(+(i d)f)p(/ u f)))(inc c)(if e(inc p)d))))) ``` **Golf 1**: Saved 5 bytes by changing `(first(filter ...))` to `(some ...)` **Golf 2**: Saved 2 bytes by changing `(zero? ...)` to `(= ... 0)` --- ## Usage: ``` (#(...) 10000) => 512 ``` ## Ungolfed code: ``` (defn prime-ant [n] (loop [counter 0 pos 0 items (vec (range 2 (+ n 9)))] (if (= n counter) pos (let [cur-item (nth items pos) prime-factor (some #(if (zero? (mod cur-item %)) %) (range 2 (inc cur-item))) equals? (= cur-item prime-factor)] (recur (inc counter) (if equals? (inc pos) (dec pos)) (if equals? items (assoc items (dec pos) (+ (items (dec pos)) prime-factor) pos (/ cur-item prime-factor)))))))) ``` ]
[Question] [ The world is full of [Turing-complete](https://en.wikipedia.org/wiki/Turing_completeness) programming languages. Just about every useful language (and most useless ones) are Turing-complete. Some even became Turing-complete [by accident](http://beza1e1.tuxen.de/articles/accidentally_turing_complete.html). Often this is great, since every Turing-complete language supports the same power of universal computation. But the power of Turing completeness also comes with a curse! The [halting problem](https://en.wikipedia.org/wiki/Halting_problem) is undecidable for arbitrary programs in a Turing-complete language, and more generally, it’s [impossible to analyze](https://en.wikipedia.org/wiki/Rice%27s_theorem) arbitrary programs in any non-trivial way. Sometimes we need less powerful languages. It takes great care to design a useful language that falls short of Turing completeness. That’s the subject of this challenge! ## Requirements Write an interpreter that will accept a **program** and some **input** for the program, and produce some **output**. The program, input, and output are given using simple data types of your choice. * Examples of “simple” data types: booleans; numbers; strings (bytes or Unicode); arrays or mappings of simple data types; [algebraic data types](https://en.wikipedia.org/wiki/Algebraic_data_type) defined in your interpreter. * Examples of data types *not* considered “simple”: function expressions; a subset of strings representing valid programs in some language (unless the subset is validated by your interpreter); [generalized algebraic data types](https://en.wikipedia.org/wiki/Generalized_algebraic_data_type). (This restriction is intended to disqualify trivial answers such as the identity function in [Agda](https://wiki.portal.chalmers.se/agda/).) Your **input format** must include some way to express arbitrarily sized **natural numbers**, in a reasonable representation of your choice (e.g. arrays or strings of unary, binary, or decimal digits, or directly as [big integers](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) if your host language has them). Your **output format** must include at least two values, distinguishable from each other, to represent **“true” and “false”**. Whether the formats can express anything else is up to you. You may interpret programs in any target language, existing or new, under three conditions: * Your interpreter must be observably **deterministic**: for a given program and input, you must always produce the same output. * Your interpreter must **not be Turing-complete**. Explain why this is the case—for example, it might be Turing incomplete because the interpreter eventually halts on every program and input, or because its halting problem is otherwise decidable. * As a minimum standard of usefulness, your target language must be able to express **every [polynomial-time](https://en.wikipedia.org/wiki/P_(complexity)) function** from natural numbers to booleans. Explain why this is the case. (To be clear, “polynomial-time” is defined over the length of the input in binary bits, even if your chosen representation of naturals is less efficient.) Whether any other functions are expressible is up to you—for example, you might design your language around the [primitive recursive functions](https://en.wikipedia.org/wiki/Primitive_recursive_function), the [elementary functions](https://en.wikipedia.org/wiki/ELEMENTARY), or [Gödel’s System T](https://en.wikipedia.org/wiki/Dialectica_interpretation), each of which includes all polynomial-time functions. Your interpreter may be written in any existing host language. You may assume it runs on an ideal machine with unlimited memory and pointers big enough to access it. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"): make the shortest interpreter you can! ## Clarifications I believe these points follow from the requirements, but they’re listed here in the hope of being helpful. Feel free to request additional clarifications in the comments. * As per our default rules, your interpreter will be a [program or function](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) that follows our [usual conventions for input and output](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods). However, programs in your target language are not bound by these rules—for example, if you decide that programs in your target language will be snippets that perform I/O by accessing a predefined variable, that is fine, as long as your interpreter translates this convention by (say) automatically reading from STDIN to the variable at startup and writing the variable to STDOUT at exit. (This can be viewed as a natural consequence of our policy that [languages are defined by their interpreters](https://codegolf.meta.stackexchange.com/questions/7832/whats-the-policy-on-interpreter-bugs/7833#7833).) * You may of course use any data types you want *within* your language, as long as the program, input, and output types are simple data types. * Your interpreter must be prepared to accept *anything* in your chosen simple data type for programs as a program. Your interpreter may of course perform extra validity checks on the program and throw errors or fall back to some default behavior or do something else that respects the requirements—but you may not impose extra validity constraints on programs purely at the specification level. Writing “`eval` but you’re not allowed to pass in anything except deterministic programs that halt” does not solve this challenge. * Because of the determinism requirement, an interpreter that works by executing arbitrary code with a timeout in seconds is unlikely to be valid. (Doubly so if it leaves programs enough wiggle room to disable or evade the timeout in some underhanded way.) * Although I ~~am willing to be~~ may already have been proven wrong, my expectation is that solving this challenge will require doing some actual work to interpret a language. I’m not looking for solutions that put in 1% of this work to satisfy 80% of the requirements, whatever that means—that wouldn’t be fair to those who put in the effort to solve the full challenge as written. * I updated the challenge with a requirement for the representation of natural number inputs to be “reasonable” after realizing there was a loophole using an unreasonable representation of naturals. Specifically: if we enumerate all polynomial-time functions as \$p\_0, p\_1, p\_2, \dotsc\$, the unreasonable representation of \$n \in \mathbb N\$ as \$(p\_0(n), p\_1(n), \dotsc, p\_{n-1}(n))\$ allows any polynomial-time function \$p\_m\$ to be “programmed” as \$\{0 \mapsto p\_m(0), 1 \mapsto p\_m(1), \dotsc, m \mapsto p\_m(m), n \mapsto n\_m\text{ for }n > m\}\$, with every output hard-coded into either the program or the input! (I don’t think any of the existing answers have tried to exploit such an unreasonable representation.) ## Related challenges * [Write a Programming language of Unknown Completeness](https://codegolf.stackexchange.com/questions/111092/write-a-programming-language-of-unknown-completeness) * [Turing-Complete Language Interpreter](https://codegolf.stackexchange.com/questions/111278/turing-complete-language-interpreter) * [Design a One Instruction Set Computer!](https://codegolf.stackexchange.com/questions/154617/design-a-one-instruction-set-computer) * [Fewest (distinct) characters for Turing Completeness](https://codegolf.stackexchange.com/questions/110648/fewest-distinct-characters-for-turing-completeness) * [Escape from the tarpit](https://codegolf.stackexchange.com/questions/162290/escape-from-the-tarpit-cops) ([Deleted sandbox post](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/18933#18933)) [Answer] # [Python 2](https://docs.python.org/2/), 38 bytes ``` lambda s,n:s.strip("()+*%n")or eval(s) ``` [Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFYJ8@qWK@4pCizQENJQ1NbSzVPSTO/SCG1LDFHo1jzv7JCcGFpYlFmXjpXAZAsUUjTUMrTylPSMdLk4lJW8MwDqstMUUgrzUsuyczPQygCicQnJ@bkaGiCFP8HAA "Python 2 – Try It Online") This evaluates a subset of Python 2 given by arithmetic expressions using only characters `()+*%n`, acting on natural-number input `n`. This computes the class [ELEMENTARY](https://en.wikipedia.org/w/index.php?title=ELEMENTARY), as the closure of the expressions in the basis \$\{n+m, n^2, n\bmod m, 2^n\}\$ as noted in [the Wikipedia article on ELEMENTARY](https://en.wikipedia.org/w/index.php?title=ELEMENTARY#Basis_for_ELEMENTARY) and proven in [Superpositions of elementary arithmetic functions](https://en.wikipedia.org/w/index.php?title=ELEMENTARY#cite_note-2). This moreover shows that Python operators can not only [do primality testing](https://codegolf.stackexchange.com/q/170398/20260), but any polynomial-time computable function. The paper's argument seems to be based on constructions similar to [Lopsy's prime-testing solution](https://codegolf.stackexchange.com/a/171453/20260), encoding lists as digits in a large base and expressing bounded summation on those elements via arithmetic operations. The proof uses [this expression for binomial coefficients](https://codegolf.stackexchange.com/a/169115/20260) as an intermediate step. We check that our operators can express all operations in the basis. The `+`, `**`, and `%` operators do addition, exponent, and modulo. We can get the \$2\$ for \$n^2\$ and \$2^n\$ as \$2=0^0+0^0\$, where \$0\$ is `n**n%n**n`, avoiding the modulo-by-zero that simply `n%n` would give for `n=0`. Parentheses allow arbitrary composition of sub-expressions, and projection is trivial. We can interpret outputs as Booleans by associating `True=1, False=0`, as is standard in Python. To ensure we that only this subset can be evaluated, we check that the input expression `s` is limited to the characters `()+*%n` by stripping them from `s` and returning what remains if non-empty. Note that an invalid string is never evaluated, rather than evaluated then discarded, preventing it from anything strange it could call or overwrite to allow its output to escape. The really isn't anything extra that's non-trivial that can be done with the whitelisted characters that we might worry allows Turing completeness. The letter `n` alone can't spell any function or keyword. We can get multiplication with `*`, but this is of course elementary. We can't even get negative numbers or floats, though these would still be harmless. We can get the empty tuple `()`, but nothing interesting can be done with it. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 14 [bytes](https://github.com/abrudz/SBCS) ``` (⍎⍞~'⎕⍎⍣⌶?{')⎕ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b/Go96@R73z6tQf9U0FMxc/6tlmX62uCeSDVPxP4zJVMOVKf9Q2wehRx4xHXc2Pulu09dO1HvVuhvAB "APL (Dyalog Unicode) – Try It Online") A full program that takes two inputs (an array of numbers in APL syntax, and then a line of APL code) from STDIN and prints the result to STDOUT. The given APL code is sanitized by deleting characters that have a possibility to invoke an unbounded loop/recursion or access to the external system. Since the input function is written in a single line, it must necessarily consist of built-in functions and operators, possibly including assignment. Using dfns is banned by the character `{`, and tradfns cannot appear because a tradfn requires at least two lines of code to be defined. [Control structures](http://help.dyalog.com/17.1/index.htm#Language/Control%20Structures/Control%20Structures%20Summary.htm) and the [Branch primitive](http://help.dyalog.com/17.1/index.htm#Language/Primitive%20Functions/Branch.htm) are only meaningful inside trandfns, so they are automatically banned as a side effect. The summary of banned characters with reasons: * `⎕` by itself is used merely as an I/O primitive, but it is used as the first character of [all the system functions](http://help.dyalog.com/17.1/#Language/System%20Functions/Summary%20Tables/System%20Functions%20Categorised.htm), which include shell and filesystem access. * `⌶` is called an [I-beam](http://help.dyalog.com/17.1/#Language/Primitive%20Operators/I%20Beam.htm#I-Beam), which grants access to experimental features. Some of the features include access to system. * `{` is required to create a dfn/dop, and has no other uses. * `⍣` is power operator, which can act as a for-loop or a while-loop depending on how it is used. * `?` is random number generator. It is excluded to satisfy the determinism requirement. * `⍎` is APL's eval. I can't think of a hole accessible via `⍎` when `⎕UCS`, `⎕AV` etc are banned, but it is included to be safe. Any one line of APL code without the six characters is guaranteed to terminate, thus it is not Turing-complete. Here is a more formal proof via structural induction. [Here](http://help.dyalog.com/17.1/#Language/Introduction/Language%20Elements.htm) is the list of all language elements for reference. Let's define a **Q-function** to be a function that terminates by returning a deterministic array or erroring in finite time. * All primitive functions except `⍎?` along with bracket indexing are Q-functions. * All primitive operators except `⍣⌶` become Q-functions when given Q-functions and/or arrays as operands. * Tacit functions made of Q-functions are Q-functions, because tacit functions cannot express recursive functions. Also, something like `g←⊢,g` does not create a self-reference; it is either illegal (if `g` is not defined beforehand) or creates a new function based on the previous value of `g`. * Any variable created/modified via assignment can only result in a Q-function or an array. The remaining functionality can be proven to be powerful enough to express [elementary functions](https://en.wikipedia.org/wiki/ELEMENTARY): Taking multiple arguments as a single array (e.g. subtraction function `f(x,y)` takes a length 2 array), * Zero = `-⍨`, Successor = `1∘+`, and Subtraction = `0⌈-/`. * Projection can be expressed as an indexing via `⊃`. * Composition can be written as `h g1,g2,g3,...` * Bounded summation and product can be implemented as tacit functions: summation is `+/(0,⍳∘⊃)(g,)¨∘⊂1∘↓` and change `+/` to `×/` for product. [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 42 [bytes](https://github.com/abrudz/SBCS) ``` {∇{×|≡⊃c i←⍺:⊃c⍺⍺⍣(i⊃⍵)⊂⍵⋄c(⊣+×)@i⊢⍵}/⍺,⍵} ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRR3v14ek1jzoXPupqTlbIfNQ24VHvLisQB0iD0WKNTCD3Ue9WzUddTUDqUXdLssajrsXah6drOgClFgHFavWBSnVAjP9pYCP6gFoOrTd@1DbxUd/U4CBnIBni4Rn8X8NAwVBTQ0PDUMFIE0xoGmoqpCkATTZWMAEA "APL (Dyalog Unicode) – Try It Online") I thought I'd give it a go at a more "proper" submission. This function interprets the programming language [LOOP](https://en.wikipedia.org/wiki/LOOP_(programming_language)) represented as a nested numeric array (which is used like an ADT), and the input to the LOOP program is represented as a simple numeric vector (enclosed once, for the sake of code golf). ### The concept LOOP has four kinds of commands: (`x_i` are variables and `P` are sub-programs) * `x_i := 0` (zero) * `x_i := x_i + 1` (increment) * `P_1; P_2` (sequence) * `LOOP x_i DO P END` (bounded loop): Run `P` `x_i` times. Here I represent a sequence of commands as an array `[P_k P_k-1 ... P_2 P_1]` instead of explicit concatenation, therefore eliminating a command. The order of command is reversed for the sake of code golf. Each command in the program is encoded as a `(c i)` pair, where `i` is the variable index to refer to and `c` is the command to run on it. I use `c←0` for zero, `c←1` for increment, and `c←P` for the bounded loop. For an illustration, the pseudocode ``` x_2 += x_1 * 2; x_1 = 0 ``` can be written in LOOP as ``` LOOP x_1 DO x_2 := x_2 + 1 x_2 := x_2 + 1 END; x_1 := 0 ``` and the representation for my submission is ``` (0 1)(((1 2)(1 2))1) ------------ Increment x_2 twice --------------- Loop x_1 times ----- Assign zero to x_1 ``` For the computational power, LOOP can precisely represent primitive recursive functions, thus satisfying the requirement of the challenge. ### The code ``` {∇{×|≡⊃c i←⍺:⊃c⍺⍺⍣(i⊃⍵)⊂⍵⋄c(⊣+×)@i⊢⍵}/⍺,⍵} ⍝ ⍺←Program; ⍵←Input { ⍺,⍵} ⍝ Append ⍵ to ⍺ for reduction ∇{ }/ ⍝ Reduce, exposing the self reference to inner dfn: c i←⍺ ⍝ Extract command type and index from the next command ×|≡⊃ : ⍝ If the command type is not simple (a loop subprogram): ⊃c⍺⍺⍣(i⊃⍵)⊃⍵ ⍝ Run the subprogram c x_i times on the state ⍵ ⋄ ⍝ Otherwise c(⊣+×)@i⊢⍵ ⍝ Multiply c and then add c to x_i, which is equivalent to ⍝ If c is 1, add 1 to x_i; if c is 0, set x_i to 0 ``` [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), ~~59~~ ~~51~~ 47 bytes ``` n=>g=([a,b,c])=>c?g(a)+g(b)**g(c):b?g(a)%g(b):n ``` [Try it online!](https://tio.run/##dU/LbsIwELznK/ZS2UtMVHEkClVz67lHxMFJXDco3Y2MKaKIb6fYJC2lQrJkaWZ2Hmv9qTe1a3s/rXRluilxY06d8WCKExULW8ilVpWqV1gs6icrNaZWVjiZWFnjvIrIQ0DmFM9KKKBs7Qv5PHnbUu1bJjC6aXreyeiEcABn/NYRDNY5HK@0H9wE4Y0simIvOicsS/mIq/wCfBnHZywejkmGVHyo4B@Ewx2TCWcjHWwUXH94M@Gm1u8qqFS0w5@SfseDtwzESCfJs3N6n/WOPft9bzLPr961ZIsxSeJh8BdLkfr3dpOtuSUpFAhMxUrkx6Rm2nBnso6tFCINafgHNLKUsxniZRXeI0One1zwvMfFWaTgIsLTNw "JavaScript (Babel Node) – Try It Online") (51 bytes thanks to @user202729) This is using @xnor's basic approach, but without `eval`, and with a reduced basis. The simple datatype D is a BigInt or an array of D. Given a program p (a D) and an input n (a BigInt), the expression `e(n)(p)` interprets the program with input n. Programs are interpreted as follows: * [a, b, c] evaluates a, b, and c, returning a + b\*\*c * [a, b] evaluates a and b, returning a modulo b * [0] returns n These three operations are enough to compute anything elementary recursive. No matter the value of n, the value of n+n\*\*n is positive, hence (n+n\*\*n)%(n+n\*\*n) gives 0, and 0 + 0\*\*0 gives 1. Hence, we have addition as a + b = a + b\*\*1 and exponentiation as a\*\*b = 0 + a\*\*b. For example, this is a program that computes the constant 2: ``` [[[[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]]], [[[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]]], [[[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]], [[[0], [0], [0]], [[0], [0], [0]]]]] ``` --- Corollary 2 of the following paper, which @xnor cited, is that this language gives all elementary recursive functions, using the usual tricks to encode a function \$\mathbb{N}^n\to\mathbb{N}\$ as a function \$\mathbb{N}\to\mathbb{N}\$. Marchenkov, S. S. (2007). Superpositions of elementary arithmetic functions. Journal of Applied and Industrial Mathematics, 1(3), 351–360. doi:10.1134/s1990478907030106 They also point out in Corollary 3 that every recursively enumerable subset \$S\$ of \$\mathbb{N}\$ has an indicator function \$f:\mathbb{N}\to \{0,1\}\$ that is of the form \$f(n)=\exists z\in\mathbb{N},n=p\_1(z)\wedge n=p\_2(z)\$, where \$p\_1(z)\$ and \$p\_2(z)\$ are functions in the above language, such that \$f(n)=1\$ if and only if \$n\in S\$. The argument is that you take a Turing machine that describes \$S\$ (say, as a nondeterministic machine that halts with elements of \$S\$ on the tape) then use the language to make nearly identical functions \$p\_1\$ and \$p\_2\$ that take an execution trace \$z\$ and check whether it brings the machine into a halt state, and if so the result of each function is the tape contents, and otherwise they result in \$p\_1(x)=0\$ and \$p\_2(x)=1\$. [Answer] # [JavaScript (Babel Node)](https://babeljs.io/), ~~96~~ ~~86~~ ~~69~~ 62 bytes ``` x=>g=([a,b,c])=>c?((v=>{for(;v-->0;)g(b)})(g(a)),g(c)):x[a]+=b ``` [Try it online!](https://tio.run/##nZLBjpswFEX3@YrXFX7FMKRVVWmoM2p3XXeJWBjiUBNiE2xSoij/0m/pj6U2w2SgmlVZoed37z3XUPMTN2UnWxsVvBBNpPRW3HbsNrBNxUjGaUHLHNmmfCLkxDaXne5IeoqiTZJiRQq8IqkIR6QVKREfh4znIStuu16VVmoFUpVEUlAIF@iE7TsF2TdZfVeWSKQwvSrMU7iu7qpG69bL4jhuzVw62SVOasSRPJ/TMSXx49Hm4QG4Mf1BwJAlOTAGa@DNL342rwle3VKnP879jybuxLYvBXGHR1c7uztTN8hpiwtOI@y/7bzxC/5EG63d/fguRME7R5PA072Jaw6PkOW4NJZKWt9umNMNJj7wljzf2bjvqw4SvkQw1BDCsH914Nut968p7J3FCuZ8E7Yr5eazZ@Su79we@42F/XwB09V1QfF@QXHom/@l@PP7jbQxbvW16/g5bjtttT23Irb6h@2kqthLLsHLFBRkQWh/ShPXWioSUAgwDPIgdS5OXwEbUTzmmn6gH6d/aU0TH1VqZXQj4kZXJAhCL8DFcEfGD@XW6Sf6GZGMK3j7Cw "JavaScript (Babel Node) – Try It Online") This is implementing a variation on [LOOP](https://en.wikipedia.org/wiki/LOOP_(programming_language)). A program is recursively defined to be an array of programs or a BigInt. A program `p` is run with input `x` (a list of BigInts) by passing `x` and `p` as curried arguments (`f(x)(p)` with `f` the above function). The program is interpreted as follows: * [i, n] adds n to x[i], returning the sum. * [p, q, r] with c = max(0, evaluate(p)), evaluates q c times then returns the result of evaluating r. The interpreter expects that every x[i] used is initialized to some BigInt. For example, the following is a program that returns the product of x[2] and x[3], assuming x[0] is set to 1 and x[1] starts with any non-negative number. ``` [[0, 0], // loop x[0] times: [[0, 0], // loop x[0] times: [[1, 0], // loop x[1] times: [1, -1], // x[1] += -1 [0, 0]], // x[0] += 0 [[2, 0], // loop x[2] times: [[3, 0], // loop x[3] times: [1, 1], // x[1] += 1 [0, 0]], // x[0] += 0 [0, 0]]], // x[0] += 0 [1, 0]] // x[1] += 0 ``` The last line returns the value of x[1]. Note that, while this version of LOOP allows variables to be negative, there is no way to clear such a value in a general way. [Answer] # VBS, 74 bytes ``` execute replace(replace(replace(lcase(inputbox(0)),"w",0),"e","ne"),"d",2) ``` Take program that looks like: ``` j=0:for i=0 to InputBox():j=j+i:ext:msgbox(j) ``` Disallow loops from `CreateObject`, `Do`, `(w)End`, `eval`, `execute`, `step`, `date`, `now`, `timer` # [JavaScript (Node.js)](https://nodejs.org), 35 bytes (67 if no state allowed, 40 for no state strict, if you keep `=`; still 35 otherwise, still elementary but program is longer without `=`) ``` x=>n=>eval(x.replace(/[^!-=n]/g,0)) x=>n=>eval('for(i in this)delete this[i];'+x.replace(/[^!-=n]/g,0)) x=>n=>eval(x.replace(/[^!-=n]/g,'var ')) ``` [Try it online!](https://tio.run/##bY/disJADIXvfQq90WR0nJn@LozxRcSF0h3FpZ6Wuohv323rooJ7k4R855yQ7@JaXMr21Pxo1F@hO0h3ky1kG65FRbd1G5qqKAOZ3edMC/bmuLLMnZ807ekcpjI90AJWsPyAhxNy2GygYNnQfbasHdgjerBXqh7cCZyCM8/94EGkEJlXp0c8KiOP5C/SKhXj7WAqfdc0FkK8JGSCZBAMnDUSBZ6PHBn3hlzuYqQ9Y54j8zPkC/aTssalrsK6qo80/k1x2kf8C/IBdL8 "JavaScript (Node.js) – Try It Online") Even not reaching Bitwise operation is powerful # JavaScript, 43 bytes ``` n=>g=([a,b,c])=>c?g(b)/g(c)-g(a)<<g(c):a||n ``` Why? ``` 0 = 1 / 1 - 1 << 1 -x = (x / 1 - 0 << 1) / -1 - 0 << -1 x+y = (-x / 1 - y << 1) / -1 - 0 << -1 x/y = -(0 / -y - (x / y - 0 << y) << -y) // If y>0 2^x = 2 / 1 - 1 << x x>=0 = (1<<x)<<-x [Convert To Positive]: 2^x + 2^x + 2^x + 2^(-1-x) + 1 ``` [Answer] # [Bash](https://www.gnu.org/software/bash/), 33 bytes ``` dc -e"?sl`sed "s/[^l+%^]//g;q"`p" ``` [Try it online!](https://tio.run/##7ZaxbsIwEIZ3nuJXkKe0BOYOfYluqBEOuQRLie36nPL46SkFligSSCxV7eHk@3X@fT59gyvNp3Gsj3il7J27A1ONjIt92eWq/CyK9u0rO/hsHLvLKqegZsllW@YL@oPluXqSz3KjKl8wu@862ao/NIOnvU3GdsfgEh//mo/F3hItiZY5LYmKRMWMComr3Q5rY/0QER18cG3Q/Qar9ceJoCv3TVcRxiKKGIdgbCvZ0fW@o0jgoWKKcA3klxNICixPpb@@poGRyGJkeoIL0Ggo9DrCMw21m/QXaFvfTm/hxCCcDRN@AA "Bash -- Try it online") Effectively the same scheme as @xnor's solution, except implemented in sed & dc, and using a subset of dc for user programs. All characters except [+^%l] are filtered out, and those that remain are evaluated by dc. Those characters are sufficient to perform the operations of addition, modulo, exponentiation(with 0^0 == 1) and to read from a variable 'l', which is written to with the user input before the inputted program is run. Numbers may be constructed using a combination of 0 = (n^n)%(n^n), 1 = 0^0, and the successor function, +0^0. Translated to dc, these would be: ``` 0 = llll^llll^% 1 = llll^llll^%llll^llll^%^ S = llll^llll^%llll^llll^%^+ ``` where S increments the value at the top of the stack. Operations may be arbitrarily nested. The set of characters is sufficient to encode the operations listed above. However, it is incapable of producing looping / recursion (which, in dc, would require executing a macro, which would require one of [x=<>], as well as either a or [] to define it). Similarly to @xnor's solution, the allowable programs are a superset of the class ELEMENTARY, adding the ability to do make arbitrary exponents, rather than just 2^ and ^2. ]
[Question] [ While there are many code golf questions on here involving randomness, I haven't seen one yet that actually asks for building an algorithmic pseudorandom number generator. There's [this one](https://codegolf.stackexchange.com/questions/6868/generate-a-completely-deterministic-pseudorandom-bit-stream) that asks you to generate a bit stream, but the randomness tests provided on that one were not very rigorous, and it's not code-golf. The program you write will have a single callable function that will return a random integer from 0 to 4294967295. This function must not call upon any libraries or other functions that were not also written as part of the program, especially calls to /dev/random or a language's built-in rand() library. More specifically, you are limited to the basic operators of the language you are working in, such as arithmetic, array access, and conditional flow control statements. The score of your program is calculated as follows: ``` Score = C / R ``` Where C is the length of the code in characters, and R is the number of [Diehard tests](http://en.wikipedia.org/wiki/Diehard_tests) that your generator passes (If your random number generator does not pass at least one Diehard test, its score is infinity and it is disqualified). Your generator passes a Diehard test if the file it generates provides a range of P-values that appear to be distributed uniformly along the interval [0, 1). To calculate R, use your random number generator with its default seed to generate a 16 MB binary data file. Each call of the function returns four bytes; if your function is too slow to return bytes, this will factor a trade-off into attaining a low score by how difficult it is to test. Then, run it through the Diehard tests and check the P-values provided. (Do not try and implement these yourself; use the ones provided [here](https://web.archive.org/web/20161114211602/http://stat.fsu.edu/pub/diehard/)) Lowest score wins, of course. [Answer] ## Perl 28 / 13 ≈ 2.15 ``` sub r{$s^=~($s^=$s/7215)<<8} ``` *log file [here](http://codepad.org/uab3DWX0)* ## Perl 29 / 13 ≈ 2.23 ``` sub r{$s^=~($s^=$s<<8)/60757} ``` *log file [here](http://codepad.org/P0YiOL29)* These are something of a variation on a [Xorshift](http://de.wikipedia.org/wiki/Xorshift), using floating point division instead of a right shift. They both pass 13 of 15 tests, failing only tests 6 and 7. I'm not exactly sure how long the cycle is, but because the following code doesn't terminate in any short period of time, it's likely the full *232*: ``` $start = r(); $i++ while $start != r(); print $i; ``` --- ## Perl 39 / 10 = 3.9 ``` $s=$^T;sub r{~($s=$s*$s%4294969373)||r} ``` *Note: if you're looking for a Blum-Blum-Shub-esque PRNG, [Keith Randall's solution](https://codegolf.stackexchange.com/a/10583/4098) is far better than either of these.* As with my original solution below, this is also an implementation of the Blum Blum Shub, with one major difference. I uses a modulus slightly larger than *232* (*M = 50971 • 84263*), and whenever a value is encountered that it is not a valid 32-bit integer (that is, larger than *232*), it returns the next value in the rotation instead. In essense, these values are pruned out, leaving the rest of the rotation undisturbed, resulting in a nearly uniform distribution. It seems to have helped. In addition to passing the same 9 tests as before, it now also convincingly passes the Minimum Distance test. A sample log file can be found [here](http://codepad.org/1OByLxUh). --- ## Perl 33 / 9 ≈ 3.67 (Invalid?) ``` $s=$^T;sub r{$s=$s*$s%4294951589} ``` *Note: this solution might be considered invalid, as the top-most 0.00037% of the range will never be observed.* A quick and dirty implementation of the [Blum Blum Shub](http://en.wikipedia.org/wiki/Blum_Blum_Shub). I claim the following results: ``` 1. passed - Birthday Spacings 2. FAILED - Overlapping Permutations 3. passed - Ranks of 31x31 and 32x32 Matrices 4. passed - Ranks of 6x8 Matrices 5. FAILED - Monkey Tests on 20-bit Words 6. FAILED - Monkey Tests OPSO, OQSO, DNA 7. FAILED - Count the 1s in a Stream of Bytes 8. passed - Count the 1s for Specific Bytes 9. passed - Parking Lot Test 10. FAILED - Minimum Distance Test 11. passed - Random Spheres Test 12. FAILED - The Squeeze Test 13. passed - Overlapping Sums Test 14. passed - Runs Test 15. passed - The Craps Test ``` A sample log file can be found [here](http://codepad.org/3yt3cwnf), feel free to dispute any of the results. The file for diehard can be generated in the following manner: ``` print pack('N', r()) for 1..4194304 ``` and then piping the output into a file. Minimum Distance looks like it might have passed, but if you run it multiple times it's always very close to *1.0*, which indicates failure. --- ## Details In general, the Blum Blum Shub is a terrible PRNG, but it's performance can be improved by choosing a good modulus. The *M* I've chosen is *7027 • 611207*. Both of these prime factors, *p* and *q*, have modular residue *3 (mod 4)*, and *gcd(φ(p-1), φ(q-1)) = 2*, which is as low as it can be. Although these are the only criteria listed on the wiki page, it doesn't seem to be enough. Almost all of the modulo I tried failed every test. But there's a handful that will pass some of the tests, and the one I've chosen seems to be exceptionally good, for whatever reason. As a final note, Test 5 on its own seems to be a fairly good indicator of how good the PRNG is. If it doesn't *almost* pass Test 5, it will fail the rest of them spectacularly. --- ## BONUS: Perl 62 / 14 ≈ 4.43 ``` $t=$^T;sub r{$t|=(($s=$s/2|$t%2<<31)^($t/=2))<<31for 1..37;$t} ``` Just for geekery, this is a 32-bit version of the PRNG used in the original Tetris for NES. Amazingly, it passes 14 of the 15 tests! ``` 1. passed - Birthday Spacings 2. passed - Overlapping Permutations 3. passed - Ranks of 31x31 and 32x32 Matrices 4. passed - Ranks for 6x8 Matrices 5. passed - Monkey Tests on 20-bit Words 6. passed - Monkey Tests OPSO, OQSO, DNA 7. FAILED - Count the 1s in a Stream of Bytes 8. passed - Count the 1s for Specific Bytes 9. passed - Parking Lot Test 10. passed - Minimum Distance Test 11. passed - Random Spheres Test 12. passed - The Squeeze Test 13. passed - Overlapping Sums Test 14. passed - Runs Test 15. passed - The Craps Test ``` Sample log file can before [here](http://codepad.org/v7zzpHcf). Admittedly, the `1..37` bit isn't an exact transcription. In the orginal version, the entropy routine is updated 60 times per second, and then queried at random intervals, largely dependent on user input. For anyone who cares to disassemble the ROM, the entropy routine begins at `0xAB47`. Python-style pseudo-code: ``` carry = entropy_1 & 1 entropy_1 >>= 1 entropy_2 = (entropy_2 >> 1) | (carry << 31) carry = (entropy_1 & 1) ^ (entropy_2 & 1) entropy_1 |= carry << 31 ``` [Answer] ## Python, 46 / 15 = 3.0666 ``` v=3 def R():global v;v=v**3%(2**32-5);return v ``` Uses modular exponentiation to generate randomness. 2\*\*32-5 is the largest prime less than 2^32. (Same deal with not being able to run test #2.) [Answer] # Mathematica, 32 / 15 = 2.133 ``` x=3;Mod[x=Mod[x^2,28!-67],2^32]& ``` A straightforward implementation of [BBS](https://en.wikipedia.org/wiki/Blum_Blum_Shub). Binary file generated with: ``` f = %; (* assigns anonymous function declared in the previous expression to f *) Export["random.bin", Array[f, 2^22], "UnsignedInteger32"]; ``` Summary of results: ``` 1. BIRTHDAY SPACINGS TEST .684805 2. OVERLAPPING 5-PERMUTATION TEST .757608/.455899 3. BINARY RANK TEST .369264/.634256 4. BINARY RANK TEST .838396 5. THE BITSTREAM TEST (no summary p-value) 6. OPSO, OQSO and DNA (no summary p-value) 7. COUNT-THE-1's TEST .649382/.831761 8. COUNT-THE-1's TEST (no summary p-value) 9. PARKING LOT TEST .266079 10. MINIMUM DISTANCE TEST .493300 11. 3DSPHERES TEST .492809 12. SQEEZE .701241 13. OVERLAPPING SUMS test .274531 14. RUNS test .074944/.396186/.825835/.742302 15. CRAPS TEST .403090/.403088/.277389 ``` [Full `random.bin` here.](https://googledrive.com/host/0B0VNJlWZGkwNfmlvUjNOQUxoZmVuTWFfeFRnUk5wRVhuRVJWcTA0YjVGaDIwdzhnSUYyNWs/random.bin) [Full log file here.](https://gist.github.com/2012rcampion/ed6287fc82adff9e8a1d) [Answer] # Ruby, 32/15 = 2.1333 This is Keith Randall's solution, implemented in Ruby. ``` $v=3;def R;$v=$v**3%(2**32-5)end ``` [Answer] # ECMAScript 6, 31 30 25 / 15 = 1.66 This is Keith Randall's solution implemented in ES6: ``` e=3;R=_=>e=e**3%(2**32-5) ``` * Removed semicolon (thanks [The Thonnu](https://codegolf.stackexchange.com/users/114446/the-thonnu)!) * Drop unnecessary comma operator and use \_ for param (an assignment statement [will return the new value](https://stackoverflow.com/questions/16027247/value-returned-by-the-assignment)) [Answer] ## Python, 41 / 15 = 2.73333 ``` v=0 def R():global v;v=hash(`v`);return v ``` Kinda cheating using the built-in hash function, but it *is* built-in, so no more cheating than using other builtins, like `len`. On the flip side, it pains me to have to pay for the `global v;` statement... Passes all the Diehard tests (I had a problem with test #2, it SEGVs on my OSX machine. For my score, I'm assuming it will pass). Here's a driver to generate the 16MB file: ``` import sys for i in xrange(1<<22): r=R() sys.stdout.write('%c%c%c%c'%(r&255, r>>8&255, r>>16&255, r>>24&255)) ``` [Answer] # C# 144 / 15 = 9.6 ``` uint a=15,b=26,y;uint q(int n){y=(a*1414549U+876619U)^(b*889453U+344753U);b=a;a=y>>12;return(a%256)<<n;}uint r(){return q(24)|q(16)|q(8)|q(0);} ``` This passed all of the tests. With not too many more characters it passes TestU01. Result: <http://codepad.org/iny6usjV> ``` uint a = 15; uint b = 26; byte prng8() { uint y = ((a * 1414549U + 876619U) ^ (b * 889453U + 344753U)) >> 12; b = a; a = y; return (byte)y; } uint prng32() { return ((uint)prng8() << 24) | ((uint)prng8() << 16) | ((uint)prng8() << 8) | (uint)prng8(); } ``` [Answer] **C, 38/15 = 2.533** ``` long long x;f(){return(x+=x*x+9)>>32;} ``` I couldn't get the Diehard tests working on my machine, but it passes the PractRand suite for up to 8GB of output so I assume it would pass them all. [Answer] # C# - 103 / 14 = 7.36 ``` double j=999;uint N(){uint i=0,n=0;for(;i++<4;n=n*256+(uint)j%256)for(j/=277;j<100000;j*=j);return n;} ``` ## Results Passes all except test #6 See results at <http://codepad.org/k1NSoyQW> ## Explanation C# just can't compete with Ruby and Python for terseness, as usual, but I enjoyed trying. There are certainly other values that will work just as well (i.e., the initial value for j=999, and the divisor=277). I picked these after brief experimentation. ## With file-creation wrapper ``` class R { public static void Main(string[] args) { var r = new R(); using (var f = new System.IO.FileStream(".\\out.bin", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read)) using (var b = new System.IO.BinaryWriter(f)) { for (long i = 0; i < 12 * 1024 * 1024; i += 4) { b.Write(r.N()); } } } double j = 999; uint N() { uint i = 0, n = 0; for (; i++ < 4; n = n * 256 + (uint)j % 256) for (j /= 277; j < 100000; j *= j) ; return n; } } ``` [Answer] # [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 344/(pending) ``` <>((()()){})<> push the amount of iterations to do for the PRNG (((((((((((((((((((((((((((((((((((()()()){}()){})){}{}){()()()()({}[()])}{})){}{})){}{})()){}{})()){}{})){}{})){}{}){}())){}{})){}{})()){}{})()){}{})){}{})){}{})()){}{})()){}{}) push M (one of the values for the Blum Blum Shub PRNG ((((((((((((()()()){}){}){})){}{}){()({}[()])}{}){}())){}{})()){}{}) push s see above <>{({}[()])<>starts the loop (({({})({}[()])}{}) squares the current number (<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({}))mods by M <>}{}<>loop ends ``` [Try it online!](https://tio.run/##jVE7DsMgDN05hUd76A0QN@gJogxUoUrUBFIgE8rZKYG0@ahDwBjJ7/k9Ix5Wdvr27OUrRi4QkZAozMQFjJNrwbcK5GAm7cE8ofPKSt8Z7cAbaAzDC4tWzSKcTsqhVNMOc4VU0/yDSsbTvc9Z6ir5jJVn3dnfEdfYZtxNt3M9ajnGRfgyueiNGcF5aX3yWOoHFXDvSVrFkAuipQ@z39aeSCnSV1SLYZ3hwTQsI6u60k2MHw "Brain-Flak – Try It Online") This works fine but the diehard tests links are all broken :( so until we get new ones i do not have a final score This uses the Blum Blum Shub PRNG so it should pass most the cases. The numbers used are large enough no patterns will appear within the 16 MB of test cases [Answer] # Objective-C, 40/1 = 40 Pretty clever approach, exploiting `.hash` to somewhat cheat here, but I like it ``` for(int v=9;v=@(v).hash;printf("%i",v)); ``` ]
[Question] [ This was inspired by a math problem I saw somewhere on the internet but do not remember where (UPDATE: The original problem was found on [the math riddles subreddit](https://www.reddit.com/r/mathriddles/comments/2v6eaj/doubling_and_adding_1/) with a proof provided that it is possible, also see [this Math SE post](https://math.stackexchange.com/a/2767139/558915)), asking for a proof if the following process is possible for any arbitrary pair of integers (from what I remember, it was possible for any given pair): Given a pair of integers, j and k, double one of them and add one to the other, resulting in a pair of new integers, i.e., (j, k) -> (j+1, k\*2) or (j\*2, k+1). Then repeat this process with those integers, with the objective of having the pair of integers be equal. These given examples are not necessarily optimal but show how this process can be done on any integers, positive, negative or zero: ``` (2, 5) -> (3, 10) -> (6, 11) -> (12, 12) (5, 6) -> (6, 12) -> (7, 24) -> (14, 25) -> (28, 26) -> (56, 27) -> (112, 28) -> (113, 56) -> (226, 57) -> (227, 114) -> (228, 228) (0, 2) -> (1, 4) -> (2, 5) -> (3, 10) -> (6, 11) -> (12, 12) (-4, 0) -> (-3, 0) -> (-2, 0) -> (-1, 0) -> (0, 0) (3, -1) -> (6, 0) -> (12, 1) -> (13, 2) -> (14, 4) -> (15, 8) -> (16, 16) (-4, -3) -> (-8, -2) -> (-16, -1) -> (-32, 0) -> (-31, 0) -> ... -> (0, 0) ``` ## Challenge Create a program that given two integers, outputs the list of steps required to make those integers equal by repeatedly incrementing one and doubling the other ## Specifications * The solution does not have to be optimal but it must solve in a finite number of steps for any arbitrary pair * Input must be two integers * Output may be any reasonable output that clearly denotes the resulting integers of each step, for example: + a string with two distinct delimiters (any symbol, whitespace, etc), one for each integer in a pair and one for each pair - e.g., input j, k: 2, 5 -> output: 3,10;6,11;12,12 + a list of lists of integers - e.g. input j, k: 2, 5 -> output: [[3, 10], [6, 11], [12, 12]] * If the input is a pair of equal numbers, you may output anything as long as it's consistent with other nontrivial answers + for example - if input [2, 5] has output [[3, 10], [6, 11], [12, 12]], which does not include the input pair, then input [4, 4] should output nothing. - if input [2, 5] has output [[2, 5], [3, 10], [6, 11], [12, 12]], which does include the input pair, then input [4, 4] should output [[4, 4]]. * Standard IO methods apply and standard loopholes banned * This is code golf so shortest answer in bytes wins [Answer] # JavaScript (ES6), ~~111~~ ~~90~~ 83 bytes ``` f=(a,b,p=q=[],u=[...p,[a,b]])=>a-b?f(...(q=[[a*2,b+1,u],[a+1,b*2,u],...q]).pop()):u ``` [Try it online!](https://tio.run/##bcpBDsIgEAXQvadgOaMDaal1YYIehLCAWoymKdSK18fZmrqaP@//p//4dXg98lvO6TbWGg14CpTNYqyjYqxSKpNlcw7NxctwjcAG3Fu/1xQOLRXHC76Bf85cLw5VThkQz6UOaV7TNKop3SGCJtEj7n6xJ3HaYENCb1AeSTQb7UjI9u9Wdoj1Cw "JavaScript (Node.js) – Try It Online") ### Commented ``` f = ( // f = recursive function taking: a, b, // (a, b) = input integers p = // p[] = current path q = [], // q[] = queue u = [...p, [a, b]] // u[] = updated path with [a, b] appended to it ) => // a - b ? // if a is not yet equal to b: f(... // recursive call, using spread syntax: (q = [ // prepend the next 2 possible moves in the queue: [a * 2, b + 1, u], // a * 2, b + 1 [a + 1, b * 2, u], // a + 1, b * 2 ...q // ]).pop() // use the move on the top of the queue ) // end of recursive call : // else: u // success: return the (updated) path ``` [Answer] ## Haskell, ~~70~~ 69 bytes ``` f(w@((i,j):_):r)|i==j=w|1<2=f$r++[(i+1,j*2):w,(i*2,j+1):w] g x=f[[x]] ``` [Try it online!](https://tio.run/##JYc9DsIgFIB3T8Hg8F55mEKtA5HEC3gCQgyDrWDbNGhCh94dSVy@n5f/vJ/TVMoA@QYQKKJ@oE64B2Oiybu8KjMcE@cWApcUG4U6E4RGUeSytjuMbDODtZtzZfZhYYbNfr0zWFNYvqcRmQVFPRL0dKlsSVWKM7VVHQn5P9GhKz8 "Haskell – Try It Online") A simple BFS. Keeps track of the steps in a list of list of pairs. ``` g x=f[[x]] -- start with a single list where the only -- step is the starting pair f (w@((i,j):_):r) = -- let w be the first list of steps -- (i,j) the last pair of the first list of steps ('last' as in last operated on. As we store the steps in reverse order it's the first element in the list) -- r all other lists of steps i==j=w -- if i==j stop and return the first list 1<2= f -- else make a recursive call r++ -- where the new input list is r followed by -- the first list extended one time by [(i+1,j*2):w, (i+1,j*2) and one time by (i*2,j+1):w] (i*2,j+1) ``` [Answer] # [Python 3](https://docs.python.org/3/), ~~90~~ ~~74~~ 72 bytes -2 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis). ``` def f(a,*x):j,k=a[0];return(j==k)*a or f(*x,[(2*j,k+1)]+a,[(j+1,2*k)]+a) ``` [Try it online!](https://tio.run/##NY1NDoIwFIT3nmI2hL7yMAXEhQYvQlgQhVjQ0rQl0dNjWbiYzE@@ZOw3PBdTbfptFxfgv/4QdfRDcMN9dV4v5qXfOohaKUXbYxgxip7lhy4Tz03fqu7qhrA6I6ammUn2WFxE5IdbUcrIZAV1WR/blBVcynlvtI2RstAGomTUxBA147y7YpS75yeG2kPFyIv/kld0OQDWaRNEmnjkNyQ@RQJhOf62tiOi7Qc "Python 3 – Try It Online") Takes input as a [singleton list](https://codegolf.meta.stackexchange.com/a/11884/64121). --- ## Ungolfed ``` def f(a,*x): # function taking at least one argument # a is the first argument, all other are stored in x j, k = a[0] # get the newest values of the current path return (j==k)*a # if j is equal to k return the current path or # else ... f( # continue ... *x, # with the remaining paths ... [(2*j,k+1)]+a # and split the current path ... [(j+1,2*k)]+a # in two new ones ) ``` [Answer] # Pyth, 41 bytes ``` J]]QL,hhb*2ebWt{KehJ=J+tJm+hJ]d,yK_y_K)hJ ``` [Try it here](http://pyth.herokuapp.com/?code=J%5D%5DQL%2Chhb%2A2ebWt%7BKehJ%3DJ%2BtJm%2BhJ%5Dd%2CyK_y_K%29hJ&input=%5B2%2C%205%5D&debug=0) ### Explanation This is pretty straightforward breadth-first search. Keep a queue of possible sequences (`J`), and until we get a matching pair, take the next sequence, stick on each of the possible moves, and put them at the end of the queue. For the sake of brevity, we define a function `y` (using the lambda expression `L`) to perform one of the moves, and apply it both forward and in reverse. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes ``` ḃ2d2;@+*¥\ 0çṪEɗ1#Ḣç ``` [Try it online!](https://tio.run/##y0rNyan8///hjmajFCNrB22tQ0tjuAwOL3@4c5XryemGyg93LDq8/P/hdsNjS9wfNa3JetS479C2Q9v@/4820lEwjdVRiDbVUTAD0QY6CkYgWtdER8EAxDDWUdA1hInoGscCAA "Jelly – Try It Online") [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), ~~25~~ ~~22~~ 20 bytes Takes a doubly nested list as input and outputs a jagged list with each step at one nest-depth. ``` [ć¤Ë#¤xs>R‚ø`R‚s¸sâ« ``` [Try it online!](https://tio.run/##MzBNTDJM/f8/@kj7oSWHu5UPLakotgt61DDr8I4EEFV8aEfx4UWHVgNVREcb6ZjGxsYCAA "05AB1E – Try It Online") **Explanation** ``` [ # start a loop ć # extract the first element of the current list (current path) ¤Ë# # break if all elements in the head are equal ¤xs> # duplicate one copy of the head and increment another R # reverse the incremented copy ‚ø # zip them together `R‚ # reverse the tail of the zipped list s¸sâ # cartesian product with the rest of the current path « # append to the list of all current paths ``` [Answer] # [Retina](https://github.com/m-ender/retina/wiki/The-Language), 72 bytes ``` \d+ * /\b(_+),\1\b/^+%`(_+),(_+)$ $&;_$&$2¶$=;$1$&_ G`\b(_+),\1\b _+ $.& ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8D8mRZtLi0s/JkkjXltTJ8YwJkk/Tls1AcwDESpcKmrW8SpqKkaHtqnYWqsYqqjFc7knIKnnitfmUtFT@//fSMeUy1THDAA "Retina – Try It Online") Only two test cases due to the limitations of unary arithmetic. Explanation: ``` \d+ * ``` Convert to unary. ``` /\b(_+),\1\b/^+ ``` While the input does not contain a pair of identical numbers... ``` %`(_+),(_+)% ``` ...match the last pair on each line... ``` $&;_$&$2¶$=;$1$&_ ``` ...and turn the line into two lines, one suffixed with the first number incremented and second doubled, the other suffixed with the first number doubled and second incremented. ``` G`\b(_+),\1\b ``` Keep the line with the matching pair. ``` _+ $.& ``` Convert back to decimal. ~~89~~ 88-byte unsigned decimal arithmetic version (works with 0 as well): ``` /\b(\d+),\1\b/^+%`(\d+),(\d+)$ $&;$.(_$1*),$.(2*$2*)¶$=;$.(2*$1*),$.(_$2* G`\b(\d+),\1\b ``` [Try it online!](https://tio.run/##K0otycxLNPyvquGe8F8/JkkjJkVbUyfGMCZJP05bNQHCBZMqXCpq1ip6GvEqhlqaOkCGkZaKkZbmoW0qttYQHlQ8HijM5Z6AbNb//0Y6plymOmZcBjpGAA "Retina – Try It Online") [Answer] # [MATL](https://github.com/lmendo/MATL), 24 bytes ``` `vxG1r/q:"tt1rEk(+]td0=~ ``` Running time is random, but it is finite with probability 1. The code is very inefficient. Inputs requiring more than 4 or 5 steps have a large probability of timing out in the online interpreter. [**Try it online!**](https://tio.run/##y00syfn/P6Gswt2wSL/QSqmkxLDINVtDO7YkxcC27v//aAMFo1gA) ### Explanation ``` ` % Do...while vx % Concatenate stack and delete. This clears the stack from contents % of previous iterations G % Push input 1 % Push 1 r % Push random number uniformly distributed on (0,1) / % Divide q % Subtract 1. The result is a random number, t, that has nonzero % probability of being arbitrarily large. Specifically, t is in % the interval (0,1) with probability 1/2; in (1,2) with probability % 1/6; ... in (k,k+1) with probability 1/((k+1)*(k+2). : % Range [1 2 ... floor(t)] " % For each (that is: do thw following floor(t) times) tt % Duplicate twice 1 % Push 1 rEk % Random number in (0,1), times 2, round down. This produces a % number i that equals 0 or 1 with probability 1/2 ( % Write 1 at entry i. So if the top of the stack is [a b], this % transforms it into either [1 b] or [a 1] + % Add, element-wise. This gives either [a+1 2*b] or [2*a b+1] ] % End for each td % Duplicate, consecutive difference between the two entries 0=~ % Is it not zero? If so, the do...while loop continues with a new % iteration. Normally the code 0=~ could be omitted, because a % nonzero consecutive difference is truthy. But for large t the % numbers a, b may have gone to infinity, and then the consecutive % difference gives NaN % End do...while (implicit). Display (implicit) ``` [Answer] # [Stax](https://github.com/tomtheisen/stax), ~~29~~ 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax) ``` ä⌠|Tô&cm♂NV↓↔╗╣¢♠╜╒█¡Φ≈ñY@ ``` [Run and debug it](https://staxlang.xyz/#p=84f47c549326636d0b4e56191dbbb99b06bdd5dbade8f7a45940&i=[[1+3]]%0A[[-1+-2]]&a=1&m=2) It's a breadth first search. It seems reasonably fast. It takes a doubly-array-wrapped pair of integers. The output is a space separated list of values. Every two values represents one pair in the path to the solution. [Answer] # [Haskell](https://www.haskell.org/), 95 bytes ``` g s|a:_<-[a|a@((x,y):_)<-s,x==y]=a g s=g$do a@((x,y):_)<-s;[(x*2,y+1):a,(x+1,y*2):a] h t=g[[t]] ``` [Try it online!](https://tio.run/##VcqxCoMwEIDh3ae4weGi56DQDqkHvkcIctCSSK2WJkMCvnt07fbD93sJ79e6luIgHKLnsTNyyISYKCs9q7ELlJizZamuhV393OHfHwZTM1Bue6WFMLU95Wa42lYeIjtjorXlI8sGDN/fskWoweON7qqc "Haskell – Try It Online") Outputs in reverse order, e.g. `h(2,5)` yields `[(12,12),(6,11),(3,10),(2,5)]`. [Answer] # [Red](http://www.red-lang.org), 142 bytes Takes the input as a doubly nested block of the pair of integers in [Red](http://www.red-lang.org)'s format `(2, 5)` -> `2x5` Returns the result as a list ot [Red](http://www.red-lang.org) pairs, for example `2x5 3x10 6x11 12x12`. Includes the initial pair. ``` func[c][a: copy[]foreach d c[l: last d if l/1 = l/2[return d]do replace/all{%+ 1x0 * 1x2 %* 2x1 + 0x1}"%""append/only a append copy d l "]f a] ``` [Try it online!](https://tio.run/##XY29CoMwAIR3n@IIuCiiibWD0JfoGjKE/FAhJCFViJQ@u7XtUOxy3Hccd8no7Wo0F4UdN7t4xZXgcoQKceXChmSkukFDcTfCyfu8@8nCtRSXXRlPZl6ShxY6IJnopDKtdO5R1qC5Q7UrK8oKLFPU6DJ9kpIQGaPxug3erZD40udzn3cgwkKKLabJz7DgnOVBiOLHQz4fuMvswM0pd4egzw39bzT9IWHvje0F "Red – Try It Online") ## Strict input: The input is two numbers, for example `2 5` # [Red](http://www.red-lang.org), 214 bytes ``` func[a b][g: func[c][a: copy[]foreach d c[l: last d if l/1 = l/2[return d]append/only a append copy d l + 1x0 * 1x2 append/only a append copy d l * 2x1 + 0x1]g a]c: copy[]insert/only c reduce[do rejoin[a 'x b]]g c] ``` [Try it online!](https://tio.run/##fY/NCsIwEITvfYq5CZViE38OBV/Ca8ghbhKthKTEFurT16XF6snL8g27M@xkZ6eLs0oXvpn8EEkZXLW6NZgFaWUaUOpeSvuUnaE7LEiFBsE8e@bWI@wEzjylyq4fcoTVputctLsUwwsGi5pj2BGwhRhrlDxl8f@yhBwF39ej0DcYTZ9n2vh0uV9shOzsQE7ZxPRIbeQSm5F7sIf01OU29vCQOBYfPuK0cg25cnVAvYo9KvG7qfbFN0tObw "Red – Try It Online") ## Explanation: ``` f: func[a b][ g: func[c][ ; recursive helper function a: copy[] ; an empty block foreach d c[ ; for each block of the input l: last d ; take the last pair if l/1 = l/2[return d] ; if the numbers are equal, return the block append/only a append copy d l + 1x0 * 1x2 ; in place of each block append two blocks append/only a append copy d l * 2x1 + 0x1 ; (j+1, k*2) and (j*2, k+1) ] ; using Red's arithmetic on pairs g a ; calls the function anew ] c: copy[]insert/only c reduce[do rejoin[a 'x b]]; prepares a nested block from the input g c ; calls the recursive function ] ``` ]
[Question] [ You may have seen something called a "perpetual dice calendar": [![perpetual dice calendar](https://i.stack.imgur.com/7O4xb.jpg)](https://i.stack.imgur.com/7O4xb.jpg) Two 6-sided dice can be rearranged and rotated. One die has the numbers 0, 1, 2, 3, 4, and 5. The second die has the numbers 0, 1, 2, 6, 7, and 8. With this, any day of the month—from 1 to 31—can be displayed on the front of the calendar. *The `6` can be rotated to be used as a `9`.* However, what if I wanted to display any number up to... 100? 365? 50287? How many 6-sided dice would I need then, and what numbers would be printed on their sides? The challenge: * Given a whole number input X, output the fewest possible 6-sided dice that are required to display all integers from 1 up to and including X. * Each side of a die must contain exactly one integer, from 0 to 8 inclusive. * `6`'s may be used as `9`'s. * If not every side of every die needs to have a number on it, then those side(s) must have `0`. * Each line of the output should represent a die, e.g.: ``` Input: 4 Output: 0 0 1 2 3 4 Input: 6 Output: 1 2 3 4 5 6 Input: 9 Output: 0 1 2 3 4 5 0 0 0 6 7 8 Input: 31 Output: 0 1 2 3 4 5 0 1 2 6 7 8 Input: 35 Output: 0 1 2 3 4 5 0 1 2 3 6 7 0 0 0 0 0 8 ``` * The output lines can be in any format, e.g.: ``` 123456 1 2 3 4 5 6 1,2,3,4,5,6 [1, 2, 3, 4, 5, 6] ``` * Assume that all the dice are used for every number, using leading 0's if necessary. For instance, if X is 35, then `2` would be displayed as `002`, because 3 dice are necessary. * The outputted numbers do not need to be in any particular order. * There may be multiple solutions for X. You need only output one. * Standard golfing rules apply. [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page) ``` D€EƇZḢḟ9s<7+5Ɗo0x6¤Y ``` A full program that accepts a positive integer and prints a set of dice as lines each having six digits from \$[0,8]\$. **[Try it online!](https://tio.run/##y0rNyan8/9/lUdMa12PtUQ93LHq4Y75lsY25tumxrnyDCrNDSyL/6xxuV8l61DDHiutRw1xNEIsLxPr/38jICAA "Jelly – Try It Online")** ### How? For small inputs (\$\le 6\$) we should fill a single die with the numbers we need and then zeros. For larger numbers, we: * need multiple dice since one dice only has six sides, and * only place up to five non-zero digits on the first dice (since we will need at least one leading zero to represent small numbers like \$7\$ or \$8\$) When we reach a rep-digit that is not repeated nines (e.g. \$444\$) we need to ensure that enough of the dice have that digit (in this case three of them), and that any others contain a zero (since we will need them in front to represent the rep-digit). Thus an optimal output for numbers greater than six is to set the first face of every die to \$0\$ and fill the remaining faces with the digits \$1\$ to \$8\$ in order as required by either the number itself (excluding \$9\$) or the digit of the rep-digit we have reached that we cannot yet make. Thus for inputs greater than six we: * fill the first dice with \$[1,2,3,4,5,0]\$ * fill the second dice with \$[6,7,a,b,c,0]\$ where \$a\$, \$b\$ and \$c\$ are \$0\$ until we encounter \$8\$ (a non-nines rep-digit), \$11\$ and \$22\$ whereupon they should be filled with \$8\$, \$1\$ and \$2\$ respectively. * at \$33\$ create a new dice \$[3,d,e,f,g,0]\$ where \$d\$, \$e\$, \$f\$, and \$g\$ are \$0\$ until we encounter \$44\$, \$55\$, \$66\$, and \$77\$ whereupon they should be filled with \$4\$, \$5\$, \$6\$, and \$7\$ respectively. * etc. ``` D€EƇZḢḟ9s<7+5Ɗo0x6¤Y - Main Link: positive integer, N € - for each i in [1,N]: D - decimal digits Ƈ - keep those for which: E - all equal -> [[1],[2],...,[9],[1,1],[2,2],...,[9,9],...,[1,1,1],...] Z - transpose Ḣ - head -> [1,2,...,9,1,2,...,9,1,...] ḟ9 - filter out nines Ɗ - last three links as a monad - f(N): <7 - less than seven? 5 - five + - add -> 6 if N < 7 else 5 s - (filtered list of digits) split into chunks of length (that) e.g.: N=3 -> [[1,2,3]] N=44 -> [[1,2,3,4,5],[6,7,8,1,2],[3,4]] ¤ - nilad followed by link(s) as a nilad: 0 - zero 6 - six x - repeat -> [0,0,0,0,0,0] o - logical OR (vectorises) e.g.: N=3 -> [[1,2,3,0,0,0]] N=44 -> [[1,2,3,4,5,0],[6,7,8,1,2,0],[3,4,0,0,0,0]] Y - join with newline characters ``` [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), ~~29~~ 17 bytes ``` ~≈∩h9F5?6=+ẇṅ6∆Z⁋ ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ+4omI4oipaDlGNT82PSvhuofhuYU24oiGWuKBiyIsIiIsIjU1NSJd) *-12 bytes by taking some ideas from @Jonathan Allan's Jelly answer* I believe this is correct but I'm not completely sure. ``` ~≈ # keep only those numbers where all digits are equal from the implicit range [1, input] ∩ # transpose h # first element 9F # remove nines 5?6=+ # 6 if input is 6 otherwise 5 ẇ # split into chunks of that length ṅ # join 6∆Z # pad with zeros to length 6 ⁋ # join by newlines ``` [Answer] # Python3, 475 bytes: ``` from itertools import* R=range N=lambda k:k+[6,9]*(6 in k or 9 in k) P=permutations def f(n): q=[({*R(1,n+1)},[[]]if n<7 else[[0]])] while q: a,b=q.pop() if not a:return[[0]*(6-len(i))+i for i in b] t=str(min(a)) for i in P(b,min(len(b),len(t))): for j,k in zip_longest(t,i): j=int(j) if not k or j not in N(k): D=[*b,[0,j]]if len(b[-1])==6 else[*b[:-1],b[-1]+[j]];q+=[(a-{int(''.join(map(str,K)))for d in P(D,len(D))for K in product(*map(N,d))},D)] ``` [Try it online!](https://tio.run/##PVDLbsMgEDzXX7G3gE2iRGndxi233CJFUa4IVbjGDX4AwURVG/XbU7CrHBDs7Aw7s/bbn4xev1h3u9XO9KC8dN6YbgDVW@N8mhypE/pTJnvaib6sBLRFm7GcbHiKclAaWjAONuMLJwdqpesvXnhl9JBUsoYaaVwkcKYMXdMjWhGdrfAvYYxzVYN@ewbZDZKxJeeYJ/B1Up2Ec1CAICU9L6yxCIcqko0HUTjpL05HQXAw76RGCuNMQR18qOijDN@Ap4N3qFcaCRzl9@4BlSTCUVhiEi@PcbQ4kRrSRtqPsu@dCckHjzxRUx8aqrRHDR6Lf0fjAprxGXR71P5zYUtZWhK2JM0YdRzI5iuOKc2n0GnJigCQEc5Y4L2es7AoMb/GObPZojHBai8sCmnILviMFqspx3Y0v52wXcSsM9Xlw6M0KvakwmHRW8xv9/DskUBOYENgvQrniRfJg3VxVh23ePsD) [Answer] # Excel, ~~161 122 120~~ 122 bytes *saved 39 bytes after looking at AndrovT's solution and fixing error for n=6* *saved 2 more bytes after realizing the die for N=6 didn't need to have a 1* *added 2 bytes because the previous statement was false* ``` =LET(x,ROW(1:8),y,LEN(A1),z,A1=6,IFERROR(HSTACK(z*1,MOD(SEQUENCE(INT((y*8+MAX(x*(REPT(x,y)*1<=A1))-4-z)/5),5)+z-1,8)+1),)) ``` The formula above determines how many faces are needed to cover all numbers less than or equal to N then generates dice from the list below so there at least that many faces. ``` 0 1 2 3 4 5 0 6 7 8 1 2 0 3 4 5 6 7 0 8 1 2 3 4 0 5 6 7 8 1 0 2 3 4 5 6 0 7 8 1 2 3 0 4 5 6 7 8 ``` If N = 6 it uses `1 2 3 4 5 6`. **Explanation:** ``` =LET(x,ROW(1:8), # x = array 1..8 y,LEN(A1), # y = number of digits in N z,A1=6, # z = (N=6) IFERROR(~,) # Pads errors with 0 HSTACK(z*1,~) # Concatenates 0 to other 5 faces MOD(SEQUENCE(~,5)+z-1,8)+1 # array of last 5 faces for each die INT((~)/5) # number of dice needed y*8+MAX(x*(~))-4-z # 4 + number of faces needed to cover all numbers up to ~ REPT(x,y)*1<=A1 # calculates the largest number the same length as N with repeated digits ``` [Answer] # JavaScript (ES8), 111 bytes Algorithm shamelessly borrowed from [@AndrovT](https://codegolf.stackexchange.com/a/260444/58563)'s latest version, which itself uses ideas from [@JonathanAllan](https://codegolf.stackexchange.com/a/260448/58563). Returns an array of digit strings. ``` n=>n-6?(g=n=>n?g(n-1)+(/^([1-8])\1*$/.test(n)?n%10:''):'')(n).match(/.{1,5}/g).map(s=>s.padEnd(6,0)):["123456"] ``` [Try it online!](https://tio.run/##HYzLCsIwFET3fkUQxRtNU6O2@CDtyo0LXbisFUIfsaI3pQmCiN9eWwcOzJnF3NVL2aypauehyYu2lC3KCL0wBi37FmtAT9AZ@FdIhLdO6UVMRz53hXWANMaxmG8nE9rTOX8ql93A5x/Bgq@v@6EGKyPLa5XvMYeQzSndJkOxWK6CcJi2u2TFSMjIhpGl6AjSAS9Ns1fdDxIZkcygNY@CP4yGw/l05NY1FeqqfEMJyJ05/x1on/YH "JavaScript (Node.js) – Try It Online") [Answer] # [Charcoal](https://github.com/somebody1234/Charcoal), 29 bytes ``` E⪪⁻⭆ΦI…·¹N⁼⌊ι⌈ι⌊ι9⁺⁵⁼θ6⭆◨ι⁶Σλ ``` [Try it online!](https://tio.run/##RYxBCsIwEEWvUrKaQgVdWCoui0IXlWK9QAyhHUjStEmKnj5Oiuhm@PPmzRcjX8TEVYzdgsZDyy30ViElNMFB7wkPiV5ReblAzZ2HxggVHK7yzs0g4VBkjbHB34J@kpLneZFd5sCVSy2ogwYk1PLXNyfhf6GFnRjNjkrh@PudiZdsk@u3ULIeJwubg0X2QC03me1ZMkryzjFWVdyt6gM "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Once I'd figured out what the problem actually was, this is an implementation of @Axuary's observation, although comparing the other answers I see I ended up with the same basic algorithm as @AndrovT and @JonathanAllan but only by coincidence. ``` …· Inclusive range from ¹ Literal integer `1` to N First input as a number I Vectorised cast to string Φ Filtered where ⌊ι Minimum digit ⁼ Is equal to ⌈ι Maximum digit ⭆ ⌊ι Extract one digit from each repdigit ⁻ 9 Remove `9`s ⪪ Split into groups of ⁵ Literal integer `5` ⁺ Plus θ First input ⁼ Equals 6 Literal string `6` E Map over groups ◨ι⁶ Pad to 6 characters ⭆ Σλ Replace spaces with `0`s Implicitly print ``` The above code is sublinear in `X`, so here's more efficient 35-byte version: ``` E⪪⁻⭆⁺÷×⁹⊕NXχLθ×⁹⊖Lθ﹪⊕ι⁹0⁺⁵⁼θ6⭆◨ι⁶Σλ ``` [Try it online!](https://tio.run/##TY7NDoIwEIRfpeG0JDXBgwTiFQ8kYoj4AhUa2KQ/UFp8/NpyUG673@zMTj8x02smvG8NKgsNm6GbBYYJlVuhswGPkbYirLWyFW44cHih5CuUlNSqN1xyZfkQ5NnZh5NvbiBNU0pa/QnjOaPkztVoJ1h2/DNX/G8@XISTRg9OaDimY8Bl1JIsidmx0IWS2@KYWGEJPE9276E0G544ThaQkjwqToKID67eF4U/beIL "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Calculates the number of repdigits up to `X` as equal to the first digit of `(X+1)*9` plus `9` times the length of `X` as a string plus a correction factor, then takes the sequence modulo `9` omitting the zeros and wraps into rows as above. The problem would have been much more interesting if each number only needed to be formed from `1+floor(log10(X))` dice. In that case, my best patterns so far are as follows: * 6: 123456 * 9: 123456, 78 * 10: 012345, 0678 * 21: 012345, 06781 * 32: 123450, 678012 * 54: 123456, 781234, 0 * 65: 123456, 781234, 05 * 76: 123456, 781234, 056 * 87: 123456, 781234, 0567 * 99: 123456, 781234, 05678 * 221: 123456, 781234, 056781, 0 * 332: 123456, 781234, 056781, 02 * 443: 123456, 781234, 056781, 023 * 554: 123456, 781234, 056781, 0234 * 665: 123456, 781234, 056781, 02345 * 776: 123456, 781234, 056781, 023456 * 887: 123456, 781234, 056781, 023456, 7 * 999: 123456, 781234, 056781, 023456, 78 * 1110: 123456, 781234, 056781, 023456, 780 * 2221: 123456, 781234, 056781, 023456, 7801 * 3332: 123456, 781234, 056781, 023456, 78012 * 4443: 123456, 781234, 056781, 023456, 780123 I believe that the dice will then continue cyclically though the digits after that point. [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 44 (or 42†) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) ``` [8Ý6ãNã.ΔULε§Xgj„9 60‡œεXsøε`å}P}à}P}D¸àd#}» ``` Extremely slow brute-force, so it'll time out for \$n\geq7\$ on TIO.. Not too happy with how long `§Igj„9 60‡œεXsøε`å}P}à` is. Will see if I can find something shorter (and hopefully faster) later on. [Try it online](https://tio.run/##AUoAtf9vc2FiaWX//1s4w502w6NOw6MuzpRVTM61wqdYZ2rigJ45IDYw4oChxZPOtVhzw7jOtWDDpX1QfcOgfVB9RMK4w6BkI33Cu///NA) or [verify some of the smaller test cases](https://tio.run/##yy9OTMpM/W96bJKSZ15BaYmVgpK936GVOlxK/qUlEL7O/2iLw3PNDi/2O7xY79yU0EPrDs89t/XQ8oj0rEcN8ywVzAweNSw8Ovnc1ojiwzvObU04vLQ2oPbwAiDhcmjH4QUpyrWHdv/XObTN/j8A). † With looser output-format of a list of lists of digits, the trailing `}»` can be removed for -2 bytes. **Explanation:** ``` [ # Start an infinite loop: 8Ý # Push a list in the range [0,8] 6ã # Cartesian power of 6 to create all sextets using these digits Nã # Cartesian power with the 0-based loop-index .Δ # Find the first one that's truthy for, # or -1 if none are truthy: U # Pop and store the current list in variable `X` Ý # Push a list in the range [0, (implicit) input-integer] ε # Map over each value: Xg # Push the length of list `X` § j # Pad leading spaces to make the current integer that length „9 60‡ # Transliterate 9s to 6s and spaces to 0s œ # Get all permutations of this integer ε # Map over each permutation: Xs # Push list of lists `X` and swap ø # Create pairs of the two lists ε # Map over each pair of [list,digit] ` # Pop and push the list and digit separately to the stack å # Check if the digit is in the list }P # After the map: check whether it's truthy for all [list,digit]-pairs }à # After the map: check whether it's truthy for any permutation }P # After the map: check whether it's truthy for all values in the range }D # After the find_first: Duplicate the resulting -1 or list ¸ # Wrap it into a list à # Pop and push the flattened maximum d # If this maximum is non-negative (thus not -1): # # Stop the infinite loop }» # After the infinite loop: join each inner list of the valid find_first # by spaces, and then all strings by newlines # (after which it is output implicitly as result) ``` [Answer] # [Nibbles](http://golfscript.com/nibbles/index.html), 18 bytes (36 nibbles) ``` &"0"6`/ ?-$6 5 $ |+|.,$`$`@~$~<<$- 9 ``` Same approach as [Androv T's answer](https://codegolf.stackexchange.com/a/260444/95126): upvote that one! ``` |+|.,$`$`@~$~<<$- 9 # part 1: get the nonzero digits needed: . # map over , # range from 1.. $ # input `@ $ # convert to digits in base ~ # 10 `$ # and remove duplicates | # now filter to keep only ~ # falsy elements when <<$ # dropping the first element of each list + # flatten the list of (1-element) lists | # and filter again to keep only # elements that are truthy (positive) when - 9 # subtracted from 9 &"0"6`/ ?-$6 5 $ # part 2: split them into dice: `/ # split into chunks of ? # if -$6 # input minus 6 is truthy 5 # then 5 $ # else input & # now justify each chunk 6 # to a width of 6 "0" # using "0" as a filler ``` [![enter image description here](https://i.stack.imgur.com/aDhaM.png)](https://i.stack.imgur.com/aDhaM.png) --- Frustratingly, if we were allowed to use `9`s instead of `6`s (rather than `6`s instead of `9`s), which would correspond to identical physical dice, we could have: # [Nibbles](http://golfscript.com/nibbles/index.html), 16.5 bytes (33 nibbles; but not permitted output) ``` &"0";6`/ +`$- $@ $ +`%+|.,@`$`@~$~<< ``` [![enter image description here](https://i.stack.imgur.com/Cw1g7.png)](https://i.stack.imgur.com/Cw1g7.png) [Answer] # [Python 2](https://docs.python.org/2/), 120 bytes ``` n=input() m=n>6 for v in zip(*[(i%10for i in range(n>1,n+1)+4*[0]if len(set(`i`))<2-i%10/9)]*(6-m)):print'0'*m+`v`[1::3] ``` A full program that accepts a positive integer from STDIN and prints the dice. **[Try it online!](https://tio.run/##FcvRCoIwFADQd79iL@G9W5KzEBvpj4zBetC60K5jLaF@fuHrgRO/@blyVwqPxPGTAasw8tRXy5rEJojFjyJIC3TQ7W60W7rzYwae9JGVRnWRtnW0iNfM8J4zePKIt67Zz@mKTkLfBEQTE3Gu21oG5TdvtTFnV8ow/AE "Python 2 – Try It Online")** Or see the [test-suite](https://tio.run/##RVDRasMwDHz3V@hl2E6cLU7arDVzfyQLJG3dzlArIfXK1rJvz2wzmEDoOKS7Q9O3/xixWg7j0WhK6fuC2uL06RknTuOuIadxhhtYhLudWNYy@yTLyNnIzQOeDcOdFJhLnq@ytuzsCS4G2dV41tue87eqiDcvW95lrCkc52qaLXpa0szl/a1vpVJ1twT3VhWyIyQF0JfB7Y@D8ubqU4gIoieTAioBtYCVgEbANuBA1WsBm9fQGwEyVvk3JVcEQiVToEkcNDx@FH0Oum7wLErztGS@zAHiM/5Pll8 "Python 2 – Try It Online"). This employs the same method I used in [my Jelly answer](https://codegolf.stackexchange.com/a/260448/53748). ]
[Question] [ > > In public-key cryptography, a public key fingerprint is a short sequence of bytes used to identify a longer public key. > > > In SSH in particular they can be used to verify that a server is in fact the server I'm expecting to communicate with and I'm not targeted by a man-in-the-middle attack. They are usually represented as a string of hexadecimal digits, so it can be rather boring and tedious to compare it with the fingerprint I would expect: ``` 37:e4:6a:2d:48:38:1a:0a:f3:72:6d:d9:17:6b:bd:5e ``` To make it a little easier, OpenSSH has introduced a method to visualize fingerprints as ASCII art, that would look like the following: ``` +-----------------+ | | | | | . | | . o | |o . o . S + | |.+ + = . B . | |o + + o B o E | | o . + . o | | .o | +-----------------+ ``` With this, I could try to remember the rough shape of the ASCII art and would then (theoretically) recognize it when the fingerprint of the server changed and the image looks different. # How it works *Taken from [Dirk Loss, Tobias Limmer, Alexander von Gernler. 2009. The drunken bishop: An analysis of the OpenSSH fingerprint visualization algorithm](http://www.dirk-loss.de/sshvis/drunken_bishop.pdf).* The grid has a width of 17 characters and a height of 9 characters. The "bishop" starts at row 4/column 8 (the center). Each position can be denoted as [x,y], i.e. [8,4] for the starting position of the bishop. ``` 1111111 01234567890123456 +-----------------+ 0| | 1| | 2| | 3| | 4| S | 5| | 6| | 7| | 8| | +-----------------+ ``` The bishop uses the fingerprint to move around. It reads it byte-wise from left to right and from the least significant bit to the most significant bit: ``` Fingerprint 37 : e4 : 6a : ... : 5e Bits 00 11 01 11 : 11 10 01 00 : 01 10 10 10 : ... : 01 01 11 10 | | | | | | | | | | | | | | | | Step 4 3 2 1 8 7 6 5 12 11 10 9 64 63 62 61 ``` The bishop will move by the following plan: ``` Bits Direction ----------------- 00 Up/Left 01 Up/Right 10 Down/Left 11 Down/Right ``` Special cases: * If the bishop is in a corner and would move into the corner again, he doesn't move at all. *i.e: The bishop is at `[0,0]` and his next step would be `00`. He remains at `[0,0]`* * If the bishop is in a corner or at a wall and would move into one of the walls, he moves horizontally or vertically only. *i.e: The bishop is at `[0,5]` and his next step would be `01`. He cannot go left, so he just moves up, to `[0,4]`.* Each position holds a value of how often the bishop has visited this field: ``` Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10| 11| 12| 13| 14| 15| 16| Character | | . | o | + | = | * | B | O | X | @ | % | & | # | / | ^ | S | E | ``` The values 15 (S) and 16 (E) are special in that they mark the start and end position of the bishop respectively and overwrite the real value of the respecting position. # Goal Create a program, that takes an alphanumeric fingerprint as input and produces its ASCII art representation as shown in the examples. # Examples ``` Input: 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48 Output: +-----------------+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+ Input: b6:dd:b7:1f:bc:25:31:d3:12:f4:92:1c:0b:93:5f:4b Output: +-----------------+ | o.o | | .= E.| | .B.o| | .= | | S = .| | . o . .= | | . . . oo.| | . o+| | .o.| +-----------------+ Input: 05:1e:1e:c1:ac:b9:d1:1c:6a:60:ce:0f:77:6c:78:47 Output: +-----------------+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ``` # Rules * This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). The code in the fewest bytes wins. * You can **not** use an existing library that produces the image. * Use whichever language you prefer! * Your submission has to be a complete program [Answer] # Dyalog APL (178) ``` {⎕ML←3⋄F←9 17⍴0⋄5 9{(⍺⌷F)+←1⋄×⍴⍵:(1 1⌈9 17⌊⍺-1 1-2×↑⍵)∇1↓⍵⋄(⍺⌷F)←16⋄F[5;9]←15⋄K⍪(M,' .o+=*BOX@%&#/^SE'[1+F],M←'|')⍪K←'+','+',⍨17⍴'-'}⊃,/{↓⊖4 2⍴⍉(4/2)⊤¯1+⍵⍳⍨⎕D,'abcdef'}¨⍵⊂⍨':'≠⍵} ``` This is a function that takes the string as its right argument, and returns a character matrix containing the ASCII art representation, e.g.: ``` F←{⎕ML←3⋄F←9 17⍴0⋄5 9{(⍺⌷F)+←1⋄×⍴⍵:(1 1⌈9 17⌊⍺-1 1-2×↑⍵)∇1↓⍵⋄(⍺⌷F)←16⋄F[5;9]←15⋄K⍪(M,' .o+=*BOX@%&#/^SE'[1+F],M←'|')⍪K←'+','+',⍨17⍴'-'}⊃,/{↓⊖4 2⍴⍉(4/2)⊤¯1+⍵⍳⍨⎕D,'abcdef'}¨⍵⊂⍨':'≠⍵} F '16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48' +-----------------+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+ F 'b6:dd:b7:1f:bc:25:31:d3:12:f4:92:1c:0b:93:5f:4b' +-----------------+ | o.o | | .= E.| | .B.o| | .= | | S = .| | . o . .= | | . . . oo.| | . o+| | .o.| +-----------------+ ``` Explanation: * `⎕ML←3`: set `⎕ML` to `3`. This makes `⊂` more useful for splitting strings. * `F←9 17⍴0`: make a 17-by-9 matrix of zeroes. `F` represents how many times each position has been visited. * `⍵⊂⍨':'≠⍵`: split `⍵` on `:` characters. * `{`...`}¨`: for each group: + `¯1+⍵⍳⍨⎕D,'abcdef'`: find the index of each character in the string `'01234567890abcdef'`. Subtract 1, because APL is 1-indexed by default. + `(4/2)⊤`: convert the values to their 4-bit representations (there should now be 2-by-4 matrix). + `↓⊖4 2⍴⍉`: rotate the matrix, use the elements to fill a 2-by-4 matrix instead, mirror that matrix horizontally, and then get each line separately. This gives us the 4 2-bit values we need. * `⊃,/`: join the resulting lists together, giving a list of 2-bit steps. * `5 9{`...`}`: given the list of steps, and starting at position [9,5]: + `(⍺⌷F)+←1`: increment the current position in `F`. + `×⍴⍵:`: if the list of steps is not empty: - `↑⍵`: take the first step from the list - `⍺-1 1-2×`: get the delta for that step, and subtract it from the current position - `1 1⌈9 17⌊`: restrict movement to within the field - `(`...`)∇1↓⍵`: continue with the new position and the rest of the steps + If it *is* empty: - `(⍺⌷F)←16`: set `F` to 16 at the final position - `F[5;9]←15`: set `F` to 15 at the start position - `' .o+=*BOX@%&#/^SE'[1+F]`: map each position to the corresponding character - `K⍪(M,`...`,M←'|')⍪K←'+','+',⍨17⍴'-'`: wrap the result in lines [Answer] # Perl, 300 + 1 (-n) = 301 bytes ``` perl -ne 'sub b{$b=$_[0]+$_[1];$_[0]=$b<0?0:$b>$_[2]?$_[2]:$b}$v=pack"(H2)*",/\w\w/g;($x,$y)=(8,4);$a[b($y,($_&2)-1,8)*17+b($x,($_&1)*2-1,16)]++for map{vec$v,$_,2}0..63;@a[76,$y*17+$x]=(15,16);$c=" .o+=*BOX@%&#/^SE";print$d="+".("-"x17)."+\n",(map{+"|",(map{substr$c,$_,1}@a[$_*17..($_+1)*17-1]),"|\n"}0..8),$d' ``` This answer is disgusting, but it's also the first one for this puzzle, so it'll do for now. `-n` to take a line of input on STDIN and fill `$_`. ``` # b($v, -1 or 1, max) modifies $v within 0..max sub b{$b=$_[0]+$_[1];$_[0]=$b<0?0:$b>$_[2]?$_[2]:$b} # turn $_ into a binary string $v=pack"(H2)*",/\w\w/g; # initialize cursor ($x,$y)=(8,4); # find an element of single-dimensional buffer @a $a[ # y += (bitpair & 2) - 1, within 8 b($y,($_&2)-1,8) * 17 # x += (bitpair & 1) * 2 - 1, within 17 + b($x,($_&1)*2-1,16) # and increment it ]++ # for each bit pair (in the right order!) for map{vec$v,$_,2}0..63; # overwrite the starting and ending positions @a[76,$y*17+$x]=(15,16); # ascii art lookup table $c=" .o+=*BOX@%&#/^SE"; # output print # the top row, saving it for later $d="+".("-"x17)."+\n", # each of the eight middle rows (map{+ # converting each character in @a in this row as appropriate "|",(map{substr$c,$_,1}@a[$_*17..($_+1)*17-1]),"|\n" }0..8), # the bottom row $d ``` [Answer] # R, ~~465~~ ~~459~~ ~~410~~ ~~393~~ ~~382~~ 357 bytes ``` f=function(a){s=strsplit;C=matrix(as.integer(sapply(strtoi(el(s(a,":")),16),intToBits)[1:8,]),2);C[!C]=-1;n=c(17,9);R=array(0,n);w=c(9,5);for(i in 1:64){w=w+C[,i];w[w<1]=1;w[w>n]=n[w>n];x=w[1];y=w[2];R[x,y]=R[x,y]+1};R[]=el(s(" .o+=*BOX@%&#/^",""))[R+1];R[9,5]="S";R[x,y]="E";z="+-----------------+\n";cat(z);for(i in 1:9)cat("|",R[,i],"|\n",sep="");cat(z)} ``` With indentations and newlines: ``` f=function(a){ s=strsplit C=matrix(as.integer(sapply(strtoi(el(s(a,":")),16),intToBits)[1:8,]),2) C[!C]=-1 n=c(17,9) R=array(0,n) w=c(9,5) for(i in 1:64){ w=w+C[,i] w[w<1]=1 w[w>n]=n[w>n] x=w[1] y=w[2] R[x,y]=R[x,y]+1 } R[]=el(s(" .o+=*BOX@%&#/^",""))[R+1] R[9,5]="S" R[x,y]="E" z="+-----------------+\n" cat(z) for(i in 1:9)cat("|",R[,i],"|\n",sep="") cat(z) } ``` Usage: ``` > f("16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48") +-----------------+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+ > f("37:e4:6a:2d:48:38:1a:0a:f3:72:6d:d9:17:6b:bd:5e") +-----------------+ | | | | | . | | . o | |o . o . S + | |.+ + = . B . | |o + + o B o E | | o . + . o | | .o | +-----------------+ ``` [Answer] # Octave, 277 ``` d=reshape(rot90(dec2bin(hex2dec(strsplit(input('','s'),':'))))>'0',2,[])*2-1;p=[9;5];for m=1:64 p=[max(min(p(:,1)+d(:,m),[17;9]),1) p];end;A=' .o+=*BOX@%&#/^SE';F=A(sparse(p(2,:),p(1,:),1,9,17)+1);F(5,9)='S';F(p(2,1),p(1,1))='E';[a='+-----------------+';b=['|||||||||']' F b;a] ``` ### Explanation: ``` %// convert the input to binary and rearrange it to be %// an array of vectors: [x_displacement; y_displacement] d=reshape(rot90(dec2bin(hex2dec(strsplit(input('','s'),':'))))>'0',2,[])*2-1; %// start position array with vector for the start position p=[9;5]; %// for each move, add displacement, clamping to valid values for m=1:64 p=[max(min(p(:,1)+d(:,m),[17;9]),1) p];end; %// alphabet for our fingerprint A=' .o+=*BOX@%&#/^SE'; %// create a sparse matrix, accumulating values for duplicate %// positions, and replace counts with symbols F=A(sparse(p(2,:),p(1,:),1,9,17)+1); %// correct the start and end symbols and construct the final output F(5,9)='S';F(p(2,1),p(1,1))='E'; [a='+-----------------+';b=['|||||||||']' F b;a] ``` ### Sample run: ``` >> bish b6:dd:b7:1f:bc:25:31:d3:12:f4:92:1c:0b:93:5f:4b ans = +-----------------+ | o.o | | .= E.| | .B.o| | .= | | S = .| | . o . .= | | . . . oo.| | . o+| | .o.| +-----------------+ ``` [Answer] # Pyth, ~~145~~ ~~143~~ 140 ``` Jm*17]09A,4K8FYcz\:V4AmhtS[0^2d+@,HGdtyv@+_.BiY16*7\0+-4dyN),3 4 X@JGHh@@JGH; X@J4K15 X@JGH16 =Y++\+*17\-\+VJ++\|s@L" .o+=*BOX@%&#/^SE"N\|)Y ``` [Try it online.](https://pyth.herokuapp.com/?code=Jm*17]09A%2C4%3Dk8FYcz%5C%3AK%2B_.BiY16*7%5C0V4AmhtS[0%5E2hd%2Bedtyv%40K%2B-4hdyN%29%2C%2C3G%2C4H+X%40JGHh%40%40JGH%3B+X%40J4k15+X%40JGH16%0A%3DY%2B%2B%5C%2B*17%5C-%5C%2BVJ%2B%2B%5C|s%40L%22+.o%2B%3D*BOX%40%25%26%23%2F%5ESE%22N%5C|%29Y&input=37%3Ae4%3A6a%3A2d%3A48%3A38%3A1a%3A0a%3Af3%3A72%3A6d%3Ad9%3A17%3A6b%3Abd%3A5e&debug=0) Pyth isn't really good at challenges with iteration. I'm expecting CJam to beat it easily. [Answer] # JavaScript (ES6) 249 ~~208~~ **Edit** Added missing border Test running the snippet below in any EcmaScript 6 compliant browser ``` B=f=>f.replace(/\w+/g,b=>{for(b=`0x1${b}`;b-1;b>>=2)++g[p=(q=(p=(q=p+~-(b&2)*18)>0&q<162?q:p)+b%2*2-1)%18?q:p]},p=81,z=`+${'-'.repeat(17)}+`,g=Array(162).fill(0))&&g.map((v,q)=>q?q-81?q-p?q%18?' .o+=*BOX@%&#/^'[v]:`| |`:'E':'S':z+` |`).join``+`| `+z // TEST console.log=x=>O.innerHTML+=x+'\n' ;['37:e4:6a:2d:48:38:1a:0a:f3:72:6d:d9:17:6b:bd:5e' ,'16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48' ,'b6:dd:b7:1f:bc:25:31:d3:12:f4:92:1c:0b:93:5f:4b' ,'05:1e:1e:c1:ac:b9:d1:1c:6a:60:ce:0f:77:6c:78:47' ].forEach(t=>console.log(t+'\n'+B(t)+'\n')) // Less golfed BB=f=>( p = 81, g = Array(162).fill(0), f.replace(/\w+/g, b => { for(b = `0x1${b}`;b != 1; b >>= 2) q = p+~-(b&2)*18, p = q>0&q<162?q:p, p = (q=p+b%2*2-1)%18?q:p, ++g[p] }), g.map((v,q) => q-81?q-p?q%18?' .o+=*BOX@%&#/^'[v]:'\n':'E':'S') .join`` ) ``` ``` pre { font-family: menlo,consolas; font-size:13px } ``` ``` <pre id=O></pre> ``` [Answer] # Python, ~~381~~328 -51 thanks to @JonathanFrech ``` def h(f): s=[f'{int(o,16)>>s&3:02b}'for o in f.split(':')for s in(0,2,4,6)];r=[0]*153;p=76;w=17 for d in s:r[p]+=1;p+=(-(p%w!=0),p%w!=16)[int(d[1])]+(-w*(p//w!=0),w*(p//w!=8))[int(d[0])] r[76]=15;r[p]=16;b='+'+'-'*w+'+';print(b);i=0 while i<153:print(f"|{''.join(' .o+=*BOX@%&#/^SE'[c]for c in r[i:i+w])}|");i+=w print(b) ``` Slightly ungolfed for the sake of explanation: ``` def h_(f): #Alias 17 because it gets used enough times for this to save bytes w=17 #Input parsing s=[f'{int(o,16)>>s&3:02b}'for o in f.split(':')for s in(0,2,4,6)] #Room setup r=[0]*153 p=76 #Apply movements for d in s: r[p]+=1 p+=(-(p%w!=0),p%w!=16)[int(d[1])]+(-w*(p//w!=0),w*(p//w!=8))[int(d[0])] r[76]=15 #Set start position r[p]=16 #Set end position #Display result b='+'+'-'*w+'+' print(b) i=0 while i<153: print(f"|{''.join(' .o+=*BOX@%&#/^SE'[c]for c in r[i:i+w])}|") i+=w print(b) ``` This mess of a line: ``` r[p]+=1;p+=(-(p%w!=0),p%w!=16)[int(d[1])]+(-w*(p//w!=0),w*(p//w!=8))[int(d[0])] ``` ​ is functionally equivalent to this: ``` if int(d[0]): #Down, Y+ if p//17!=8: p+=17 else: #Up, Y- if p//17!=0: p-=17 ​ if int(d[1]): #Right, X+ if p%17!=16: p+=1 else: #Left, X- if p%17!=0: p-=1 ``` but nests all of the conditionals in this style of golf shortcut: `(false_value,true_value)[condition]` Hopefully the rest is fairly self-explanatory # Tests ``` h('16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48') +-----------------+ | . | | + . | | . B . | | o * + | | X * S | | + O o . . | | . E . o | | . . o | | . . | +-----------------+ h("b6:dd:b7:1f:bc:25:31:d3:12:f4:92:1c:0b:93:5f:4b") +-----------------+ | o.o | | .= E.| | .B.o| | .= | | S = .| | . o . .= | | . . . oo.| | . o+| | .o.| +-----------------+ h("05:1e:1e:c1:ac:b9:d1:1c:6a:60:ce:0f:77:6c:78:47") +-----------------+ | o=. | | o o++E | | + . Ooo. | | + O B.. | | = *S. | | o | | | | | | | +-----------------+ ``` ``` [Answer] # Pyth, 125 bytes ``` Jj*17\-"++"JVc9XXsm@"^ .o+=*BOX@%&#/"hdrS+*U9U17K.u.e@S[0b*8hk)1.b+tNyYNYsm_c4.[08jxsM^.HM16 2d2cz\:,4 8 8ieK17\E76\SjN"||")J ``` Try it online: [Demonstration](http://pyth.herokuapp.com/?code=Jj*17%5C-%22%2B%2B%22JVc9XXsm%40%22%5E+.o%2B%3D*BOX%40%25%26%23%2F%22hdrS%2B*U9U17K.u.e%40S[0b*8hk%291.b%2BtNyYNYsm_c4.[08jxsM%5E.HM16+2d2cz%5C%3A%2C4+8+8ieK17%5CE76%5CSjN%22||%22%29J&input=37%3Ae4%3A6a%3A2d%3A48%3A38%3A1a%3A0a%3Af3%3A72%3A6d%3Ad9%3A17%3A6b%3Abd%3A5e&test_suite_input=16%3A27%3Aac%3Aa5%3A76%3A28%3A2d%3A36%3A63%3A1b%3A56%3A4d%3Aeb%3Adf%3Aa6%3A48%0Ab6%3Add%3Ab7%3A1f%3Abc%3A25%3A31%3Ad3%3A12%3Af4%3A92%3A1c%3A0b%3A93%3A5f%3A4b%0A05%3A1e%3A1e%3Ac1%3Aac%3Ab9%3Ad1%3A1c%3A6a%3A60%3Ace%3A0f%3A77%3A6c%3A78%3A47&debug=0) or [Test-Suite](http://pyth.herokuapp.com/?code=Jj*17%5C-%22%2B%2B%22JVc9XXsm%40%22%5E%20.o%2B%3D*BOX%40%25%26%23%2F%22hdrS%2B*U9U17K.u.e%40S[0b*8hk%291.b%2BtNyYNYsm_c4.[08jxsM%5E.HM16%202d2cz%5C%3A%2C4%208%208ieK17%5CE76%5CSjN%22%7C%7C%22%29J&input=37%3Ae4%3A6a%3A2d%3A48%3A38%3A1a%3A0a%3Af3%3A72%3A6d%3Ad9%3A17%3A6b%3Abd%3A5e&test_suite=1&test_suite_input=16%3A27%3Aac%3Aa5%3A76%3A28%3A2d%3A36%3A63%3A1b%3A56%3A4d%3Aeb%3Adf%3Aa6%3A48%0Ab6%3Add%3Ab7%3A1f%3Abc%3A25%3A31%3Ad3%3A12%3Af4%3A92%3A1c%3A0b%3A93%3A5f%3A4b%0A05%3A1e%3A1e%3Ac1%3Aac%3Ab9%3Ad1%3A1c%3A6a%3A60%3Ace%3A0f%3A77%3A6c%3A78%3A47&debug=0) I wrote a few days ago, but didn't post it, because I wasn't really happy about it. ### Explanation: The basic idea is the following. I start with the pair `(4, 8)`. In each move `(m1,m2)` I go from the `(x, y)` to `(x-1+2*m1, y-1+2*m2)`. To make sure, that these coordinates don't go outside the boarders, I'll make some lists, sort them and return the middle element: `(sorted(0,8,newx)[1], sorted(0,16,newy)[1])`. I keep track of all positions. To this list of positions I add a list of all possible positions, sort them and run-length-encode them. Which gives me a number for each position. With this number I can choose the coorect char, and at the end overwrite the chars of the start and end position. [Answer] # Ruby 288 ``` ->k{w=17 r=[z=?++?-*w+?+] (0...w*9).each_slice(w).map{|o|r<<?|+o.map{|x|c=76 q=0 k.split(?:).flat_map{|b|(0..7).map{|i|b.to_i(16)[i]}}.each_slice(2){|h,v|v<1?(c>w&&c-=w):c<w*8&&c+=w c+=h<1?c%w>0?-1:0:c%w<16?1:0 c==x&&q+=1} x==76?'S':c==x ?'E':' .o+=*BOX@%&#/^'[q]}.join+?|} (r+[z]).join' '} ``` Try it online: <http://ideone.com/QOHAnM> The readable version (the one I started golfing from) is here: <http://ideone.com/XR64km> [Answer] # C 361 **Thanks to @ceilingcat for some very nice pieces of golfing - now even shorter** ``` #define H h[i]|=*++p-48-*p/59*39 #define L puts("+-----------------+") #define F(m,s)for(m=0;m<s;m++) h[16],m[17][9],i,j,n,x=8,y=4;main(w,v)char**v;{for(char*p=v[1]-1;i<16;p++,i++)H<<4,H;F(j,16)F(n,4)x+=h[j]>>n*2&1?x!=16:-!!x,y+=h[j]>>n*2&2?y!=8:-!!y,m[x][y]++;m[8][4]=15;m[x][y]=L-4;F(i,9){printf("|");F(j,17)printf(L" .o+=*BOX@%&#/^SE"+m[j][i]);puts("|");}L;} ``` [Try it online!](https://tio.run/##XVDLboJAFN37FYCpYZihOjDymGG0aVLjgqSLbppMpgnyKJiARK2FqN9Osdqm6d3d87jn5sTmexx33TBJs6JKlaWSi0KeuAFhbRLPNOrx1Ddsf/AjCJX6Y7/TNWj@H6iBX9VCL9EOZJutXvIJK4MdKyEEg1xgR6JSYFcKX6ICrVGFGu6hlhNWRkWlf6IDiPNoaxgHdrz4v5eaHwSWJmZFgB1WQ4iK/twyCAhasoW@RtgBC71CBDSQ52ItZ7PKsEZ43qgcO9RU1Qa1fxlr3qrcuxBt/04jRSshZKXwpCCS4ym7gTw0SR9QIB8c621R7TNdO2ngmumCGxRqyv0GcuPx@fXhbjQcv708abDsw/oqAbv2dXGdQ3buus52aUqoE1ErocSjtkdxRCcRzWzqWtRJaOJT7FJnRVcJnaZf "C (gcc) – Try It Online") [Answer] # [C (gcc)](https://gcc.gnu.org/), ~~333 326 314 292~~ 288 bytes ``` f[17][9],i,x=8,y=4;main(n){for(;i++%4||read(0,&n,3)*sscanf(&n,"%x",&n);n/=4)f[x+=n%2?x<16:-!!x][y+=n&2?y<8:-!!y]+=f[x][y]<14;f[8][4]=15;for(f[x][y]=puts(n="+-----------------+")-4;++i<75;puts("|"))for(x=!printf("|");x<17;)putchar(" .o+=*BOX@%&#/^SE"[y=fmin(f[x++][i-66],16)]);puts(n);} ``` [Try it online!](https://tio.run/##XY9Bb8IwDIX/yshU1JB2kDakxWnENInzDrtMijIptIRVgoBaJrUa@@vrUrbTfPPnZ/u9Mt6X5TBYRTOtVjqqo07mUS@ZOJrahQ5/2lMTipqQgF2vzc5U4SKauijFs7YtjbOhb1DQIQ@xcHPJsFUdkS5I1l1BOcSTSadV78k0WfdFPoJeE@lVHuuCMmFVrhXTki7F@OxvIs8flzZ0EpH4fxGEYyYIqYtsKW4ydEUYj8udnJyb2l3sDQlvIRPYS8p304To7uFE5Ozp@fUxmN7P3142SPXSHn3Q0TTRqo451xHlWOPfwz7U1zCkGewYcANJBSyHNAdqYGHAppAlwCuoVkAz4FvYVrDcfZf2YPbtEB@OPw "C (gcc) – Try It Online") Golfed from openssh source code `key_fingerprint_randomart()`. Edit: Now a complete program. Less golfed: ``` /* initialize field */ f[17][9],i,x=8,y=4; main(n){ /* process raw key */ /* each byte conveys four 2-bit move commands */ for(;i%4||read(0,&n,3)+sscanf(&n,"%x",&n);n/=4) /* evaluate 2 bit, rest is shifted later */ /* assure we are still in bounds; augment the field */ f[x+=n%2?x<16:-!!x][y+=n&2?y<8:-!!y]+=f[x][y]<14; /* mark starting point and end point; output upper border */ f[8][4]=15; f[x][y]=puts(n="+-----------------+")-4 /* output content */ for(;++i<75;puts("|")) for(x=!printf("|");x<17;) /* * Chars to be used after each other every time the worm * intersects with itself. */ putchar(" .o+=*BOX@%&#/^SE"[y=fmin(f[x++][i-66],16)]); /* output lower border */ puts(n); } ``` [Answer] # [Burlesque](https://github.com/FMNSSun/Burlesque), 200 bytes ``` ':;;m{b6b28'0P[2cob2^p}m{{-1 1}Jcpj!!}{4 8}+]qr{?+q0cy{>.}Z]{8 16}cy{<.}Z]}pal_g_jf:u[j" .o+=*BOX@%&#/^"XXbcjq!!Z]z[{(D!)_+p^}m[' 17.*9.*)XXje!j'SD!j'ED!"|\n|"IC'|+]'|[+\['+'-17.*_+<-"+\n".+J<-#rCL\[Q ``` [Try it online!](https://tio.run/##FcpbT4MwGIDhv0K7aB0NSAGBfcNDHF64mKjxhqwcQoGZkLEBhgst/e243bzJk7xiHA71Tz/W80xgvW6l8IQdEOuD2@VJ2FmnWikNpjG1LbsGISVdLVA07Qf5SHur/JUPptqlMtCYp84KL1Jdcci/82YPI2@wZp7ovf78Hj9dXS9uMxzHomx6hHbpH5c3EVrmtMtUy4nGfFNfmfoyjpsaNeQrOuclQnhKjhN@3ZCJpmTiNOGEEuMy5zQ0ME2O2KTb0FgMm7eEf86z40PtgleAXYEbgBMAK8AqYO@Ab4NXQbUC5oMnQFRwV/8D "Burlesque – Try It Online") ``` ':;; # Split at colons m{ # Map over these b6b2 # Read as hex, then to binary 8'0P[ # Pad to 8 bit 2co # Chunks of 2 b2 # Read as binary ^p} # Push each m{ # Map over these {-1 1}Jcp # Construct direction array {{- -}{- +}{+ -}{+ +}} j!! # Select the block indexed by binary val } {4 8}+] # Push starting pos qr{ # Boxed reduce ?+ # Add together q0cy{>.}Z] # If < 0 -> 0 {8 16}cy{<.}Z] # If > box -> boxwidth pa # Apply on inits l_g_j # Take start and end for later f: # Calculate frequency of everything but head and tail u[j # Unzip to {pos} {counts} " .o+=*BOX@%&#/^"XXbcj # Magic string q!!Z] # Select element based on count z[ # Rezip to {pos icon} {(D!)_+p^}m[ # Add D! (set at pos) to the each ' 17.*9.*)XX # Create 17x9 array of spaces je! # Evaluate block of ({pos icon D!}, ...) j'SD!j'ED! # Set start and end to S & E "|\n|"IC # Intercalate surrounding v-bars '|+]'|[+ # Add first and last \[ # Concatenate '+'-17.*_+<-"+\n".+ # Create top-bar J<- # Duplicate and reverse (putting newline at the front #r # Rotate stack CL # Collect stack as list \[ # Concatenate Q # Pretty print ``` [Answer] # [Perl 5](https://www.perl.org/), ~~283~~ ~~276~~ ~~266~~ 254 + 1 (-p) = 255 bytes ``` $x=8;$y=4;for$n(map{hex}split(/:/)){$n&2?$y<8&&$y++:$y&&$y--,$n&1?$x<16&&$x++:$x&&$x--,$a[$x][$y]++,$n>>=2 for 1..4}$a[8][4]=15;$a[$x][$y]=16;map{$y=$_;$s.="|";$s.=substr' .o+=*BOX@%&#/^SE',$a[$_][$y],1 for 0..16;$s.="| "}0..8;$l='-'x17;$_="+$l+ $s+$l+ " ``` Uses `-p` to take a line of input into `$_`, and to print the (modified) value of `$_` at the end. [Try it online!](https://tio.run/##RU/BToNAEL33KwiO0LplcSksZLbbGhPPHryYECQgNDZBIIDJktpfFxc8eHpv5s2bN9OWXRVMEygZCRilL05NB/X6M2svH6W69m11HtYuupvNBWrLO8K4jywLRkIQxpk4zlYL7Ahqz7huqFlRM5mVLAaVxDAmhOixw0F6hg4wGKX@VYtREvuJZIH4H5SMizldHwOpgJ5K89tcsP/K@6GzDdoQeff4/Ppwa924by9P9hKTLu4tW/bfU6rX/JlX5lWX@rtK2o6tWCgglSaBiqygX8CcJsbRCzF7xyzAUPMIvQJ3HPkOWY4BR7/AMsfihJnm0U/TDuem7ien/QU "Perl 5 – Try It Online") Ungolfed: ``` # Implicit from running with perl -p: # read line from standard input #while($_ = <STDIN>) { # Initialise starting coordinates $x=8; $y=4; # Split input line at colons, convert each element (2-digit hex value) to integer, iterate over the list of integers for $n (map { hex($_) } split(/:/)) { # for each integer, iterate 4 times, looking at 2 of the 8 bits each time for(1..4) { # if second-last bit is set if($n & 2) { # move down, unless we are already at the bottom $y++ if($y < 8); } else { # move up, unless we are already at the top $y-- if($y); } # if last bit is set if($n & 1) { # move right, unless already at the right edge $x++ if($x<16); } else { # move left, unless already at the left edge $x-- if($x); } # Increment the counter for this position $a[$x][$y]++; # Shift number right two bits for next iteration $n = $n >> 2 } } # Set fixed values (15 and 16) for start and end positions respectively $a[8][4] = 15; $a[$x][$y] = 16; # Iterate over the rows of the grid, building a string containing the output rows for(0..8) { # save the y-coordinate for use in inner loop below $y = $_; # append the line start $s .= "|"; # iterate over the columns of the row for(0..16) { # get the value for this position $v = $a[$_][$y]; # map the value to the appropriate character $s .= substr(' .o+=*BOX@%&#/^SE', $v, 1) } # append the line end $s .= "|\n" } # build the hyphen lines for the top and bottom rows $l = '-' x 17; # build the full output string and assign to $_ $_ = "+$l+\n$s+$l+\n" # Implicit from running under perl -p #print $_; #} ``` [Answer] # Java 11, ~~460~~ ~~453~~ ~~452~~ 449 bytes ``` interface M{static void main(String[]a){var m=new char[9][17];Integer x=4,y=8,i=0,s;for(var p:a[0].split(":"))for(p=x.toString(x.parseInt(p,16),2),i=4;i-->0;m[x-=s<2?x>0?1:0:x/8-1][y-=s%2>0?y/16-1:y>0?1:0]++)s=x.decode(("0".repeat(8-p.length())+p).split("(?<=\\G..)")[i]);String t="+"+"-".repeat(m[x][y]=16)+"-+\n",r=t+"|";for(m[4][8]=15;++i<153;r+=y>15?"|\n"+(x<8?"|":""):"")r+=" .o+=*BOX@%&#/^SE".charAt(m[x=i/17][y=i%17]);System.out.print(r+t);}} ``` -11 bytes thanks to *@ceilingcat*. [Try it online.](https://tio.run/##PZBfa9swFMW/itHIkCZbsR3Hca@jZBuMsYexh74MFA/UWEnV1X@QtdSm7WfPbho2hJA45@rcn@6DPunoof59PtvWG3fQexN8fx689nYfnDpbB422Lb31zrZHVWn2fNIuaGRrnoL9vXbqplLJqiq/4eujccEos3CSRWhlHA7loXP0Ut@DVnElhv7RekqAMHZxejkK312j6Sh67QaDObQPk5yFKcOQrLRRtInLRo2RHNbpdtzE2wRiGOdFlFRqQnWWojbNkzxKYLraFedswPTa7LvaUEpiIpzpjfa0iHrxaNqjv6eM8Z79g6LbtdztvgrBCFO2YuWVK/CScFzR/wBEwb6VREaU@a4loZOekxfy9t1GZZUq0F6WnNt1slyUjstpkyy35AWLOR3XBV5xCoRdNrokEB2XHz7/@Plx9v7d/NftFyIuw/301k3aOU5YTdLO8ESwafCmEd0fL3pE9NRxz8rX1/P5vFiBySDXkNaQFbAoINEQazgsYJVCXkN9A8kK8ju4q2Fp/gI) **Explanation:** ``` interface M{ // Class static void main(String[]a){ // Mandatory main method var m=new char[9][17];// Create a character-matrix of size 9 by 17 Integer x=4,y=8, // Current position, starting at 4,8 i=0,s; // Temp integers for(var p:a[0].split(":")) // Loop over the argument-String, split by ":" for(p=x.toString(x.parseInt(p,16), // Convert the current part from hexadecimal String to integer 2),// And then from integer to binary String i=4;i-->0 // Inner loop `i` in the range (4,0]: ; // After every iteration: m[x-= // Update the `x` position: s<2? // If `s` is 0 or 1: x>0? // If we're not out of bounds yet at the top: 1 // Go up : // Else: 0 // Stay at the top border : // Else (s is 10 or 11): x/8 // If we're not out of bounds yet at the bottom: -1] // Go down // Else: // Stay at the bottom border [y-= // Update the `y` position: s%2>0? // If `s` is odd (1 or 11): y/16 // If we're not out of bounds yet at the right side: -1 // Go right // Else: // Stay at the right border : // Else (s is 0 or 10): y>0? // If we're not out of bounds yet at the left side: 1 // Go left : // Else: 0] // Stay at the left border ++) // And increase the value at x,y cell by 1 s= // Set `s` to: x.decode(("0".repeat(8-p.length())+p) // Left-pad the binary-String `p` with 0s up to length 8 .split("(?<=\\G..)") // Split it into parts of size 2 [i] // Get the `i`'th part ); // And convert it from binary-String to integer // After the nested loops are done: String t="+"+"-".repeat(m[x][y]=16 // Set the value at position x,y to 16 )+"-+\n", // Push a temp String for the top/bottom borders r=t+"|"; // Result-String, starting with the top border + one "|" for(m[4][8]=15; // Set the value at position 4,8 to 15 ;++i<153 // Loop over all cells: ; // After every iteration: r+= // Append the following to the result-String: y>15? // If we're done with a row: "|\n" // Append "|" and a newline +(x<8? // And unless it's the last row: "|" // Also append a "|" : // If it is the last row: "") // Append nothing : // And if we're not done with the row yet: "") // Append nothing r+= // Append the following to the result-String: " .o+=*BOX@%&#/^SE".charAt(m[x=i/17][y=i%17]); // The `i`'th character of the String " .o+=*BOX@%&#/^SE" // where `i` is the current value of cell x,y System.out.print(r // And finally output this result-String, +t);}} // including its bottom border ``` [Answer] # Rust - 509 bytes ``` fn b(s:&str)->String{let(mut v,mut b)=([[0;11];20],[9,5]);v[19]=[19;11];for i in 0..16{let mut c=usize::from_str_radix(&s[i*3..i*3+2],16).unwrap();for k in 0..4{for j in 0..2{v[j*18][i%9+1]=18;v[i+k][j*10]=[17,3][(i+k+17)%18/17];b[j]=match(if c&(j+1)==j+1{b[j]+1}else{b[j]-1},j,){(0,_)=>1,(18,0)=>17,(10,1)=>9,x@_=>x.0 as usize,}}v[b[0]][b[1]]+=1;c>>=2;}}v[9][5]=15;v[b[0]][b[1]]=16;(0..220).fold("\n".to_string(),|s,i|{format!("{}{}",s," .o+=*BOX@%&#/^SE-|\n".chars().nth(v[i%20][i/20] as usize).unwrap())})} ``` Large but... almost close to C. As usual there are many bytes used up due to the way Rust does not automagically cast types into each other. But there is also probably room for improvement.... could probably use some ideas from other solutions. [ungolfed version is on the Rust Playground online](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=24ecd8e1acef083f22629543508afa3c) ]
[Question] [ # Tupper's Self-Referential Formula (copied from Wikipedia) Tupper's self-referential formula is a formula defined by Jeff Tupper that, when graphed in two dimensions at a very specific location in the plane, can be "programmed" to visually reproduce the formula itself. It is used in various math and computer science courses as an exercise in graphing formulae. $$ \frac{1}{2} < \left\lfloor \text{mod}\left( \left\lfloor \frac{y}{17} \right\rfloor 2^{ -17 \lfloor x \rfloor -\text{mod}\left( \lfloor y \rfloor ,17 \right) } ,2 \right) \right\rfloor $$ where \$\lfloor\cdot\rfloor\$ is the floor function. Let \$k\$ be the following 543-digit number: `960939379918958884971672962127852754715004339660129306651505519271702802395266424689642842174350718121267153782770623355993237280874144307891325963941337723487857735749823926629715517173716995165232890538221612403238855866184013235585136048828693337902491454229288667081096184496091705183454067827731551705405381627380967602565625016981482083418783163849115590225610003652351370343874461848378737238198224849863465033159410054974700593138339226497249461751545728366702369745461014655997933798537483143786841806593422227898388722980000748404719` If one graphs the set of points \$(x, y)\$ in \$0 \le x < 106\$ and \$k \le y < k + 17\$ satisfying the inequality given above, the resulting graph looks like this (note that the axes in this plot have been reversed, otherwise the picture comes out upside-down): ![Result of Tupper's Self-Referential Formula](https://i.stack.imgur.com/GiemD.png) # So what? The interesting thing about this formula is that it can be used to graph any possible black and white 106x17 image. Now, actually searching through to search would be extremely tedious, so there's a way to figure out the k-value where your image appears. The process is fairly simple: 1. Start from the bottom pixel of the first column of your image. 2. If the pixel is white, a 0 will be appended to the k-value. If it is black, append a 1. 3. Move up the column, repeating step 2. 4. Once at the end of the column, move to the next column and start from the bottom, following the same process. 5. After each pixel is analyzed, convert this binary string to decimal, and multiply by 17 to get the k-value. # What's my job? Your job is to create a program which can take in any 106x17 image, and output its corresponding k-value. You can make the following assumptions: 1. All images will be exactly 106x17 2. All images will only contain black (#000000) or white (#FFFFFF) pixels, nothing in between. There's a few rules, too: 1. Output is simply the k-value. It must be in the proper base, but can be in any format. 2. Images must be read from either a PNG or PPM. 3. [No standard loopholes.](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) # Test Images [ ![Nintendo](https://i.stack.imgur.com/ncFyl.png) ] should produce ~1.4946x10542 [ ![A big number](https://i.stack.imgur.com/rIGMu.png) ] should produce ~7.2355x10159 [ ![2^1801 * 17](https://i.stack.imgur.com/DMlHP.png) ] should produce 21801 \* 17 [ ![2^1802 - 1 * 17](https://i.stack.imgur.com/5hD7r.png) ] should produce (21802-1) \* 17 [Check out this Gist for the exact solutions.](https://gist.github.com/anonymous/dfff13a7986d468a51b1) This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so least number of bytes wins. --- **Helpful Links** [Wikipedia](https://en.wikipedia.org/wiki/Tupper%27s_self-referential_formula) [Wolfram Mathworld](http://mathworld.wolfram.com/TuppersSelf-ReferentialFormula.html) [Answer] # Pyth - 21 bytes Simple to do with pyth's `i` base conversion. Takes input as `PBM` file name and reads using `'` command. I had to use `!M` to negate blacks and whites. Everything else is self-explanatory. ``` *J17i!MsC_cJrstt.z7 2 ``` [Try it here online](http://pyth.herokuapp.com/?code=*J17i!MsC_cJrstt.z7+2&input=P1%0A106+17%0A1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+0+0+0+1+1+1+1+1+1+1+1+0+0+0+0+0+0+1+1+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+1+1+0+0+0+0+0+0+1+1+1+1+1+0+1+1+0+0+0+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+1+1+1+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+0+0+0+0+1+1+0+1+1+1+0+1+1+0+0+0+0+0+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+1+0+1+1+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+0+0+0+0+0+0+1+1+0+1+1+0+1+0+0+1+1+1+1+0+0+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+0+0+1+1+0+1+1+0+1+1+1+1+1+1+1+1+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+0+0+1+1+1+1+0+0+1+0+1+0+0+0+0+1+1+1+1+1+1+0+0+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+0+0+1+1+0+1+1+0+0+0+0+0+0+1+1+0+1+1+0+1+1+0+0+0+1+1+0+0+0+0+0+1+1+1+0+0+0+1+1+0+1+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+0+0+0+1+1+1+1+1+1+0+0+0+0+0+0+0+0+1+1+1+1+1+1+0+0+1+0+0+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+0+1+1+0+0+0+0+1+1+1+1+1+0+0+1+1+1+1+0+0+1+1+1+0+0+1+1+1+1+1+0+1+0+1+1+1+1+1+0+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+1+0+0+1+1+1+1+1+1+0+0+0+0+0+1+0+0+1+1+1+1+1+1+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+1+1+1+1+0+1+1+0+1+1+0+0+1+1+0+0+1+1+0+0+1+1+0+1+1+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+0+1+1+1+1+1+1+0+0+1+0+0+1+1+0+0+1+1+1+1+0+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+0+1+1+1+0+1+1+0+1+1+0+0+1+1+0+0+1+1+0+0+1+1+1+1+1+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+0+0+1+1+1+1+0+0+1+1+0+0+1+1+0+0+0+0+0+0+0+0+0+1+1+0+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+0+1+1+1+0+1+1+0+1+1+0+0+1+1+0+0+1+1+0+0+1+1+0+0+0+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+0+0+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+0+0+1+1+0+0+0+0+0+0+0+0+0+1+1+0+0+1+0+0+0+0+0+0+0+0+0+0+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+0+1+1+0+1+0+1+1+0+1+1+0+1+1+0+0+1+1+0+0+1+1+0+1+0+1+1+1+0+0+1+1+0+0+1+1+0+0+1+1+1+1+1+0+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+0+0+0+0+0+0+0+0+0+0+0+1+0+1+0+0+0+1+1+0+1+1+0+1+1+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+1+1+1+0+0+1+0+0+1+0+0+1+1+0+0+1+1+0+0+1+1+1+0+0+0+1+1+0+0+1+1+0+0+1+1+0+0+0+0+0+1+1+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+1+1+0+1+1+0+1+1+0+0+0+1+1+1+0+1+1+1+0+1+1+0+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+0+1+1+0+1+1+1+0+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+1+0+1+1+1+1+1+1+1+1+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+1+1+1+1+1+1+1+1+0+1+1+1+1+1+1+1+0+0+0+0+0+0+0+0+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+0+0+0+0+0+0+0+0+1+1+1+1&debug=1). (Web interpreter can't read files, so is modified and takes file as input). [Answer] # CJam, 16 ``` l,l~q:~f*/W%ze_b ``` With big thanks to Dennis. [Try it online](http://cjam.aditsu.net/#code=l%2Cl~q%3A~f*%2FW%25ze_b&input=P1%0A106%2017%0A0000000000000000000000000000000000000000000000000000000000000000000000%0A0000000000000000000000000000000000000000011111100000000000000000000000%0A0000000000000000000000000000000000000000000000000000000000000111111000%0A0000011111100110000000000000000000000000000000000000000000000000000000%0A0000000000000000000000000110011111100000100111100001000000000000001100%0A0110000000000000000000000000000000000000000000000000000000001000011110%0A0100010011111100001000000000000100101001110000000000000000000000000000%0A0011000000000000000000000100001111110010010110000110001000000000000100%0A0110010010000000011000000000000000000100100000000000000000000100011000%0A0110101111000000111111000000000001000110010011111100100100111001111100%0A0111001011110000000000000011111100000011111111000000110111000000000001%0A0000100111100000110000110001100000101000001100001000000000000011101100%0A0000111110110000001000010000000000010010000100100110011001100100100110%0A0100110010011001000000000000100001000000110110011000011000010000000000%0A0100110001001001100110011000001001100100110010011001000000000000100001%0A1000011001100111111111001100000000000100110001001001100110011001111001%0A1001001100100110010000000000001100111111111001101111111111111100000000%0A0001001010010010011001100101000110011001100000110000100000000000001111%0A1111111111010111001001001110000000000000110001101101100110011000111001%0A1001100111110011110000000000000001110010010011100010001001000100000000%0A0000000000000000000000000000000000000000000000000000000000000000000000%0A1000100100010000100000000001000000000000000000000000000000000000000000%0A0000000000000000000000000000000000001000000000010000010000000010000000%0A0000000000000000000000000000000000000000000000000000000000000000000000%0A0001000000001000000011111111000000000000000000000000000000000000000000%0A0000000000000000000000000000000000000000111111110000) In case you're having problems with the url, this is the input I tested: ``` P1 106 17 0000000000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000011111100000000000000000000000 0000000000000000000000000000000000000000000000000000000000000111111000 0000011111100110000000000000000000000000000000000000000000000000000000 0000000000000000000000000110011111100000100111100001000000000000001100 0110000000000000000000000000000000000000000000000000000000001000011110 0100010011111100001000000000000100101001110000000000000000000000000000 0011000000000000000000000100001111110010010110000110001000000000000100 0110010010000000011000000000000000000100100000000000000000000100011000 0110101111000000111111000000000001000110010011111100100100111001111100 0111001011110000000000000011111100000011111111000000110111000000000001 0000100111100000110000110001100000101000001100001000000000000011101100 0000111110110000001000010000000000010010000100100110011001100100100110 0100110010011001000000000000100001000000110110011000011000010000000000 0100110001001001100110011000001001100100110010011001000000000000100001 1000011001100111111111001100000000000100110001001001100110011001111001 1001001100100110010000000000001100111111111001101111111111111100000000 0001001010010010011001100101000110011001100000110000100000000000001111 1111111111010111001001001110000000000000110001101101100110011000111001 1001100111110011110000000000000001110010010011100010001001000100000000 0000000000000000000000000000000000000000000000000000000000000000000000 1000100100010000100000000001000000000000000000000000000000000000000000 0000000000000000000000000000000000001000000000010000010000000010000000 0000000000000000000000000000000000000000000000000000000000000000000000 0001000000001000000011111111000000000000000000000000000000000000000000 0000000000000000000000000000000000000000111111110000 ``` I used the format that GIMP generated when exporting as ASCII pbm, with the comment removed. **Explanation:** ``` l, read the first line ("P1" magic number) and get its length (2) l~ read and evaluate the second line (106 17) q read the rest of the input (actual pixels) :~ evaluate each character ('0' -> 0, '1' -> 1, newline -> nothing) f* multiply each number by 17 / split into rows of length 106 W% reverse the order of the rows z transpose e_ flatten (effectively, concatenate the lines) now we have all the pixels in the desired order, as 0 and 17 b convert from base 2 "digits" to a number ``` [Answer] # Python 2: 133 110 bytes A first attempt in python using PIL: ``` from PIL.Image import* j=open(input()).load() a=k=0 while a<1802:k=(j[a/17,16-a%17][0]<1)+k*2;a+=1 print k*17 ``` Thanks to helpful commenters below [Answer] # C#, 199 This was fun! There's nothing wrong with reloading a bitmap 106 \* 17 times, right? I did it as a function to save some bytes, not sure if that's legal. ``` BigInteger s(string i){return (Enumerable.Range(0,106).SelectMany(x=>Enumerable.Range(0,17).Select(y=>new BigInteger(new Bitmap(i).GetPixel(x,y).B==0?1:0)).Reverse()).Aggregate((x,y)=>(x<<1)+y)*17);} ``` `i` is the input file name. Also, as a single expression, just because it is one expression, with `i` provided or subbed (167 bytes) ``` (Enumerable.Range(0,106).SelectMany(x=>Enumerable.Range(0,17).Select(y=>new BigInteger(new Bitmap(i).GetPixel(x,y).B==0?1:0)).Reverse()).Aggregate((x,y)=>(x<<1)+y)*17) ``` [Answer] # Wolfram Language (Mathematica) ~~69~~ 50 Bytes Update: After revisiting this code a few years later due to @Matt's comment, I've found a few bytes of savings. Note that the test pictures must be `Binarized` first, because they are 24 bit color PNGs as downloaded from the posted question, instead of being monochrome format as posted in the assumptions. ``` 17Fold[#+##&,1-Join@@Reverse/@Thread@ImageData@#]& ``` old code ``` 17*FromDigits[1-Flatten[Reverse/@Transpose[ImageData@Binarize@#]],2]& ``` This function will reproduce the image: ``` ArrayPlot[Table[Boole[1/2<Floor[Mod[Floor[y/17]2^(-17Floor[x]-Mod[Abs[y],17]),2]]],{y,1+#,17+#},{x,106,1,-1}]]& ``` ]
[Question] [ ### The challenge The shortest code by character count to help Robot find kitten in the fewest steps possible. Golfers, this is a time of crisis - Kitten gone missing and it's Robot's job to find it! Robot needs to reach Kitten in the shortest path possible. However, there are a lot of obstacles in Robot's way, and he needs you to program a solution for him. Robot used to have a program do it for him, but that program was lost and Robot have no backup :(. Robot's runtime is not the best, and the least characters Robot has to read from the source code, the least time it will spend processing, and that means Kitten will be found faster! Robot's memory contains a map of the location he is currently in with the top representing North, bottom representing South, right representing East and left representing West. Robot is always in a rectangular room of an unknown size surrounded by walls, represented by `#` in his radar map. Areas Robot can walk in are represented by a space . Robot's radar also scans for many obstacles in the room and marks them in various ASCII letters. Robot cannot walk across those obstacles. The radar will mark Kitten as the special ASCII character `K`, while Robot's location is marked with `R`. Robot's navigation system works this way: He can understand a duo of direction and number of movement units he should travel to - for example, `N 3` means 'go north 3 movement units'. Robot's radar map is made such that a movement unit is one ASCII character. Robot can only go in 4 directions and cannot travel diagonally. Your task, brave Kitten saver, is to read Robot's radar map once, and output the least amount of directions, with the least movement unit travel distance. Robot is guaranteed to have at least one path to Kitten. To ensure Robot does not waste time executing a malfunctioning program that will not help Robot find Kitten, I encourage you, brave Kitten saver, to use this output of Robot's past program to ensure no time is wasted on finding Kitten! ## Test cases ``` Input: ###################### # d 3 Kj # # # # R # # q # ###################### Output: E 13 N 2 ``` --- ``` Input: ###################### # d r 3 Kj # # p p # # T X # # q s t # # # # R o d W # # # # g t U # # # ###################### Output: N 1 E 10 N 4 E 2 ``` --- ``` Input: ###################### # spdfmsdlwe9mw WEK3# # we hi # # rdf fsszr# # sdfg gjkti # # fc d g i # # dfg sdd # # g zfg # # df df # # xcf R# ###################### Output: N 1 W 9 N 5 E 4 N 1 E 4 N 1 ``` Code count includes input/output (i.e full program). [Answer] ### C++ 1002 899 799chars Note requires the use of C++0x to eliminate the space between > > in templates. It does find the route with the minimum number of turns. ``` #include<iostream> #include<vector> #include<string> #include<set> #include<memory> #define D make_pair #define F first #define S second using namespace std;typedef pair<int,int>L;typedef vector<L>R;typedef multiset<pair<float,pair<L,R>>>B;vector<string> M;string l;int z,c,r=0;set<L> s;B b;L n;B::iterator f;R v;void A(int x,int y,int w){n=f->S.F;for(c=1;(z=M[n.S+=y][n.F+=x])==32||(z==75);++c)v.back()=D(w,c),b.insert(D(f->F+c+1./c,D(n,v)));}int main(){for(;getline(cin,l);++r){if((c=l.find(82))!=string::npos)b.insert(D(0,D(D(c,r),R())));M.push_back(l);}while(!b.empty()){f=b.begin();n=f->S.F;v=f->S.S;if(M[n.S][n.F]==75)break;if(s.find(n)==s.end()){s.insert(n);v.push_back(L());A(0,1,83);A(0,-1,78);A(1,0,69);A(-1,0,87);}b.erase(f);}for(c=v.size(),r=0;r<c;++r)n=v[r],printf("%c %d\n",n.F,n.S);} ``` It `Dijkstra's Algorithm` for solving the shortest path problem. To distinguish between multiple equal size routes a long straight line has less weight that multiple short lines (this favors routes with less turns). ``` Cost of a path: Len + 1/Len Looking at Test Case 1: ======================== Thus Path E13 + N2 has a cost of 13 + 1/13 + 2 + 1/2 An alternative path E9 + N2 + E4 has a cost of 9 + 1/9 + 2 + 1/2 + 4 + 1/4 The difference is Straight Path: 1/13 < Bendy Path: (1/9 + 1/4) ``` In a more readable form: ``` #include<iostream> #include<vector> #include<string> #include<set> #include<memory> using namespace std; typedef pair<int,int> L; typedef vector<L> R; typedef multiset<pair<float,pair<L,R>>> B; vector<string> M; string l; int z,c,r=0; set<L> s; B b; L n; B::iterator f; R v; void A(int x,int y,int w) { n=f->second.first; for(c=1;(z=M[n.second+=y][n.first+=x])==32||(z==75);++c) v.back()=make_pair(w,c), b.insert(make_pair(f->first+c+1./c,make_pair(n,v))); } int main() { for(;getline(cin,l);++r) { if((c=l.find(82))!=string::npos) b.insert(make_pair(0,make_pair(make_pair(c,r),R()))); M.push_back(l); } while(!b.empty()) { f=b.begin(); n=f->second.first; v=f->second.second; if(M[n.second][n.first]==75) break; if(s.find(n)==s.end()) { s.insert(n); v.push_back(L()); A(0,1,83); A(0,-1,78); A(1,0,69); A(-1,0,87); } b.erase(f); } for(c=v.size(),r=0;r<c;++r) n=v[r], printf("%c %d\n",n.first,n.second); } ``` [Answer] ## Scala 2.8 (451 characters) ...but it doesn't solve ties in favor of least amount of directions (though it does find the least amount of steps). ``` val m=io.Source.stdin.getLines.map(_.toArray).toSeq var l=m.indexWhere(_ contains'R') var c=m(l)indexOf'R' val q=collection.mutable.Queue(l->c->"") def s{val((l,c),p)=q.dequeue if("R "contains m(l)(c))for((i,j,k)<-Seq((-1,0,"N"),(0,1,"E"),(1,0,"S"),(0,-1,"W")))q.enqueue(((l+i,c+j),p+k)) m(l)(c)='X'} def P(s:String){if(s.nonEmpty){val (h,t)=s.span(s.head==) println(s.head+" "+h.size) P(t)}} def Q{s val((l,c),p)=q.head if (m(l)(c)=='K')P(p)else Q} Q ``` Scala 2.8, 642 characters, solves ties correctly; ``` val m=io.Source.stdin.getLines.toSeq var b=Map(0->0->0).withDefault(_=>Int.MaxValue) var l=m.indexWhere(_ contains'R') var c=m(l)indexOf'R' val q=collection.mutable.PriorityQueue(l->c->List((' ',0)))(Ordering.by(t=>(-t._2.map(_._2).sum,-t._2.size))) def s{val(p@(l,c),u@(h@(d,n))::t)=q.dequeue if("R ".contains(m(l)(c))&&u.map(_._2).sum<=b(p)){b=b.updated(p,u.map(_._2).sum) for((i,j,k)<-Seq((-1,0,'N'),(0,1,'E'),(1,0,'S'),(0,-1,'W'))){ val o=if(k==d)(d,n+1)::t else (k,1)::h::t q.enqueue(((l+i,c+j),o))}}} def P(l:List[(Char,Int)]){l.reverse.tail.foreach{t=>println(t._1+" "+t._2)}} def Q{s;val((l,c),p)=q.head;if (m(l)(c)=='K')P(p)else Q} Q ``` It discovered a shorter path for the second example than the one given in the problem: ``` N 1 E 10 N 4 E 2 ``` [Answer] ## Python 2.6 (504 characters) ``` import sys,itertools W,Q=len,list M=[] B=[] for l in sys.stdin.readlines(): r=Q(l.strip()) B.append([0]*W(r)) M.append(r) if "R" in r:x,y=r.index("R"),W(B)-1 def S(B,M,x,y,P): c=M[y][x] b=B[y][x] if b and W(P)>b:return 0 B[y][x]=W(P) if c=="K":return P elif c=="R" and P:return 0 if c in "R ": b=[] for q,w,s in((1,0,"E"),(-1,0,"W"),(0,-1,"N"),(0,1,"S")): r=S(B,M,x+q,y+w,P+s) if r and(W(r)<W(b)or not b):b=r if b:return b return 0 print "\n".join(k+str(W(Q(g)))for k,g in itertools.groupby(S(B,M,x,y,""))) ``` [Answer] ## Python 2.6 (535 characters) ``` exec 'eJzNlLFugzAQhneewhki2/KBworksVOkDu3QgVqVE2hBioFgCDhV371nJ1VbKR3SKYtl/jvs77MwtenafiBVqbs9WGcjLW05MB69tj05QEfqhpTNaMpeDyXDhsQORd3wLCK+YwT7u6PzFVK/Ep9Tsn6gmU50UTA2woHzc01KuqYZ20PPZSh85/iCO2etzBnTG8tcvlLxnovTPFVxzyGEC4lpiBay5xiuYMXBcRVtzxqTfP+IpqrelaRFsheoYJbBNvFj13asxd23gXHGmZU7bTaFDgiZH+MUYydtKBuZRuS0nvPmOt564Sl3CmlxcWAG6D3lXIkpeUMGB7nyfj82HW3FWvjTTVSYCXNJEUupEimannu+nl04WyM8XoB1F13E9S6Pt+ki0vDZXOdyd5su8X9cnm7DBa/tLGW4yh7yKCn1rIF+9vSTj/HiBeqCS1M3bMrnwOvbl5Ysi+eGLlkBhosjxl1fNwM5Ak7xH6CiT3SdT4U='.decode('base64').decode('zlib') ``` Unpacks to a severely mistreated A\* implementation. Reads stdin. Searches for solutions with minimal total distance. Breaks ties by preferring minimal number of directions. Lists moves to stdout. Finds kittens. **Unpacked**: The source has been manually anti-golfed in a few places in order to obtain a smaller compressed representation. For example, a for loop over the compass directions was unrolled. ``` import heapq,sys a=set() for v,p in enumerate(sys.stdin): for u,s in enumerate(p): if s in' KR':a.add((u,v)) if s=='K':(q,r)=(u,v) if s=='R':y=(u,v) o=[((abs(y[0]-q)+abs(y[1]-r),(y[0]!=q)+(y[1]!=r)),(0,0),y)] c=set() w={} while o: _,h,x=heapq.heappop(o) c.add(x) s=lambda(u,v):(u,v-1) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'N'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u,v+1) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'S'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u+1,v) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'E'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) s=lambda(u,v):(u-1,v) y=s(x) m=1 while y in a-c: w[y]=[(h,x,(m,'W'))]+w.get(y,[]) heapq.heappush(o,((abs(y[0]-q)+abs(y[1]-r)+h[0]+m,(y[0]!=q)+(y[1]!=r)+h[1]+1),(h[0]+m,h[1]+1),y)) m+=1 y=s(y) if x==(q,r): z='' while x in w: _,x,(m,d)=min(w[x]) z='%s %d\n'%(d,m)+z print z, o=[] ``` [Answer] ## c++ -- 681 necessary characters ``` #include <string> #include <iostream> #include <sstream> using namespace std; int d[]={-1,0,1,0},i,j,k,l,L=0,p=41,S;string I,m,D("ESWN"); int r(int o,int s){S=s;while((m[o]==32||m[o]==37)&&m[o+S]-35) if(m[o+S]-p)S+=s;else return o+S;return 0;} void w(int o){for(i=0;i<m.length();++i)for(j=0;j<4;++j) if(k=r(o,d[j])){stringstream O;O<<D[j]<<" "<<int((k-o)/d[j])<<"\n"<<I; I=O.str();if(p-41)--p,m[k]=37,w(k);cout<<I;exit(0);}} int main(){while(getline(cin,I))m+=I,l=I.length(); d[1]-=d[3]=l;I="";for(i=0;i<m.length();++i) switch(m[i]){case 82:case 75:m[i]/=2;case 32:break;default:m[i]=35;} do{for(i=0;i<m.length();++i)if(r(i,-1)+r(i,-l)+r(i,1)+r(i,l)) {if(m[i]==37)w(i);m[i]=p+1;}}while(++p);} ``` It first replaces all the obstacles on the map with into `#`s (and changes the values of `K` and `R`, to leave headroom in the character space for very long paths. *Then it scribbles on the map.* An iterative process marks all the successively accessible squares until it is able to reach the kitten in one move. After that is uses the *same* accessibility checking routine to find a string of positions that lead back to the start in minimal instructions. These instructions are loaded into a string by pre-pending, so that they print in the proper order. I don't intend to golf it further as it does not properly resolve ties and can not be easily adapted to do so. It fails on ``` ##### # # # # # #R#K# # # ##### ``` producing ``` $ ./a.out < kitten_4.txt N 2 E 2 S 2 ``` **More or less readable version:** ``` #include <string> #include <iostream> #include <sstream> using namespace std; int d[]={-1,0,1,0} , i, j, k , l /* length of a line on input */ , L=0 /* length of the whole map */ , p=41 /* previous count ( starts 'R'/2 ) */ , S /* step accumulator for step function */ ; string I/*nput line, later the instructions*/ , m/*ap*/ , D("ESWN"); /* Reversed sence for back tracking the path */ int r/*eachable?*/(int o/*ffset*/, int s/*step*/){ // cerr << "\tReachable?" // << endl // << "\t\tOffset: " << o << " (" << o/5 << ", " << o%5 << ")" // << " [" << m[o] << "]" << endl // << "\t\tStep: " << s // << endl // << "\t\tSeeking: " << "[" << char(p) << "]" // << endl // << "\t\tWall: " << "[" << char(35) << "]" // << endl; S=s; while ( ( (m[o]==32) /* Current character is a space */ || (m[o]==37) ) /* Current character is a kitten */ && (m[o+S]-35) /* Target character is not a wall */ ) { // cerr << "\t\tTry: " << o+S << "(" << (o+S)/5 << ", " << (o+S)%5 << ")" // << " [" << m[o+S] << "]" << endl; if (m[o+S]-p /* Target character is not the previous count */ ) { // cerr << "\t\twrong " << " [" << m[o+S] << "] !!!" << endl; S+=s; } else { /* Target character *is* the previous count */ // cerr << "\t\tFound " << " [" << m[o+S] << "] !!!" << endl; return o+S; } /* while ends */ } return 0; } void w/*on*/(int o/*ffset*/){ // cerr << "\tWON" << endl // << "\t\tOffset: " << o << "(" << o/5 << ", " << o%5 << ")" // << " [" << m[o] << "]" // << endl // << "\t\tSeeking: " << "[" << char(p) << "]" // << endl; for(i=0;i<m.length();++i) /* On all map squares */ for(j=0;j<4;++j) if (k=r(o,d[j])) { // cerr << "found path segment..." // << (k-o)/d[j] << " in the " << d[j] << " direction." << endl; stringstream O; O << D[j] << " " << int((k-o)/d[j]) << "\n" << I; I = O.str(); // cerr << I << endl; /* test for final solution */ if (p-41) --p,m[k]=37, w(k); /* recur for further steps */ cout << I; exit(0); } /* inner for ends */ /* outer for ends */ } int main(){ while(getline(cin,I)) m+=I,l=I.length(); // cerr << "Read the map: '" << m << "'." << endl; d[1]-=d[3]=l;I=""; // cerr << "Direction array: " << D << endl; // cerr << "Displacement array: " << d[0] << d[1] << d[2] << d[3] << endl; // cerr << "Line length: " << l << endl; /* Rewrite the map so that all obstacles are '#' and the start and goal are '%' and ')' respectively. Now I can do pathfinding *on* the map. */ for(i=0;i<m.length();++i) switch (m[i]) { case 82: /* ASCII 82 == 'R' (41 == ')' ) */ case 75:m[i]/=2; /* ASCII 75 == 'K' (37 == '%' ) */ case ' ':break; default: m[i]=35; /* ASCII 35 == '#' */ }; // cerr << "Re-wrote the map: '" << m << "'." << endl; do { /* For each needed count */ // cerr << "Starting to mark up for step count " // << p-41+1 << " '" << char(p) << "'" << endl; for(i=0;i<m.length();++i){ /* On all map squares */ // cerr << "\tTrying position (" << i/l << ", " << i%l << ")" // << " [" << m[i] << "]" // << endl; if ( r(i, -1) /* west */ + r(i, -l) /* north */ + r(i, 1) /* east */ + r(i, l) /* south */ ) { // cerr << "Got a hit on : '" << m << "'." << endl; // cerr << "\twith '" << char(m[i]) <<" at position " << i << endl; // cerr << "target is " << char(37) << endl; if(m[i]==37) w(i); /* jump into the win routine which never returns */ m[i]=p+1; // cerr << "Marked on map: '" << m << "'." << endl; } } } while(++p); } ``` [Answer] ## Ruby - 539 characters Could do with a lot of improvement, but it does work for shortest steps as well as directions. ``` M=[*$<] r=M.map{|q|q.index('R')||0} k=M.map{|q|q.index('K')||0} D=M.map{|q|q.split('').map{[99,[]]}} def c h h.map{|i|i.inject([[]]){|a,b|a.last[0]!=b ? a<<[b, 1]:a.last[1]+=1;a}}.sort_by{|a|a.length}[0] end def t x,y,s,i z,w=D[x][y][0],D[x][y][1] if [' ','R','K'].index(M[x][y, 1])&&(z>s||z==s&&c(w).length>=c([i]).length) D[x][y]=[s,z==s ? w<<i:[i]] s+=1 t x+1,y,s,i+['S'] t x-1,y,s,i+['N'] t x,y+1,s,i+['E'] t x,y-1,s,i+['W'] end end t r.index(r.max), r.max, 0, [] puts c(D[k.index(k.max)][k.max][1]).map{|a|a*''} ``` [Answer] ## Ruby - 648 characters Another one that fails the least number of directions test as I can't think of any easy way to embed it in A\*. ``` m=$<.read.gsub /[^RK\n ]/,'#' l=m.index($/)+1 s=m.index'R' g=m.index'K' h=->y{(g%l-y%l).abs+(g/l-y/l).abs} n=->y{[y+1,y-1,y+l,y-l].reject{|i|m[i]=='#'}} a=o=[s] d=Array.new(m.length,9e9) c,k,f=[],[],[] d[s]=0 f[s]=h[s] r=->y,u{u<<y;(y=k[y])?redo:u} (x=o.min_by{|y|f[y]} x==g ? (a=r[x,[]].reverse;break):0 o-=[x];c<<x n[x].map{|y|c&[y]!=[]?0:(t=d[x]+1 o&[y]==[]?(o<<y;b=true):b=t<d[y] b ? (k[y]=x;d[y]=t;f[y]=t+h[y]):0)})until o==[] k=a.inject([[],nil]){|k,u|(c=k[1]) ? (k[0]<<(c==u-1?'E':c==u+1?'W':c==u+l ? 'N':'S')) : 0;[k[0],u]}[0].inject(["","",0]){|k,v|k[1]==v ? k[2]+=1 : (k[0]+=k[1]+" #{k[2]}\n";k[1]=v;k[2]=1);k} puts k[0][3,9e9]+k[1]+" #{k[2]}\n" ``` ]
[Question] [ This! is an RGB colour grid... [![Basic RGB grid](https://i.stack.imgur.com/ED5wv.png)](https://i.stack.imgur.com/ED5wv.png) Basically it's a 2-dimensional matrix in which: * The first row, and the first column, are red. * The second row, and the second column, are green. * The third row, and the third column, are blue. Here are the colours described graphically, using the letters R, G, and B. [![row and column diagram](https://i.stack.imgur.com/aVA92.png)](https://i.stack.imgur.com/aVA92.png) Here's how we calculate the colour of each space on the grid is calculated. * Red + Red = Red (#FF0000) * Green + Green = Green (#00FF00) * Blue + Blue = Blue (#0000FF) * Red + Green = Yellow (#FFFF00) * Red + Blue = Purple (#FF00FF) * Green + Blue = Teal (#00FFFF) # The Challenge * Write code to generate an RGB colour grid. * It's code golf, so attempt to do so in the smallest number of bytes. * Use any programming language or markup language to generate your grid. * Things I care about: + The result should graphically display an RGB grid with the defined colours. * Things I don't care about: + If the output is an image, HTML, SVG or other markup. + The size or shape of the colour blocks. + Borders, spacing etc between or around the blocks. + It definitely doesn't have to have labels telling you what the row and column colours should be. [Answer] # Bash, 44 * 2 bytes saved thanks to @NahuelFouilleul * 2 bytes saved thanks to @manatwork ``` printf "${f=^[[3%dm.}$f$f " 1 3 5 3 2 6 5 6 4 ``` Here, blocks are `.` characters. `^[` is a literal ASCII escape character (0x1b). [![enter image description here](https://i.stack.imgur.com/fbAOo.png)](https://i.stack.imgur.com/fbAOo.png) You can recreate this script as follows: ``` base64 -d <<< cHJpbnRmICIke2Y9G1szJWRtLn0kZiRmCiIgMSAzIDUgMyAyIDYgNSA2IDQ= > rgbgrid.sh ``` [Answer] # x86-16 machine code, IBM PC DOS, 43 bytes ``` 00000000: be22 01b9 0100 ac8a d83c 10b8 db09 cd10 .".......<...... 00000010: b403 cd10 7204 7809 b2ff 42b4 02cd 10eb ....r.x...B..... 00000020: e2c3 0c0e 1d0e 0a1b 0d0b 91 ........... ``` **Listing:** ``` BE 0122 MOV SI, OFFSET CT ; load color bar table into [SI] LOOP_COLOR: B9 0001 MOV CX, 1 ; display 1 char and clear CH (changed by INT 10H:3) AC LODSB ; load next color byte 8A D8 MOV BL, AL ; move new color to BL 3C 10 CMP AL, 010H ; if this is third color in row: SF=0, CF=0 ; else if last color: SF=1, CF=0 ; else continue on same row: CF=1 B8 09DB MOV AX, 09DBH ; AH=9 (write char with attr), AL=0DBH (block char) CD 10 INT 10H ; call PC BIOS, display color block B4 03 MOV AH, 3 ; get cursor position function CD 10 INT 10H ; call PC BIOS, get cursor 72 04 JC NEXT_COL ; if not last in row, move to next column 78 09 JS EXIT ; if last color, exit B2 FF MOV DL, -1 ; otherwise move to first column and next row NEXT_COL: 42 INC DX ; move to next column (and/or row) B4 02 MOV AH, 2 ; set cursor position function CD 10 INT 10H ; call PC BIOS, set cursor position EB E2 JMP LOOP_COLOR ; loop to next color byte EXIT: C3 RET ; return to DOS CT DB 0CH, 0EH, 1DH ; color table DB 0EH, 0AH, 1BH DB 0DH, 0BH, 91H ``` This uses the IBM PC BIOS `INT 10H` video services to write the color grid to the screen. Unfortunately the only way to write a specific color attribute requires also writing code to place the cursor in the next correct location, so there's a lot of extra code for that. Here's the output running on an IBM PC CGA (in 40x25 text mode to make it bigger). [![enter image description here](https://i.stack.imgur.com/Z95ED.png)](https://i.stack.imgur.com/Z95ED.png) ## TL;DR Here's a more verbose explanation, with more detail of what some of these machine code instructions do. ### Color table The colors are stored as bytes in the color table (`CTBL`) with the 4-bit color value in the low nibble and a flag value in the high nibble. A `1` in the high nibble signals the end of the row and a `9` signals the end of the list. This is checked using a single `CMP` instruction which subtracts `0x10` from the color values and sets the result flags. These operands are treated as 8-bit signed values, so the sign flag (positive or negative result) and carry flag (a subtractive borrow was required, meaning the color byte is less than `0x10`) are the interesting ones here. These flags are then checked further down for the conditional logic of whether to advance the row, the column or end the program. **Examples:** High nibble `0` means **not** the last in the row and **not** the last in the list: * `0x0C - 0x10 = 0xFC` -- Result is negative and a carry (borrow) was required High nibble `1` means it **is** the last color in the row and **not** the last in the list: * `0x1D - 0x10 = 0x0D` -- Result is positive and no borrow High nibble `9` means it **is** the last color of the list: * `0x91 - 0x10 = 0x81` -- Result is negative and no borrow ### Cursor movement Using the PC BIOS or DOS API for output, the function that allows setting a character color does not automatically advance the cursor, so that has to be done by the program. The cursor position must be fetched each time since the registers are overwritten later by the other functions. The "get" function puts these into the 8-bit registers `DL` for the column, and `DH` for the row. These same registers are what is used by the "set" function to move the cursor to a new location. We can take advantage of the fact that, on x86 architecture `DH` and `DL` can be manipulated as a single 16-bit register (`DX`). To advance to the next column, we increment `DX` which effectively only increments `DL` (column position). To advance to the next column we would need to instead increment the row number and set the column to `0`. We can do this in only one additional instruction by setting the low nibble (`DL`) to `0xFF` and then continuing the normal program flow incrementing `DX`. Since we're now looking at `DH`/`DL` as a 16-bit value, `DL` becomes `0` and the carry from `0xFF + 1` is added to `DH`. **Examples:** Advance to next column: ``` DH DL DX 1 1 0101 ; at row 1, column 1 1 2 0102 ; add one to DX ``` Advance to next row, first column: ``` DH DL DX 1 2 0102 ; at row 1, column 2 1 FF 01FF ; +set DL to 0xFF 2 0 0200 ; add one to DX ``` [Answer] # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 41 bytes ``` Image@Outer[Plus,#,#,1]&@IdentityMatrix@3 ``` [![enter image description here](https://i.stack.imgur.com/rM91f.png)](https://i.stack.imgur.com/rM91f.png) --- # [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 68 bytes Mathematica has built-ins for all these colors. ``` Image@{{Red,Yellow,Magenta},{Yellow,Green,Cyan},{Magenta,Cyan,Blue}} ``` [![enter image description here](https://i.stack.imgur.com/Si3kZ.png)](https://i.stack.imgur.com/Si3kZ.png) [Answer] # 80386 machine code, IBM PC DOS, 38 bytes hex: ``` B0 13 CD 10 68 00 A0 1F 66 C7 06 00 00 28 2C 24 00 66 C7 06 40 01 2C 30 34 00 66 C7 06 80 02 24 34 20 00 CD 16 C3 ``` asm: ``` mov al,13h int 10h ; initialize vga 13h mode (320x200x256 colors) push 0a000h pop ds ; push video buffer address to ds mov dword ptr ds:0, 242c28h ; print 3 pixels mov dword ptr ds:320, 34302ch ; print 3 pixels mov dword ptr ds:640, 203424h ; print 3 pixels int 16h ; wait for any keypress ret ; exit to os ``` scaled output from dosbox: [![enter image description here](https://i.stack.imgur.com/YQuUm.png)](https://i.stack.imgur.com/YQuUm.png) [Answer] # Excel VBA (Immediate Window), 80 bytes ``` For i=1To 9:Cells(i Mod 3+1,(i+1)/3).Interior.ColorIndex=Mid(673486857,i,1):Next ``` # Excel VBA (Function), 96 bytes ``` Sub g() For i=1To 9 Cells(i Mod 3+1,(i+1)/3).Interior.ColorIndex=Mid(673486857,i,1) Next End Sub ``` Not a horrible tool for the job... I appreciate the fact that Excel already shows a grid so it is a matter of setting the background color. [![Excel Colour Grid](https://i.stack.imgur.com/Kvu6x.png)](https://i.stack.imgur.com/Kvu6x.png) Credit to @Neil for suggesting I use `ColorIndex` instead of `Color` leading to a 43 byte savings. -21 bytes thanks to @Keeta -16 bytes thanks to @Chronocidal for suggesting the "Immediate Window" -2 bytes thanks to @i\_saw\_drones Lots of changes from my original submission :) [Answer] # SVG, ~~210~~ 182 bytes ``` <svg><path d="h3v3h-3" fill=#f0f/><path d="h2v2h-2" fill=#ff0/><path d="m1 1h2v2h-2" fill=#0ff/><line x2=1 stroke=red/><path d="m1 1h1v1h-1" fill=#0f0/><path d="m2 2h1v1" fill=#00f/> ``` Since the size or shape of the colour blocks doesn't matter, quite a few bytes can be golfed off with this slightly odd layout: [![svg layout](https://i.stack.imgur.com/m3M8D.png)](https://i.stack.imgur.com/m3M8D.png) [Answer] # HTML + CSS, ~~121~~ 120 bytes Worst piece of HTML I've ever wrote. One byte save thanks to @Gust van de Wal ``` b{color:#ff0}a{color:cyan}i{color:lime}u{color:blue ``` ``` <pre><body bgcolor=#f0f text=red>█<b>█ █<i>█<a>█ █<u>█ ``` # HTML + CSS, 114 bytes (semi valid) I'm putting this as semi-valid because the blue is not exactly #0000FF blue and also relies on not having clicked the link. Thanks to @Lynn for the idea ``` b{color:#ff0}i{color:lime}c{color:cyan ``` ``` <pre><body bgcolor=#f0f text=red>█<b>█ █<i>█<c>█ █<a href=x>█ ``` [Answer] # [GFA Basic 2.02](https://en.wikipedia.org/wiki/GFA_BASIC) (Atari ST), 48 bytes A manually edited listing in .LST format. Includes many non-printable characters, whose codes are shown within brackets. ``` ?"[ESC]c[SOH] [ESC]c[ETX] [ESC]c[ENQ] "[CR] ?"[ESC]c[ETX] [ESC]c[STX] [ESC]c[ACK] "[CR] ?"[ESC]c[ENQ] [ESC]c[ACK] [ESC]c[EOT] "[CR] ``` The operating system of the Atari ST defines [extended VT52 commands](https://en.wikipedia.org/wiki/VT52#GEMDOS/TOS_extensions) which are used here. ### Output The output is a block of \$24\times24\$ pixels (9 space characters of \$8\times8\$ pixels). [![output](https://i.stack.imgur.com/unrq2.png)](https://i.stack.imgur.com/unrq2.png) *screenshot from [Steem SSE](https://sourceforge.net/projects/steemsse/)* [Answer] # [ditaa](https://github.com/stathissideris/ditaa), 118 bytes ``` /----+----+----\ |cF00|cFF0|cF0F| +----+----+----+ |cFF0|c0F0|c0FF| +----+----+----+ |cF0F|c0FF|c00F| \----+----+----/ ``` This is the output using `-E` option: [![enter image description here](https://i.stack.imgur.com/Od7Ke.png)](https://i.stack.imgur.com/Od7Ke.png) [Answer] # R, ~~89~~ ~~50~~ 48 bytes **Newest version:** ``` image(matrix(c(6,4,5,2:4,1,2),3),col=rainbow(6)) ``` Not enough elements in the vector to fill the 3x3 matrix, so it wraps around and reuses the first element. **Old versions:** ``` image(matrix(c(6,4,5,2:4,1,2,6),3),col=rainbow(6)) image(matrix(c(3,5,6,2,4,5,1:3),3),col=c('red','yellow','magenta','green','cyan','blue')) ``` [![enter image description here](https://i.stack.imgur.com/3CT9L.png)](https://i.stack.imgur.com/3CT9L.png) [Answer] ## Factorio Blueprint String, 705 bytes I admit, I'm just pushing the limits of what counts as a solution. ``` 0eNrdWNGOqyAQ/ReedeNo0daH/ZHNTYOW7ZJFNAi91zT99wua7ZpdaaT1pb40oQ6HOecwA3pGBde0kUwolJ8RK2vRovztjFp2FITb/1TXUJQjpmiFAiRIZUdtzYkMGyIoR5cAMXGg/1AOlz8BokIxxegA0w+6vdBVQaUJuAKQstSV5kTV0qA2dWvm1MKuZ3FecIA6lIf4BV8uwS+YeDKPXzBhPKAkUxjJPAy4AbG5QljZFBEqLOuqYGKa1Vc6YAQzE5Ss+b6gH+TETLQJeWdcUemQ/8Sk0oSPHOgjQkkPqMfT1kEYWzEsI2hpc2gtFtgfO2NkDTMjbIKnCOLv1SrCechJ1UzwSm7zKpksNVN78+xwnffOZKv2s2kS0akPJo4D10FslEd2UDVE9oLn6NU+1i01S/HaKqmkpvNl2DhkSGfJEK1Eha1DhWyWCmvZCzuHCtu7aj5asuQ7ynn99/GqT0f07BjAwXnnx3kohEW7XMPE5+OEs5+EUwdhiL4T0IVh3LNzHlMwfUoB+LTPeK19A2LPkoGbety1f46SUvH4BoLExTHxOCKe3mmIXTJ43ogGp5MlnS47soTR+GeryFyUscex+PzOu65IkPr0OrzW2wFkHn0Ar3c3eN6S4pt63NUH7GvtAn3AafTOo+yf3+jhbDcv9/1XgHz00SBAJ+NNn3uWRJDiDcDWXIf+Aya7oEk= ``` Produced output when placed in-game (low graphics settings used): [![enter image description here](https://i.stack.imgur.com/T5A0u.png)](https://i.stack.imgur.com/T5A0u.png) To prove that it is a valid solution you need to sample this grid of pixels which do match the specification exactly: [![enter image description here](https://i.stack.imgur.com/bhMIe.png)](https://i.stack.imgur.com/bhMIe.png) The rest of the image is classified as a border or a spacing which, as said in the question, doesn't matter. [Answer] # Perl 6 (and probably similar for many languages) (31 bytes) ``` {'ÿ ÿÿÿ ÿ ÿÿ ÿ ÿÿÿ ÿ ÿÿ ÿ'} # replace spaces with ASCII 00 # which I can't seem to enter ``` This outputs a headless TIFF file, which used to be generated by Photoshop with the file extension .raw and is presumed to be square unless otherwise specified at the time of opening. Playing around with the color depth (if allowed) could reduce this down further. [Answer] # ffplay (ffmpeg), 93 bytes ``` ffplay -f rawvideo -s 3x3 -pix_fmt rgb24 "data:/;base64,/wAA//8A/wD///8AAP8AAP///wD/AP//AAD/" ``` **Old**: ``` ffplay -f lavfi -i testsrc=s=3x3,geq=r=255*not(X*Y):g=255*not((X-1)*(Y-1)):b=255*not((X-2)*(Y-2)) ``` [Answer] # Excel-VBA, ~~89~~ ~~73~~ ~~72~~ 70 bytes Edit: You can use the immediate window and dispense with the `Sub`/`End Sub` to save 16 bytes: ``` For i=1To 9:[A:C].Cells(i).Interior.ColorIndex=Mid(367648785,i,1):Next ``` Original answer: ``` Sub a() For i=1To 9 [A1:C3].Cells(i).Interior.ColorIndex=Mid(367648785,i,1) Next End Sub ``` This was inspired by [Neil](https://codegolf.stackexchange.com/users/17602/neil)'s suggestion on [this](https://codegolf.stackexchange.com/a/183352/86631) answer, and is my first submission! Result: [![Result Grid](https://i.stack.imgur.com/wsWFQ.png)](https://i.stack.imgur.com/wsWFQ.png) **-2 bytes**: Removal of cell row numbers - thanks to [Taylor Scott](https://codegolf.stackexchange.com/users/61846/taylor-scott)! [Answer] ## JavaScript, ~~108~~ 102 bytes ``` console.log(`%c█%c█%c█ `.repeat(3),...[...`320251014`].map(c=>`color:#`+`f0ff00f0`.substr(c,3))) ``` No snippet because this only works in a real browser console and not the snippet's console. Edit: Thanks to @AJFaraday for the screenshot. Explanation: Browsers allow the first parameter of `console.log` to include substitutions. The `%c` substitution takes a parameter and applies it as (sanitised) CSS. Each `█` block is therefore coloured using the appropriate substring of `f0ff00f0` interpreted as a three-hex-digit colour code. [![Example of code execution](https://i.stack.imgur.com/T34aZ.png)](https://i.stack.imgur.com/T34aZ.png) [Answer] # [Octave/MATLAB](https://www.gnu.org/software/octave/), ~~57 56~~ 40 bytes -17 byte thanks to @ExpiredData! Check out their [even golfier solution](https://codegolf.stackexchange.com/a/183367/24877)! ``` image(reshape(de2bi(126973007),[3,3,3])) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/MzcxPVWjKLU4I7EgVSMl1SgpU8PQyMzS3NjAwFxTJ9pYBwhjNTX//wcA "Octave – Try It Online") [Answer] \$\Large{\mathbf{\TeX} \left(\text{MathJax}\right)},~122\,\text{bytes}\$ $$ \def\c#1{\color{#1}{\rule{5em}{5em}}} \c{red} \c{yellow} \c{fuchsia} \\ \c{yellow} \c{lime} \c{aqua} \\ \c{fuchsia} \c{aqua} \c{blue} $$ **Golf'd:** ``` $\def\c#1{\color{#1}{\rule{5em}{5em}}}\c{red}\c{yellow}\c{fuchsia}\\\c{yellow}\c{lime}\c{aqua}\\\c{fuchsia}\c{aqua}\c{blue}$ ``` **Ungolf'd:** ``` $$ \def\coloredBox#1{\color{#1}{\rule{5em}{5em}}} \coloredBox{red} \coloredBox{yellow} \coloredBox{fuchsia} \\ \coloredBox{yellow} \coloredBox{lime} \coloredBox{aqua} \\ \coloredBox{fuchsia} \coloredBox{aqua} \coloredBox{blue} $$ ``` --- **Edits:** 1. Thanks to [@flawr](https://codegolf.stackexchange.com/users/24877/flawr) for pointing out how to fix the colors! 2. Could shave off \$14\,\text{bytes}\$ by replacing `\rule{5em}{5em}` with `▉`, which'd look like$$ \def\d#1{\color{#1}{▉}} \d{red} \d{yellow} \d{fuchsia} \\ \d{yellow} \d{lime} \d{aqua} \\ \d{fuchsia} \d{aqua} \d{blue} $$ , but just doesn't look quite the same. 3. Could probably shave off a few more bytes by finding color names that acceptably resemble the intended colors. 4. Just to show what a decently \$\mathrm{\TeX}\text{'d}\$ version of this would look like:$$ {\newcommand{\rotate}[2]{{\style{transform-origin: center middle; display: inline-block; transform: rotate(#1deg); padding: 50px}{#2}}}} {\def\place#1#2#3{\smash{\rlap{\hskip{#1em}\raise{#2em}{#3}}}}} {\def\placeBox#1#2#3{\place{#1}{#2}{\color{#3}{\rule{5em}{5em}}}}} {\def\placeLabelTop#1#2#3{\place{#1}{#2}{\large{\textbf{#3}}}}} {\def\placeLabelLeft#1#2#3{\place{#1}{#2}{\rotate{-90}{\large{\textbf{#3}}}}}} \placeLabelTop{1.1}{15.5}{Red} \placeLabelTop{5.5}{15.5}{Green} \placeLabelTop{11.2}{15.5}{Blue} \placeLabelLeft{-6.2}{13.6}{Red} \placeLabelLeft{-7.1}{8.5}{Green} \placeLabelLeft{-6.5}{3.5}{Blue} \placeBox{0}{10}{red} \placeBox{5}{10}{yellow} \placeBox{10}{10}{fuchsia} \placeBox{0}{5}{yellow} \placeBox{5}{5}{lime} \placeBox{10}{5}{aqua} \placeBox{0}{0}{fuchsia} \placeBox{5}{0}{aqua} \placeBox{10}{0}{blue} \place{15.1}{0}{\large{.}} \phantom{\rule{15em}{16.5em}} $$ [Answer] # Lua + [LÖVE/Love2D](https://love2d.org/), ~~186~~ 183 bytes ``` t={[0>1]=0,[0<1]=1}l=love g=l.graphics function l.draw()for i=1,3 do for j=1,3 do g.setColor(t[i<2 or j<2],t[i==2 or j==2],t[i>2 or j>2])g.rectangle('fill',j*10,i*10,10,10)end end end ``` [Try it online!](https://repl.it/repls/MatureTimelyProgram) [![enter image description here](https://i.stack.imgur.com/s7q1U.png)](https://i.stack.imgur.com/s7q1U.png) My first code golf entry! [Answer] # HTML/CSS, ~~278~~ ~~141~~ 137 bytes ``` r{color:red}y{color:#ff0}m{color:#f0f}g{color:#0f0}c{color:#0ff}l{color:#00f ``` ``` <pre><r>█<y>█<m>█ <y>█<g>█<c>█ <m>█<c>█<l>█ ``` *-137 bytes thanks to commenters, most notably @data* *-4 bytes thanks to @Einacio* Uses Unicode `█` (U+2588) for the "blocks", and uses CSS classes/inline style to color them. I think the `<font>` tags could be golfed more, however changing them to a shorter tag such as `<a>` breaks the `color` attribute [Answer] # MATL, ~~44 23 21 20~~ 19 bytes A direct port of my Octave answer with the suggestions from @ExpiredData and @LuisMendo. ``` 126973007Bo7B3*e0YG ``` [try it online](https://matl.suever.net/?code=126973007Bo7B3%2ae0YG&inputs=&version=20.10.0) [Answer] # [Octave](https://www.gnu.org/software/octave/), 38 bytes ``` image(reshape(de2bi(126973007),3,3,3)) ``` [Try it online!](https://tio.run/##y08uSSxL/f8/MzcxPVWjKLU4I7EgVSMl1SgpU8PQyMzS3NjAwFxTxxgENTX//wcA "Octave – Try It Online") [Answer] # HTML (GIF), 108 bytes It's the battle of the web-based image formats! (Any TIF or JPG contenders out there?) Answer by [@A C](https://codegolf.stackexchange.com/questions/183315/generate-an-rgb-colour-grid?page=1&tab=votes#comment441323_183338). ``` <img src=data:image/gif;base64,R0lGODdhAwADAMIGAAAA//8AAP8A/wD/AAD/////AAAAAAAAACwAAAAAAwADAAADBhglNSQEJAA7> ``` --- # HTML (BMP), ~~116~~ 115 bytes Answer by [@ASCII-only](https://codegolf.stackexchange.com/questions/183315/generate-an-rgb-colour-grid?page=1&tab=votes#comment441127_183338). ``` <img src=data:image/bmp;base64,Qk0+AAAAQVNDTxoAAAAMAAAAAwADAAEAGAD/AP///wD/AAAAAAAA//8A/wD//wAAAAAAAP8A////AP8AAAA> ``` --- # HTML (WebP), 116 bytes Answer by [@Hohmannfan](https://codegolf.stackexchange.com/questions/183315/generate-an-rgb-colour-grid/183338?noredirect=1#comment441358_183338). ``` <img src=data:image/webp;base64,UklGRjYAAABXRUJQVlA4TCoAAAAvAoAAAC8gEEjaH3qN+RcQFPk/2vwHH0QCg0I2kuDYvghLcAoX0f/4Hgc> ``` --- # HTML (PNG), ~~151~~ ~~136~~ 135 bytes -15 bytes thanks to [@Hohmannfan](https://codegolf.stackexchange.com/questions/183315/generate-an-rgb-colour-grid/183338?noredirect=1#comment441358_183338). ``` <img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAADCAIAAADZSiLoAAAAFElEQVR4AWP4z8Dw/z8DEIIodB4A4D0O8pOGuTgAAAAASUVORK5CYII> ``` --- Also, see my [CSS](https://codegolf.stackexchange.com/a/183337/47097) and [SVG](https://codegolf.stackexchange.com/a/183461/47097) answers. [Answer] ## Blockly turtle, 45 blocks [Try it online!](https://blockly-games.appspot.com/turtle?lang=en&level=10#gtugp7) How about we play a little game of finding the most ridiculous tool for the job? Output: [![The glorious output of this glorious piece of crappy programming](https://i.stack.imgur.com/fwFTu.png)](https://i.stack.imgur.com/fwFTu.png) The program (as a screenshot for additional heresy): [![The program as a screenshot for additional heresy](https://i.stack.imgur.com/SSUGT.png)](https://i.stack.imgur.com/SSUGT.png) Note: The grayed out blocks are also counted towards the metric. [Answer] # Node.js, 79 bytes ``` require('fs').writeFile(a='P',a+[...'3331100110101110010011101011001'].join` `) ``` Produces a file named "P" in the PPM format containing the color grid. [Answer] # [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html) (on xterm), 64 bytes ``` Fi16[AP]sF36dD6r31 101dD6rD1[1CP61P[38;5;]Pn[mX]Pz3%0=Fz0<M]dsMx ``` You'll just get a bunch of wacky escape codes instead of colors, but you can still [try it online!](https://tio.run/##S0n@/98t09As2jEgttjN2CzFxazI2FDB0MAQxHIxjDZ0DjAzDIg2trA2tY4NyIvOjYgNqDJWNbB1qzKw8Y1NKfat@P8fAA "dc – Try It Online") By my understanding, the 16 basic ANSI colors are free to be interpreted however the terminal wants. On the other hand, the 216 colors in the xterm color cube have explicit RGB values. I am using these codes and printing a grid of `X`s: [![buncha colorful 'x's](https://i.stack.imgur.com/VYMck.png)](https://i.stack.imgur.com/VYMck.png) First we set the input radix to base 15 with `Fi`. This costs two bytes, but gives back three, so... a net gain of a byte (and a big ol' loss in readability). Next we're trying to get our color values onto the stack. In decimal, this would be `21 51 201 51 46 226 201 226 196`, but we're in wacky mode so it's going to be `16 36 D6 36 31 101 D6 101 D1`. We eliminate one of the spaces by slotting in a macro we need to define at some point, `[AP]sF` (which simply prints a line feed). We can shrink `36 D6 36` and `101 D6 101` by placing the first value on the stack, duplicating it, placing the second, and then swapping (`36dD6r`, `101dD6r`). Macro `M` handles the printing and whatnot. `1CP` prints the escape character. Brackets are used to delimit strings, and as far as I know are not escapable, so we need to print the bracket with an ASCII value as well, `61P`. `[38;5;]P` is the 'set foreground color from the numbered list' code. `n` prints the value from the top of the stack w/o a newline, popping it. `[mX]P` ends the code and prints an 'X'. `z3%0=F` checks the stack depth mod 3, running our line feed macro `F` when necessary. `z0<M` keeps `M` running as long as there's stuff on the stack. `dsMx` to run. Note that if you run this in dc in an xterm, it'll leave your foreground color blue. `1CP61P74P` (input shown in the screenshot) should reset this. [Answer] ## C#, ~~248~~ ~~204~~ 198 bytes ``` class P{static void Main(){for(int i=0;i<12;i++){foreach(dynamic n in Enum.GetValues(typeof(ConsoleColor)))if((""+n)[0]=="RYMRYGCRMCBR"[i])Console.BackgroundColor=n;Console.Write(i%4<3?" ":"\n");}}} ``` Output: [![enter image description here](https://i.stack.imgur.com/FqmAz.png)](https://i.stack.imgur.com/FqmAz.png) [Answer] # TI-Basic, x bytes (will score when I can) Note: content filter is blocking me from looking up the token sizes for each of these commands. If anyone wants to score for me, go for it. ``` TextColor(11 Text(0,0,"0" TextColor(19 Text(0,2,"0" Text(2,0,"0" TextColor(13 Text(4,0,"0" Text(0,4,"0" TextColor(14 Text(2,2,"0" TextColor(18 Text(2,4,"0" Text(4,2,"0" TextColor(17 Text(4,4,"0" ``` This look really bad on my little calculator screen. But hey, shape doesn't matter :^) Golf output: [![enter image description here](https://i.stack.imgur.com/Ay8yM.png)](https://i.stack.imgur.com/Ay8yM.png) Modified for 8x larger output: [![enter image description here](https://i.stack.imgur.com/bqBbc.png)](https://i.stack.imgur.com/bqBbc.png) # TI-BASIC, x bytes Using Pxl-On instead of Text: ``` Pxl-On(0,0,11 Pxl-On(0,1,19 Pxl-On(0,2,13 Pxl-On(1,0,19 Pxl-On(1,1,14 Pxl-On(1,2,18 Pxl-On(2,0,13 Pxl-On(2,1,18 Pxl-On(2,2,17 ``` Output: [![enter image description here](https://i.stack.imgur.com/3k70l.png)](https://i.stack.imgur.com/3k70l.png) Blown up ~11x: [![enter image description here](https://i.stack.imgur.com/CDlKq.png)](https://i.stack.imgur.com/CDlKq.png) [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes ``` “IỤỵ7ỤĖm8’b4K”P; ``` [Try it online!](https://tio.run/##y0rNyan8//9RwxzPh7uXPNy91RxIHZmWa/GoYWaSifejhrkB1v//AwA "Jelly – Try It Online") Niladic link or full program that produces a portable pixmap format image of the desired grid. [Answer] ## C++, SFML, 177 bytes ``` #include<SFML/Graphics.hpp> int d[]={255,65535,0xFF00FF,65535,65280,0xFFFF00,0xFF00FF,0xFFFF00,0xFF0000};void f(){sf::Image g;g.create(3,3,(sf::Uint8*)d);g.saveToFile("a.jpg");} ``` Uses `sf::Image::create(int,int,unsigned char*)` method to create an image with rgb values in it [Answer] # PostScript, 195 bytes Output look closer: [![enter image description here](https://i.stack.imgur.com/2a2Ux.png)](https://i.stack.imgur.com/2a2Ux.png) ``` %!PS /r{rlineto}def/s{newpath moveto 0 1 r 1 0 r 0 -1 r closepath setrgbcolor fill}def 1 0 0 0 2 s 1 1 0 1 2 s 1 0 1 2 2 s 1 1 0 0 1 s 0 1 0 1 1 s 0 1 1 2 1 s 1 0 1 0 0 s 0 1 1 1 0 s 0 0 1 2 0 s ``` To test just paste the code in a blank file and save as `something.ps` and open in a pdf viewer. To enlarge the output add `50 50 scale` (or some other number) on the second line of the file. ]
[Question] [ # The Task Given a natural number as input, your task is to output a truthy or falsey value based on whether the input is a factorial of any natural number. You can assume that the input number will always be in the range of numbers supported by your language, but you must not [abuse native number types to trivialize the problem](//codegolf.meta.stackexchange.com/a/8245). [Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply. --- ## Input You'll be given a natural number (of type `Integer` or similar). You can take input in any way you want except assuming it to be in a predefined variable. Reading from file, console, dialog box (`prompt`), input box etc. is allowed. Input as function argument is allowed as well! --- ## Output Your program should output a truthy or falsey value based on whether the input number is a factorial of any natural number. Make sure that your truthy/falsey values are consistent for all inputs, i.e, if you are using pair of 1 and 0 to denote truthy and falsey values respectively, then your program must output 1 for all inputs that should have truthy values and 0 for all inputs that should have falsey values. You can take output in any way you want except writing it to a variable. Writing to file, console, screen etc. is allowed. Function `return` is allowed as well! Your program must not produce errors for any input! --- ## Test Cases ``` Input Output 1 Truthy (0! or 1!) 2 Truthy (2!) 3 Falsey 4 Falsey 5 Falsey 6 Truthy (3!) 7 Falsey 8 Falsey 24 Truthy (4!) 120 Truthy (5!) ``` --- ## Winning Criterion This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins! [Answer] # [Brachylog](https://github.com/JCumin/Brachylog), 1 byte ``` ḟ ``` [Try it online!](https://tio.run/nexus/brachylog2#dYtRFQRBCMMsQYHSql0ba@eUzI2BzV9fmvN7n3OOq0DkdJe7c0AlbZQ0BLkR7dgcU2DXtcimxjBLHuSOLwXYOQy576G8vGtSEDFFrxHCArUjTKZuG06KHR/8AQ "Brachylog – TIO Nexus") ### Explanation `ḟ` is a built-in that asserts the following relation: its output is the factorial of its input. We simply give it a set output and see whether it suceeds or not with a variable input. [Answer] # ECMAScript Regex, ~~733⚛~~ ~~690⚛~~ ~~158~~ ~~119~~ ~~118~~ 92 bytes * *dropped 1 byte (119 → 118) using a trick found by [Grimmy](https://codegolf.stackexchange.com/users/6484/grimmy) that can futher shorten division in the case that the quotient is guaranteed to be greater than or equal to the divisor* * *dropped 26 bytes (118 ~~(117🐌)~~ → 92) thanks to [Grimmy in collaboration with H.PWiz](https://chat.stackexchange.com/transcript/message/50183034#50183034). I've finally analyzed, commented, and proved this version.* My interest in regex has been sparked with renewed vigor after over 4½ years of inactivity. As such, I went in search of more natural number sets and functions to match with unary ECMAScript regexes, resumed improving my regex engine, and started brushing up on PCRE as well. I'm fascinated by the alienness of constructing mathematical functions in ECMAScript regex. Problems must be approached from an entirely different perspective, and until the arrival of a key insight, it's unknown whether they're solvable at all. It forces casting a much wider net in finding which mathematical properties might be able to be used to make a particular problem solvable. Matching factorial numbers was a problem I didn't even consider tackling in 2014 – or if I did, only momentarily, dismissing it as too unlikely to be possible. But last month, I realized that it could be done. As with my other ECMA regex posts, I'll give a **warning:** I highly recommend learning how to solve unary mathematical problems in ECMAScript regex. It's been a fascinating journey for me, and I don't want to spoil it for anybody who might potentially want to try it themselves, especially those with an interest in number theory. [See this earlier post](https://codegolf.stackexchange.com/a/178889/17216) for a list of consecutively spoiler-tagged recommended problems to solve one by one. So **do not read any further if you don't want some advanced unary regex magic spoiled for you**. If you do want to take a shot at figuring out this magic yourself, I highly recommend starting by solving some problems in ECMAScript regex as outlined in that post linked above. This was my idea: > > The problem with matching this number set, as with most others, is that in ECMA it's usually not possible to keep track of two changing numbers in a loop. Sometimes they can be multiplexed (e.g. powers of the same base can be added together unambiguously), but it depends on their properties. So I couldn't just start with the input number, and divide it by an incrementally increasing dividend until reaching 1 (or so I thought, at least). > > > > Then I did some research on the multiplicities of prime factors in factorial numbers, and learned that there's [a formula for this](https://janmr.com/blog/2010/10/prime-factors-of-factorial-numbers/) – and it's one that I could probably implement in an ECMA regex! > > > After stewing on it for a while, and constructing some other regexes in the meantime, I took up the task of writing the factorial regex. It took a number of hours, but ended up working nicely. As an added bonus, the algorithm could return the inverse factorial as a match. There was no avoiding it, even; by the very nature of how it must be implemented in ECMA, it's necessary to take a guess as to what the inverse factorial is before doing anything else. The downside was that this algorithm made for a very long regex... but I was pleased that it ended up requiring a technique used in my 651 byte multiplication regex (the one that ended up being obsolete, because a different method made for a 50 byte regex). I had been hoping a problem would pop up that required this trick: Operating on two numbers, which are both powers of the same base, in a loop, by adding them together unambiguously and separating them at each iteration. But because of the difficulty and length of this algorithm, I used molecular lookaheads (of the form `(?*...)`) to implement it. That is a feature not in ECMAScript or any other mainstream regex engine, but one that I had [implemented in my engine](https://github.com/Davidebyzero/RegexMathEngine/commit/db4e4a266d55ec66663ccaa17de944508ace4067). Without any captures inside a molecular lookahead, it's functionally equivalent to an atomic lookahead, but with captures it can be very powerful. The engine will backtrack into the lookahead, and this can be used to conjecture a value which cycles through all possibilities (for later testing) without consuming characters of the input. Using them can make for a much cleaner implementation. (Variable-length lookbehind is for most uses at least equal in power to molecular lookahead, but the latter tends to make for more straightforward and elegant implementations. Molecular lookahead may also be able to do things in loops that aren't possible with variable-length lookebehind.) So the 733 and 690 byte lengths do not actually represent ECMAScript-compatible incarnations of the solution – hence the "⚛" after them; it's surely possible to port that algorithm to pure ECMAScript (which would increase its length quite a bit) but I didn't get around to it... because I thought of a much simpler and more compact algorithm! One that could easily be implemented without molecular lookaheads. It's also significantly faster. This new one, like the previous, must take a guess at the inverse factorial M, cycling through all possibilities and testing them for a match. It divides N by 2 to make room for the work it needs to do, and then seeds a loop in which it will repeatedly divide the input by a divisor that starts at 3 and increments up to M-1.\* (As such, 1! and 2! can't be matched by the main algorithm, and must be dealt with separately.) The divisor is kept track of by adding it to the running quotient; these two numbers can be unambiguously separated because, assuming M! == N, the running quotient will continue to be divisible by M until it equals M. \*But it later turned out that starting the divisor at M-1, and decrementing down to 3, can result in a shorter regex. This was part of golfing 118 → 92 bytes. > > This regex does division-by-a-variable in the innermost portion of the loop. The division algorithm is the same as in my other regexes (and similar to the multiplication algorithm): for A≤B, A\*B=C if any only if C%A=0 and B is the largest number which satisfies B≤C and C%B=0 and (C-B-(A-1))%(B-1)=0, where C is the dividend, A is the divisor, and B is the quotient. (A similar algorithm can be used for the case that A≥B, and if it is not known how A compares to B, one extra divisibility test is all that is needed.) > > > So I love that the problem was able to be reduced to even less complexity than my golf-optimized [Fibonacci regex](https://codegolf.stackexchange.com/a/178956/17216), but I do sigh with disappointment that my multiplexing-powers-of-the-same-base technique will have to wait for another problem that actually requires it, because this one doesn't. It's the story of my 651 byte multiplication algorithm being supplanted by a 50 byte one, all over again! With no further ado, here's the regex: True/false version (**92 bytes**): `^(((x+)\3+)(?=\3\3\2$)(x(?=\3+(x*))(?=\5+$)(?=((x+)(?=\5\7*$)x)\6*$)\3+(?=\5\7$))*\3xx|x?)x$` [Try it online!](https://tio.run/##TY9Lb8IwEITv/RU0imA3aUIgPCRcw6mHXji0x6aVLDCJW@NEtgGXx29Pk1SVqj2MZuaTVvPJjsxstKhsZCqx5Xpfqi/@XWuq@Kn3wvMnVwGc6XIY1B8A4ELM0hBhRbO0ubGP4DoTgguwy6eh32rHdj6bBz46zGaNtOBv5iMGWerc1a3Q@XUwPGNsy1erhcoBYyPFhsPsIZogEkMTciqE5ACSas62UigOiPdUHaTES05lbCopLAyiARKxA1A0jyVXuS1wOb5ehVmzNQhaMW34s7KQvyXviH8F/1@o5Wg1WrQ12kKXJ@9ZHZkU255mKueLnhdKsis1EPFIORFhiM1Dz3mx5hVnFgTGe2Y3BWjEi@n3q2aShXbFiFQHa6xuEHK71Uk0T5O7aTJJfgA "JavaScript (SpiderMonkey) – Try It Online") Return inverse factorial or no-match (109 bytes): `^(?=((x(x*))\2+)(?=\2\2\1$)(x(?=\2+(x*))(?=\5+$)(?=((x+)(?=\5\7*$)x)\6*$)\2+(?=\5\7$))*\2xxx$)(\3|xx)?x|^xx?$` (relies on ECMAScript [no-empty-optional](https://github.com/Davidebyzero/RegexMathEngine/issues/1) behavior) [Try it online!](https://tio.run/##TU9LbsIwEN33FGkUkZmkhCT8JFKTVRdsWLTLpkgWmODWmMg24PLZ9gA9Yi9CkyKkahYz7yPNe@90R/Vc8cq0dcUXTK038oN9XhSRbO88s/LJVgAHMu4ElxnkBMCCDRCLNMQaFmk9iYc124DwT2vOfujh1X719Yth4KHFYlCvxnjlPMSgSK21tbvonqzF3J5m1ubeJegcMDKbF6O4LAEjLficweCh3UPMNImz/YoLBiCIYnQhuGSAeE/kVgg8lkREuhLcgN/2MeNLAEnKSDBZmhWO09OJ6ymdAicVVZpNpIHyNX5DvAnsvyDHSZ6MGhnNSm327kTuqOALR1FZspHjhiJbbhRk/JGwjIch1g/XxLVupFjFqAGO0Zqa@QoU4lG3WlVdykDTI8mqrdFGAQ995@fr2/HDdZ3kFjU7ny9xe9iN7/pxL77rxd00/gU "JavaScript (SpiderMonkey) – Try It Online") Return inverse factorial or no-match, in [ECMAScript + `\K`](https://github.com/Davidebyzero/RegexMathEngine/commit/c24020605295aa562e7a67290f3d78c69481d0e3) (103 bytes): `^(((x(x*))\3+)(?=\3\3\2$)(x(?=\3+(x*))(?=\6+$)(?=((x+)(?=\6\8*$)x)\7*$)\3+(?=\6\8$))*x\Kxx(\K\4)?|x?)x$` (relies on ECMAScript [no-empty-optional](https://github.com/Davidebyzero/RegexMathEngine/issues/1) behavior) Return inverse factorial or no-match, in [ECMAScript + `(?*)`](https://github.com/Davidebyzero/RegexMathEngine/commit/db4e4a266d55ec66663ccaa17de944508ace4067) (103 bytes): When adapted to molecular lookahead, this regex can match \$3!\$ in a straightforward way: `^(?=(?*(x+))(\1*)(?=\1\1\2$)(x(?=\1+(x*))(?=\4+$)(?=((x+)(?=\4\6*$)x)\5*$)\1+(?=\4\6$))*\1xxx$)\1|^xx?$` Return inverse factorial or no-match, in ECMAScript + [`(?*)`](https://github.com/Davidebyzero/RegexMathEngine/commit/db4e4a266d55ec66663ccaa17de944508ace4067) + [`\K`](https://github.com/Davidebyzero/RegexMathEngine/commit/c24020605295aa562e7a67290f3d78c69481d0e3) (**99 bytes**): `^(?*(x+))(\1*)(?=\1\1\2$)(x(?=\1+(x*))(?=\4+$)(?=((x+)(?=\4\6*$)x)\5*$)\1+(?=\4\6$))*xxx\K\1$|^xx?$` And the free-spaced version with comments: ``` # Match factorial numbers in the domain ^x*$ ^ # N = tail = input ( ((x+)\3+)(?=\3\3\2$) # \3 = conjectured inverse factorial of N if N >= 4! = 24; # \2 = N/2 - \3; assert tail is divisible by \3 and by 2; # assert tail is divisible by a number >= 6; # tail = N/2 + \3; # Note that if N = 3! = 6, \3 will behave differently, # because sticking to the pattern, we'd need \2=0, which # is of course impossible, because we must have \2 >= \3. # However, when N=6, \3=1 happens to result in a match after # zero loop iterations. # The loop is seeded: X = N/2; I = \3 - 1; tail = X + I + 1 # The loop will divide X by the numbers in the range \3-1 downward to 3, inclusive. # Since we don't divide by \3 itself, and already divided by 2, if N is factorial, # the end result of these divisions will be X = \3. ( # Main loop x # tail = tail-1 = X + I (?=\3+(x*)) # \5 = tail % \3 = I; assert X >= \3 (?=\5+$) # assert X is divisible by I; if \3=1, then \5=0, # and the main loop will exit after zero iterations (?= ( # \6 = tail / \5 = (X+I)/I = X/I + 1 (x+) # \7 = \6-1 = X/I; assert X/I >= 1 (?=\5\7*$) x ) \6*$ ) \3+(?=\5\7$) # Prepare the next iteration of the loop: X = \7; I -= 1; # tail = X + I + 1; # Assert that the tail difference is divisible by \3, i.e. # that, with our previous values of X and I: # X + I - (X/I + I-1 + 1) # = X/I*(I-1) is divisible by \3 # Since I is coprime with I-1, if X was divisible by \3 # but X/I is not, then X/I*(I-1) will not be either, so this # indirectly asserts that X/I, our new X, is divisible by \3. # The initial value of X was asserted to be divisible by \3 # before the loop started, so by induction, every new value # of X will be asserted to be divisible by \3. This is # important because we use modulo by \3 to recover the value # of I at the beginning of each loop iteration. # And if N = \3! and the previous of I=2 and X was able to be # divided by 2, this will force this iteration of the loop to # fail, and the loop will exit with the values of X and I # backtracked to their values before this iteration, i.e. # with X = \3 and I = 2. )* \3xx # assert tail = \3 + 2 + 1, meaning when the loop finished # we ended up with X = \3 and I = 2 | x? # match N=1 and N=2, which the main algorithm can't ) x$ ``` The full history of my golf optimizations of these regexes is on github: [regex for matching factorial numbers - multiplicity-comparing method, with molecular lookahead.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20factorial%20numbers%20-%20multiplicity-comparing%20method%2C%20with%20molecular%20lookahead.txt) [regex for matching factorial numbers.txt](https://github.com/Davidebyzero/RegexGolf/blob/master/regex%20for%20matching%20factorial%20numbers.txt) (the one shown above) ## Optimized for returning the inverse factorial The above algorithm has the quirk of happening to match \$3!\$ by coincidence, yielding a false inverse factorial value of \$1\$ instead of \$3\$. This complicates turning the regex into one that returns the inverse factorial as a match. The below algorithm is cleaner in that it straightforwardly matches \$3!\$ with the correct inverse factorial value. It does however result in a longer true/false regex. True/false version – returns inverse factorial minus 1 in `\1` (**96 bytes**): `^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x+))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*\1x?$` [Try it online!](https://tio.run/##TY/NbsIwEITvfQoaIdhNSkhoAInUcOqBC4f2WLeSBSZxaxzLNpDy8@ypUxWpp9XstzOr@WQHZtdGaDewWmy42VXqi383hih@7Lzw4rnWACcyH4bNB9QhwoLUUNMUwy6CF3QU/q3pCGkGdYS/Yhx12wk3OKZT76iRTvxoTT6HZnTihc@iab3oNuHwhLGrXp0RqgCMrRRrDpOHQYaYW5Lkx1JIDiCJ4WwjheKAeE/UXko8F0TGVkvhoD/oYy62AIoUseSqcCXOR5eLsCu2AkE0M5YvlYPiLXlHvAH@H6h5ukhnLUZXmuoYLNWBSbHpGKYKPusEkcy3lYFcPBGeiyhC/zCog9hwzZkDgfGOuXUJBvFsez3tKzloW6S53jvrjD/Jr9cmGUwfk7txkiU/ "JavaScript (SpiderMonkey) – Try It Online") - true/false [Try it online!](https://tio.run/##TY9NbsIwEIX3PUWKEJlJmpCEABKpYdUFGxbtElPJAhPcGieyDaT8bHuAHrEXoUlVpK5Gbz69N/Pe2J6ZpRalDUwpVlxvC/XOP66aKH5wnnn@VJUARzLuetdXqDyECamgojF6bYRa0MT7W9MEaQqVj7@i77ebCTfYp8PaUSEd1KMx1Tk0pYNa1Fk0ribtq9c9YmiLF6uFygFDI8WSw@AhSBEzQ6LssBGSA0iiOVtJoTgg3hO1kxJPOZGhKaWw4AYuZmINoEgeSq5yu8Fxcj4LM2MzEKRk2vCpspDPowXiDfD/QI3jSTxqMNqNLg6tqdozKVaOZirnI6fly2xdaMjEI@GZ8H2sD25Jq2qFmpecWRAYbpldbkAjnkynU9alLDQ94qzcWWM1CN91vj@/HNffzuPF7dXscrlGwbAX3fWjNLpLo14S/QA "JavaScript (SpiderMonkey) – Try It Online") - return value in `\1` Return inverse factorial or no-match (**103 bytes**): `^(?=(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x*))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*\1x?$)x\1` [Try it online!](https://tio.run/##TY9NbsIwEIX3PUUaIZhJSkgggERqWHXBhkW7rFvJApO4dUxkG0j52fYAPWIvQp2qSF29efNpZt68sR0zSy0q2zWVWHFdbtQ7/7hoovjee@T5Q10BHMi0F1xeYUagDtBJDTVNMGghOEP7wV@b9pGmTf1rhmGrUbjCIR27iRrpyEkz5PbQlI6ccbtoUs8cpckl6B0wspsnq4XKASMjxZLD6K6bImaGxNm@EJIDSKI5W0mhOCDeErWVEo85kZGppLDQ6XYwE2sARfJIcpXbAqf900mYBVuAIBXThs@Vhfw5fkG8Av4fqGkySyYNRlvozd6fqx2TYuVppnI@8fxQZuuNhkzcE56JMER3sCR@7UeaV5xZEBiVzC4L0IhH025X7ikLzR9JVm2tsRpE2PG@P7@8Tli6JNeo2fl8ibvjQXwzjNP4Jo0H/fgH "JavaScript (SpiderMonkey) – Try It Online") Return inverse factorial in `\1` or no-match, in [ECMAScript + `(?*)`](https://github.com/Davidebyzero/RegexMathEngine/commit/db4e4a266d55ec66663ccaa17de944508ace4067) (**97 bytes**): `^(?*(x(x*))\1*$)\2((?=\1*(x*)(?=\1)\4(x*))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\1*(?=x\4\6$)\2)*\2x?$` Return inverse factorial or no-match, in [ECMAScript + `\K`](https://github.com/Davidebyzero/RegexMathEngine/commit/c24020605295aa562e7a67290f3d78c69481d0e3) (**101 bytes**): `^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x(x*)))(?=\5+$)(?=((x*)(?=\5\8*$)x)\7*$)\2*\4(?=x\7$)\K\6)*\1x?$` Return inverse factorial minus 1 or no-match, in [ECMAScript + `\K`](https://github.com/Davidebyzero/RegexMathEngine/commit/c24020605295aa562e7a67290f3d78c69481d0e3) (**98 bytes**): `^(x*)(?=x(x\1)*$)((?=\2*(x*)(?=\2)\4(x+))(?=\5+$)(?=((x*)(?=\5\7*$)x)\6*$)\2*(?=x\4\6$)\1)*x?\K\1$` ``` # Match factorial numbers in the domain ^x*$ and return the inverse factorial as the match ^ # N = tail = input (?= (x*) # \1 = conjectured inverse factorial - 1; tail -= \1 (?=x(x\1)*$) # \2 = conjectured inverse factorial; assert \2 divides N; # assert N >= 2 * \2; # If N=1 or N=2, then \2 will be unset (having experienced 0 # iterations of its mini-loop) and \1=0 or \1=1, respectively # The loop is seeded: X = N; I = \1; tail = X - I # The loop will divide X by the numbers in the range \2-1 downward to 2, inclusive. # We don't divide by \2 itself, so if N is factorial, the end result of these # divisions will be X = \2 - 1. ( (?= \2*(x*)(?=\2) # \4 = tail % \2 = \2-I; assert tail >= \2 \4(x*) # \5 = \2-\4 = I ) (?=\5+$) # assert X is divisible by I (?= ( # \6 = tail / \5 = (X-I)/I = X/I - 1 (x*) # \7 = \6-1 (?=\5\7*$) x ) \6*$ ) \2*(?=x\4\6$)\1 # Prepare next iteration of loop: X = \6+1; I -= 1; # tail = X - I; # Assert that, with our previous values of X and I: # (X - I) - (1 + \2-I + X/I - 1) # = X - \2 - X/I is divisible by \2 # Assuming X was already divisible by \2, this asserts # X/I is also divisible by \2. The initial value of X was # asserted to be divisible by \2, so by induction, every # new value of X will be asserted to be divisible by \2. # This is important because we use modulo by \2 to recover # the value of I at the beginning of each loop iteration. # And if I = 1, this iteration of the loop will fail # because in this case, # 1 + \4 + \6 > tail # \2-I + X/I > X - I # \2 > 0 # and the loop will exit with I = 1. # But note that if N = \2!, then when we reach I = 1, and # thus have X = \2 and tail = \2 - 1, this iteration of the # loop will have already failed at its beginning due to the # assertion that tail >= \2. )* \1x?$ # assert tail = \1 = \2-1, meaning when the loop finished we # ended up with X = \2 and I = 1, # or tail = \1+1 (what would be \2), which can only happen if # \2 is unset and N=1 or N=2 and the loop did 0 iterations. ) x\1 # return \1 + 1 as a match; don't use \2 because it will be # unset in the case of N=1 or N=2 ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes ``` Œ?IE ``` Not the shortest Jelly answer, but it's rather efficient. [Try it online!](https://tio.run/nexus/jelly#@390kr2n639DAxA43H54QlqkwsMd2x81zFFwzMlRSEtMLskvykzMKVZISs3JL1cAKtQBqtT7DwA "Jelly – TIO Nexus") ### How it works ``` Œ?IE Main link. Argument: n Œ? Yield the n-th permutation of the positive integers, without the sorted tail. For 120, this yields [5, 4, 3, 2, 1], the tail being [6, 7, 8, ...]. I Increments; compute all forward differences. For 120, this yields [-1, -1, -1, -1]. E Check if all differences are equal. ``` [Answer] # [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes ``` !€ċ ``` [Try it online!](https://tio.run/nexus/jelly#@6/4qGnNke7///8bGhkAAA "Jelly – TIO Nexus") 1 for yes, 0 for no. ## How it works ``` !€ċ argument as z !€ [1!, 2!, 3!, ..., z!] ċ count the number of occurrence of z ``` [Answer] ## JavaScript (ES6), ~~30~~ ~~29~~ 28 bytes Expects a positive integer. Returns `-1` for falsy and `-2` for truthy. ``` f=(n,k=2)=>n>1?f(n/k,k+1):~n console.log(1, '-->',f(1)) // Truthy (0! or 1!) console.log(2, '-->',f(2)) // Truthy (2!) console.log(3, '-->',f(3)) // Falsey console.log(4, '-->',f(4)) // Falsey console.log(5, '-->',f(5)) // Falsey console.log(6, '-->',f(6)) // Truthy (3!) console.log(7, '-->',f(7)) // Falsey console.log(8, '-->',f(8)) // Falsey console.log(24, '-->',f(24)) // Truthy (4!) console.log(120,'-->',f(120)) // Truthy (5!) ``` **Note**: This function supports pretty large inputs (you should read this as: 'pretty large for JS'). It should work safely up to *253 - 1*. It will fail for sure starting at *N = 121,645,100,408,831,992*, this input being rounded to *19! = 121,645,100,408,832,000* because of its IEEE-754 encoding. There *may* be other false positive results before *121,645,100,408,831,991* because of rounding errors, but I don't know for sure. [Answer] # [Python 3](https://docs.python.org/3/), ~~39~~ 38 bytes ``` f=lambda n,i=1:n>1and f(n/i,i+1)or n<1 ``` A recursive function taking an integer, `n`, returning a boolean value inversley representing the result (truthy: `False`, falsey: `True`) **[Try it online!](https://tio.run/nexus/python3#FYzNCoMwEAbP@hR7M8Gv6Kb@FKm@S8QGFnQVm/ePehoGhklhXP02L54UMvKgE3tdKBitBFKy3U/SL6dwM/7@kUTJMBzeaNCiQ48PXAN2tR3y7DhFo3lCUPGaCtynx6xNFw)** Repeatedly divides `n` by `i`, with an initial value of `1`, until the remainder is less than or equal to `1` then tests if that remainder is less then `1`, only factorials will end with a remainder equal to `1`, and `<` is a byte shorter than `==`. [Answer] # Java 8, 46 bytes ``` i->{int j=1,c=0;for(;j<i;j*=++c);return j==i;} ``` This is based on Roman Gräf's entry that I was able to knock a dozen or so bytes off of. I would have suggested it there but I don't have enough reputation to comment yet! My modified test runner code: ``` import java.util.function.Function; import java.util.stream.IntStream; public class IsFactorial { public static Function<Integer, Boolean> isFactorial = i->{int j=1,c=0;for(;j<i;j*=++c);return j==i;}; public static int[] truthyCases = {1,2,6,24,120}; public static int[] falsyCases = {3,4,5,7,8}; public static void main(String[] args){ System.out.println( IntStream.of(truthyCases).allMatch(i->isFactorial.apply(i)) && IntStream.of(falsyCases).allMatch(i->!isFactorial.apply(i))); } } ``` [Answer] # [Retina](https://github.com/m-ender/retina), ~~50~~ 38 bytes *12 bytes saved thanks to @Neil by combining shortening the loop and by getting rid of the `;`* ``` .+ 1¶$&$* +`^(1+)¶(\1)+$ 1$1¶$#2$* ¶.$ ``` [Try it online!](https://tio.run/##Fcu7DcIwFIbR/luDC3KwFOW/dl4TsARCoaCgoUDM5gG8mBPqo/N9/d6fZzuH29b6iGqxi12J2yModrWEu7poyP5y8oNq6a014SQyIxMzCysakJCjhDIa0YRmtKAVH/DjOJ7wvAM "Retina – Try It Online") Outputs `1` for true and `0` for false. `.+` matches the entire number `1¶$&$*` replacing it with `1` followed by a newline and the match converted to unary The remaining program divides the unary number in the bottom line by successively increasing positive integers, kept track in the top line, while it is possible to do so. `+`` loop until string remains same * `^(1+)¶(\1)+$` match the top line many `1`s and a multiple of it many `1`s on the bottom line and replace it with * `1$1¶$#2$*` the top line many `1`s with another `1`, that is, increasing the number represented by the top line by 1, followed by the newline and the number of matches of the top line in the bottom line (ie. count of matches of the second capturing group) many `1`s, that is, dividing the bottom number by the top number Once it is no longer possible to do so, `¶.$` give the number of matches of this regex, ie. does there exist a lone `1` on the bottom line, which only happens if the number is a factorial --- If no-crash/crash is allowed instead of truthy/falsy values, then I can get ~~36~~ 34 bytes. ``` ^ 1¶ {`.+$ $* ^(1+)¶(\1)+$ 1$1¶$#2 ``` This goes by the same approach, but combines the `$*` into the third and fourth lines. The third line onward is a part of the same loop, `{` is short for `+(` where the `(` groups the remaining lines into the loop. Factorials end in the program breaking out of the loop, while non-factorials get stuck in the loop forever until Retina throws an OverflowException caused by the last replacement failing thus having the bottom in unary instead of in decimal, and the first replacement of the loop converts the bottom line from decimal to unary, so it blows up quickly. [Answer] # C++, ~~102~~ ~~100~~ 92 Bytes ``` #include<cmath> int a(int n){int i=n,j=0;for(;i;)j|=lround(exp(lgamma(i--+1)))==n;return j;} ``` Loops through all the values from `0` to `n` and calculates the factorial and then checks if it's equal to `n`. Thanks Christoph! (saved 8 bytes) [Answer] # [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes ``` L!QO ``` [Try it online!](https://tio.run/nexus/05ab1e#@@@jGOj//7@hkQEA "05AB1E – TIO Nexus") **Explanation** ``` L # range [1 ... input] ! # calculate factorial of each Q # compare with input for equality O # sum ``` [Answer] # [Haskell](https://www.haskell.org/), ~~43~~ 26 bytes ``` f n=elem n$scanl1(*)[1..n] ``` [Try it online!](https://tio.run/nexus/haskell#DchNCoAgEAbQq3wLFyVDNP0vsotIC4kCQQepVl3eXL6XL4g5wxkh6jmcBK50bblpZM/ReTHp9vJC4fMJq94QXcJVbJnQEXrCQBgJE2EmLCWLuWv3/AM "Haskell – TIO Nexus") * Saved 17 bytes, thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni) [Answer] # [Haskell](https://www.haskell.org/), 38 bytes ``` m#n=n<2||mod n m<1&&(m+1)#div n m (2#) ``` [Try it online!](https://tio.run/nexus/haskell#XYw7CsMwEAX7nGLBwdik2Z9Wu2AfJmAMLqSEEFL57orSZro3D6aVoa514fMsjw0qlIXGcSo3moft@PzEZV8nHuZW7keFFZ6vo77hCjuQJnLBYGRnT25hopgxu6KbYJcaLllRcjAro0tyV8tOKau5o1EEiQYl6zc6oiXuASPWPv5pXw "Haskell – TIO Nexus") Example usage: `(2#) 24`. Returns `True` or `False`. This is the shortest I could get while still being very efficient. Even for numbers as large as ``` 145183092028285869634070784086308284983740379224208358846781574688061991349156420080065207861248000000000000000000 ``` the result is immediately given. The solution works by dividing the input `n` by `m = 2,3,4,5,...` until either the result is one or `n` is not divisible by `m`. For the shorter but incredible inefficient 26-byte solution which computes `n!` for inputs that are not factorials look [here](https://codegolf.stackexchange.com/a/121745/56433). [Answer] # [MATL](https://github.com/lmendo/MATL), 5 bytes ``` t:Ypm ``` [Try it online!](https://tio.run/nexus/matl#@19iFVmQ@/@/oZEBAA "MATL – TIO Nexus") ### Explanation ``` t % Implicit input. Duplicate : % Range from 1 to that Yp % Cumulative product m % Ismember. Implicit display ``` [Answer] # [Fourier](https://github.com/beta-decay/Fourier), ~~40~~ 39 bytes ``` I~Q1~N(i^~i*N~N{Q}{1~Xo}N>Q{1}{1~X0o}X) ``` [**Try it on FourIDE!**](https://beta-decay.github.io/editor/?code=SX5RMX5OKGlefmkqTn5Oe1F9ezF-WG99Tj5RezF9ezF-WDBvfVgp) Basically multiplies the number N by an increasing amount until N is either equal to (output 1) or greater than (output 0) the input. ***Explanation Pseudocode:*** ``` Q = Input N = 1 While X != 1 i += 1 N = N*i If N = Q Then Print 1 X = 1 End If If N > Q Then Print 0 X = 1 End If End While ``` [Answer] # [Japt](https://github.com/ETHproductions/japt), ~~8~~ 6 bytes ``` ol x¥U ``` [Try it online!](http://ethproductions.github.io/japt/?v=1.4.4&code=b2wgeKVV&input=OQ==) This outputs 0 for false and 1 for true. # Explanation ``` ol x¥ U Uol x==U Uo # Create the range [0 ... input] l # Replace each element by its factorial ==U # Compare each element to the input (yielding 1 if equal and 0 otherwise) x # And sum the result ``` [Answer] # [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 ~~6~~ ~~7~~ bytes *Golfed a byte by changing `×/` to `!` thanks to Erik the Outgolfer* ``` ⊢∊!∘⍳ ``` [Try it online!](https://tio.run/##SyzI0U2pTMzJT///3/FR24RHXYsedXQpPuqY8ah38///j9omVj/q3arjCCRqD60AihmZAAA "APL (Dyalog Unicode) – Try It Online") ### Explanation ``` ⍳ Range of numbers from 1 to argument, 1 2 3 4 .. n ! Factorial; 1! 2! 3! 4! .. n! ⊢∊ Is the right argument a member of this list? ``` [Answer] # C++ (clang), ~~51~~ 47 bytes *-4 bytes thanks to Grimmy* Recursion wins out as far as golfing goes. **47 bytes**, with floating point and a global variable: `int i;int f(double n){return n>1?f(n/++i):i=n;}` [Try it online!](https://tio.run/##RY7NCsIwEITveYpFERLiTwVPpq0v4iUmjS7ETUnTU@mzx6YKfodhGWaGNX1/MF7TM2ekBKiKOm7D@PAdkJhil8ZIQO355jidpERxxYbUnLdIxo@2g3pIFsPx1bJSfmskLtjEYMGFCHwdbioFWF@qL8stpVgjBXTAHUfxdwp9XJqOb3YWcACnTQoRtb/TZg8o1Jr9vVcpNucP "C++ (clang) – Try It Online") `double` is used instead of `float` because otherwise it'd start giving false positives around 11! (everything from 39916798 to 39916802 would be identified as factorial). This takes advantage of global variables being initialized (in the case of the integer `i`, to zero). `i=n` casts a `double` floating point value to `int`. Any `n<1` will be rounded down to `0` (falsey). A value of `1` (truthy) will result if and only if `n==1` exactly. The function cleans up after its change to the global variable upon finishing its recursion, by setting it to `0` or `1` with `i=n`. Which of those it is makes no difference; an value of `1` will merely result in the initial division by `1` being skipped the next time the function is invoked. **49 bytes**, with floating point: `int f(double n,int i=2){return n>1?f(n/i,i+1):n;}` [Try it online!](https://tio.run/##RY7BDoIwEETvfMUGY9IGVDCeLOKPeKkt1U3qlpRyInx7pWDiO81OZiar@v6grKRXjEgBDNNufNoOqEwn3s588l0YPQG19d0wOmGJRc2vJOa4Q1J21B00Q9Doju82S62PRGI8mzJYMM4D27YqAdhcqo1FFwVfIwk0wAxD/ncSvV@ahuV7DTiAkSo4j9I@KC8BuVizv/cqkc3xCw "C++ (clang) – Try It Online") --- **51 bytes**, zero is true: `int f(int n,int i=2){return n<2?!n:n%i|f(n/i,i+1);}` This sacrifices quite a lot of speed for 1 byte of savings. Replace the `|` with `||` to make it fast, due to short-circuit evaluation of the logical OR. [Try it online!](https://tio.run/##RY7BDoIwEETv/YoFQ9IGVCSeLOqPeGkK1U1wIaWckG@vLZj4DpPNZmZn9TDsdafo6T2SA8OjUhEVr5WYbesmS0B1dU/oQhl@DKcjFpifhFz8Dkl3U9NCPboG@8PrxmL0rZC4YDODgOkt8O1gKQHrc7kR5jwXqyWCBngS@sV/FRlsiBqeZg3gCEZp11tU3YPSAlDI1ft7spRs8V8 "C++ (clang) – Try It Online") (51 byte slow version) [Try it online!](https://tio.run/##RY7BDoIwEETv/YoVQ9IGVCSeLOqPeGkK1U1wIaWcgG@vLZj4DpPNZGYzuu8PulX08h7JgeFRKY@Kt1JMtnGjJaCqfOzoSinOs@F0whyzs5CL3yPpdqwbqAZXY3d831nsfhQSF2xiEDCdBb59LCRgdSk2wp1lYo1E0ADfhQHib0V6G6qGJ2kNOIBR2nUWVfukJAcUcs3@VhaSLf4L "C++ (clang) – Try It Online") (52 byte fast version) Ungolfed slow version: ``` int isFactorial(int n, int i=2) // returns 0 for true, and nonzero for false { if (n < 2) // same as "if (n==0 || n==1)" in our natural number input domain { if (n==0) return 1; // not factorial else // n==1 return 0; // is factorial (could be either 0! or 1!) } // Because any nonzero value represents "false", using "|" here is equivalent // to "||", provided that the chain of recursion always eventually ends. And // it does always end, because whether or not "n" is factorial, the "n / i" // repeated division will eventually give the value of zero or one, satisfying // the above condition of termination. return (n % i) | isFactorial(n / i, i+1); } ``` Ungolfed fast version: ``` int isFactorial(int n, int i=2) // returns 0 for true, and nonzero for false { if (n < 2) // same as "if (n==0 || n==1)" in our natural number input domain { if (n==0) return 1; // not factorial else // n==1 return 0; // is factorial (could be either 0! or 1!) } if (n % i != 0) return 1; // not factorial else return isFactorial(n / i, i+1); } ``` There are many ways to rearrange this. **52 bytes**, nonzero is true: `int f(int n,int i=2){return n<2?n:n%i?0:f(n/i,i+1);}` [Try it online!](https://tio.run/##RY7BDoIwEETv/YoNhqQNqNV4oig/4qUpVDfBhZRyInx7bcHEd5hsNjM7a8bxaHpNrxCQPFielMqkeL@KxXV@dgRUXxuqKMdGVpbTGUssLkKt4YBk@rntoJ58i8Pp/WAp@9FIXLCFQcQODvh@USrA@iZ34lwUYrMk0AKP/eK/SYwuJi3P8hZwAquNHxzq/klZCSjU5v09KRVbwxc "C++ (clang) – Try It Online") **52 bytes**, zero is true: `int f(int n,int i=2){return!n?1:n%i?n-1:f(n/i,i+1);}` [Try it online!](https://tio.run/##RY7BDoIwEETv/YoVQ9IGUDCeKMqPeGkK1U1wIaWcCN9eWzj4DpPNZGYzepoKPSh6e4/kwPColEfFx02stneLpRO1VU0ptlRUteF0xRyzSsjNn5H0sHQ9NLPrcLx8nix2vwqJC7YyCJjRAj8@lhKwuZcH4c4ysUciaICfwgDxtyKTDVXDk7QDnMEo7UaLanhRkgMKuWePlVBKtvkf "C++ (clang) – Try It Online") --- [Answer] # Perl 5, 31 bytes ``` $a=<>;$a/=++$i while$a>1;exit$a ``` Input is taken via STDIN, output is given via exit code (1 for factorial, 0 for non-factorial). The input is divided by successive integers until it's either 1 or some fraction less than one, which is truncated into the result. [Answer] # [Perl 6](https://perl6.org), 29 bytes ``` {($_,{$_/++$}...2>*).tail==1} ``` [Test it](https://tio.run/nexus/perl6#ZY/faoMwFMbv8xTHIiOpWVat7Upd7K72BF4KRTRlglpp4phInt1F0V2kuTiE3/d9508nBfwcWR6huoeX/F4I4OOA3Ssd3Oub57maMRbEW8JUVlac@3o0xk8lpAIOVdkIiQmrs/Y8IIB6KgDuR9m0nYqNIy28GaVyu0hTdFJwQi4G6cgUb03Qy2JAGnVmtcT8I9RWWQPePDRCt/tjmf8aA07nHE3FbytyJQoC0wqlhOkUPIuEwqpS2Awz08BjGFasN0iPPqwveXTquwe8c8DM8h2CgictMHT/T7@ySooehTY42OD41GhvGr3btpMNgtDOhSbnBzuLHhzyBw "Perl 6 – TIO Nexus") ## Expanded: ``` { # bare block lambda with implicit parameter 「$_」 ( # generate a sequence $_, # starting with the input { $_ / ++$ # divide previous element by an ever increasing number # 1,2,3,4,5,6,7,8 ... * } ... # keep generating until 2 > * # 2 is greater than what was generated # ( 1 or a fractional number ) ).tail == 1 # check if it ended at 1 } ``` [Answer] # [setlX](https://randoom.org/Software/SetlX), 32 bytes ``` f:=n|=>exists(x in{0..n}|n==x!); ``` Creates a function called `f` where your use your potential factorial as parameter. It works with arbitrary integer size but it's fairly inefficient. [![](https://i.stack.imgur.com/lZHRI.png)](https://i.stack.imgur.com/lZHRI.png) (by the way: this is my first participation at a programming puzzle) [Answer] # C (gcc), 33 bytes ``` e;f(n){n=n%++e?n==!(e=0):f(n/e);} ``` Note that some authors define "natural number" as *positive* integer. Hence I don't care that `f(0)` causes an infinite recursion. [Answer] ## [><>](https://esolangs.org/wiki/Fish), ~~24~~ 22 bytes *-2 bytes thanks to @Aaron* I'm trying a new language (since my Mathematica licence expired…) ``` 01\{=n; ?!\$1+:@*:{:}( ``` [Try it online](https://tio.run/nexus/fish#@29gWGZXbZtnzWWoYhOnaK9Ra1VtpeVgpf3//3/dMgVzIwMA "><> – TIO Nexus"), or at the [fish playground](https://fishlanguage.com/playground) Assumes the input number is [already on the stack](https://codegolf.meta.stackexchange.com/a/8493/66104), and returns 0 or 1. It works by multiplying together the first *n* numbers until that stops being less than the input, and then printing 1 if it equals the input, and 0 if it doesn't. [Answer] # [R](https://www.r-project.org/), ~~28~~ 22 bytes ``` scan()%in%gamma(1:171) ``` [Try it online!](https://tio.run/##K/r/vzg5MU9DUzUzTzU9MTc3UcPQytDcUPO/oZHBfwA "R – Try It Online") [Answer] # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 68 bytes ``` bool f(System.Numerics.BigInteger n,int k=2)=>n<2||n%k<1&f(n/k,k+1); ``` [Try it online!](https://tio.run/##lY@xTsMwEIb3PMVRAbKpmyahpUhpOsCEBCgSA0PVwTVOuTh1qtgUodTPHhxAHUGcdNt///edMCNRN7ITFTcGcmgDY7lFAfsaX@CBoybGNqg3yxXwZmOoT@Swgwy0fIec0DQYj2HNjT@x0lgQ3EgTFL6Ti1ey5w0goO7Ty1Ubs4Rdsgmbsis2Y9csmbA4idjM7zSaRI4GAE8fxspteFtrU1cyfG7QynvUkpwOWnQwWkC7CwuC1A2@4ZX3ks0X/b/gOPLj@p@O3Me3rWxQmPAGN3fayr66zOLUJ3w3QW1BZUmq5hmmajjsjQHKi0ylf7qfHOVL6oC0paP9Cy5w3bquKyjILw6a/aBpttDz5HDQZ2oenxdEjxVTw5imnes@AQ "C# (.NET Core) – Try It Online") Not the shortest solution, but works with really big numbers. The TIO link includes an example with `10000!`. Here is a shorter version that uses `int` which has a maximum value of [2147483647](https://docs.microsoft.com/en-us/dotnet/api/system.int32.maxvalue?view=netframework-4.7.2). # [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 45 bytes ``` bool f(int n,int k=2)=>n<2||n%k<1&f(n/k,k+1); ``` [Try it online!](https://tio.run/##FY3BasMwEETv/ooltEWiGztW06aQOJdeWzD0kEPIQVHlVNhdBa1IKY6@3VUuAwPvzRieGx/sZAbNDC2MBUcdnYGLd1/woR0JjsHRaX8AHU4sM9HCGRog@wutkOuiquCoOSvRcgSj2XLR5U1tvsVFB3Dg6EbvD2ONCp9wic/4git8RbXEWi1wpRZJFgCffxztT/nmif1gy11w0b47suJuNroE8y2M57ITTqZZ/k3T0fsBcqcIhLfsGyWbLW3U9Ur3/aZ@6ARVPfaPtVxPafoH "C# (.NET Core) – Try It Online") Credit to @KevinCruijssen for golfing 3 bytes in total from both answers! [Answer] # [Julia 1.0](http://julialang.org/), 26 bytes ``` x->x in Base._fact_table64 ``` Factorial is [implemented as a lookup table](https://github.com/JuliaLang/julia/blob/099e826241fca365a120df9bac9a9fede6e7bae4/base/combinatorics.jl#L1) in Julia, so lets just see if our value is in the table. Accurate for `Int64`, would be wrong for factorials that require a larger Integer type to represent. [Try it online!](https://tio.run/##yyrNyUw0rPifZpuUmp6Zx/m/QteuQiEzT8EpsThVLz4tMbkkviQxKSfVzOR/al4Kl0NxRn65QpqGoSacaYRgGiOYJgimKYJphmCaI5gWSIYh6TM0MtD8DwA "Julia 1.0 – Try It Online") [Answer] # [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes ``` Þ!c ``` [Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDniFjIiwiIiwiMjQiXQ==) Updated to 2.16.0 This checks if the input is in an infinite list of factorials. Now you're probably wondering "but what if it isn't in the factorial list? A linear search won't ever terminate it'll just keep on going!" Well Vyxal is smart enough to know that in strictly ascending infinite lists of numbers, you stop once you reach a number bigger than what you're searching for. [Answer] ## Mathematica, 20 bytes ``` !FreeQ[Range[#]!,#]& ``` other version to test big numbers (see comments) ``` Range[10^3]!~MemberQ~#& ``` tests up to 1000! [Answer] # [Cubix](https://github.com/ETHproductions/cubix), 24 bytes ``` U0O@1I1>-?1u>*w;W;@Orq)p ``` [Try it online](https://ethproductions.github.io/cubix/?code=VTBPQDFJMT4tPzF1Pip3O1c7QE9ycSlw&input=MTIw&speed=10) Cubified ``` U 0 O @ 1 I 1 > - ? 1 u > * w ; W ; @ O r q ) p ``` We start by pushing `1`, `I`nput, `1` onto the stack. These will be our index, our target, and our accumulator, respectively. We then loop. At each iteration, we subtract the accumulator from the input. If the result is 0, we're done, so we push `1`, `O`utput, and exit. If it's negative, we've gone too far, so we push `0`, `O`utput, and exit. Otherwise, we see ``` ;p)*rq; ; Pop the difference off the stack. p) Move the index to the top of the stack and increment it. * Multiply the accumulator by the index to get the next factorial. rq; Put the stack back in the right order. ``` [Answer] # TI-BASIC, 13 bytes ``` sum(Ans=seq(X!,X,1,69 ``` Input is an integer in Ans. Output is 1 if the input is a factorial, 0 if not. Due to precision in `=` checks being limited to 10 decimal places, this program will produce erroneous answers for numbers whose length is \$>10\$ digits. **Explanation:** ``` seq(X!,X,1,69 ;generate a list of all factorial numbers that ; TI-BASIC can store Ans= ;equality check of the input against all members, ; 1 if true, 0 if false sum( ;sum the elements in the list ;leave the result in Ans ;implicit print of Ans ``` **Examples:** ``` 720:prgmCDGF27 1 25:prgmCDGF27 0 ``` **Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count. [Answer] # [cQuents](https://github.com/stestoltz/cQuents), 3 bytes ``` ?$! ``` [Try it online!](https://tio.run/##Sy4sTc0rKf7/315F8f9/IxMA "cQuents – Try It Online") As I said in another question, cQuents is made for this. ``` ? # Query (Outputs if in the sequence) $! # Factorial ``` ]
[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/6836/edit). Closed 3 years ago. [Improve this question](/posts/6836/edit) Quoting [this question on SO](https://stackoverflow.com/q/11694546/698590) (Spoiler alert!): > > This question has been asked in an Oracle interview. > > > How would you divide a number by 3 without using \*, /, +, -, %, > operators? > > > The number may be signed or unsigned. > > > The task is solvable, but see if you can write the shortest code. ## Rules: * Perform the required **integer** division (`/3`) * Do not use the non-text-based operators `*`, `/`, `+`, `-`, or `%` (or their equivalents, such as `__div__` or `add()`). This also applies to incrementing and decrementing operators, like `i++` or `i--`. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary `-` operator for negative numbers, or `*` to represent a pointer in C is OK as well. * Input value can be arbitrarily large (whatever your system can handle), both positive and negative * Input can be on STDIN or ARGV or entered any other way * Create the shortest code you can to do the above [Answer] # C, 167503724710 Here's my solution to the problem. I admit it is unlikely to win a strict code golf competition, but it doesn't use any tricks to indirectly call built-in division functionality, it is written in portable C (as the original Stack Overflow question asked for), it works perfectly for negative numbers, and the code is exceptionally clear and explicit. My program is the *output* of the following script: ``` #!/usr/bin/env python3 import sys # 71 sys.stdout.write('''#include <stdint.h> #include <stdio.h> int32_t div_by_3(int32_t input){''') # 39 * 2**32 for i in range(-2**31, 2**31): # 18 + 11 + 10 = 39 sys.stdout.write('if(input==%11d)return%10d;' % (i, i / 3)) # 95 sys.stdout.write(r'''return 7;}int main(int c,char**v){int32_t n=atoi(a[1]);printf("%d / 3 = %d\n",n, div_by_3(n));}''') ``` Character count: 71 + 39 \* 2\*\*32 + 95 = **167503724710** ### Benchmarks It was asked how long this would take and how much memory it would use, so here are some benchmarks: * Script execution time — Running `./test.py | pv --buffer-size=1M --average-rate > /dev/null` for about 30 seconds gives a rate of about 14.8 MB/s. The rate of output can reasonably be assumed to be roughly constant, so the running time to completion should be about 167503724710 B / (14.8 \* 1048576 B/s) ≈ 10794 s. * Compilation time — The TCC compiler [claims to compile C code at 29.6 MB/s](http://bellard.org/tcc/#speed), which makes for a compilation time of 167503724710 B / (29.6 \* 1048576 B/s) ≈ 5397 s. (Of course this can run in a pipeline with the script.) * Size of compiled code — I tried estimating it using `./test.py | tcc -c - -o /dev/stdout | pv --buffer-size=1M --average-rate > /dev/null`, but it seems `tcc` doesn't output anything until it reads the entire source file in. * Memory usage to run — Since the algorithm is linear (and tcc doesn't optimize across lines), the memory overhead should be only a few kilobytes (apart from the code itself, of course). [Answer] # Ruby 28 ``` b=->n{n.to_s(3).chop.to_i 3} ``` To divide by 3 we just need to remove the trailing zero in base 3 number: `120 -> 11110 -> 1111 -> 40` Works with negatives: ``` ice distantstar:~/virt/golf [349:1]% ruby ./div3.rb 666 222 ice distantstar:~/virt/golf [349]% ruby ./div3.rb -15 -5 ``` # Ruby, ~~60~~45 Alternatively, w/o using base conversion: ~~d=->n{x=n.abs;r=(0..1.0/0).step(3).take(x).index x;n>0?r:-r}~~ ``` d=->n{(r=1.step(n.abs,3).to_a.size);n>0?r:-r} ``` [Answer] # Mathematica, 13 chars ``` Mean@{#,0,0}& ``` [Answer] ## JavaScript, 56 ``` alert(Array(-~prompt()).join().replace(/,,,/g,1).length) ``` Makes a string of length `n` of repeating `,`s and replaces `,,,` with `1`. Then, it measures the string's resulting length. (Hopefully unary `-` is allowed!) [Answer] ## Python, 41 38 ``` print"-"[x:]+`len(xrange(2,abs(x),3))` ``` `xrange` seems to be able to handle large numbers (I think the limit is the same as for a long in C) almost instantly. ``` >>> x = -72 -24 >>> x = 9223372036854775806 3074457345618258602 ``` [Answer] # J, ~~45 44~~ 10 chars `".,&'r3'":` Works with negatives: ``` ".,&'r3'": 15 5 ".,&'r3'": _9 _3 ".,&'r3'": 3e99 1e99 ``` `":` - format as text `,&'r3'` - append `r3` to the end `".` - execute the string, e.g. `15r3` [Answer] ## Haskell, 90 ~~106~~ ``` d n=snd.head.dropWhile((/=n).fst)$zip([0..]>>=ν)([0..]>>=replicate 3>>=ν);ν q=[negate q,q] ``` Creates an infinite (lazy) lookup list `[(0,0),(0,0),(-1,0),(1,0),(-2,0),(2,0),(-3,-1),(3,1), ...]`, trims all elements that don't match `n` (`/=` is inequality in Haskell) and returns the first which does. This gets much simpler if there are no negative numbers: ## 25 ~~27~~ ``` (([0..]>>=replicate 3)!!) ``` simply returns the `n`th element of the list `[0,0,0,1,1,1,2, ...]`. [Answer] ## C#, 232 bytes My first code golf... And since there wasn't any C# and I wanted to try a different method not tried here, thought I would give it a shot. Like some others here, only non-negative numbers. ``` class l:System.Collections.Generic.List<int>{}class p{static void Main(string[] g){int n=int.Parse(g[0]);l b,a=new l();b=new l();while(a.Count<n)a.Add(1);while(a.Count>2){a.RemoveRange(0,3);b.Add(1);}System.Console.Write(b.Count);}} ``` ## Ungolfed ``` class l : System.Collections.Generic.List<int> { } class p { static void Main(string[] g) { int n = int.Parse(g[0]); l b, a = new l(); b = new l(); while (a.Count < n) a.Add(1); while (a.Count > 2) { a.RemoveRange(0, 3); b.Add(1); } System.Console.Write(b.Count); } } ``` [Answer] ## Perl (~~26~~ 22) ``` $_=3x pop;say s|333||g ``` This version (ab)uses Perl's regex engine. It reads a number as the last command line argument (`pop`) and builds a string of `3`s of this length (`"3" x $number`). The regex substitution operator (`s///`, here written with different delimitiers because of the puzzle's rules and with a `g`lobal flag) substitues three characters by the empty string and returns the number of substitutions, which is the input number integer-divided by three. It could even be written without `3`, but the above version looks funnier. ``` $ perl -E '$_=3x pop;say s|333||g' 42 14 ``` [Answer] ## C, 160 chars Character by character long division solution using lookup tables, i.e. without string atoi() or printf() to convert between base 10 strings and integers. Output will sometimes include a leading zero - part of it's charm. ``` main(int n,char**a){ char*s=a[1],*x=0; if(*s==45)s=&s[1]; for(;*s;s=&s[1])n=&x[*s&15],x="036"[(int)x],*s=&x["000111222333"[n]&3],x="012012012012"[n]&3; puts(a[1]); } ``` Note: * abuses array access to implement addition. * compiles with clang 4.0, other compilers may barf. Testing: ``` ./a.out -6 -2 ./a.out -5 -1 ./a.out -4 -1 ./a.out -3 -1 ./a.out -2 -0 ./a.out -1 -0 ./a.out 0 0 ./a.out 1 0 ./a.out 2 0 ./a.out 3 1 ./a.out 4 1 ./a.out 5 1 ./a.out 6 2 ./a.out 42 14 ./a.out 2011 0670 ``` [Answer] # Python 42 ``` int(' -'[x<0]+str(len(range(2,abs(x),3)))) ``` Since every solution posted here that Ive checked truncates decimals here is my solution that does that. # Python 50 51 ``` int(' -'[x<0]+str(len(range([2,0][x<0],abs(x),3)))) ``` Since python does floor division, here is my solution that implements that. Input integer is in the variable x. Tested in Python 2.7 but I suspect it works in 3 as well. [Answer] ## JavaScript, 55 ``` alert(parseInt((~~prompt()).toString(3).slice(0,-1),3)) ``` If one can't use `-1`, then here is a version replacing it with `~0` (thanks Peter Taylor!). ``` alert(parseInt((~~prompt()).toString(3).slice(0,~0),3)) ``` [Answer] # C 83 characters The number to divide is passed in through stdin, and it returns it as the exit code from `main()` (%ERRORLEVEL% in CMD). This code abuses some versions of MinGW in that when optimizations aren't on, it treats the last assignment value as a return statement. It can probably be reduced a bit. Supports all numbers that can fit in to an `int` If unary negate (-) is not permitted: (129) ``` I(unsigned a){a=a&1?I(a>>1)<<1:a|1;}main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:I(~a);for(c=0;a<~1;a=I(I(I(a))))c=I(c);b=b<0?I(~c):c;} ``` If unary negate **IS** permitted: (123) ``` I(unsigned a){a=a&1?I(a>>1)<<1:a|1;}main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:-a;for(c=0;a<~1;a=I(I(I(a))))c=I(c);b=b<0?-c:c;} ``` # EDIT: ugoren pointed out to me that -~ is an increment... 83 Characters if unary negate is permitted :D ``` main(a,b,c){scanf("%i",&b);a=b;a=a<0?a:-a;for(c=0;a<~1;a=-~-~-~a)c=-~c;b=b<0?-c:c;} ``` [Answer] # C, 139 chars ``` t;A(a,b){return a?A((a&b)<<1,a^b):b;}main(int n,char**a){n=atoi(a[1]);for(n=A(n,n<0?2:1);n&~3;t=A(n>>2,t),n=A(n>>2,n&3));printf("%d\n",t);} ``` Run with number as command line argument * Handles both negative and positive numbers Testing: ``` ./a.out -6 -2 ./a.out -5 -1 ./a.out -4 -1 ./a.out -3 -1 ./a.out -2 0 ./a.out -1 0 ./a.out 0 0 ./a.out 1 0 ./a.out 2 0 ./a.out 3 1 ./a.out 4 1 ./a.out 5 1 ./a.out 6 2 ./a.out 42 14 ./a.out 2011 670 ``` Edits: * saved 10 chars by shuffling addition (A) to remove local variables. [Answer] ## ZSH — ~~31~~ 20/21 ``` echo {2..x..3}|wc -w ``` For negative numbers: ``` echo {-2..x..3}|wc -w ``` ### With negative numbers (ZSH + `bc`) — ~~62~~ 61 I probably shouldn't give two programs as my answer, so here's one that works for any sign of number: ``` echo 'obase=10;ibase=3;'`echo 'obase=3;x'|bc|sed 's/.$//'`|bc ``` This uses the same base conversion trick as [Artem Ice's answer](https://codegolf.stackexchange.com/a/6838/1136). [Answer] ## C, 81 73 chars Supports non-negative numbers only. ``` char*x,*i; main(){ for(scanf("%d",&x);x>2;x=&x[~2])i=&i[1]; printf("%d",i); } ``` The idea is to use pointer arithemtic. The number is read into the pointer `x`, which doesn't point anywhere. `&x[~2]` = `&x[-3]` = `x-3` is used to subtract 3. This is repeated as long as the number is above 2. `i` counts the number of times this is done (`&i[1]` = `i+1`). [Answer] ## Java ~~86~~ 79 Assume the integer is in y: Converts to a string in base 3, removes the last character ( right shift ">>" in base 3 ), then converts back to integer. Works for negative numbers. If the number, y, is < 3 or > -3, then it gives 0. ``` System.out.print(~2<y&y<3?0:Long.valueOf(Long.toString(y,3).split(".$")[0],3)); ``` First time posting on code golf. =) So can't comment yet. Thx Kevin Cruijssen for the tips. [Answer] # Python2.6 (~~29~~)(~~71~~)(~~57~~)(~~52~~)(43) ``` z=len(range(2,abs(x),3)) print (z,-z)[x<0] ``` ``` print len(range(2,input(),3)) ``` Edit - Just realized that we have to handle negative integers too. Will fix that later Edit2 - Fixed Edit3 - Saved 5 chars by following Joel Cornett's advice Edit4 - Since input doesn't have to be necessarily be from STDIN or ARGV, saved 9 chars by not taking any input from stdin [Answer] # Javascript, ~~47~~ 29 Uses `eval` to dynamically generate a `/`. Uses `+` only for string concatenation, not addition. ``` alert(eval(prompt()+"\57"+3)) ``` EDIT: Used `"\57"` instead of `String.fromCharCode(47)` [Answer] ## Ruby (~~43~~ ~~22~~ 17) Not only golf, but elegance also :) ``` p Rational gets,3 ``` Output will be like `(41/1)`. If it must be integer then we must add `.to_i` to result, and if we change `to_i` to `to_f` then we will can get output for floats also. [Answer] # TI-Basic, 8 bytes Winner? :) ``` int(mean({Ans,0,0 ``` P.S. Rounds towards infinity for negative numbers (see [here](https://stackoverflow.com/questions/19517868/integer-division-by-negative-number) for why). To round to zero instead, replace `int(` with `iPart(` for no byte change. **Test cases** ``` -4:prgmDIVIDE -2 11:prgmDIVIDE 3 109:prgmDIVIDE 36 ``` [Answer] # Python 2.x, ~~54~~ ~~53~~ 51 `print' -'[x<0],len(range(*(2,-2,x,x,3,-3)[x<0::2]))` Where `_` is the dividend and is entered as such. ``` >>> x=-19 >>> print' -'[x<0],len(range(*(2,-2,x,x,3,-3)[x<0::2])) - 6 ``` Note: Not sure if using the interactive interpreter is allowed, but according to the OP: "Input can be on STDIN or ARGV or entered any other way" Edit: Now for python 3 (works in 2.x, but prints a tuple). Works with negatives. [Answer] ## C++, 191 With main and includes, its 246, without main and includes, it's only 178. Newlines count as 1 character. Treats all numbers as unsigned. I don't get warnings for having main return an unsigned int so its fair game. My first ever codegolf submission. ``` #include<iostream> #define R return typedef unsigned int U;U a(U x,U y){R y?a(x^y,(x|y^x^y)<<1):x;}U d(U i){if(i==3)R 1;U t=i&3,r=i>>=2;t=a(t,i&3);while(i>>=2)t=a(t,i&3),r=a(r,i);R r&&t?a(r,d(t)):0;}U main(){U i;std::cin>>i,std::cout<<d(i);R 0;} ``` uses shifts to divide number by 4 repeatedly, and calculates sum (which converges to 1/3) Pseudocode: ``` // typedefs and #defines for brevity function a(x, y): magically add x and y using recursion and bitwise things return x+y. function d(x): if x = 3: return 1. variable total, remainder until x is zero: remainder = x mod 4 x = x / 4 total = total + x if total and remainder both zero: return 0. else: return a(total, d(remainder)). ``` As an aside, I could eliminate the main method by naming d main and making it take a char \*\* and using the programs return value as the output. It will return the number of command line arguments divided by three, rounded down. This brings its length to the advertised 191: ``` #define R return typedef unsigned int U;U a(U x,U y){R y?a(x^y,(x|y^x^y)<<1):x;}U main(U i,char**q){if(i==3)R 1;U t=i&3,r=i>>=2;t=a(t,i&3);while(i>>=2)t=a(t,i&3),r=a(r,i);R r&&t?a(r,d(t)):0;} ``` [Answer] ## Golfscript - 13 chars ``` ~3base);3base ``` [Answer] ## **PowerShell 57 or 46** In 57 characters using `%` as the PowerShell foreach operator, not modulo. This solution can accept positive or negative integers. ``` (-join(1..(Read-Host)|%{1})-replace111,0-replace1).Length ``` In 46 characters if `*` is allowed as the string repetition operator, not multiply. This option requires positive integers as input values. ``` ("1"*(Read-Host)-replace111,0-replace1).Length ``` [Answer] # R These only work with positive integers: ``` max(sapply(split(1:x,1:3), length)) # Gives a warning that should be ignored ``` Or: ``` min(table(rep(1:3, x)[1:x])) ``` Or: ``` length((1:x)[seq(3,x,3)]) ``` Or: ``` sum(rep(1,x)[seq(3,x,3)]) ``` [[EDIT]] And an ugly one: ``` trunc(sum(rep(0.3333333333, x))) ``` [[EDIT2]] Plus probably the best one - inspired by the matlab code above by Elliot G: ``` length(seq(1,x,3)) ``` [Answer] # SmileBASIC, ~~58~~ ~~51~~ 36 bytes (no mathematical functions!) ``` INPUT N BGANIM.,4,-3,N WAIT?BGROT(0) ``` Explanation: ``` INPUT N 'get input BGANIM 0,"R",-3,N 'smoothly rotate background layer 0 by N degrees over 3 frames WAIT 'wait 1 frame PRINT BGROT(0) 'display angle of layer 0 ``` The program moves the background layer smoothly over 3 frames, and then gets the angle after 1 frame, when it has traveled 1/3 of its total distance. ### Float division version, 38 bytes: ``` INPUT N BGANIM.,7,-3,N WAIT?BGVAR(0,7) ``` Explanation: ``` INPUT N 'input BGANIM 0,"V",-3,N 'smoothly change layer 0's internal variable to N over 3 frames WAIT 'wait 1 frame PRINT BGVAR(0,7) 'display layer 0's internal variable ``` [Answer] # Haskell ~~41~~ 39 chars Works with the full set of positive and negative integers ``` f n=sum[sum$1:[-2|n<0]|i<-[3,6..abs n]] ``` First creates a list 1's or (-1)'s (depending on the sign of the input) for every third integer from 0 up until the input `n`. `abs(n)` for negative numbers inclusive. e.g `n=8 -> [0,3,6]` It then returns the sum of this list. [Answer] # [Python 3](https://docs.python.org/3/), 72 bytes ``` f=lambda x:x and s(x>>1,f(x>>1)) s=lambda x,y:y and s(x^y,(~x&y)<<1)or x ``` [Try it online!](https://tio.run/##PYwxCsMwDAB3v0JoKBYIgjF0MEmeUnBI3QpaJTgZ7KVfd0KhXe6W49a6Pxf1raXhFd/THKGEAlFn2GwZR8fpKyKz/QOuof6SW2X7KZdKfe9oyVBaOikgCjnq427dlYIBWLPoboWxAw8DnlshRossnWckJNMO "Python 3 – Try It Online") A bitwise solution consisting of two recursive functions, one to calculate third, the other to subtract. Because multiplying and dividing by 2 is easy to do bitwise, we can use the fact: \$X/3=X/2-(X/2)/3\$ to recursively find the third. It does produce some weird rounding patterns for non-multiples of three. ``` 0 -> 0 (0) 1 -> 0 (0.333...) 2 -> 1 (0.666...) 3 -> 1 (1) 4 -> 1 (1.333...) 5 -> 1 (1.666...) 6 -> 2 (2) 7 -> 2 (2.333...) 8 -> 3 (2.666...) 9 -> 3 (3) 10 -> 4 (3.333...) 11 -> 4 (3.666...) 12 -> 4 (4) 13 -> 4 (4.333...) 14 -> 5 (4.666...) 15 -> 5 (5) ``` [Answer] # Clojure, 87; works with negatives; based on lazyseqs ``` (defn d[n](def r(nth(apply interleave(repeat 3(range)))(Math/abs n)))(if(> n 0)r(- r))) ``` Ungolfed: ``` (defn d [n] (let [r (nth (->> (range) (repeat 3) (apply interleave)) (Math/abs n))] (if (pos? n) r (- r)))) ``` ]